<template>
  <ele-modal
    custom-class="ele-dialog-form long-dialog-form"
    :centered="true"
    :visible.sync="addOrEditDialogFlag"
    :title="title"
    :close-on-click-modal="false"
    width="70%"
    :before-close="cancel"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="el-form-box">
      <headerTitle title="收货信息"></headerTitle>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            label="选择订单"
            prop="orderNo"

          >
            <el-input
              clearable
              v-model="form.orderNo"
              @click.native="handleOrderBtn"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <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-row>
      <el-row :gutter="20">
        <!-- <el-col :span="12">
          <el-form-item
            label="计价方式"
          >
            <el-select v-model="form.pricingWay" disabled style="width: 100%">
              <el-option label="按数量计费" :value="1"></el-option>
              <el-option label="按重量计费" :value="2"></el-option>
            </el-select>
          </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-col :span="12">
          <el-form-item label="车辆号" prop="carNo" >
            <el-input clearable v-model="form.carNo" placeholder="请输入"/>
          </el-form-item>
        </el-col>
        <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="receiveDate"
          >
            <el-date-picker
              v-model="form.receiveDate"
              style="width: 100%"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="收货单号"
            prop="sendNoteNo"
          >
            <el-input
              clearable
              v-model="form.sendNoteNo"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="files" label="附件">
            <fileMain v-model="row.files"></fileMain>
<!--            <fileUpload-->
<!--              v-model="form.files"-->
<!--              module="main"-->
<!--              :showLib="false"-->
<!--              :limit="10"-->
<!--            />-->
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>

    <headerTitle title="物品清单" style="margin-top: 30px"></headerTitle>
    <inventoryTable
      :pricingWay="form.pricingWay"
      ref="inventoryTableref"
      :orderId="form.orderId"
    ></inventoryTable>

    <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
      :searchParams="orderSearchParams"
      ref="orderListDialogRef"
      @changeParent="changeOrder"
    ></orderListDialog>
    <process-submit-dialog  :isNotNeedProcess="false" :processSubmitDialogFlag.sync="processSubmitDialogFlag" v-if="processSubmitDialogFlag" ref="processSubmitDialogRef" @reload="reload"></process-submit-dialog>

  </ele-modal>
</template>

<script>

import fileUpload from '@/components/upload/fileUpload';
import dictMixins from '@/mixins/dictMixins';
import {
  saveSaleEntrustedReceiveAPI,
  updateSaleEntrustedReceiveAPI,
  getPSaleEntrustedReceiveDetailAPI,
  submit, getReceiveCountAPI
} from "@/api/saleManage/entrustedReceive";
import {getcontactlink} from '@/api/saleManage/businessFollow';
import inventoryTable from './inventoryTable.vue';
import orderListDialog from '../../invoice/components/orderListDialog.vue';
import {getSaleOrderDetail} from "@/api/saleManage/saleorder";
import {getInventoryTotalAPI} from "@/api/wms";
import fileMain from "@/components/addDoc/index.vue";
import processSubmitDialog from "@/BIZComponents/processSubmitDialog/processSubmitDialog.vue";

export default {
  props: {
    addOrEditDialogFlag: Boolean
  },
  mixins: [dictMixins],
  components: {
    processSubmitDialog,
    fileMain,
    fileUpload,
    inventoryTable,
    orderListDialog
  },
  data() {
    return {
      orderSearchParams: {
        saleType: '5',
      },
      detailData: {},
      payWayOptions: [],
      delDetailIds: [],
      linkNameOptions: [],

      title: '',
      row: {},
      form: {
        id: '',
        receiveDate: '',
        carNo: '',
        files: [],
        linkName: '',
        linkPhone: '',
        orderId: '',
        orderNo: '',
        pricingWay: '',
        productList: [],
        sendNoteNo: '',
        contactId: '',
        contactName: '',

      },
      rules: {
        contactName: [
          {required: true, message: '请选择客户名称', trigger: 'change'}
        ],
        linkName: [
          {required: true, message: '请输入', trigger: ['blur', 'change']}
        ],
        linkPhone: [
          {required: true, message: '请输入', trigger: ['blur', 'change']}
        ],
        orderNo: [
          {required: true, message: '请选择', trigger: 'change'}
        ],
        receiveAddress: [
          {required: true, message: '请输入', trigger: 'change'}
        ],
      },

      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      processSubmitDialogFlag: false,
      businessId: ''
    };
  },

  methods: {
    //打开新增编辑弹框
    async open(type, row, orderId) {
      this.title = type === 'add' ? '新增受托收货单' : '修改';
      this.row = row;
      if (orderId) {
        await this.getOrderDetail(orderId);
      }
      if (row && row?.id) {
        await this.getSendSaleOrderDetail(row?.id);
      }

      this.isUpdate = type !== 'add';
      if(!this.isUpdate){
        this.form.receiveDate = new Date()
      }
    },
    //选择订单弹框
    handleOrderBtn(e) {
      if (e.target.nodeName == 'I') {
        this.form = Object.assign({}, this.form, {
          contactId: '',
          contactName: '',
          linkName: '',
          linkPhone: '',
          orderNo: '',
          orderId: '',
          productList: [],
          pricingWay: ''
        });
        this.$refs.inventoryTableref &&
        this.$refs.inventoryTableref.putTableValue([]);
        return
      }
      this.$refs.orderListDialogRef.open();
    },
    //选择订单回调
    changeOrder(obj) {
      this.getOrderDetail(obj.id);
    },
    //获取订单详情
    async getOrderDetail(id) {
      this.loading = true;
      let data = await getSaleOrderDetail(id);

      this.loading = false;
      if (data) {
        this.$nextTick(async () => {
          let {
            partaId,
            partaName,
            partaTel,
            orderNo,
            id,
            partaLinkName,
            productList,
            pricingWay
          } = data;
          if (productList && productList.length > 0) {
            productList.forEach((v) => {
              v.orderTotalCount = v.orderTotalCount || v.totalCount;
            });
          }
          this.form = Object.assign({}, this.form, {
            contactId: partaId,
            contactName: partaName,
            linkName: partaLinkName,
            linkPhone: partaTel,
            orderNo,
            orderId: id,
            productList,
            pricingWay
          });
          this.form = await this.getTotalCountHistory(this.form);
          this.$refs.inventoryTableref &&
          this.$refs.inventoryTableref.putTableValue(this.form.productList);
        });
      }
    },

    //发货单详情
    async getSendSaleOrderDetail(id) {
      this.businessId = id;

      this.loading = true;
      let data = await getPSaleEntrustedReceiveDetailAPI(id);
      this.loading = false;
      if (data) {
        this.$nextTick(() => {
          this.form = data;
          this.form.pricingWay = data?.saleOrder?.pricingWay
          this.$refs.inventoryTableref &&
          this.$refs.inventoryTableref.putTableValue(data.productList);
        });
      }
    },
    //获取产品已发货数总量
    async getTotalCountHistory(data) {
      let list = await getReceiveCountAPI({orderId: data.orderId, entrustedReceiveId: this.form.id});
      data.productList.forEach((item) => {
        let find = list.find((key) => key.productCode == item.productCode) || {};
        item.receiveTotalCount = find.receiveTotalCount || 0;
        item.orderTotalCount = item.totalCount || 0
        item.totalCount = item.orderTotalCount - item.receiveTotalCount
      });
      return data
    },
    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);
            }
          });
        })
      ]);
    },
    async save(type) {
      try {
        await this.getValidate();
        // 表单验证通过，执行保存操作
        this.loading = true;
        if (!this.isUpdate) {
          delete this.form.id;
        }
        this.form.files = this.form.files || [];
        // this.form.replied = this.form.repliedFiles.length > 0 ? 1 : 0;
        let commitData = Object.assign({}, this.form, {
          productList: this.$refs.inventoryTableref.getTableValue()
        });
        const API = this.isUpdate ? updateSaleEntrustedReceiveAPI : saveSaleEntrustedReceiveAPI
        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) {
      let data = await getPSaleEntrustedReceiveDetailAPI(this.businessId || res);
      this.processSubmitDialogFlag = true

      this.$nextTick(()=>{
        let params = {
          businessId: this.businessId || res,
          businessKey : 'sale_entrusted_receive_approve',
          formCreateUserId: data.createUserId,
          variables: {
            businessCode: data.code
          },
          // 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');
      // });
    },
    reload(){
        this.cancel();
        this.$emit('done');
    },
    cancel() {
      this.$emit('update:addOrEditDialogFlag', 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>
