<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="addRepairNotesDialog"
    title="发货单"
    :close-on-click-modal="false"
    width="85%"
    append-to-body
    @close="handleClose"
    :maxable="true"
  >
    <div class="main_container">
      <el-form :model="searchForm" label-width="120px" @keyup.enter.native="onSearch" @submit.native.prevent>
        <el-row>
          <el-col :span="8">
            <el-form-item label="发货单编码:">
              <el-input
                style="width: 100%"
                type="text"
                clearable
                placeholder="请输入"
                v-model="searchForm.docNo"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="销售订单编码:">
              <el-input
                style="width: 100%"
                type="text"
                clearable
                placeholder="请输入"
                v-model="searchForm.orderNo"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称:">
              <el-input
                style="width: 100%"
                type="text"
                clearable
                placeholder="请输入"
                v-model="searchForm.contactName"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间:">
              <el-date-picker
                style="width: 100%;"
                v-model="searchForm.time"
                type="datetimerange"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00']"
                value-format="yyyy-MM-dd HH:mm:ss"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item>
              <el-button
                size="small"
                type="primary"
                icon="el-icon-search"
                class="ele-btn-icon"
                @click="onSearch"
              >查询</el-button>

              <el-button @click="reset" icon="el-icon-refresh" class="ele-btn-icon" size="medium">重置</el-button>
              <slot></slot>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <headerTitle title="发货单" style="margin-top: 8px"></headerTitle>
      <ele-pro-table
        ref="tableRef2"
        :columns="columns"
        :datasource="datasource"
        tool-class="ele-toolbar-form"
        :initLoad="false"
        height="300px"
        @cell-click="rowClick"
      ></ele-pro-table>
      <headerTitle title="物品明细" style="margin-top: 8px"></headerTitle>
      <ele-pro-table
        ref="tableRef3"
        :columns="columnsPro"
        :datasource="packingList"
        :need-page="false"
        tool-class="ele-toolbar-form"
        :selection.sync="selection"
        height="400px"
      ></ele-pro-table>
      <!-- <ele-pro-table
        v-else
        ref="tableRef3"
        :columns="listColumn"
        :datasource="packingList"
        :need-page="false"
        tool-class="ele-toolbar-form"
        :selection.sync="selection"
        height="400px"
      >
        <template v-slot:industryArtFiles="scope">
          <el-form-item style="margin-bottom: 20px">
            <fileMain v-model="scope.row.industryArtFiles" type="view"></fileMain>
          </el-form-item>
        </template>
      </ele-pro-table>-->
    </div>
    <div slot="footer" class="footer">
      <el-button type="primary" @click="submitAdd">确认</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
  </ele-modal>
</template>

<script>
import { parameterGetByCode } from '@/api/main';
import {
  getSendTableList,
  getSendSaleOrderrecordDetailSplit
} from '@/api/saleManage/saleordersendrecord';
import { reviewStatusEnum } from '@/enum/dict';
import { lbjtList } from '@/enum/dict.js';
import { getInfoBySourceBizNoAll } from '@/api/wms';
const dayjs = require('dayjs');

export default {
  props: {
    contractBookType: {
      //合同类型 1销售 2采购
      type: [String, Number],
      default: 1
    }
  },
  components: {},

  data() {
    return {
      addRepairNotesDialog: false,
      rowClickData: {},
      selection: [],
      packingList: [],
      columns: [
        {
          columnKey: 'index',
          label: '序号',
          type: 'index',
          width: 55,
          align: 'center',
          showOverflowTooltip: true
        },

        {
          prop: 'docNo',
          label: '发货单编码',
          sortable: true,
          align: 'center',
          slot: 'docNo',
          showOverflowTooltip: true,
          minWidth: 120
        },

        {
          prop: 'orderNo',
          label: '销售订单编码',
          sortable: true,
          align: 'center',
          slot: 'orderNo',
          showOverflowTooltip: true,
          minWidth: 120
        },
        {
          prop: 'contactName',
          label: '客户名称',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120
        },
        {
          prop: 'replied',
          label: '是否回执',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120,
          formatter: (_row, _column, cellValue) => {
            return _row.replied == 1 ? '是' : '否';
          }
        },
        {
          prop: 'reviewStatus',
          label: '状态',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120,
          formatter: (_row, _column, cellValue) => {
            return reviewStatusEnum[_row.reviewStatus].label;
          }
        },
        {
          prop: 'createTime',
          label: '创建时间',
          align: 'center',
          showOverflowTooltip: true,
          minWidth: 120
        }
      ],
      columnsPro: [
        {
          width: 45,
          type: 'selection',
          columnKey: 'selection',
          align: 'center'
        },
        {
          columnKey: 'index',
          label: '序号',
          type: 'index',
          width: 55,
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'productCategoryName',
          label: '类型',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'categoryCode',
          label: '编码',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'categoryName',
          label: '名称',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'productBrand',
          label: '牌号',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'categoryModel',
          label: '型号',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'packingSpecification',
          label: '规格',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'batchNo',
          label: '批次号',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'measureQuantity',
          label: '计量数量',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'singlePrice',
          label: '单价（元）',
          align: 'center',
          showOverflowTooltip: true
        },
        {
          prop: 'barcodes',
          label: '发货条码/车架号',
          align: 'center',
          showOverflowTooltip: true
        }
        // {
        //   prop: 'materielDesignation',
        //   label: '物料代号',
        //   align: 'center',
        //   showOverflowTooltip: true
        // },
        // {
        //   prop: 'engrave',
        //   label: '刻码',
        //   align: 'center',
        //   showOverflowTooltip: true
        // }
      ],
      contactId: '',
      goodsShow: false,
      searchForm: {}
    };
  },
  created() {},
  methods: {
    // 初始化数据(父组件调用)
    open(data, obj) {
      this.contactId = data;
      this.addRepairNotesDialog = true;
      // this.contractId = data.contractId;
      // this.rowClickData.id = data.orderId;
      // this.rowClickData.docNo = data.orderCode;
      // 数据回显 ***
      this.rowClickData.id = obj.orderId;
      this.rowClickData.docNo = obj.orderCode;
      this.packingList = JSON.parse(JSON.stringify(obj.tableList));

      this.$nextTick(() => {
        this.packingList.forEach((row) => {
          this.$refs.tableRef3.toggleRowSelection(row);
        });
        this.reload();
      });
    },

    datasource({ page, limit, where, order }) {
      return getSendTableList({
        pageNum: page,
        size: limit,
        ...where
      });
    },
    onSearch() {
      console.log(this.searchForm, 'form');
      let data = JSON.parse(JSON.stringify(this.searchForm));
      if (data.time?.length > 0) {
        data.createTimeStart = data.time[0];
        data.createTimeEnd = data.time[1];
      }
      delete data.time;
      this.reload(data);
    },
    reset() {
      this.searchForm = {
        docNo: '',
        orderNo: '',
        contactName: '',
        time: []
      };
      this.reload({});
    },
    reload(where) {
      where = {
        ...where,
        // contractId: this.contractId,
        contactId: this.contactId,
        reviewStatus: 2
      };
      this.$refs.tableRef2.reload({ page: 1, where });
    },
    async rowClick(row) {
      this.rowClickData = row;
      let params = {
        code: 'after_sales_product_list_source'
      };
      const res = await parameterGetByCode(params);
      if (res.value == '1') {
        this.getInfo(row);
      } else {
        this._getInfo(row.docNo);
      }
    },
    handleClose() {
      this.addRepairNotesDialog = false;
    },
    submitAdd() {
      console.log(this.selection, 'this.selection 确定');
      if (!this.selection.length) {
        return this.$message.warning('请至少选择一条数据');
      }
      this.$emit('changeParent', {
        orderCode: this.rowClickData.docNo,
        orderId: this.rowClickData.id,
        tableList: this.selection
      });
      this.handleClose();
    },

    async getInfo(row) {
      const res = await getSendSaleOrderrecordDetailSplit(row.id);
      let list = res.productList.map((el) => {
        el.categoryCode = el.productCode;
        el.categoryName = el.productName;
        el.categoryModel = el.modelType;
        el.measureQuantity = el.totalCount;
        el.barcodes = el.carCode;
        el.packingSpecification = el.specification;
        el.shipmentDate = row.createTime || null;
        (el.guaranteePeriodDeadline = this.getTime(row.createTime)[0]),
          (el.warrantyStatus = this.getTime(row.createTime)[1]);
        return el;
      });
      this.packingList = list;
    },

    async _getInfo(sourceBizNo) {
      const dataArray = await getInfoBySourceBizNoAll(sourceBizNo);
      let res = {};
      if (dataArray && dataArray.length > 0) {
        res = JSON.parse(JSON.stringify(dataArray[0]));
        res['outInDetailList'] = [];
        dataArray.forEach((item) => {
          item.outInDetailList.forEach((val) => {
            res['outInDetailList'].push(val);
          });
        });
      }
      this.init(res);
    },
    init(res) {
      this.infoData = res;
      this.productList = res?.outInDetailList?.map(
        (productItem, productIndex) => {
          return {
            ...productItem,
            outInDetailRecordRequestList:
              productItem.outInDetailRecordRequestList.map((packingItem) => {
                return {
                  ...packingItem,
                  categoryName: productItem.categoryName,
                  categoryCode: productItem.categoryCode,
                  categoryModel: productItem.categoryModel,
                  produceTime: packingItem.produceTime || null,
                  shipmentDate: res.createTime || null,
                  guaranteePeriodDeadline: this.getTime(res.createTime)[0],
                  warrantyStatus: this.getTime(res.createTime)[1]
                };
              })
          };
        }
      );
      // 获取包装维度数据
      const arr = [];
      for (const key in this.productList) {
        for (const k in this.productList[key].outInDetailRecordRequestList) {
          arr.push({
            ...this.productList[key].outInDetailRecordRequestList[k]
          });
        }
      }
      this.packingList = arr;
    },

    getTime(createTime) {
      let date = new Date(createTime);
      date.setMonth(date.getMonth() + 13); // 月份加13月
      let time = dayjs(date).format('YYYY-MM-DD HH:mm:ss');
      let warrantyStatus =
        new Date(time).getTime() > new Date().getTime() ? 0 : 1;
      return [time, warrantyStatus];
    }
  }
};
</script>

<style lang="scss" scoped></style>
