<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"
    width="70%"
    @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="委外发货单">
            <el-input
              clearable
              v-model="form.outsourceSendCode"
              @click.native="handleOutsourceSend"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input
              clearable
              v-model="form.supplierName"
              disabled
              placeholder="请输入"
            />
          </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="20">
        <el-col :span="12">
          <el-form-item label="订单类型">
            <el-input v-model="form.sourceTypeName" disabled></el-input>
          </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-row>
      <el-row :gutter="20">
        <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="sendNoteNo">
            <el-input
              clearable
              v-model="form.sendNoteNo"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item prop="receiveDate" label="收货日期">
            <el-date-picker
              style="width: 100%"
              v-model="form.receiveDate"
              type="date"
              placeholder="选择日期"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <!-- <el-col :span="12">
          <el-form-item prop="isQmsCheck" label="是否需要质检">
            <el-select v-model="form.isQmsCheck" style="width: 100%" placeholder="请选择">
              <el-option label="是" :value="1"></el-option>
              <el-option label="否" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item prop="receiveFiles" label="附件">
            <fileMain v-model="form.receiveFiles"></fileMain>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <headerTitle title="物品清单" style="margin-top: 30px"></headerTitle>
    <inventoryTable
      :pricingWay="form.pricingWay"
      :sourceType="form.sourceType"
      :outsourceSendCode="form.outsourceSendCode"
      :is-show-supplier-mark="true"
      ref="inventoryTableref"
      :orderId="form.orderId"
      :productType="2"
    ></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
      ref="orderListDialogRef"
      @changeParent="changeOrder"
      :isOutsourcing="1"
    ></orderListDialog>
    <!-- 委外发货单   -->
    <out-source-send-dialog
      :out-source-send-dialog-flag.sync="outSourceSendDialogFlag"
      v-if="outSourceSendDialogFlag"
      ref="outSourceSendDialogRef"
      :searchParams="searchParams"
      @changeParent="getOutSourceInfo"
    ></out-source-send-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 dictMixins from '@/mixins/dictMixins';
  import {
    getByIdCondition
  } from '@/api/purchasingManage/purchaseOrder';

  import {
    addReceiveInformation,
    UpdateReceiveInformation,
    getReceiveSaleOrderrecordDetail,
  } from '@/api/purchasingManage/purchaseorderreceive';
  import inventoryTable from './inventoryTable.vue';
  import orderListDialog from './orderListDialog.vue';
  import { copyObj } from '@/utils/util';
  import outSourceSendDialog from '@/views/purchasingManage/purchaseOrder/invoice/components/outSourceSendDialog.vue';
  import { getPurchaseOutSourceSendDetailAPI } from '@/api/purchasingManage/outSourceSend';
  import { getWarehouseListByIds } from '@/api/purchasingManage/returnGoods';
  import fileMain from '@/components/addDoc/index.vue';
  import processSubmitDialog from '@/BIZComponents/processSubmitDialog/processSubmitDialog.vue';

  export default {
    mixins: [dictMixins],
    components: {
      processSubmitDialog,
      fileMain,
      inventoryTable,
      orderListDialog,
      outSourceSendDialog,
    },
    data() {
      let formDef = {
        id: '',
        contractId: '',
        isQmsCheck: 0,
        receiveFiles: [],
        contractName: '',
        carNo: '',
        carId: '',
        linkName: '',
        linkPhone: '',
        orderNo: '',
        orderId: '',
        outsourceSendCode: '',
        outsourceSendId: '',
        sendNoteNo: '',
        sourceTypeName: '',
        receiveDate: '',
        receiveType: ''
      };

      return {
        fullscreen: false,
        searchParams: {},
        detailData: {},
        payWayOptions: [],
        delDetailIds: [],
        linkNameOptions: [],
        acceptUnpackoptions,
        visible: false,
        outSourceSendDialogFlag: false,
        processSubmitDialogFlag: false,
        title: '',
        row: {},
        activeName: 'base',
        formDef,
        form: copyObj(formDef),
        tableBankData: [],
        tableLinkData: [],
        businessId: '',
        // 组织机构树形结构数据
        rules: {
          orderNo: [
            { required: true, message: '请选择采购订单', trigger: 'change' }
          ],
          receiveType: [
            { required: true, message: '请选择采购单类型', trigger: 'change' }
          ]
        },

        // 提交状态
        loading: false,
        // 是否是修改
        isUpdate: false,
        pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      };
    },
    computed: {
      allcountAmount() {
        return this.$store.state.order.allcountAmount;
      }
    },

    methods: {
      //选择订单回调
      changeOrder(obj) {
        this.form = Object.assign({}, this.form, {
          orderId: obj.id,
          orderNo: obj.orderNo
        });
        this.getPurchaseorderDetail(obj.id);
      },

      //获取订单详情
      async getPurchaseorderDetail(id) {
        this.loading = true;
        const data = await getByIdCondition(id, 2);
        this.loading = false;
        if (data) {
          this.$nextTick(() => {
            let {
              partbId,
              partbName,
              partbTel,
              orderNo,
              id,
              partbLinkName,
              productList,
              sourceTypeName,
              sourceType,
              pricingWay
            } = 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,
              pricingWay
            });
            // if(sourceType==1){
            //   this.form.isQmsCheck=1
            // }
            console.log(data, 'productList');
            this.$refs.inventoryTableref &&
              this.$refs.inventoryTableref.putTableValue(productList);
          });
        }
      },

      //发货单详情
      async getReceiveSaleOrderDetail(id) {
        this.businessId = id;
        this.loading = true;
        const data = await getReceiveSaleOrderrecordDetail(id);
        this.loading = false;
        if (data) {
          this.$nextTick(() => {
            this.form = data;
            this.$refs.inventoryTableref &&
              this.$refs.inventoryTableref.putTableValue(data.productList);
          });
        }
      },

      handHead() {
        let item = {
          id: this.form.partbLinkId
        };
        this.$refs.headRef.open(item);
      },

      //选择订单弹框
      handleOrderBtn(e) {
        if (e.target.nodeName == 'I') {
          this.form = Object.assign({}, this.form, {
            contractId: '',
            receiveFiles: [],
            contractName: '',
            carNo: '',
            carId: '',
            linkName: '',
            linkPhone: '',
            orderNo: '',
            orderId: '',
            pricingWay: '',
            outsourceSendCode: '',
            outsourceSendId: '',
            sendNoteNo: '',
            sourceTypeName: '',
            receiveType: ''
          });
          this.$refs.inventoryTableref &&
            this.$refs.inventoryTableref.putTableValue([]);
          return;
        }
        let item = {
          id: this.form.orderId
        };
        this.$refs.orderListDialogRef.open(item);
      },
      //选择委外发货单弹框
      handleOutsourceSend(e) {
        if (e.target.nodeName == 'I') {
          this.form = Object.assign({}, this.form, {
            contractId: '',
            receiveFiles: [],
            contractName: '',
            carNo: '',
            carId: '',
            linkName: '',
            linkPhone: '',
            orderNo: '',
            orderId: '',
            outsourceSendCode: '',
            outsourceSendId: '',
            sendNoteNo: '',
            sourceTypeName: '',
            receiveType: '',
            pricingWay: ''
          });
          this.$refs.inventoryTableref &&
            this.$refs.inventoryTableref.putTableValue([]);
          return;
        }
        this.searchParams = {
          orderId: this.form.orderId
        };
        this.outSourceSendDialogFlag = true;
        this.$nextTick(() => {
          this.$refs.outSourceSendDialogRef.init();
        });
      },
      //获取委外发货单数据回调
      async getOutSourceInfo(row) {
        const data = await getPurchaseOutSourceSendDetailAPI(row.id);
       let orderData = await getByIdCondition(data.orderId,2);
 
        this.$nextTick(() => {
          let {
            carNo,
            code,
            linkName,
            linkPhone,
            orderId,
            orderNo,
            // productList,
            sendNoteNo,
            supplierId,
            supplierName,
            sourceType,
            sourceTypeName,
            pricingWay,
            id
          } = data;
          if (orderData.productList && orderData.productList.length > 0) {
            orderData.productList.forEach((v) => {
              v.id = '';
              v.orderTotalCount = v.orderTotalCount || v.totalCount;
            });
          }
          this.form = Object.assign({}, this.form, {
            supplierId,
            supplierName,
            linkName,
            linkPhone,
            orderNo,
            orderId,
            sourceTypeName,
            sourceType,
            // productList,
            sendNoteNo,
            carNo,
            pricingWay,
            outsourceSendCode: code,
            outsourceSendId: id,
          });
          // productList.forEach((item) => {
          //   item.id = '';
          // });
          this.$refs.inventoryTableref &&
            this.$refs.inventoryTableref.putTableValue(orderData.productList, code);
        });
      },
      //打开新增编辑弹框
      async open(type, row, orderId, outSourceId) {
        this.title = type === 'add' ? '新增收货单' : '修改';
        this.row = row;
        this.visible = true;
        if (orderId) {
          await this.getPurchaseorderDetail(orderId);
        }
        if (row && row?.id) {
          await this.getReceiveSaleOrderDetail(row?.id);
        }
        if (outSourceId) {
          await this.getOutSourceInfo({ id: outSourceId });
        }

        if (type == 'add') {
          this.isUpdate = false;
          this.form.receiveDate = new Date();
        } else {
          this.isUpdate = true;
        }
      },

      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.receiveTypeName = this.getDictValue(
            '采购收货单类型',
            this.form.receiveType
          );
          let commitData = Object.assign({}, this.form, {
            productList: this.$refs.inventoryTableref.getTableValue()
          });

          if (this.isUpdate) {
            UpdateReceiveInformation(commitData)
              .then(async (res) => {
                this.loading = false;
                this.$message.success('修改成功');
                if (type === 'sub') {
                  let storemanIds = '';
                  let ids = commitData.productList.map(
                    (item) => item.warehouseId
                  );
                  let warehouseList = await getWarehouseListByIds(ids || []);
                  storemanIds = warehouseList.map((item) => item.ownerId);
                  this.sub(res, commitData.sourceType, storemanIds.toString());
                  return;
                }
                this.cancel();
                this.$emit('done');
              })
              .catch((e) => {
                //this.loading = false;
              });
          } else {
            commitData.createTime = '';
            addReceiveInformation(commitData)
              .then(async (res) => {
                this.loading = false;
                this.$message.success('新增成功');
                if (type === 'sub') {
                  let storemanIds = '';
                  let ids = commitData.productList.map(
                    (item) => item.warehouseId
                  );
                  let warehouseList = await getWarehouseListByIds(ids || []);
                  storemanIds = warehouseList.map((item) => item.ownerId);
                  this.sub(res, commitData.sourceType, storemanIds.toString());
                  return;
                }
                this.cancel();
                this.$emit('done');
              })
              .catch((e) => {
                //this.loading = false;
              });
          }
        } catch (error) {
          console.log(error);
          // 表单验证未通过，不执行保存操作
        }
      },
      async sub(res, sourceType, storemanIds) {
        const data = await getReceiveSaleOrderrecordDetail(
          this.businessId || res
        );
        this.processSubmitDialogFlag = true;
        let key =
          sourceType == '1'
            ? 'purchase_receive_approve'
            : 'purchase_receive_approve_2';
        this.$nextTick(() => {
          let params = {
            businessId: data.id,
            businessKey: key,
            formCreateUserId: data.createUserId,
            variables: {
              businessCode: data.receiveNo,
              receiveType: data.receiveType,
              sourceType: data.sourceType,
              storemanIds: storemanIds.toString(),
              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,
        //   receiveType: this.form.receiveType,
        //   sourceType,
        //   variables: {
        //     storemanIds
        //   }
        // }).then((res) => {
        //   this.cancel();
        //   this.$emit('done');
        // });
      },
      reload() {
        this.cancel();
        this.$emit('done');
      },
      cancel() {
        this.$nextTick(() => {
          this.activeName = 'base';
          // 关闭后，销毁所有的表单数据
          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>
