<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"
  >
    <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="选择日期"
            >
            </el-date-picker>
          </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-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="receiveFiles" label="附件">
            <fileUpload
              v-model="form.receiveFiles"
              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"
      :sourceType="form.sourceType"
      :outsourceSendCode="form.outsourceSendCode"
      :is-show-supplier-mark="true"
      ref="inventoryTableref"
      :orderId="form.orderId"
    ></inventoryTable>

    <div slot="footer" class="footer">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button type="primary" @click="save('sub')">提交</el-button>
      <el-button @click="cancel">返回</el-button>
    </div>
    <!-- 采购订单   -->
    <orderListDialog
      ref="orderListDialogRef"
      @changeParent="changeOrder"
    ></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>
  </ele-modal>
</template>

<script>
import {acceptUnpackoptions} from '@/enum/dict';
import fileUpload from '@/components/upload/fileUpload';
import dictMixins from '@/mixins/dictMixins';
import {
  // getpurchaseorderDetail,
  getpurchaseorderDetail
} from '@/api/purchasingManage/purchaseOrder';

import {
  addReceiveInformation,
  UpdateReceiveInformation,
  getReceiveSaleOrderrecordDetail, submit
} 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";

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

    return {
      searchParams: {},
      detailData: {},
      payWayOptions: [],
      delDetailIds: [],
      linkNameOptions: [],
      acceptUnpackoptions,
      visible: false,
      outSourceSendDialogFlag: 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
    };
  },
  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 getpurchaseorderDetail(id);
      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,
          });
          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);
      this.$nextTick(() => {
        let {
          carNo,
          code,
          linkName,
          linkPhone,
          orderId,
          orderNo,
          productList,
          sendNoteNo,
          supplierId,
          supplierName,
          sourceType,
          sourceTypeName,
          pricingWay
        } = data;
        if (productList && productList.length > 0) {
          productList.forEach((v) => {
            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
        });
        productList.forEach(item => {
          item.id = ''
        })
        this.$refs.inventoryTableref &&
        this.$refs.inventoryTableref.putTableValue(productList, code);
      });
    },
    //打开新增编辑弹框
    async open(type, row, orderId, outSourceId) {
      this.title = type === 'add' ? '新增收货单' : '修改';
      this.row = row;
      this.visible = true;
      if (orderId) {
        this.getPurchaseorderDetail(orderId);
      }
      if (row && row?.id) {
        this.getReceiveSaleOrderDetail(row?.id);
      }
      if (outSourceId) {
        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 {
          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);
        // 表单验证未通过，不执行保存操作
      }
    },
    sub(res, sourceType, storemanIds) {
      submit({
        businessId: this.businessId || res,
        receiveType: this.form.receiveType,
        sourceType,
        variables: {
          storemanIds
        }
      }).then((res) => {
        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>
