<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="客户名称"
            prop="contactName"
            style="margin-bottom: 22px"
          >
            <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="计价方式"
            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-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="车辆号" 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="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="sendNoteNo"
            style="margin-bottom: 22px"
          >
            <el-input
              clearable
              v-model="form.sendNoteNo"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="sendFiles" label="附件">
            <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>
    <!--  采购订单  -->
    <orderListDialog
      :searchParams="orderSearchParams"
      ref="orderListDialogRef"
      @changeParent="changeOrder"
    ></orderListDialog>
  </div>
</template>

<script>

import fileUpload from '@/components/upload/fileUpload';
import dictMixins from '@/mixins/dictMixins';
import {
  updateSaleEntrustedReceiveAPI,
  getPSaleEntrustedReceiveDetailAPI,
  getReceiveCountAPI
} from '@/api/bpm/components/saleManage/entrustedReceive';
// import {getcontactlink} from '@/api/saleManage/businessFollow';
import inventoryTable from './inventoryTable.vue';
import orderListDialog from '../invoice/orderListDialog.vue';
import {copyObj} from '@/utils/util';
import {getpurchaseorderDetail} from "@/api/bpm/components/purchasingManage/purchaseOrder";

export default {
  mixins: [dictMixins],
  components: {
    fileUpload,
    inventoryTable,
    orderListDialog
  },
  props: {
    businessId: {
      default: ''
    }
  },
  data() {
    return {
      orderSearchParams: {
        saleType: '5',
      },
      detailData: {},
      payWayOptions: [],
      delDetailIds: [],
      linkNameOptions: [],
      title: '',
      row: {},
      form: {
        id: '',
        carNo: '',
        files: [],
        linkName: '',
        linkPhone: '',
        orderId: '',
        orderNo: '',
        pricingWay: '',
        productList: [],
        sendNoteNo: '',
        contactId: '',
        contactName: '',

      },
      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,
    };
  },
  async created() {
    await this.getSendSaleOrderDetail(this.businessId);
  },
  methods: {
    //选择订单弹框
    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.getPurchaseOrderDetail(obj.id);
    },
    //获取订单详情
    async getPurchaseOrderDetail(id) {
      this.loading = true;
      const data = await getpurchaseorderDetail(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);
          await this.$refs.inventoryTableref &&
          this.$refs.inventoryTableref.putTableValue(this.form.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
    },
    //发货单详情
    async getSendSaleOrderDetail(id) {
      this.businessId = id;

      this.loading = true;
      const 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);
        });
      }
    },

    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() {
      return new Promise(async (resolve, reject) => {
        try {
          await this.getValidate();
          this.form.files = this.form.files || [];
          let commitData = Object.assign({}, this.form, {
            productList: this.$refs.inventoryTableref.getTableValue()
          });
          await updateSaleEntrustedReceiveAPI(commitData)
          resolve(true)

        } catch (error) {
          reject(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>
