<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.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="tableRefs2"
        :columns="columns"
        :datasource="datasource"
        tool-class="ele-toolbar-form"
        :initLoad="false"
        height="300px"
        highlight-current-row
        @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>
    </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 { reviewStatus } from '@/enum/dict';
  import {
    getTableListHome,
    getSaleOrderDetail
  } from '@/api/saleManage/saleorder.js';

  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: 'orderNo',
            label: '订单编码',
            align: 'center',
            slot: 'orderNo',
            showOverflowTooltip: true,
            minWidth: 200
          },
          {
            prop: 'needProduce',
            label: '订单类型',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150,
            formatter: (_row, _column, cellValue) => {
              let businessType =
                cellValue == 1
                  ? '有客户生产性订单'
                  : cellValue == 2
                  ? '无客户生产性订单'
                  : cellValue == 4
                  ? '不定向订单'
                  : '库存式订单';

              return businessType;
            }
          },
          {
            prop: 'preOrderNo',
            label: '预销售订单编码',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 200
          },
          {
            prop: 'productNames',
            label: '产品名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            minWidth: 160,
            prop: 'productionCodes',
            label: '生产编号',
            align: 'center'
          },
          {
            prop: 'batchNos',
            label: '批次号',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'productCount',
            label: '数量',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 140
          },
          {
            prop: 'orderStatus',
            label: '审核状态',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100,
            formatter: (_row, _column, cellValue) => {
              return reviewStatus[_row.orderStatus];
            }
          }
        ],
        columnsPro: [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center'
          },
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'categoryName',
            label: '名称',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'productCategoryName',
            label: '类型',
            align: 'center',
            showOverflowTooltip: true
          },
          {
            prop: 'categoryCode',
            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
          }
        ],
        contactId: '',
        searchForm: {}
      };
    },
    created() {},
    methods: {
      // 初始化数据(父组件调用)
      open(data, obj) {
        this.contactId = data;
        this.addRepairNotesDialog = true;
        // 数据回显 ***
        this.rowClickData.id = obj.orderId;
        this.rowClickData.orderNo = 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 getTableListHome({
          pageNum: page,
          size: limit,
          ...where
        });
      },
      onSearch() {
        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 = {
          orderNo: '',
          contactName: '',
          time: []
        };
        this.reload({});
      },
      reload(where) {
        where = {
          ...where,
          // contractId: this.contractId,
          contactId: this.contactId
          // reviewStatus: 2
        };
        this.$refs.tableRefs2.reload({ page: 1, where });
      },
      async rowClick(row) {
        this.rowClickData = { orderNo: row.orderNo, id: row.id };
        this.getInfo(row);
      },
      handleClose() {
        this.addRepairNotesDialog = false;
        this.rowClickData = {};
      },
      submitAdd() {
        if (!this.rowClickData.id) {
          return this.$message.warning('请至少选择一条销售订单数据');
        }
        if (this.selection.length > 1) {
          return this.$message.warning('只能选择一条物品明细数据');
        }
        this.$emit('changeParent', {
          orderCode: this.rowClickData.orderNo,
          orderId: this.rowClickData.id,
          tableList: this.selection
        });
        this.handleClose();
      },

      async getInfo(row) {
        const res = await getSaleOrderDetail(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;
      },
      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>
