<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form v-bind="formItemLayout" name="SaleOrderForm" ref="formRef">
          <a-row>
            <a-col :span="12">
              <a-form-item label="组织(organize)" v-bind="validateInfos.organize" id="SaleOrderForm-organize" name="organize">
                <a-select v-model:value="formData.organize" :disabled="formData.id!==''&&formData.submit == '1'">
                  <a-select-option value="上海">上海</a-select-option>
                  <a-select-option value="香港">香港</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="订单编号(bill code)" v-bind="validateInfos.billCode" id="SaleOrderForm-billCode" name="billCode">
                <a-input v-model:value="formData.billCode" placeholder="自动生成" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="单据日期(bill date)" v-bind="validateInfos.billDate" id="SaleOrderForm-billDate" name="billDate">
                <a-date-picker
                  placeholder="请选择单据日期(bill date)"
                  v-model:value="formData.billDate"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  allow-clear
                />
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="项目(project)" v-bind="validateInfos.projectName" id="SaleOrderForm-projectName" name="projectName">
                <a-input-search
                  v-model:value="formData.projectName"
                  placeholder="请输入项目(project)"
                  readonly
                  :disabled="notAllowEdit"
                  allow-clear
                  enter-button="Search"
                  AutoComplete="off"
                  @search="onSearchProject"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="供应商(supplier)" v-bind="validateInfos.supplier" id="SaleOrderForm-supplier" name="supplier">
                <ApiSelect
                  :api="supplierOption"
                  showSearch
                  v-model:value="formData.supplier"
                  optionFilterProp="label"
                  resultField="records"
                  labelField="name"
                  valueField="id"
                  disabled
                  :params="{ pageSize: -1,status:1}"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="优先级(priority)" v-bind="validateInfos.priority" id="SaleOrderForm-priority" name="priority">
                <JDictSelectTag v-model:value="formData.priority" placeholder="请选择" dictCode="priority" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="产品分类(production class)"
                v-bind="validateInfos.productionClass"
                id="SaleOrderForm-productionClass"
                name="productionClass"
              >
                <ApiSelect
                  :api="ClassList"
                  showSearch
                  v-model:value="formData.productionClass"
                  optionFilterProp="label"
                  resultField="records"
                  labelField="name"
                  valueField="id"
                  disabled
                  :params="{ pageSize: -1 }"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="机型(model)" v-bind="validateInfos.model" id="SaleOrderForm-model" name="model">
                <JDictSelectTag v-model:value="formData.model" placeholder="请选择" dictCode="model_typer" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="厂家(maker)" v-bind="validateInfos.maker" id="SaleOrderForm-maker" name="maker">
                <a-input v-model:value="formData.maker" placeholder="请输入厂家(maker)" allow-clear disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="贸易条款(trade term)" v-bind="validateInfos.tradeTerms" id="SaleOrderForm-tradeTerms" name="tradeTerms">
                <JDictSelectTag v-model:value="formData.tradeTerms" placeholder="请选择" dictCode="delivery_terms" />
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="是否出口(export)" v-bind="validateInfos.isExport" id="SaleOrderForm-isExport" name="isExport">
                <JDictSelectTag v-model:value="formData.isExport" placeholder="请选择" dictCode="yes_or_no" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="包装要求(package requirement)"
                v-bind="validateInfos.packagebRequirement"
                id="SaleOrderForm-packagebRequirement"
                name="packagebRequirement"
              >
                <a-input
                  v-model:value="formData.packagebRequirement"
                  placeholder="请输入包装要求(package requirement)"
                  allow-clear
                  AutoComplete="off"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="收件人(recipient)" v-bind="validateInfos.recipient" id="SaleOrderForm-recipient" name="recipient">
                <a-input v-model:value="formData.recipient" placeholder="请输入" AutoComplete="off" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="运输方式(transport)" v-bind="validateInfos.transport" id="SaleOrderForm-transport" name="transport">
                <JDictSelectTag v-model:value="formData.transport" placeholder="请选择" dictCode="delivery_methods" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="收件人地址(recipient address)"
                v-bind="validateInfos.recipientAddress"
                id="SaleOrderForm-recipientAddress"
                name="recipientAddress"
              >
                <a-input v-model:value="formData.recipientAddress" placeholder="请输入" AutoComplete="off" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="付款条件(payment terms)" v-bind="validateInfos.paymentTerms" id="SaleOrderForm-paymentTerms" name="paymentTerms">
                <JDictSelectTag v-model:value="formData.paymentTerms" placeholder="请选择" dictCode="payment_terms" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="收件人电话(recipient tel)" v-bind="validateInfos.recipientTel" id="SaleOrderForm-recipientTel" name="recipientTel">
                <a-input v-model:value="formData.recipientTel" placeholder="请输入" AutoComplete="off" />
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="发货方式(delivery)" v-bind="validateInfos.delivery" id="SaleOrderForm-delivery" name="delivery">
                <JDictSelectTag v-model:value="formData.delivery" placeholder="请选择" dictCode="delivery_sale_order" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="质保期(warranty period)"
                v-bind="validateInfos.warrantyPeriod"
                id="SaleOrderForm-warrantyPeriod"
                name="warrantyPeriod"
              >
                <a-input
                  v-model:value="formData.warrantyPeriod"
                  placeholder="请输入"
                  style="width: 85%; margin-right: 1%"
                  AutoComplete="off"
                />月(month)
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="质保条款(warranty terms)"
                v-bind="validateInfos.warrantyTerms"
                id="SaleOrderForm-warrantyTerms"
                name="warrantyTerms"
              >
                <a-input v-model:value="formData.warrantyTerms" placeholder="请输入质保条款(warranty terms)" allow-clear AutoComplete="off" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="汇率(exchange rate)" v-bind="validateInfos.exchangeRate" id="SaleOrderForm-exchangeRate" name="exchangeRate">
                <a-input v-model:value="formData.exchangeRate" placeholder="请输入" allow-clear AutoComplete="off" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="币种(currency)" v-bind="validateInfos.currency" id="SaleOrderForm-currency" name="currency">
                <JDictSelectTag v-model:value="formData.currency" placeholder="请选择" dictCode="currency" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="采购部门(purchase department)"
                v-bind="validateInfos.purchaseDepartment"
                id="SaleOrderForm-purchaseDepartment"
                name="purchaseDepartment"
              >
                <a-input v-model:value="formData.purchaseDepartmentName" placeholder="请输入" allow-clear disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="采购员(purchasesman)" v-bind="validateInfos.purchaseman" id="SaleOrderForm-purchaseman" name="purchaseman">
                <a-input v-model:value="formData.purchasemanName" placeholder="请输入采购员(salesman)" allow-clear disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="折扣(discountHead)" v-bind="validateInfos.discountHead" id="SaleOrderForm-discountHead" name="discountHead">
                <a-input-number
                  v-model:value="formData.discountHead"
                  placeholder="请输入折扣(discountHead)"
                  :min="0"
                  :max="100"
                  @blur="discountHeadChange"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="折后金额(discounted amount)"
                v-bind="validateInfos.discountAmount"
                id="SaleOrderForm-discountAmount"
                name="discountAmount"
              >
                <a-input v-model:value="formData.discountAmount" allow-clear disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="备注(notes)" v-bind="validateInfos.notes" id="SaleOrderForm-notes" name="notes">
                <a-input v-model:value="formData.notes" AutoComplete="off" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="协议条款(agreement terms)"
                v-bind="validateInfos.agreementTerms"
                id="SaleOrderForm-agreementTerms"
                name="agreementTerms"
              >
                <JSelectMultiple
                  v-model:value="formData.agreementTerms"
                  placeholder=""
                  dictCode="base_agreement_terms,name,name"
                  page="false"
                  showSearch
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="附件(attachs)" v-bind="validateInfos.attachs" id="SaleOrderForm-attachs" name="attachs">
                <JUpload v-model:value="formData.attachs" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </template>
    </JFormContainer>

    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated style="padding: 24px; padding-top: 0px">
      <a-tab-pane tab="采购订单 - 产品明细(product details)" key="purOrderFormShipFormProduct" :forceRender="true">
        <a-button type="primary" style="margin-right: 1%; margin-bottom: 1%" @click="selectSaleOrderList" :disabled="formData.sourceCode !== ''">
          选择销售订单(select saleorder)</a-button
        >
        <a-button type="primary" style="margin-right: 1%; margin-bottom: 1%" @click="selectVirtualProducts">
          选择虚拟产品(select virtual products)</a-button
        >
        <a-button
          type="primary"
          style="margin-right: 1%; margin-bottom: 1%"
          @click="SelectSupplierQuotationList"
          v-auth="'purCode:pur_order:selection'"
          :disabled="formData.sourceCode2 !== ''"
          >选择供应商报价选定(select supplier quotation selection)</a-button
        >
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="purOrderFormShipFormProductTableRef"
          :loading="purOrderFormShipFormProductTable.loading"
          :columns="purOrderFormShipFormProductTable.columns"
          :dataSource="purOrderFormShipFormProductTable.dataSource"
          :maxHeight="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          asyncRemove
          @value-change="changeValues"
        >
          <template #action="props" >
            <a-popconfirm title="确定删除吗？" @confirm="handleDelete(props)" v-if="!(formData.id!==''&&formData.submit == '1')">
              <a v-if="!(formData.id!==''&&formData.submit == '1')">删除(delete)</a>
            </a-popconfirm>
          </template>
        </j-vxe-table>
      </a-tab-pane>
      <a-tab-pane tab="采购订单 - 船明细(ship details)" key="PurOrderFormShipFormShip" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="PurOrderFormShipFormShipTableRef"
          :loading="PurOrderFormShipFormShipTable.loading"
          :columns="PurOrderFormShipFormShipTable.columns"
          :dataSource="PurOrderFormShipFormShipTable.dataSource"
          :maxHeight="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
        >
          <template #action="props">
            <a @click="viewAccessory(props)">查看配件信息(view accessory information)</a>
          </template>
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
    <SelectPrpductModal ref="SelectPrpductModalRef" @select-product="addProduct" />
    <SelectProjectModal ref="SelectProjectModalRef" @select-project="addProject" />
    <BaseShipArchiveAccessoriesModal ref="BaseShipArchiveAccessoriesModalRef" />
    <SelectSaleOrderModal ref="SelectSaleOrderModalRef" @select-sale-order="addFormSaleOrder" />
    <SelectSupplierQuotation ref="SelectSupplierQuotationRef" @select-supplier-quatation-confirm="addFromQuotation" />
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, watch } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import {
    queryPurOrderFormShipFormShippTable,
    queryPurOrderFormProductListByMainId,
    ClassList,
    queryDataById,
    supplierOption,
    saveOrUpdate,
    queryVersonHistoryById,
    queryPurVersonFormShipListByMainId,
    queryPurVersonProductListByMainId,
  } from '../PurchaseOrderyForm.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import { purchaseOrderShipColumns, purchaseOrderProductColumns } from '../PurchaseOrderForm.data';
  import SelectPrpductModal from '../../../publicComponents/SelectPrpductModal.vue';
  import SelectProjectModal from '../../../publicComponents/SelectProjectModal.vue';
  import SelectSaleOrderModal from '../../../publicComponents/SelectSaleOrderModal.vue';
  import BaseShipArchiveAccessoriesModal from '../../../publicComponents/BaseShipArchiveAccessoriesModal.vue';
  import SelectSupplierQuotation from '../../../publicComponents/SelectSupplierQuotation.vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { JDictSelectTag, ApiSelect } from '/@/components/Form';
  import JSelectInput from '/@/components/Form/src/jeecg/components/JSelectInput.vue';
  import JSelectMultiple from '/@/components/Form/src/jeecg/components/JSelectMultiple.vue';
  import { Form, message } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import moment from 'moment';
  const useForm = Form.useForm;
  export default defineComponent({
    name: 'SaleOrderForm',
    components: {
      JVxeTable,
      JFormContainer,
      SelectPrpductModal,
      JUpload,
      JDictSelectTag,
      JSelectInput,
      SelectProjectModal,
      BaseShipArchiveAccessoriesModal,
      SelectSaleOrderModal,
      ApiSelect,
      JSelectMultiple,
      SelectSupplierQuotation,
    },
    props: {
      formDisabled: {
        type: Boolean,
        default: false,
      },
      formData: { type: Object, default: () => {} },
      formBpm: { type: Boolean, default: true },
    },
    emits: ['success'],
    setup(props, { emit }) {
      const userStore = useUserStore();
      const loading = ref(false);
      const formRef = ref();
      const PurOrderFormShipFormShipTableRef = ref();
      const SelectPrpductModalRef = ref();
      const SelectProjectModalRef = ref();
      const SelectSupplierQuotationRef = ref();
      const BaseShipArchiveAccessoriesModalRef = ref();
      const SelectSaleOrderModalRef = ref();
      const PurOrderFormShipFormShipTable = reactive<Record<string, any>>({
        loading: false,
        columns: purchaseOrderShipColumns,
        dataSource: [],
      });
      const purOrderFormShipFormProductTableRef = ref();
      const purOrderFormShipFormProductTable = reactive<Record<string, any>>({
        loading: false,
        columns: purchaseOrderProductColumns,
        dataSource: [],
      });
      const activeKey = ref('purOrderFormShipFormProduct');
      var notAllowEdit = ref(false);
      const formData = reactive<Record<string, any>>({
        id: '',
        status: undefined,
        delFlag: undefined,
        sourceCode: '',
        sourceCode2: '',
        submit: undefined,
        organize: '',
        billCode: '',
        billDate: moment(new Date()).format('YYYY-MM-DD'),
        project: '',
        projectName: '',
        supplier: '',
        supplierName: '',
        priority: '',
        productionClass: '',
        model: '',
        maker: '',
        tradeTerms: '',
        isExport: '',
        packagebRequirement: '',
        recipient: '',
        recipientTel: '',
        recipientAddress: '',
        paymentTerms: '',
        delivery: '',
        transport: '',
        warrantyPeriod: '',
        warrantyTerms: '',
        exchangeRate: '',
        purchaseDepartment: '',
        purchaseDepartmentName: '',
        purchaseman: '',
        purchasemanName: '',
        currency: '',
        notes: '',
        agreementTerms: '',
        discountHead: 0,
        discountAmount: '',
        totalAmount: '',
        attachs:''
      });

      //表单验证
      const validatorRules = reactive({
        projectName: [{ required: true, message: '请选择报价项目(select project)' }],
        organize: [{ required: true, message: '请选择组织(select organize)' }],
        // currency:[
        //   { required: true, message: '请选择币种(currency)' }
        // ],
      });
      const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
      const dbData = {};
      const formItemLayout = {
        labelCol: { xs: { span: 24 }, sm: { span: 7 } },
        wrapperCol: { xs: { span: 24 }, sm: { span: 15 } },
        labelCol1: { xs: { span: 24 }, sm: { span: 7 } },
        wrapperCol1: { xs: { span: 24 }, sm: { span: 15 } },
      };

      // 表单禁用
      const disabled = computed(() => {
        if (props.formBpm === true) {
          if (props.formData.disabled === false) {
            return false;
          } else {
            return true;
          }
        }
        return props.formDisabled;
      });

      function add() {
        resetFields();
        PurOrderFormShipFormShipTable.dataSource = [];
        purOrderFormShipFormProductTable.dataSource = [];
        activeKey.value = 'purOrderFormShipFormProduct';
        formData.purchaseman = userStore.getUserInfo.username;
        formData.purchasemanName = userStore.getUserInfo.realname;
        formData.purchaseDepartment = userStore.getUserInfo.orgCode;
        formData.purchaseDepartmentName = userStore.getUserInfo.orgName;
        formData.discountHead = 0;
      }
      async function copy(data, id) {
        //主表数据
        await queryMainData(id);
        formData.id = '';
        formData.billCode = '';
        formData.submit = undefined;
        formData.sourceCode = '';
        formData.sourceCode2 = '';
        formData.project = '';
        formData.projectName = '';
        //子表数据
        const PurOrderFormShipFormShipDataList = await queryPurOrderFormShipFormShippTable(id);
        PurOrderFormShipFormShipTable.dataSource = [...PurOrderFormShipFormShipDataList];
        data.map((item) => {
          item.sourceId = '';
          item.sourceType = '';
        });
        purOrderFormShipFormProductTable.dataSource = [...data];
        notAllowEdit.value = false;
      }
      // 判断有没有参照的子表
      // function isSelect() {
      //   var arrQuo = [],
      //     arrCon = [];
      //   purOrderFormShipFormProductTable.dataSource.map((item) => {
      //     var sign = '';
      //     sign = item.sourceId ? item.sourceId.substring(0, 3) : '';
      //     if (item.sourceId && sign == 'Quo') {
      //       arrQuo.push(item.sourceId);
      //     } else if (item.sourceId && sign == 'Con') {
      //       arrCon.push(item.sourceId);
      //     }
      //   });
      //   if (arrQuo.length == 0 && arrCon.length == 0) {
      //     formData.sourceCode2 = '';
      //     formData.sourceCode = '';
      //     notAllowEdit.value = false;
      //   } else if (arrQuo.length == 0) {
      //     formData.sourceCode = '';
      //     notAllowEdit.value = true;
      //   } else if (arrCon.length == 0) {
      //     formData.sourceCode2 = '';
      //     notAllowEdit.value = true;
      //   }
      // }
      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const PurOrderFormShipFormShipDataList = await queryPurOrderFormShipFormShippTable(row['id']);
        PurOrderFormShipFormShipTable.dataSource = [...PurOrderFormShipFormShipDataList];
        const purOrderFormShipFormProductDataList = await queryPurOrderFormProductListByMainId(row['id']);
        purOrderFormShipFormProductTable.dataSource = [...purOrderFormShipFormProductDataList];
        notAllowEdit.value = true;
      }

      async function queryMainData(id) {
        const row = await queryDataById(id);
        resetFields();
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if (row.hasOwnProperty(key)) {
            tmpData[key] = row[key];
          }
        });
        //赋值
        Object.assign(formData, tmpData);
      }
      //查看版本详情
      async function VersionDetail(record) {
        //主表数据
        await queryVersonHistoryData(record.id);
        //子表数据
        const SaleOrderFormShipFormShipDataList = await queryPurVersonFormShipListByMainId(record.id);
        PurOrderFormShipFormShipTable.dataSource = [...SaleOrderFormShipFormShipDataList];
        const purOrderFormShipFormProductDataList = await queryPurVersonProductListByMainId(record.id);
        purOrderFormShipFormProductTable.dataSource = [...purOrderFormShipFormProductDataList];
      }
      async function queryVersonHistoryData(id) {
        const row = await queryVersonHistoryById(id);
        resetFields();
        const tmpData = {};
        Object.keys(formData).forEach((key) => {
          if (row.hasOwnProperty(key)) {
            tmpData[key] = row[key];
          }
        });
        //赋值
        Object.assign(formData, tmpData);
      }

      const { getSubFormAndTableData, transformData } = useValidateAntFormAndTable(activeKey, {
        purOrderShip: PurOrderFormShipFormShipTableRef,
        purOrderProduct: purOrderFormShipFormProductTableRef,
      });

      async function getFormData() {
        try {
          // 触发表单验证
          await validate();
        } catch ({ errorFields }) {
          if (errorFields) {
            const firstField = errorFields[0];
            if (firstField) {
              formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
            }
          }
          return Promise.reject(errorFields);
        }
        return transformData(toRaw(formData));
      }

      async function submitForm() {
        var xTable = purOrderFormShipFormProductTableRef.value!.getXTable();
        if (xTable.data.length == 0) {
          message.warning('请添加产品明细');
        } else {
          purOrderFormShipFormProductTableRef.value!.validateTable().then(async (errMap) => {
            if (errMap) {
              console.log('表单验证未通过：', { errMap });
            } else {
              const mainData = await getFormData();
              const subData = await getSubFormAndTableData();
              const values = Object.assign({}, dbData, mainData, subData);
              console.log('表单提交数据', values);
              const isUpdate = values.id ? true : false;
              const isRevise = values.submit == '1' ? true : false;
              await saveOrUpdate(values, isUpdate, isRevise);
              //关闭弹窗
              emit('success');
            }
          });
        }
      }

      function setFieldsValue(values) {
        if (values) {
          Object.keys(values).map((k) => {
            formData[k] = values[k];
          });
        }
      }
      function onSearchProject() {
        SelectProjectModalRef.value.getTable();
      }
      function addProduct(data) {
        data.map((item) => {
          item.productClass = item.classId_dictText;
          item.productCode = item.code;
          item.productId = item.id;
          item.id = undefined;
        });
        var xTable = purOrderFormShipFormProductTableRef.value!.getXTable();
        var arrProduct = xTable.data.concat(data);
        purOrderFormShipFormProductTable.dataSource = arrProduct;
      }
      function getShipList(id, status) {
        let params = { id: id };
        let url =
          status == 'quotation'
            ? '/purCode/purQuotationSelection/queryPurQuotationSelectionShipByMainId'
            : '/saleCode/saleOrder/querySaleOrderShipByMainId';
        defHttp.get({ url: url, params }, { isTransformResponse: false }).then((res) => {
          if (res) {
            PurOrderFormShipFormShipTable.dataSource = res.result;
          }
        });
      }
      function addFormSaleOrder(data) {
        data.map((item) => {
          item.model = item.childModel;
          item.sourceId = item.childId;
          item.sourceType = 'Con' + item.childId;
          item.sourceCode = item.billCode;
          item.taxPrice = item.taxPriceGys;
          item.taxAmount = item.taxPrice * item.quantity;
          // item.productClass =data[0].productClass
        });
        var xTable = purOrderFormShipFormProductTableRef.value!.getXTable();
        var arrProduct = xTable.data.concat(data);
        purOrderFormShipFormProductTable.dataSource = arrProduct;
        notAllowEdit.value = true;
        if(formData.sourceCode2.includes(data[0].billCode)){
          formData.sourceCode2 = formData.sourceCode2
        }else{
          formData.sourceCode2 = formData.sourceCode2==''?data[0].billCode: formData.sourceCode2+','+data[0].billCode
        }
        if (formData.sourceCode == '') {
          formData.project = data[0].project;
          formData.projectName = data[0].projectName;
          formData.supplierName = data[0].supplierName;
          formData.supplier = data[0].supplierId;
          formData.priority = data[0].priority;
          formData.productionClass = data[0].productionClass;
          formData.model = data[0].headModel;
          formData.maker = data[0].maker;
          formData.packagebRequirement = data[0].packagebRequirement;
          formData.delivery = data[0].delivery;
          formData.paymentTerms = data[0].paymentTerms;
          formData.warrantyPeriod = data[0].warrantyPeriod;
          formData.warrantyTerms = data[0].warrantyTerms;
          formData.isExport = data[0].isExport;
          formData.exchangeRate = data[0].exchangeRateGys;
          formData.currency = data[0].currencyGys;
          formData.tradeTerms = data[0].deliveryTerms;
          formData.attachs = data[0].attachs;
          formData.notes = data[0].notes;
          getShipList(data[0].headId, 'contract');
        }
      }
      function addFromQuotation(data) {
        data.map((item) => {
          item.fatherModel = item.model;
          item.model = item.childModel;
          item.sourceId = item.childId;
          item.sourceType = 'Quo' + item.childId;
          item.sourceCode = item.billCode;
        });
        var arrProduct = data.concat(purOrderFormShipFormProductTable.dataSource);
        purOrderFormShipFormProductTable.dataSource = arrProduct;
        notAllowEdit.value = true;
        formData.sourceCode = data[0].billCode;
        if (formData.sourceCode2 == '') {
          formData.project = data[0].inquiryProject;
          formData.projectName = data[0].projectName;
          formData.supplier = data[0].selectionSupplier;
          formData.supplierName = data[0].selectionSupplier_dictText;
          formData.priority = data[0].priority;
          formData.productionClass = data[0].productionClass;
          formData.model = data[0].fatherModel;
          formData.maker = data[0].maker;
          formData.exchangeRate = data[0].exchangeRateUsd;
          formData.currency = data[0].currency;
          getShipList(data[0].headId, 'quotation');
        }
      }
      //选择供应商报价单选定
      function SelectSupplierQuotationList() {
        SelectSupplierQuotationRef.value.getTable(formData, 'purOrder');
      }
      function addProject(data) {
        if (data.lenght == 0) {
          formData.projectName = '';
          formData.projectName = '';
        } else {
          formData.project = data[0].id;
          formData.projectName = data[0].code;
        }
      }
      //查看配件信息
      function viewAccessory(prop) {
        BaseShipArchiveAccessoriesModalRef.value.getTable(prop.row);
      }
      //产品明细-删除行
      function handleDelete(prop) {
        var xTable = purOrderFormShipFormProductTableRef.value!.getXTable();
        var newArray = [...xTable.data];
        newArray.splice(prop.rowIndex, 1);
        purOrderFormShipFormProductTable.dataSource = newArray;
        if (purOrderFormShipFormProductTable.dataSource.length !== 0) {
          var arrQuo = [],
            arrCon = [];
          purOrderFormShipFormProductTable.dataSource.map((item) => {
            var sign = '';
            sign = item.sourceType ? item.sourceType.substring(0, 3) : '';
            if (item.sourceType && sign == 'Quo') {
              arrQuo.push(item.sourceType);
            } else if (item.sourceType && sign == 'Con') {
              arrCon.push(item.sourceType);
            }
          });
          if (arrQuo.length == 0 && arrCon.length == 0) {
            formData.sourceCode2 = '';
            formData.sourceCode = '';
            notAllowEdit.value = false;
          } else if (arrQuo.length == 0) {
            formData.sourceCode = '';
          } else if (arrCon.length == 0) {
            formData.sourceCode2 = '';
          }
        } else {
          notAllowEdit.value = false;
          formData.sourceCode2 = '';
          formData.sourceCode = '';
        }
      }

      // 选择销售订单
      function selectSaleOrderList() {
        SelectSaleOrderModalRef.value.getTable(formData, 'purOrder');
      }
      function selectVirtualProducts() {
        SelectPrpductModalRef.value.getTableVirtual();
      }
      function changeValues(prop) {
        if (prop.col.key == 'quantity') {
          if (prop.row.quantity==0||prop.row.quantity) {
            var num = prop.row.quantity * Number(prop.row.taxPrice);
            prop.row.taxAmount = isNaN(num) ? '' : num.toFixed(2);
            purOrderFormShipFormProductTable.dataSource[prop.rowIndex].taxAmount = Number(prop.row.taxAmount);
          }
        }
        if (prop.col.key == 'taxPrice') {
          if (prop.row.taxPrice) {
            var num = prop.row.quantity * Number(prop.row.taxPrice);
            prop.row.taxAmount = isNaN(num) ? '' : num.toFixed(2);
            purOrderFormShipFormProductTable.dataSource[prop.rowIndex].taxAmount = Number(prop.row.taxAmount);
          }
        }
      }
      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }

      // 折扣改变
      const discountHeadChange = (event) => {
        if (formData.totalAmount) {
          getDiscountAmount();
        }
      };
      // 计算折扣金额
      const getDiscountAmount = () => {
        formData.discountAmount = Number((formData.totalAmount * (1 - formData.discountHead / 100)).toFixed(2));
      };
      // 监听 count 的变化
      watch(
        purOrderFormShipFormProductTable,
        (newValue, oldValue) => {
          let data = newValue.dataSource;
          let total = 0;
          data.map((item) => {
            total += item.taxAmount;
          });
          formData.totalAmount = total;
          getDiscountAmount();
          if (data.length < 1) {
            formData.discountHead = 0;
            formData.discountAmount = '';
          }
        },
        { deep: true }
      );

      return {
        discountHeadChange,
        PurOrderFormShipFormShipTableRef,
        PurOrderFormShipFormShipTable,
        purOrderFormShipFormProductTableRef,
        purOrderFormShipFormProductTable,
        SelectSaleOrderModalRef,
        SelectSupplierQuotationRef,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        copy,
        formRef,
        SelectPrpductModalRef,
        addProduct,
        onSearchProject,
        SelectProjectModalRef,
        addProject,
        handleDelete,
        BaseShipArchiveAccessoriesModalRef,
        viewAccessory,
        VersionDetail,
        notAllowEdit,
        selectSaleOrderList,
        addFormSaleOrder,
        ClassList,
        supplierOption,
        selectVirtualProducts,
        changeValues,
        SelectSupplierQuotationList,
        addFromQuotation,
      };
    },
  });
</script>
<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
  // /deep/.vxe-table--body-wrapper{
  //   height: 100% !important;
  // }
  /deep/.ant-modal-body {
    padding: 24px !important;
  }

  /deep/.ant-form-item {
    margin-bottom: 8px !important;
  }
  /deep/.vxe-cell--valid-error-msg {
    color: white !important;
    background-color: white !important;
  }
</style>
