<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <headerTitle title="收货信息"></headerTitle>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item
            label="选择订单"
            prop="orderNo"
            style="margin-bottom: 22px"
          >
            <el-input
              clearable
              v-model="form.orderNo"
              @click.native="handleOrderBtn"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="委外发货单"
            style="margin-bottom: 22px"
          >
            <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"
            style="margin-bottom: 22px"
          >
            <el-input
              clearable
              v-model="form.supplierName"
              disabled
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="供应商联系人"
            prop="linkName"
            style="margin-bottom: 22px"
          >
            <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="订单类型"
            style="margin-bottom: 22px"
          >
            <el-input v-model="form.sourceTypeName" disabled></el-input>
          </el-form-item>

        </el-col>
        <el-col :span="12">
          <el-form-item
            label="供应商电话"
            prop="linkPhone"
            style="margin-bottom: 22px"
          >
            <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"
            style="margin-bottom: 22px">
            <el-input clearable v-model="form.carNo" placeholder="请输入"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label="送货单号"
            prop="sendNoteNo"
            style="margin-bottom: 22px"
          >
            <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="计价方式"
            style="margin-bottom: 22px">
            <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 :gutter="20">
        <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>

    <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>
  </div>
</template>

<script>
import fileUpload from '@/components/upload/fileUpload';
import dictMixins from '@/mixins/dictMixins';
import {getpurchaseorderDetail} from '@/api/bpm/components/purchasingManage/purchaseOrder';
import outSourceSendDialog from "./outSourceSendDialog.vue";
import {getReceiveSaleOrderrecordDetail} from '@/api/bpm/components/purchasingManage/purchaseorderreceive';
import inventoryTable from './inventoryTable.vue';
import orderListDialog from './orderListDialog.vue';
import {copyObj} from '@/utils/util';
import {getPurchaseOutSourceSendDetailAPI} from "@/api/bpm/components/purchasingManage/outSourceSend";

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

    return {
      detailData: {},
      searchParams: {},
      payWayOptions: [],
      delDetailIds: [],
      linkNameOptions: [],
      outSourceSendDialogFlag: false,
      visible: false,
      title: '',
      row: {},
      activeName: 'base',
      formDef,
      form: copyObj(formDef),
      tableBankData: [],
      tableLinkData: [],
      // 组织机构树形结构数据
      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;
    }
  },

  created() {
    this.getReceiveSaleOrderDetail(this.businessId);
  },
  methods: {
    //选择订单回调
    changeOrder(obj) {
      this.form = Object.assign({}, this.form, {
        orderId: obj.id,
        orderNo: obj.orderNo
      });
      this.getPurchaseorder(obj.id);
    },
    //获取订单详情
    async getPurchaseorder(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,
            sourceTypeName,
            sourceType,
            orderId: id,
            productList,
            pricingWay,
          });
          this.$refs.inventoryTableref &&
          this.$refs.inventoryTableref.putTableValue(productList);
        });
      }
    },

    //发货单详情
    async getReceiveSaleOrderDetail(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);
    },
    //选择委外发货单弹框
    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);
      });
    },
    //选择订单弹框
    handleOrderBtn() {
      let item = {
        id: this.form.orderId
      };
      this.$refs.orderListDialogRef.open(item);
    },

    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 getTableValue() {
      try {
        await this.getValidate();
        this.form.receiveTypeName = this.getDictValue(
          '采购收货单类型',
          this.form.receiveType
        );
        // 表单验证通过，执行保存操作
        this.loading = true;
        let commitData = Object.assign({}, this.form, {
          productList: this.$refs.inventoryTableref.getTableValue()
        });
        return commitData;
      } catch (error) {
        console.log(error);
        // 表单验证未通过，不执行保存操作
      }
    }
  }
};
</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>
