<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    v-if="visible"
    :visible.sync="visible"
    :title="title"
    :close-on-click-modal="false"
    :append-to-body="true"
    :fullscreen="fullscreen"
    width="70%"
    @close="cancel"
  >
    <template slot="title">
      <modalTitle
        :title="title"
        @setFullscreen="fullscreen = !fullscreen"
      ></modalTitle>
    </template>
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      class="el-form-box"
      label-width="120px"
    >
      <headerTitle title="收货确认单信息"></headerTitle>
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="发货单" prop="sendNo">
            <el-input
              clearable
              v-model="form.sendNo"
              @click.native="handleSendOrderBtn"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="repliedFiles" label="回执附件">
            <fileMain v-model="form.repliedFiles"></fileMain>
          </el-form-item>
        </el-col>
      </el-row>

      <headerTitle title="发货信息"></headerTitle>

      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="销售订单" prop="orderNo">
            <el-input
              clearable
              v-model="form.orderNo"
              disabled
              @click.native="handleOrderBtn"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="受托收货单">
            <el-input
              clearable
              disabled
              v-model="form.entrustedCode"
              @click.native="handleEntrustedReceive"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="客户名称" prop="contactName">
            <el-input v-model="form.contactName" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户联系人" prop="linkName">
            <el-input
              clearable
              v-model="form.linkName"
              disabled
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="客户电话" prop="linkPhone">
            <el-input
              clearable
              v-model="form.linkPhone"
              disabled
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收货地址" prop="receiveAddress">
            <el-input
              disabled
              clearable
              v-model="form.receiveAddress"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="项目名称" prop="projectName">
            <el-input clearable v-model="form.projectName" :disabled="true" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="sendFiles" label="发货附件">
            <fileMain v-model="form.sendFiles" type="view"></fileMain>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-tabs v-model="activeName" style="margin-top: 15px" type="border-card">
      <el-tab-pane label="收货产品明细" name="first">
        <ele-pro-table
          ref="table"
          :needPage="false"
          :columns="columns"
          :toolkit="[]"
          :datasource="form.productList"
          row-key="id"
        >
          <template v-slot:isException="scope">
            <el-select v-model="scope.row.isException" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
          <template v-slot:notaxSinglePrice="scope">
     
              <el-input
                v-model="scope.row.notaxSinglePrice"
                placeholder="请输入"
                type="number"
              >
                <template slot="append">元</template>
              </el-input>
          </template>
        </ele-pro-table>
      </el-tab-pane>

      <el-tab-pane label="托盘清单" name="second">
        <!-- <palletTable ref="palletTableRef" type="view"></palletTable> -->
        <ele-pro-table
          ref="table"
          :needPage="false"
          :columns="trayListColumns"
          :toolkit="[]"
          :datasource="trayListData"
          row-key="id"
        >
          <template v-slot:type="scope">
            <el-select v-model="scope.row.type" placeholder="请选择">
              <el-option
                v-for="item in options1"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </ele-pro-table>
      </el-tab-pane>
      <el-tab-pane label="装载车叉车信息" name="third">
        <stowageTable ref="stowageTableRef" dialogType="view"></stowageTable>
      </el-tab-pane>
      <el-tab-pane label="运输清单" name="fourth">
        <taskInfoTable ref="taskInfoTableRef" dialogType="view"></taskInfoTable>
      </el-tab-pane>
    </el-tabs>

    <div slot="footer" class="footer">
      <el-button type="primary" @click="save" v-click-once>保存</el-button>
      <el-button
        type="primary"
        v-if="isNeed_process_is_close"
        @click="save('sub')"
        v-click-once
        >提交</el-button
      >

      <el-button @click="cancel">返回</el-button>
    </div>
    <sendListDialog
      ref="orderListDialogRef"
      @changeParent="changeOrder"
      :contactData="contactData"
    ></sendListDialog>
    <!--出库详情-->
    <outbound-details-dialog
      v-if="outboundDetailsDialogFlag"
      ref="outboundDetailsDialogRef"
      :outboundDetailsDialogFlag.sync="outboundDetailsDialogFlag"
      @saveDate="saveDate"
    ></outbound-details-dialog>
    <process-submit-dialog
      :isNotNeedProcess="false"
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
    ></process-submit-dialog>
  </ele-modal>
</template>

<script>
  import { acceptUnpackoptions } from '@/enum/dict';
  import fileUpload from '@/components/upload/fileUpload';
  import dictMixins from '@/mixins/dictMixins';
  import outboundDetailsDialog from '@/views/saleManage/saleOrder/returnGoods/components/outboundDetailsDialog.vue';
  import { getSaleOrderDetail } from '@/api/saleManage/saleorder';
  import taskInfoTable from '../../invoice/components/taskInfoTable.vue';
  import {
    addSendInformation,
    getSendSaleOrderrecordDetailSplit
  } from '@/api/saleManage/saleordersendrecord';
  import { getPSaleEntrustedReceiveDetailAPI } from '@/api/saleManage/entrustedReceive';
  import { getcontactlink } from '@/api/saleManage/businessFollow';
  import inventoryTable from '../../invoice/components/inventoryTable.vue';
  import stowageTable from '../../invoice/components/stowageTable.vue';

  import sendListDialog from './sendListDialog.vue';
  import { copyObj } from '@/utils/util';

  // import PalletTable from '@/views/saleManage/saleOrder/invoice/components/palletTable.vue';
  import fileMain from '@/components/addDoc/index.vue';
  import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';
  import getDynamicsColumns from '@/mixins/getDynamicsColumns';
  import {
    addSendConfirmInformation,
    getSendSaleOrderConfirmDetail,
    getSendSaleOrderConfirmDetailSplit,
    UpdateSendConfirmInformation
  } from '@/api/saleManage/invoiceConfirm';
  import modalTitle from '@/BIZComponents/modalTitle.vue';

  export default {
    mixins: [dictMixins, getDynamicsColumns],
    components: {
      processSubmitDialog,
      fileMain,
      // PalletTable,
      sendListDialog,
      taskInfoTable,
      fileUpload,
      inventoryTable,
      stowageTable,
      modalTitle,
      outboundDetailsDialog
    },

    //客户管理数据
    props: {
      contactData: {
        type: Object,
        default: () => {
          return {};
        }
      },
      saleOrderData: {
        type: Object,
        default: () => {
          return {};
        }
      }
    },
    data() {
      let formDef = {
        id: '',
        sendNo: '',
        sendId: '',
        contactId: '',
        contactName: '',
        entrustedCode: '',
        entrustedId: '',
        pricingWay: 1,
        sendFiles: [],
        repliedFiles: [],
        productList: [],
        projectName: '',
        projectId: '',
        receiveAddress: '',
        deviceName: '',
        deviceId: '',
        carNo: '',
        linkName: '',
        linkPhone: '',
        orderNo: '',
        orderId: '',
        replied: 0
      };

      return {
        fullscreen: false,
        outboundDetailsDialogFlag: false,
        payWayOptions: [],
        delDetailIds: [],
        linkNameOptions: [],
        productList: [],
        trayList: [],
        trayListData: [],

        acceptUnpackoptions,
        visible: false,
        entrustedReceiveDialogFlag: false,
        processSubmitDialogFlag: false,
        title: '',
        row: {},
        activeName: 'first',
        formDef,
        options: [
          { value: 0, label: '已收货' },
          { value: 1, label: '未收货' }
        ],
        options1: [
          { value: 0, label: '未回收' },
          { value: 1, label: '已回收' }
        ],
        columns: [
          {
            width: 45,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            fixed: 'left'
          },
          {
            minWidth: 160,
            prop: 'productCode',
            label: '编码',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 120,
            prop: 'productName',
            label: '名称',
            showOverflowTooltip: true,
            align: 'center'
          },

          {
            minWidth: 160,
            prop: 'batchNo',
            label: '批次号',
            showOverflowTooltip: true,
            slot: 'batchNo',
            align: 'center'
          },
          {
            minWidth: 160,
            prop: 'barcodes',
            label: '发货条码',
            showOverflowTooltip: true,
            slot: 'barcodes',
            align: 'center'
          },
          {
            minWidth: 120,
            prop: 'materielDesignation',
            label: '物料代号',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 120,
            prop: 'clientCode',
            label: '客户代号',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 120,
            prop: 'engrave',
            label: '刻码',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 160,
            prop: 'packageNo',
            align: 'center',
            label: '包装编码',
            showOverflowTooltip: true
          },
          {
            minWidth: 100,
            prop: 'packingQuantity',
            align: 'center',
            label: '包装数量',
            showOverflowTooltip: true
          },
          {
            minWidth: 120,
            prop: 'packingUnit',
            align: 'center',
            label: '包装单位',
            showOverflowTooltip: true
          },
          {
            minWidth: 100,
            prop: 'totalCount',
            label: '计量数量',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 150,
            prop: 'measuringUnit',
            label: '计量单位',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            width: 160,
            prop: 'pricingWay',
            label: '计价方式',
            slot: 'pricingWay',
            align: 'center',
            formatter: (row, column) => {
              return row.pricingWay == 1
                ? '按数量计费'
                : row.pricingWay == 2
                ? '按重量计费'
                : '';
            }
          },
          {
            width: 100,
            prop: 'singlePrice',
            label: '单价',
            slot: 'singlePrice',
            align: 'center'
          },
          {
            width: 180,
            prop: 'notaxSinglePrice',
            label: '不含税单价',
            slot: 'notaxSinglePrice',
            align: 'center'
          },
          {
            width: 100,
            prop: 'totalPrice',
            label: '合计',
            align: 'center'
          },

          {
            minWidth: 80,
            prop: 'sendTotalWeight',
            label: '重量',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 100,
            prop: 'weightUnit',
            label: '重量单位',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            prop: 'provenance',
            label: '产地',
            slot: 'provenance',
            align: 'center',
            // show:this.contractBookType==2,
            minWidth: 200,
            showOverflowTooltip: true,
            formatter: (row, column) => {
              return row.provenance && row.provenance.length
                ? row.provenance
                    .map((item) => this.getDictValue('产地', item))
                    .join(',')
                : '';
            }
          },
          {
            width: 220,
            prop: 'remark',
            label: '备注',
            slot: 'remark',
            align: 'center'
          },
          {
            width: 120,
            slot: 'isException',
            prop: 'isException',
            label: '收货状态',
            align: 'center',
            fixed: 'right'
          }
        ],
        trayListColumns: [
          {
            width: 45,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            fixed: 'left'
          },
          {
            minWidth: 160,
            prop: 'productCode',
            label: '编码',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 120,
            prop: 'productName',
            label: '名称',
            showOverflowTooltip: true,
            align: 'center'
          },

          {
            minWidth: 160,
            prop: 'batchNo',
            label: '批次号',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 160,
            prop: 'barcodes',
            label: '发货条码',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 120,
            prop: 'materielDesignation',
            label: '物料代号',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 120,
            prop: 'clientCode',
            label: '客户代号',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 120,
            prop: 'engrave',
            label: '刻码',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 160,
            prop: 'packageNo',
            align: 'center',
            label: '包装编码',
            showOverflowTooltip: true
          },
          {
            minWidth: 100,
            prop: 'packingQuantity',
            align: 'center',
            label: '包装数量',
            showOverflowTooltip: true
          },
          {
            minWidth: 120,
            prop: 'packingUnit',
            align: 'center',
            label: '包装单位',
            showOverflowTooltip: true
          },
          {
            minWidth: 100,
            prop: 'totalCount',
            label: '计量数量',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            minWidth: 150,
            prop: 'measuringUnit',
            label: '计量单位',
            showOverflowTooltip: true,
            align: 'center'
          },
          {
            width: 120,
            slot: 'type',
            prop: 'type',
            label: '回收状态',
            align: 'center',
            fixed: 'right'
          }
        ],
        form: copyObj(formDef),
        tableBankData: [],
        tableLinkData: [],
        oldId: '',
        oldDocNo: '',
        // 组织机构树形结构数据
        groupTreeData: [],
        groupData: [],
        rules: {
          sendNo: [
            { required: true, message: '请选择发货单', trigger: 'change' }
          ],
          repliedFiles: [
            { required: true, message: '请上传回执附件', trigger: 'change' }
          ]
        },

        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,
        businessId: ''
      };
    },
    created() {
      this.requestDict('产地');
    },
    computed: {},

    methods: {
      //选择订单回调
      changeOrder(obj) {
        this.form = Object.assign({}, this.form, {
          sendId: obj.id,
          sendNo: obj.docNo
        });
        this.getSaleOrderDetail(obj.id);
      },
      //发货单详情
      async getSaleOrderDetail(id) {
        this.loading = true;
        const data = await getSendSaleOrderrecordDetailSplit(id);

        this.loading = false;
        if (data) {
          this.form = data;
          this.form.sendId = data.id;
          this.form.sendNo = data.docNo;
          this.form.docNo = this.oldDocNo;
          this.form.id = this.oldId;
          this.form.reviewStatus = 0;
          this.form.processInstanceId = '';
          this.$refs.taskInfoTableRef &&
            this.$refs.taskInfoTableRef.putTableValue(
              data.logisticTrakListNoteVOList
            );
          this.$refs.stowageTableRef &&
            this.$refs.stowageTableRef.putTableValue(data.carList);
          this.trayList = data.trayList;

          this.productList = data.productList;

          // this.form.pricingWay = data?.saleOrder?.pricingWay;
          this.form.productList = [];
          this.handleSelectGoods();
        }
      },
      //选择退货明细
      handleSelectGoods(list) {
        this.outboundDetailsDialogFlag = true;
        this.$nextTick(() => {
          this.$refs.outboundDetailsDialogRef.init(
            { ...this.form, type: 10 },
            list
          );
        });
      },
      saveDate(data) {
        data.forEach((item) => {
          item['totalCount'] = item.measureQuantity;
          item['qmsResult'] = item.result;
          item['qmsStatus'] = item.status;
          item['sendProductId'] = item.categoryId;
          item['sendTotalWeight'] = item.weight;

          this.productList.forEach((val) => {
            if (item.productCode == val.productCode) {
              item['singlePrice'] = val.singlePrice;
              item['clientCode'] = item.clientCode || val.customerMark;
              item['pricingWay'] = item.pricingWay || val.pricingWay || 1;

              if (item.pricingWay == 1) {
                item.totalPrice = item.singlePrice * item.measureQuantity;
              }
              if (item.pricingWay == 2) {
                item.totalPrice =
                  item.singlePrice *
                  item.measureQuantity *
                  item.sendTotalWeight;
              }
            }
          });
        });
        let trayListCodes = this.trayList.map((item) => item.productCode);
        this.form.productList = data.filter(
          (item) => !trayListCodes.includes(item.productCode)
        );
        this.form.productList.forEach((item, index) => {
          this.$set(this.form.productList[index], 'isException', 0);
        });

        this.trayListData = data.filter((item) => {
          if (trayListCodes.includes(item.productCode)) {
            item['orderProductType'] = 1;
            return item;
          }
        });
        this.trayListData.forEach((item, index) => {
          this.$set(this.trayListData[index], 'type', 0);
        });
      },
      // //发货单确认详情
      async getSendSaleOrderDetail(id) {
        this.businessId = id;

        this.loading = true;
        const data = await getSendSaleOrderConfirmDetail(id);
        this.oldId = data.id;
        this.oldDocNo = data.docNo;
        this.loading = false;
        if (data) {
          this.form = data;
          this.trayListData = data.trayList;

          this.$nextTick(() => {
            this.form.pricingWay = data?.saleOrder?.pricingWay;
            this.$refs.inventoryTableref &&
              this.$refs.inventoryTableref.putTableValue(data.productList);
            this.$refs.stowageTableRef &&
              this.$refs.stowageTableRef.putTableValue(data.carList);
            this.$refs.taskInfoTableRef &&
              this.$refs.taskInfoTableRef.putTableValue(
                data.logisticTrakListNoteVOList
              );
            // this.$refs.palletTableRef &&
            //   this.$refs.palletTableRef.putTableValue(data.trayList);
          });
        }
      },

      //选择订单弹框
      handleSendOrderBtn(e) {
        if (e.target.nodeName == 'I') {
          this.form = Object.assign({}, this.form, {
            sendId: '',
            sendNo: '',
            contactId: '',
            contactName: '',
            carNo: '',
            deviceName: '',
            deviceId: '',
            linkName: '',
            linkPhone: '',
            orderNo: '',
            orderId: '',
            pricingWay: '',
            receiveAddress: '',
            entrustedCode: '',
            entrustedId: '',
            productList: [],
            sendFiles: [],
            repliedFiles: []
          });
          // this.$refs.inventoryTableref && this.$refs.inventoryTableref.putTableValue([]);
          this.$refs.stowageTableRef &&
            this.$refs.stowageTableRef.putTableValue([]);
          this.$refs.taskInfoTableRef &&
            this.$refs.taskInfoTableRef.putTableValue([]);
          this.trayListData = [];
          this.trayList = [];
          return;
        }
        let item = {
          id: this.form.sendId
        };
        this.$refs.orderListDialogRef.open(item);
      },

      //打开新增编辑弹框
      async open(type, row, invoiceData) {
        this.title = type === 'add' ? '新增收货确认单' : '修改';
        this.row = row;
        this.visible = true;
        if (row && row?.id) {
          await this.getSendSaleOrderDetail(row?.id);
        }
        if (invoiceData) {
          this.changeOrder(invoiceData);
        }
        this.isUpdate = type != 'add';
      },
      totalCountChange(row) {
        if (row.totalCount > row.sendTotalCount) {
          row.totalCount = row.sendTotalCount;
        }
        if (row.totalCount < 0) {
          row.totalCount = 0;
        }
      },
      getValidate() {
        return Promise.all([
          new Promise((resolve, reject) => {
            this.$refs.form.validate((valid) => {
              if (!valid) {
                reject(false);
              } else {
                resolve(true);
              }
            });
          })
        ]).catch((e) => {
          this.$message.warning('有必填项未填写，请检查');
          return Promise.reject(e);
        });
      },
      // 添加
      handlAdd() {
        if (!this.form.sendNo) return this.$message.error('请先选择来源单据');
        this.handleSelectGoods();

        // this.$refs.productListRef.open(this.form.datasource);
      },
      async save(type) {
        try {
          await this.getValidate();
          // 表单验证通过，执行保存操作
          this.loading = true;

          if (!this.isUpdate) {
            delete this.form.id;
          }
          this.form.repliedFiles = this.form.repliedFiles || [];

          this.form.replied = this.form.repliedFiles.length > 0 ? 1 : 0;
          let commitData = Object.assign({}, this.form, {
            trayList: this.trayListData,
            carList: this.$refs.stowageTableRef.getTableValue(),
            trakNoteList: this.$refs.taskInfoTableRef.getTableValue()
          });
          const API = this.isUpdate
            ? UpdateSendConfirmInformation
            : addSendConfirmInformation;
          API(commitData)
            .then((res) => {
              this.loading = false;
              this.$message.success('修改成功');
              if (type === 'sub') {
                this.sendSubmit(res);
                return;
              }
              this.cancel();
              this.$emit('done');
            })
            .catch((e) => {
              //this.loading = false;
            });
        } catch (error) {
          console.log(error);
          // 表单验证未通过，不执行保存操作
        }
      },
      async sendSubmit(res) {
        const data = await getSendSaleOrderConfirmDetail(
          this.businessId || res
        );
        this.processSubmitDialogFlag = true;

        this.$nextTick(() => {
          let params = {
            businessId: this.businessId || res,
            businessKey: 'sales_sendconfirm_approve',
            formCreateUserId: data.createUserId,
            variables: {
              businessCode: data.docNo
            }
            // callBackMethodType : '1',
            // callBackMethod : 'proTargetPlanApproveApiImpl.updatePlanApprovalStatus',
            // pcHandle : '/bpm/handleTask/components/project-manage/plan-manage/submit.vue',
            // pcView : '/bpm/handleTask/components/project-manage/plan-manage/detailDialog.vue',
            // miniHandle : '',
            // miniView : '',
          };

          this.$refs.processSubmitDialogRef.init(params);
        });
        // submit({
        //   businessId: this.businessId || res
        //   // productionSupervisorId
        // }).then((res) => {
        //   this.cancel();
        //   this.$emit('done');
        // });
      },
      remove(index) {
        this.form.productList.splice(index, 1);
      },
      reload() {
        this.cancel();
        this.$emit('done');
      },
      cancel() {
        this.$nextTick(() => {
          this.activeName = 'first';
          // 关闭后，销毁所有的表单数据
          this.$refs['otherForm'] && this.$refs['otherForm'].resetFields();
          this.$refs['formRef'] && this.$refs['formRef'].resetFields();
          this.$store.commit('order/clearUserData');
          this.form = copyObj(this.formDef);
          this.visible = false;
          this.trayListData = [];
          this.trayLis = [];
        });
      }
    }
  };
</script>
<style scoped lang="scss">
  .TotalAmount {
    font-size: 16px;
    padding-right: 30px;
  }

  .headbox {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    .amount {
      font-size: 14px;
      font-weight: bold;
      margin-right: 20px;
    }
  }
</style>
