<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"
    width="70%"
    :maxable="true"
    :resizable="true"
    @close="cancel"
  >
    <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="orderNo">
            <el-input
              clearable
              v-model="form.orderNo"
              @click.native="handleOrderBtn"
              placeholder="请输入"
              :disabled="!!saleOrderData.id"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="受托收货单">
            <el-input
              clearable
              :disabled="!!saleOrderData.id"
              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" 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" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="收货地址" prop="receiveAddress">
            <el-input
              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 label="车牌号" prop="carNo">
            <el-select v-model="form.carNo" style="width: 100%">
              <el-option
                :label="item.trakNumber"
                :value="item.trakNumber"
                v-for="(item, index) in carList"
                :key="index"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="托盘数" prop="trayNum">
            <el-input clearable v-model="form.trayNum" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="打印编码" prop="printNo">
            <el-input clearable v-model="form.printNo" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item prop="sendFiles" label="发货附件">
            <fileMain v-model="form.sendFiles"></fileMain>
          </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>
    </el-form>
    <el-tabs v-model="activeName" style="margin-top: 15px" type="border-card">
      <el-tab-pane label="物品清单" name="first">
        <inventoryTable
          :pricingWay="form.pricingWay"
          :entrustedCode="form.entrustedCode"
          ref="inventoryTableref"
          :orderId="form.orderId"
          :orderIds="form.orderIds"
          @replaceTableChange="replaceTableChange"
          :needProduce="saleOrderValue.needProduce"
          :typeIds="saleOrderValue.typedetailIds"
        ></inventoryTable>
      </el-tab-pane>
      <el-tab-pane label="托盘清单" name="second">
        <palletTable
          ref="palletTableRef"
          @totalCountChange="totalCountChange"
        ></palletTable>
      </el-tab-pane>
      <el-tab-pane label="装载车叉车信息" name="third">
        <stowageTable ref="stowageTableRef"></stowageTable>
      </el-tab-pane>
      <el-tab-pane label="运输清单" name="fourth">
        <taskInfoTable
          ref="taskInfoTableRef"
          @setAddress="setAddress"
        ></taskInfoTable>
      </el-tab-pane>
      <el-tab-pane label="替代料" name="5">
        <replaceTable
          :pricingWay="form.pricingWay"
          ref="replaceRef"
        ></replaceTable>
      </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>
    <orderListDialog
      ref="orderListDialogRef"
      @changeParent="changeOrder"
      :contactData="contactData"
      :isAll="true"
    ></orderListDialog>
    <!--  受托发货单  -->
    <entrusted-receive-dialog
      :entrusted-receive-dialog-flag.sync="entrustedReceiveDialogFlag"
      v-if="entrustedReceiveDialogFlag"
      @changeParent="getInfo"
      ref="entrustedReceiveDialogRef"
    ></entrusted-receive-dialog>
    <process-submit-dialog
      :isNotNeedProcess="false"
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
    ></process-submit-dialog>
  </ele-modal>
</template>

<script>
  import { treeClassifyCodeEnum } from '@/enum/dict';
  import fileUpload from '@/components/upload/fileUpload';
  import dictMixins from '@/mixins/dictMixins';
  import parentList from '@/views/saleManage/contact/components/parentList.vue';
  import {
    getSaleOrderDetail,
    getSaleOrderDetails
  } from '@/api/saleManage/saleorder';
  import taskInfoTable from './taskInfoTable.vue';
  import {
    addSendInformation,
    UpdateSendInformation,
    getSendSaleOrderrecordDetailSplit,
    submit
  } from '@/api/saleManage/saleordersendrecord';
  import { getPSaleEntrustedReceiveDetailAPI } from '@/api/saleManage/entrustedReceive';
  import { getcontactlink } from '@/api/saleManage/businessFollow';
  import inventoryTable from './inventoryTable.vue';
  import replaceTable from './replaceTable.vue';
  import stowageTable from './stowageTable.vue';

  import orderListDialog from './orderListDialog.vue';
  import { copyObj } from '@/utils/util';
  import entrustedReceiveDialog from './entrustedReceiveDialog.vue';
  import outSourceSendDialog from '@/views/purchasingManage/purchaseOrder/invoice/components/outSourceSendDialog.vue';
  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 { carBookPageListAPI } from '@/api/transportManager/carBook';
  import { projectsGetByIdAPI } from '@/api/pro';

  export default {
    mixins: [dictMixins],
    components: {
      processSubmitDialog,
      // fileMain,
      PalletTable,
      outSourceSendDialog,
      taskInfoTable,
      fileUpload,
      inventoryTable,
      orderListDialog,
      parentList,
      entrustedReceiveDialog,
      stowageTable,
      replaceTable
    },

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

      return {
        fullscreen: false,
        saleOrderValue: {},
        detailData: {},
        payWayOptions: [],
        delDetailIds: [],
        carList: [],
        visible: false,
        entrustedReceiveDialogFlag: false,
        processSubmitDialogFlag: false,
        title: '',
        activeName: 'first',
        formDef,
        form: copyObj(formDef),

        rules: {
          partaName: [
            { required: true, message: '请选择客户名称', trigger: 'change' }
          ],
          linkName: [
            { required: true, message: '请输入', trigger: ['blur', 'change'] }
          ],
          orderNo: [{ required: true, message: '请选择', trigger: 'change' }],
          receiveAddress: [
            { required: true, message: '请输入', trigger: 'change' }
          ],
          deviceName: [
            { required: true, message: '前选择车辆', trigger: 'change' }
          ]
        },

        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,
        businessId: ''
      };
    },
    computed: {
      allcountAmount() {
        return this.$store.state.order.allcountAmount;
      }
    },

    methods: {
      //选择订单回调
      changeOrder(obj) {
        this.form = Object.assign({}, this.form, {
          orderIds: obj.map((item) => item.id).toString(),
          orderNo: obj.map((item) => item.orderNo).toString()
        });
        this.getSaleOrderDetails(obj.map((item) => item.id));
      },

      setData(res, type) {
        let data = {
          ...res[0],
          orderIds: res.map((item) => item.id).toString(),
          orderNo: res.map((item) => item.orderNo).toString(),
          productList: res.map((item) => item.productList).flat(),
          typedetailIds: res.map((item) => item.typedetailIds).flat(),

          totalAmount: res.reduce(
            (sum, obj) =>
              sum + ((obj.totalAmount && Number(obj.totalAmount)) || 0),
            0
          ),
          payAmount: res.reduce(
            (sum, obj) => sum + ((obj.payAmount && Number(obj.payAmount)) || 0),
            0
          ),
          projectName: res
            .filter((item) => item.projectName)
            .map((item) => item.projectName)
            .toString(),
          projectId: res
            .filter((item) => item.projectId)
            .map((item) => item.projectId)
            .toString(),
          projectCode: res
            .filter((item) => item.projectCode)
            .map((item) => item.projectCode)
            .toString()
        };

        this.loading = false;
        this.saleOrderValue = data;
        this.partbAddress = data.partbAddress;
        if (type == 'sendInit') {
          return;
        }
        this.$nextTick(() => {
          let {
            partaId,
            partaName,
            partaTel,
            orderIds,
            orderNo,
            partaLinkName,
            partaAddress,
            productList,
            trayList,
            trakNoteList,
            totalAmount,
            payAmount,
            projectName,
            projectId,
            projectCode,
            totalPrice,
            receiveAddress
          } = data;
          if (productList && productList.length > 0) {
            productList.forEach((v) => {
              v.orderTotalCount = v.totalCount;
              v.extField = {};
            });
          }
          this.form = Object.assign({}, this.form, {
            contactId: partaId,
            contactName: partaName,
            linkName: partaLinkName,
            linkPhone: partaTel,
            orderNo,
            orderIds,
            receiveAddress: receiveAddress || partaAddress,
            productList,
            trakNoteList,
            trayList,
            totalAmount,
            totalPrice,
            payAmount,
            projectName,
            projectId,
            projectSn: projectCode
          });
          productList.forEach((item, index) => {
            item['tempId'] = index;
            item.id = '';
          });
          this.$refs.inventoryTableref &&
            this.$refs.inventoryTableref.putTableValue(productList);
          this.$refs.taskInfoTableRef &&
            this.$refs.taskInfoTableRef.putTableValue(trakNoteList);
          this.setAddress();
          if (projectId) {
            this.getProjectData(projectId);
          }
        });
      },
      // //获取订单详情
      // async getSaleOrderDetail(id) {
      //   this.loading = true;
      //   this.form = Object.assign({}, this.form, {
      //     orderIds: id,
      //   });
      //   // const data = await getSaleOrderDetail(id);
      //   this.setData(data);
      // },

      //获取订单详情 多id
      async getSaleOrderDetails(ids) {
        this.loading = true;
        let res = await getSaleOrderDetails(ids);
        if (res?.length) {
          this.setData(res);
        }
      },
      setAddress() {
        this.$refs.taskInfoTableRef.setAddress(
          this.partbAddress,
          this.form.receiveAddress
        );
      },
      async getProjectData(id) {
        const data = await projectsGetByIdAPI(id);
        if (data.contactAddressId) {
          this.form.receiveAddress =
            data.contactAddressName + data.contactAddress;
          this.setAddress();
        }

        if (data.contactRelationPhone) {
          this.form.linkPhone = data.contactRelationPhone;
        }
        if (data.contactRelationUserName) {
          this.form.linkName = data.contactRelationUserName;
        }
      },
      //发货单详情
      async getSendSaleOrderDetail(id) {
        this.businessId = id;

        this.loading = true;
        const data = await getSendSaleOrderrecordDetailSplit(id);
        // this.partbAddress = data.saleOrder[0].partbAddress;
        // this.saleOrderValue = data.saleOrder;
        if (data.saleOrderList) {
          this.setData(data.saleOrderList, 'sendInit');
        } else if (data.saleOrder) {
          this.setData([data.saleOrder], 'sendInit');
        }

        this.loading = false;
        if (data) {
          this.$nextTick(() => {
            data.productList.forEach((item) => {
              item['tempId'] = item.id;
            });
            this.form = data;
            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);
            this.$refs.replaceRef &&
              this.$refs.replaceRef.putTableValue(data.replaceList);
          });
        }
      },
      //选择受托收货单弹框
      handleEntrustedReceive(e) {
        if (e.target.nodeName == 'I') {
          this.form = Object.assign({}, this.form, {
            carNo: '',
            deviceName: '',
            deviceId: '',
            linkName: '',
            linkPhone: '',
            orderNo: '',
            orderId: '',
            contactId: '',
            contactName: '',
            entrustedCode: '',
            entrustedId: '',
            sendNoteNo: '',
            pricingWay: ''
          });
          this.$refs.inventoryTableref &&
            this.$refs.inventoryTableref.putTableValue([]);
          return;
        }
        this.searchParams = {
          orderId: this.form.orderId
        };
        this.entrustedReceiveDialogFlag = true;
        this.$nextTick(() => {
          this.$refs.entrustedReceiveDialogRef.init();
        });
      },
      //获取受托收货单数据回调
      async getInfo(row) {
        const data = await getPSaleEntrustedReceiveDetailAPI(row.id);
        this.$nextTick(() => {
          let {
            carNo,
            code,
            id,
            linkName,
            linkPhone,
            orderId,
            orderNo,
            productList,
            contactId,
            contactName,
            pricingWay = data?.saleOrder?.pricingWay
          } = data;
          if (productList && productList.length > 0) {
            productList.forEach((v) => {
              v.orderTotalCount = v.orderTotalCount || v.totalCount;
              v.extField = {};
            });
          }
          this.form = Object.assign({}, this.form, {
            contactId,
            contactName,
            linkName,
            linkPhone,
            orderNo,
            orderIds: orderId,
            productList,
            carNo,
            pricingWay,
            entrustedCode: code,
            entrustedId: id
          });
          productList.forEach((item, index) => {
            item.id = '';
            item['tempId'] = index;
          });
          this.$refs.inventoryTableref &&
            this.$refs.inventoryTableref.putTableValue(productList, code);
        });
      },
      //替代料
      replaceTableChange(list) {
        this.$refs.replaceRef.putTableValue(list, 'add');
      },

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

      //打开新增编辑弹框
      async open(type, row, orderId) {
        this.title = type === 'add' ? '新增发货单' : '修改';
        this.visible = true;
        this.carList = await carBookPageListAPI({ pageNum: 1, size: 100 });

        if (orderId) {
          await this.getSaleOrderDetails(orderId);
        }
        if (this.saleOrderData.id) {
          await this.getSaleOrderDetails([this.saleOrderData.id]);
        }
        if (row && row?.id) {
          await this.getSendSaleOrderDetail(row?.id);
        }

        if (type == 'add') {
          this.isUpdate = false;
        } else {
          this.isUpdate = true;
        }
      },
      entrustedReceiveInit(row) {
        this.title = '新增发货单';
        this.visible = true;
        this.isUpdate = false;
        this.getInfo(row);
      },
      totalCountChange(num) {
        this.form.trayNum = num;
      },

      getValidate() {
        return Promise.all([
          new Promise((resolve, reject) => {
            this.$refs.form.validate((valid) => {
              if (!valid) {
                reject(false);
              } else {
                resolve(true);
              }
            });
          }),
          new Promise((resolve, reject) => {
            this.$refs.inventoryTableref.validateForm((valid) => {
              if (!valid) {
                reject(false);
              } else {
                resolve(true);
              }
            });
          }),
          new Promise((resolve, reject) => {
            this.$refs.taskInfoTableRef.getTableValidate((valid) => {
              if (!valid) {
                reject(false);
              } else {
                resolve(true);
              }
            });
          }),
          new Promise((resolve, reject) => {
            this.$refs.palletTableRef.validateForm((valid) => {
              if (!valid) {
                reject(false);
              } else {
                resolve(true);
              }
            });
          })
        ]).catch((e) => {
          return Promise.reject(e);
        });
      },
      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;
          const replaceList =
            (this.$refs.replaceRef && this.$refs.replaceRef.getTableValue()) ||
            [];
          const productList = this.$refs.inventoryTableref.getTableValue();
          productList.forEach((item) => {
            if (
              replaceList.map((_item) => _item.relationId).includes(item.tempId)
            ) {
              item['isReplace'] = 1;
            }
          });

          let commitData = Object.assign({}, this.form, {
            productList,
            replaceList,
            trayList: this.$refs.palletTableRef.getTableValue(),
            carList: this.$refs.stowageTableRef.getTableValue(),
            trakNoteList: this.$refs.taskInfoTableRef.getTableValue()
          });

          if (this.isUpdate) {
            UpdateSendInformation(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;
              });
          } else {
            addSendInformation(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 getSendSaleOrderrecordDetailSplit(
          this.businessId || res
        );
        this.processSubmitDialogFlag = true;

        this.$nextTick(() => {
          let params = {
            businessId: this.businessId || res,
            businessKey:
              data.saleTypeName.indexOf('技改') != '-1'
                ? 'sele_order_send_correction'
                : data.saleTypeName.indexOf('三包') != '-1'
                ? 'eom_sh'
                : data.saleTypeName.indexOf('补发') != '-1'
                ? 'eom_sh'
                : data.saleTypeName.indexOf('赠品') != '-1'
                ? 'sale_order_send_giftAndOther'
                : 'sales_send_approve',
            formCreateUserId: data.createUserId,
            variables: {
              businessCode: data.docNo,
              businessName: data.contactName,
              businessType: '销售发货单'
            }
          };

          this.$refs.processSubmitDialogRef.init(params);
        });
      },
      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;
        });
      }
    }
  };
</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>
