<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"
    :maxable="true"
    :resizable="true"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      class="el-form-box"
      label-width="120px"
    >
      <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.supplierName" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="订单类型" prop="contactName">
            <el-input v-model="form.sourceTypeName" 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-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="linkPhone">
            <el-input clearable v-model="form.linkPhone" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发货日期" prop="sendDate">
            <el-date-picker
              v-model="form.sendDate"
              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 label="车辆号" prop="carNo">
            <el-input clearable v-model="form.carNo" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="sendFiles" label="附件">
            <fileMain v-model="form.files"></fileMain>
      
          </el-form-item>
        </el-col>
        <el-col :span="12"> </el-col>
      </el-row>
    </el-form>

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

    <div slot="footer" class="footer">
      <el-button type="primary" @click="save" v-click-once>保存</el-button>
      <el-button type="primary" @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 {
    savePurchaseOutSourceSendAPI,
    updatePurchaseOutSourceSendAPI,
    getPurchaseOutSourceSendDetailAPI,
    submit
  } from '@/api/purchasingManage/outSourceSend';
  import { getcontactlink } from '@/api/saleManage/businessFollow';
  import inventoryTable from './inventoryTable.vue';
  import orderListDialog from '../../invoice/components/orderListDialog.vue';
  import { copyObj } from '@/utils/util';
  import { getByIdCondition } from '@/api/purchasingManage/purchaseOrder';
  // 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: {
          sourceType: '3,4,5,6,7'
        },
        detailData: {},
        payWayOptions: [],
        delDetailIds: [],
        linkNameOptions: [],
        fullscreen: false,

        title: '',
        row: {},
        form: {
          id: '',
          carNo: '',
          sendDate: '',
          files: [],
          linkName: '',
          linkPhone: '',
          orderId: '',
          orderNo: '',
          pricingWay: '',
          productList: [],
          sendNoteNo: '',
          sourceType: '',
          sourceTypeName: '',
          supplierId: '',
          supplierName: ''
        },
        rules: {
          partaName: [
            { 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.getPurchaseOrderDetail(orderId);
        }

        if (row && row?.id) {
          await this.getSendSaleOrderDetail(row?.id);
        }

        this.isUpdate = type !== 'add';
        if (!this.isUpdate) {
          this.form.sendDate = new Date();
        }
      },
      //选择订单弹框
      handleOrderBtn(e) {
        if (e.target.nodeName == 'I') {
          this.form = Object.assign({}, this.form, {
            supplierId: '',
            supplierName: '',
            linkName: '',
            linkPhone: '',
            orderNo: '',
            orderId: '',
            sourceTypeName: '',
            sourceType: '',
            productList: [],
            pricingWay: ''
          });
          this.$refs.inventoryTableref &&
            this.$refs.inventoryTableref.putTableValue([]);
          return;
        }
        this.$refs.orderListDialogRef.open();
      },
      //选择订单回调
      changeOrder(obj) {
        this.getPurchaseOrderDetail(obj.id);
      },
      //获取订单详情
      async getPurchaseOrderDetail(id) {
        this.loading = true;
        const data = await getByIdCondition(id, 1);
        this.loading = false;
        if (data) {
          this.$nextTick(() => {
            let {
              partbId,
              partbName,
              partbTel,
              orderNo,
              id,
              partbLinkName,
              productList,
              sourceTypeName,
              sourceType,
            } = data;
            if (productList && productList.length > 0) {
              productList.forEach((v) => {
                v.orderTotalCount = v.orderTotalCount || v.totalCount;
              });
            }
            this.form = Object.assign({}, this.form, {
              supplierId: partbId,
              supplierName: partbName,
              linkName: partbLinkName,
              linkPhone: partbTel,
              orderNo,
              orderId: id,
              sourceTypeName,
              sourceType,
              productList,
              
            });
            this.$refs.inventoryTableref &&
              this.$refs.inventoryTableref.putTableValue(productList);
          });
        }
      },

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

        this.loading = true;
        const data = await getPurchaseOutSourceSendDetailAPI(id);
        this.loading = false;
        if (data) {
          this.$nextTick(() => {
            this.form = data;
            this.$refs.inventoryTableref &&
              this.$refs.inventoryTableref.putTableValue(data.productList);
          });
        }
      },

      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 || [];
          let productList = this.$refs.inventoryTableref.getTableValue();

          if (type == 'sub') {
            let tabName = [];
            productList.forEach((item) => {
              if (item.totalCount > (item.warehouseNum || 0)) {
                tabName.push(item.productName);
              }
            });
            if (tabName.length > 0) {
              this.$message.error(tabName.toString() + '库存不足无法提交');
              return;
            }
          }
          // 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
            ? updatePurchaseOutSourceSendAPI
            : savePurchaseOutSourceSendAPI;
          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 getPurchaseOutSourceSendDetailAPI(
          this.businessId || res
        );
        this.processSubmitDialogFlag = true;
        this.$nextTick(() => {
          let params = {
            businessId: data.id,
            businessKey: 'purchase_outsource_send_approve',
            formCreateUserId: data.createUserId,
            variables: {
              businessCode: data.code,
              businessName: data.supplierName,
              businessType: '委外发货单'
            }
            // 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>
