<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form v-bind="formItemLayout" name="quotationFormForm" ref="formRef">
          <a-row>
            <a-col :span="12">
              <a-form-item
                label="报价单号(bill code)"
                v-bind="validateInfos.billCode"
                id="quotationFormForm-billCode"
                name="billCode"
                :labelCol="formItemLayout.labelCol1"
                :wrapperCol="formItemLayout.wrapperCol1"
              >
                <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="quotationFormForm-billDate" name="billDate">
                <a-date-picker
                  placeholder="请选择单据日期(bill date)"
                  v-model:value="formData.billDate"
                  value-format="YYYY-MM-DD"
                  disabled
                  style="width: 100%"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item  label="报价项目(quotation project)"     v-bind="validateInfos.quotationProjectName"  id="quotationFormForm-quotationProjectName"    name="quotationProjectName">
                <a-input-search
                  v-model:value="formData.quotationProjectName"
                  readonly
                  placeholder="请输入报价项目(inquiry project)"
                  allow-clear
                  enter-button="Search"
                  :disabled="notAllowEdit"
                  @search="onSearchProject"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="报价客户(quotation customer)"
                v-bind="validateInfos.quotationCustomer"
                id="quotationFormForm-quotationCustomer"
                name="quotationCustomer"
                :labelCol="formItemLayout.labelCol1"
                :wrapperCol="formItemLayout.wrapperCol1"
              >
                <JSelectInput v-model:value="formData.quotationCustomer" placeholder="请选择" :options="customerOption" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="报价有效期(quotation period)"
                v-bind="validateInfos.quotationPeriod"
                id="quotationFormForm-quotationPeriod"
                name="quotationPeriod"
              >
                <a-range-picker
                  v-model:value="quotationPeriod"
                  :format="['YYYY-MM-DD', 'YYYY-MM-DD']"
                  @change="onChangequotationPeriod"
                  style="width: 100%"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
							<a-form-item label="客户联系人(inquiry platform)" v-bind="validateInfos.inquiryPlatform" id="SaleInquiryFormForm-inquiryPlatform" name="inquiryPlatform">
                <a-select  v-model:value="formData.liaisonId" labelInValue @change="onChangeLiaison" allowClear>
                    <a-select-option v-for="item in linkOption" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
                </a-select>
							</a-form-item>
						</a-col>
            <a-col :span="12">
              <a-form-item label="优先级(priority)" v-bind="validateInfos.priority" id="quotationFormForm-priority" name="priority">
                <JDictSelectTag v-model:value="formData.priority" placeholder="请选择" dictCode="priority" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="产品分类(production class)"
                v-bind="validateInfos.productionClass"
                id="quotationFormForm-productionClass"
                name="productionClass"
                :labelCol="formItemLayout.labelCol1"
                :wrapperCol="formItemLayout.wrapperCol1"
              >
                <JDictSelectTag
                  v-model:value="formData.productionClass"
                  placeholder=""
                  dictCode="base_product_class,name,id,del_flag=0 and parent_id is null"
                  page="false"
                  showSearch
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="机型(model)" v-bind="validateInfos.model" id="quotationFormForm-model" name="model">
                <JSelectMultiple v-model:value="formData.model" placeholder="请选择" dictCode="model_typer" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="厂家(maker)"
                v-bind="validateInfos.maker"
                id="quotationFormForm-maker"
                name="maker"
                :labelCol="formItemLayout.labelCol1"
                :wrapperCol="formItemLayout.wrapperCol1"
              >
                <JDictSelectTag v-model:value="formData.maker" placeholder="请选择" dictCode="factory" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="币种(currency)"
                v-bind="validateInfos.currency"
                id="quotationFormForm-currency"
                name="currency"
                :labelCol="formItemLayout.labelCol1"
                :wrapperCol="formItemLayout.wrapperCol1"
              >
                <JDictSelectTag v-model:value="formData.currency" placeholder="请选择" dictCode="currency" @select="changeExchangeRate" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="汇率(exchangeRate)" v-bind="validateInfos.exchangeRate" id="quotationFormForm-exchangeRate" name="exchangeRate">
                <a-input-number
                  v-model:value="formData.exchangeRate"
                  placeholder="请输入"
                  allow-clear
                  AutoComplete="off"
                  @change="changeDiscountOrExchangeRate"
                  suffix="%"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="贸易方式(delivery terms)"
                v-bind="validateInfos.deliveryTerms"
                id="quotationFormForm-deliveryTerms"
                name="deliveryTerms"
                :labelCol="formItemLayout.labelCol1"
                :wrapperCol="formItemLayout.wrapperCol1"
              >
                <JDictSelectTag v-model:value="formData.deliveryTerms" placeholder="请选择" dictCode="delivery_terms" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="交期(delivery time)"
                v-bind="validateInfos.deliveryDayHead"
                id="quotationFormForm-deliveryDayHead"
                name="deliveryDayHead"
              >
                <a-input-number
                  placeholder=""
                  v-model:value="formData.deliveryDayHead"
                  @change="changeDelivertTime"
                  style="width: 100%"
                  allow-clear
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="付款条件(payment terms)"
                v-bind="validateInfos.paymentTerms"
                id="quotationFormForm-paymentTerms"
                name="paymentTerms"
                :labelCol="formItemLayout.labelCol1"
                :wrapperCol="formItemLayout.wrapperCol1"
              >
                <JDictSelectTag v-model:value="formData.paymentTerms" placeholder="请选择" dictCode="payment_terms" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="交货地点(place of delivery)"
                v-bind="validateInfos.placeDelivery"
                id="quotationFormForm-placeDelivery"
                name="placeDelivery"
              >
                <a-input v-model:value="formData.placeDelivery" placeholder="请输入交货地点(place of delivery)" allow-clear AutoComplete="off" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="毛利率(grossMargin)"
                v-bind="validateInfos.grossMarginHead"
                id="quotationFormForm-grossMarginHead"
                name="grossMarginHead"
              >
                <a-input v-model:value="formData.grossMarginHead" placeholder="" allow-clear AutoComplete="off" disabled/>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="客户折扣(custumer discount)"
                v-bind="validateInfos.custumerDiscount"
                id="quotationFormForm-custumerDiscount"
                name="custumerDiscount"
                :labelCol="formItemLayout.labelCol1"
                :wrapperCol="formItemLayout.wrapperCol1"
              >
                <a-input
                  v-model:value="formData.custumerDiscount"
                  placeholder="请输入客户折扣(custumer discount)"
                  allow-clear
                  AutoComplete="off"
                  @change="changeDiscountOrExchangeRate"
                  suffix="%"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="销售部门(sale department)"
                v-bind="validateInfos.saleDepartment"
                id="SaleInquiryFormForm-saleDepartment"
                name="saleDepartment"
              >
                <a-input v-model:value="formData.saleDepartmentName" placeholder="" allow-clear disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="包装方式(packaging method)"
                v-bind="validateInfos.packagingMethod"
                id="quotationFormForm-packagingMethod"
                name="packagingMethod"
                :labelCol="formItemLayout.labelCol1"
                :wrapperCol="formItemLayout.wrapperCol1"
              >
                <a-input v-model:value="formData.packagingMethod" placeholder="请输入包装方式(packaging method)" allow-clear AutoComplete="off" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="业务员(salesman)" v-bind="validateInfos.salesman" id="quotationFormForm-salesman" name="salesman">
                <a-input v-model:value="formData.salesmanName" placeholder="" allow-clear disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="报价备注(quotation notes)"
                v-bind="validateInfos.quotationNotes"
                id="quotationFormForm-quotationNotes"
                name="quotationNotes"
                :labelCol="formItemLayout.labelCol1"
                :wrapperCol="formItemLayout.wrapperCol1"
              >
                <a-input v-model:value="formData.quotationNotes" placeholder="请输入报价备注(quotation notes)" allow-clear 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"
                :labelCol="formItemLayout.labelCol1"
                :wrapperCol="formItemLayout.wrapperCol1"
              >
                <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="供应商技术资料(supplier quotation attachs)"
                v-bind="validateInfos.supplierAttachs"
                id="quotationFormForm-supplierAttachs"
                name="supplierAttachs"
                :labelCol="formItemLayout.labelCol1"
                :wrapperCol="formItemLayout.wrapperCol1"
              >
                <a :href="baseUrl + formData.supplierAttachs" v-if="formData.supplierAttachs">{{ formData.supplierAttachs }}</a>
                <a-input v-model:value="formData.supplierAttachs" disabled v-if="!formData.supplierAttachs" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="附件(attachs)" v-bind="validateInfos.attachs" id="quotationFormForm-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="saleQuotationFormProduct" :forceRender="true">
        <a-button type="primary" @click="selectProducts" style="margin-right: 1%; margin-bottom: 1%"> 选择产品(select product)</a-button>
        <a-button type="primary" @click="chooseSupplier"> 选择供应商报价选定(select supplier quotation selection)</a-button>
        <a-button type="primary" @click="setSonList" style="margin-left: 1%; margin-bottom: 1%"> 配置毛利率(Configure gross margin)</a-button>
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="saleQuotationFormProductTableRef"
          :loading="saleQuotationFormProductTable.loading"
          :columns="saleQuotationFormProductTable.columns"
          :dataSource="saleQuotationFormProductTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          asyncRemove
          @value-change="changeValues"
        >
          <template #lastPrice="props">
            <a @click="viewHistory">{{ props.row.lastPrice }}</a>
          </template>
          <template #action="props">
            <a-popconfirm title="确定删除吗？" @confirm="handleDelete1(props)">
              <a>删除(delete)</a>
            </a-popconfirm>
          </template>
        </j-vxe-table>
      </a-tab-pane>
      <a-tab-pane tab="销售报价单 - 船明细(ship details)" key="saleQuotationFormShip" :forceRender="true">
        <a-button type="primary" @click="selectShip"> 选择船(select ship)</a-button>
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="saleQuotationFormShipTableRef"
          :loading="saleQuotationFormShipTable.loading"
          :columns="saleQuotationFormShipTable.columns"
          :dataSource="saleQuotationFormShipTable.dataSource"
          :maxHeight="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
        >
          <template #action="props">
            <a @click="viewAccessory(props)">查看配件信息(view accessory information)</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定删除吗？" @confirm="handleDelete(props)">
              <a>删除(delete)</a>
            </a-popconfirm>
          </template>
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
    <SelectShipSModal ref="SelectShipSModalRef" @select="addShip" />
    <BaseShipArchiveAccessoriesModal ref="BaseShipArchiveAccessoriesListRef" />
    <SelectPrpductModal ref="SelectPrpductModalRef" @select-product="addProduct" />
    <SelectProjectModal ref="SelectProjectModalRef" @select-project="addProject" />
    <ViewHistoryQuotationModal ref="ViewHistoryQuotationModalRef" />
    <SelectSupplierQuotation ref="SelectSupplierQuotationRef" @select-supplier-quatation-confirm="addProductFromSupplier" />
    <SetSonList ref="SetSonListRef" @success="setSonListFiled"></SetSonList>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import {
    querysaleQuotationFormShipListByMainId,
    querysaleVersonFormShipListByMainId,
    querySaleQuotationFormProductListByMainId,
    querySaleVersonProductListByMainId,
    queryDataById,
    saveOrUpdate,
    HistoryQuotation,
    queryVersonHistoryById,
    queryRate,
    LinkOption
  } from '../quotationForm.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import { saleQuotationFormShipColumns, saleQuotationFormProductColumns } from '../quotationForm.data';
  import SelectShipSModal from '../../../publicComponents/SelectShipSModal.vue';
  import SetSonList from './SetSonList.vue';
  import BaseShipArchiveAccessoriesModal from '../../../publicComponents/BaseShipArchiveAccessoriesModal.vue';
  import SelectPrpductModal from '../../../publicComponents/SelectPrpductModal.vue';
  import SelectProjectModal from '../../../publicComponents/SelectProjectModal.vue';
  import SelectSupplierQuotation from '../../../publicComponents/SelectSupplierQuotation.vue';
  import ViewHistoryQuotationModal from './ViewHistoryQuotationModal.vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { JDictSelectTag, JSelectMultiple } from '/@/components/Form';
  import JSelectInput from '/@/components/Form/src/jeecg/components/JSelectInput.vue';
  import { Form, message } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import dayjs from 'dayjs';
  import { useGlobSetting } from '/@/hooks/setting';
  const { domainUrl } = useGlobSetting();
  const userStore = useUserStore();
  const useForm = Form.useForm;
  export default defineComponent({
    name: 'QuotationFormForm',
    components: {
      JVxeTable,
      JFormContainer,
      SelectShipSModal,
      BaseShipArchiveAccessoriesModal,
      SelectPrpductModal,
      JUpload,
      SelectProjectModal,
      SelectSupplierQuotation,
      ViewHistoryQuotationModal,
      JDictSelectTag,
      JSelectInput,
      JSelectMultiple,
      SetSonList,
      
    },
    props: {
      formDisabled: {
        type: Boolean,
        default: false,
      },
      formData: { type: Object, default: () => {} },
      formBpm: { type: Boolean, default: true },
    },
    emits: ['success'],
    setup(props, { emit }) {
      const baseUrl = domainUrl + '/sys/common/static/';
      const loading = ref(false);
      const formRef = ref();
      var linkOption = ref([]);
      var SetSonListRef = ref();
      var SelectPrpductModalRef = ref();
      var SelectProjectModalRef = ref();
      var ViewHistoryQuotationModalRef = ref();
      var SelectSupplierQuotationRef = ref();
      var quotationPeriod = ref([]);
      const saleQuotationFormShipTableRef = ref();
      const saleQuotationFormShipTable = reactive<Record<string, any>>({
        loading: false,
        columns: saleQuotationFormShipColumns,
        dataSource: [],
      });
      const saleQuotationFormProductTableRef = ref();
      const saleQuotationFormProductTable = reactive<Record<string, any>>({
        loading: false,
        columns: saleQuotationFormProductColumns,
        dataSource: [],
      });
      var SelectShipSModalRef = ref();
      var BaseShipArchiveAccessoriesListRef = ref();
      const activeKey = ref('saleQuotationFormProduct');
      var notAllowEdit = ref(false);
      var classOption = ref([]);
      var customerOption = ref([]);
      const formData = reactive<Record<string, any>>({
        id: '',
        status: undefined,
        delFlag: undefined,
        otherStatus: '',
        billDate: dayjs(new Date()).format('YYYY-MM-DD'),
        billCode: '',
        quotationProject: '',
        quotationProjectName: '',
        quotationCustomer: '',
        quotationCustomerName: '',
        quotationPeriodBegin: '',
        quotationPeriodEnd: '',
        busynessType: '',
        priority: '',
        productionClass: '',
        model: '',
        maker: '',
        currency: '',
        deliveryTerms: '',
        deliveryDayHead: '',
        paymentTerms: '',
        placeDelivery: '',
        custumerDiscount: '',
        saleDepartment: '',
        saleDepartmentName: '',
        packagingMethod: '',
        salesman: '',
        salesmanName: '',
        quotationNotes: '',
        attachs: '',
        supplierAttachs: '',
        sourceCode: '',
        exchangeRate: '',
        agreementTerms: '',
        grossMarginHead:'',
        liaisonId : '',
        liaisonInfo : '',
      });

      //表单验证
      const validatorRules = reactive({
        quotationProjectName: [{ required: true, message: '请选择报价项目(select project)' }],
        quotationCustomer: [{ required: true, message: '请选择报价客户(select customer)' }],
        currency: [{ required: true, message: '请选择币种(select currency)' }],
        model: [{ required: true, message: '请选择机型(model)' }],
        deliveryTerms: [{ required: true, message: '请选择贸易方式(delivery terms)' }],
        deliveryDayHead: [{ required: true, message: '请选择交期(deliveryDayHead)' }],
      });
      const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
      const dbData = {};
      const formItemLayout = {
        labelCol: { xs: { span: 24 }, sm: { span: 8 } },
        wrapperCol: { xs: { span: 24 }, sm: { span: 13 } },
        labelCol1: { xs: { span: 24 }, sm: { span: 8 } },
        wrapperCol1: { xs: { span: 24 }, sm: { span: 13 } },
      };

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

      //新增方法
      function add() {
        resetFields();
        saleQuotationFormShipTable.dataSource = [];
        saleQuotationFormProductTable.dataSource = [];
        activeKey.value = 'saleQuotationFormProduct';
        getOptiom();
        getCustomerOptions();
        quotationPeriod.value = [];
        formData.salesman = userStore.getUserInfo.username;
        formData.salesmanName = userStore.getUserInfo.realname;
        formData.saleDepartment = userStore.getUserInfo.orgCode;
        formData.saleDepartmentName = userStore.getUserInfo.orgName;
        notAllowEdit.value = false;
        linkOption.value = []
      }
      async function changeExchangeRate() {
        if (formData.currency !== '美元') {
          var param = {
            month: dayjs(new Date()).month() + 1,
            year: dayjs(new Date()).year(),
            currency: formData.currency,
          };
          var info = await queryRate(param);
          formData.exchangeRate = info;
        } else {
          formData.exchangeRate = 1;
        }
        await changeDiscountOrExchangeRate();
      }
      //编辑方法
      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const saleQuotationFormShipDataList = await querysaleQuotationFormShipListByMainId(row['id']);
        saleQuotationFormShipTable.dataSource = [...saleQuotationFormShipDataList];
        const saleQuotationFormProductDataList = await querySaleQuotationFormProductListByMainId(row['id']);
        saleQuotationFormProductTable.dataSource = [...saleQuotationFormProductDataList];
        getOptiom();
        getCustomerOptions();
        quotationPeriod.value[0] = formData.quotationPeriodBegin ? dayjs(formData.quotationPeriodBegin,'YYYY/MM/DD') : '';
        quotationPeriod.value[1] = formData.quotationPeriodEnd ? dayjs(formData.quotationPeriodEnd,'YYYY/MM/DD') : '';
        notAllowEdit.value = true;
        getLinkOptionsArr(formData.quotationCustomer)
      }
      //获取主表
      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);
      }

      const { getSubFormAndTableData, transformData } = useValidateAntFormAndTable(activeKey, {
        saleQuotationShip: saleQuotationFormShipTableRef,
        saleQuotationProduct: saleQuotationFormProductTableRef,
      });
      //获取表单信息
      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() {
        const xTable = saleQuotationFormProductTableRef.value!.getXTable()
        if (xTable.data.length==0) {
          message.warning('请添加明细');
        } else {
          saleQuotationFormProductTableRef.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.status == '1' ? true : false;
              await saveOrUpdate(values, isUpdate, isRevise);
              //关闭弹窗
              emit('success');
            }
          });
        }
      }

      function setFieldsValue(values) {
        if (values) {
          Object.keys(values).map((k) => {
            formData[k] = values[k];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }
      //传明细-删除行
      async function handleDelete(prop) {
        var xTable = saleQuotationFormShipTableRef.value!.getXTable();
        var newArray = [...xTable.data];
        newArray.splice(prop.rowIndex, 1);
        saleQuotationFormShipTable.dataSource = newArray;
      }
      //产品明细-删除行
      async function handleDelete1(prop) {
        var xTable = saleQuotationFormProductTableRef.value!.getXTable();
        var newArray = [...xTable.data];
        newArray.splice(prop.rowIndex, 1);
        saleQuotationFormProductTable.dataSource = newArray;
        if (saleQuotationFormProductTable.dataSource.length !== 0) {
          var arr = [];
          saleQuotationFormProductTable.dataSource.map((item) => {
            if (item.sourceId) {
              arr.push(item.sourceId);
            }
          });
          if (arr.length == 0) {
            formData.sourceCode = '';
            notAllowEdit.value = false;
          }
        } else {
          formData.sourceCode = '';
          notAllowEdit.value = false;
          add();
        }
      }
      //查询船
      function selectShip() {
        SelectShipSModalRef.value.getTable();
      }
      //增行-船明细
      function addShip(data) {
        data.map((item) => {
          item.shipowner = item.relateCustomer;
          item.shipId = item.id;
          item.id=undefined;
        });
        var xTable = saleQuotationFormShipTableRef.value!.getXTable();
        var arr = xTable.data.concat(data);
        saleQuotationFormShipTable.dataSource = arr;
      }
      //增行-产品明细
      async function addProduct(data) {
        for (const item of data) {
          item.productClass = item.classId_dictText;
          item.productCode = item.code;
          // item.unit = item.measurementUnit
          item.deliveryDayChild = formData.deliveryDayHead;
          item.productId = item.id;
          var obj = await getRowRate(item);
          item.taxRate = obj.rateNumber;
          item.grossMargin = obj.grossMargin;
          item.discount = formData.custumerDiscount;
          item.id = undefined;
          item.notes=''
        }
        var xTable = saleQuotationFormProductTableRef.value!.getXTable();
        var arrProduct = xTable.data.concat(data);
        saleQuotationFormProductTable.dataSource = arrProduct;
      }
      //选择项目
      function addProject(data) {
        if (data.length == 0) {
          formData.quotationProject = formData.quotationProjectName = '';
        } else {
          formData.quotationProject = data[0].id;
          formData.quotationProjectName = data[0].code;
          formData.quotationCustomer = data[0].customerId;
          formData.quotationCustomerName = data[0].customerId_dictText;
          formData.custumerDiscount == data[0].discount;
          formData.currency = '美元';
          formData.exchangeRate = '1';
          customerOption.value.map((item) => {
            if (item.value == data[0].customerId) {
              formData.priority = item.priority;
              formData.custumerDiscount = item.discount;
              formData.paymentTerms = item.paymentTerms;
              formData.currency = item.currency;              
            }
          });
          if (saleQuotationFormProductTable.dataSource.length > 0) {
            var xTable = saleQuotationFormProductTableRef.value!.getXTable();
            var newArr = [...xTable.data];
            newArr.map((item) => {
              item.discount = formData.custumerDiscount;
            });
            saleQuotationFormProductTable.dataSource = newArr;
          }
          changeExchangeRate()
          getLinkOptionsArr(formData.quotationCustomer)
        }
      }
      //获取客户列表
      function getCustomerOptions() {
        let params = { pageSize: '-1', status: 1 };
        defHttp.get({ url: '/cuspCode/cuspCustomerProfile/list', params }, { isTransformResponse: false }).then((res) => {
          if (res) {
            customerOption.value = [];
            res.result.records.forEach((item) => {
              customerOption.value.push({
                label: item.name,
                value: item.id,
                priority: item.priority,
                intermediatorCommission: item.intermediatorCommission,
                commission: item.commission,
                discount: item.discount,
                paymentTerms: item.paymentTerms,
                currency: item.currency,
              });
            });
          }
        });
      }
      //查看配件信息
      function viewAccessory(prop) {
        BaseShipArchiveAccessoriesListRef.value.getTable(prop.row);
      }
      //选择产品
      function selectProducts() {
        SelectPrpductModalRef.value.getTable();
      }
      //选择供应商报价单
      function chooseSupplier() {
        SelectSupplierQuotationRef.value.getTable(formData);
      }
      //选择项目
      function onSearchProject() {
        SelectProjectModalRef.value.getTable();
      }
      //获取产品分类下拉框
      function getOptiom() {
        defHttp
          .get({ url: 'baseCode/baseProductClass/list' }, { isTransformResponse: false })
          .then((res) => {
            if (res.success) {
              classOption.value = [];
              res.result.records.forEach((element) => {
                var obj = {
                  label: element.name ? element.name : '无名称请维护',
                  value: element.id ? element.id : '',
                  taxRate: element.taxRate ? element.taxRate : 0,
                  grossMargin: element.grossMargin ? element.grossMargin : 0,
                };
                classOption.value.push(obj);
              });
            }
          })
          .finally(() => {
            // loading.value = false;
          });
      }
      //修改报价有效期
      function onChangequotationPeriod(data) {
        quotationPeriod.value = data;
        formData.quotationPeriodBegin = data[0].format('YYYY-MM-DD');
        formData.quotationPeriodEnd = data[1].format('YYYY-MM-DD');
      }
      //修改主表交期
      function changeDelivertTime() {
        if (saleQuotationFormProductTable.dataSource.length > 0) {
          var xTable = saleQuotationFormProductTableRef.value!.getXTable();
          var newArr = [...xTable.data];
          newArr.map((item) => {
            item.deliveryDayChild = formData.deliveryDayHead;
          });
          saleQuotationFormProductTable.dataSource = newArr;
        }
      }
      //查看上次报价
      function viewHistory() {
        ViewHistoryQuotationModalRef.value.getTable();
      }
      //查看版本详情
      async function VersionDetail(record) {
        //主表数据
        await queryVersonHistoryData(record.id);
        //子表数据
        const saleQuotationFormShipDataList = await querysaleVersonFormShipListByMainId(record.id);
        saleQuotationFormShipTable.dataSource = [...saleQuotationFormShipDataList];
        const saleQuotationFormProductDataList = await querySaleVersonProductListByMainId(record.id);
        saleQuotationFormProductTable.dataSource = [...saleQuotationFormProductDataList];
        getOptiom();
        getCustomerOptions();
        quotationPeriod.value[0] = formData.quotationPeriodBegin ? dayjs(formData.quotationPeriodBegin,'YYYY/MM/DD') : '';
        quotationPeriod.value[1] = formData.quotationPeriodEnd ? dayjs(formData.quotationPeriodEnd,'YYYY/MM/DD') : '';
      }
      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);
      }
      //新增行-产品明细-选择供应商报价单
      async function addProductFromSupplier(data) {
        //查询客户名称
        var obj = await SelectProjectModalRef.value.getCustom(data[0].inquiryProject);
        formData.quotationCustomer = obj.length == 0 ? '' : obj[0].customerId;
        formData.quotationCustomerName = obj.length == 0 ? '' : obj[0].customerId_dictText;
        for (const item of data) {
          var obj = await getRowRate(item);
          item.taxRate = obj.rateNumber;
          item.grossMargin = obj.grossMargin;
          item.productClass = item.productClass;
          item.productCode = item.productCode;
          item.sourceId = item.childId;
          item.id = undefined
          item.fatherModel = item.model;
          item.model = item.childModel;
          item.deliveryTime = formData.deliveryTime;
          item.supplierCurrency = item.currency;
          item.supplierId = item.selectionSupplier;
          item.supplierName = item.selectionSupplier_dictText;
          item.purchasePrice = item.taxPriceUsd;
          item.taxAmount = 0;
          item.currencyGys = item.currency;
          item.exchangeRateGys = item.exchangeRateUsd;
          item.taxPriceGys = item.taxPrice;
          item.notes=''
          item.purchaseAmount=(Number(item.quantity) * Number(item.purchasePrice)).toFixed(2)
        }
        var xTable = saleQuotationFormProductTableRef.value!.getXTable();
        var arrProduct = xTable.data.concat(data);
        arrProduct.map((item) => {
          customerOption.value.map((event) => {
            if (event.value == formData.quotationCustomer) {
              (item.intermediatorCommission = event.intermediatorCommission), (item.customerCommision = event.commission);
              formData.custumerDiscount = event.discoun;
              item.discount = event.discount;
              formData.paymentTerms = event.paymentTerms;
              formData.currency = event.currency;
            }
          });
        });
        saleQuotationFormProductTable.dataSource = arrProduct;
        notAllowEdit.value = true;
        formData.quotationProject = data[0].inquiryProject;
        formData.quotationProjectName = data[0].projectName;
        formData.sourceCode = data[0].billCode;
        formData.priority = data[0].priority;
        formData.model = data[0].fatherModel;
        formData.maker = data[0].maker;
        formData.productionClass = data[0].productionClass;
        formData.deliveryDayHead = data[0].deliveryDayChild;
        // formData.currency = '美元';
        // formData.exchangeRate = '1';
        await getShipList(data[0].headId);
        await getLinkOptionsArr(formData.quotationCustomer)
        await changeExchangeRate()
        // countGrossMargin()
        // await changeDiscountOrExchangeRate()
      }
      function getShipList(id) {
        let params = { id: id };
        defHttp.get({ url: '/purCode/purQuotationSelection/queryPurQuotationSelectionShipByMainId', params }, { isTransformResponse: false }).then((res) => {
          if (res) {
            saleQuotationFormShipTable.dataSource = res.result;
          }
        });
      }
      async function getRowRate(row) {
        var obj = {
          rateNumber: 0,
          grossMargin: 0,
        };
        let params = { pageSize: '-1', status: 1, code: row.productCode };
        await defHttp.get({ url: '/baseCode/baseProductArchive/list', params }, { isTransformResponse: false }).then((res) => {
          if (res) {
            if (res.result.records[0].taxRate && res.result.records[0].taxRate !== '') {
              obj.rateNumber = res.result.records[0].taxRate;
            } else {
              classOption.value.map((event) => {
                if (event.label == row.productClass) {
                  obj.rateNumber = event.taxRate;
                }
              });
            }
            classOption.value.map((event) => {
              if (event.label == row.productClass) {
                obj.grossMargin = event.grossMargin;
              }
            });
          }
        });
        return obj;
      }
      function changeValues(prop) {
        //设置 默认值
        formData.exchangeRate = formData.exchangeRate == '' || formData.exchangeRate === null ? 1 : formData.exchangeRate;
        prop.row.customerCommision = prop.row.customerCommision == '' || prop.row.customerCommision === null || !prop.row.customerCommision ? 0 : prop.row.customerCommision;
        prop.row.discount = prop.row.discount == '' || prop.row.discount === null || !prop.row.discount ? 0 : prop.row.discount;
        prop.row.tariff = prop.row.tariff == '' || prop.row.tariff === null || !prop.row.tariff ? 0 : prop.row.tariff;
        prop.row.intermediatorCommission =prop.row.intermediatorCommission == '' || prop.row.intermediatorCommission === null || !prop.row.intermediatorCommission? 0: prop.row.intermediatorCommission;
        //计算销售单价
        if (prop.col.key == 'purchasePrice' || prop.col.key == 'taxRate' || prop.col.key == 'tariff' || prop.col.key == 'discount' || prop.col.key == 'grossMargin' || prop.col.key == 'customerCommision' || prop.col.key == 'intermediatorCommission') {
          // var num =((prop.row.purchasePrice / Number(formData.exchangeRate)) *(1 + prop.row.taxRate / 100) *(1 + prop.row.tariff / 100) *(1 - prop.row.discount / 100)) /(1 - prop.row.grossMargin / 100 - prop.row.customerCommision / 100 - prop.row.intermediatorCommission / 100);
          var num=(prop.row.purchasePrice * Number(formData.exchangeRate)*(1 + prop.row.tariff / 100))/(1 - prop.row.grossMargin / 100 - prop.row.customerCommision / 100)*(1 + prop.row.taxRate / 100)/(1 - prop.row.discount / 100)
          prop.row.salePrice = !isNaN(num) ? num.toFixed(2) : '';
          if (prop.row.quantity) {
            prop.row.taxAmount = (prop.row.salePrice * prop.row.quantity).toFixed(2); //计算金额
            prop.row.purchaseAmount = (prop.row.purchasePrice * prop.row.quantity).toFixed(2);  //计算采购金额
          }
        }
        //计算金额
        if (prop.col.key == 'quantity'&& prop.row.salePrice && prop.row.quantity) {
          prop.row.taxAmount = (prop.row.salePrice * prop.row.quantity).toFixed(2);
        }
        //计算采购金额
        if (prop.col.key == 'quantity' && prop.row.quantity&& prop.row.purchasePrice) {
          prop.row.purchaseAmount = (prop.row.purchasePrice * prop.row.quantity).toFixed(2);
        }
        //计算毛利率/金额
        if (prop.col.key == 'salePrice') {
          // var num =1 - prop.row.customerCommision / 100 - prop.row.intermediatorCommission / 100-((prop.row.purchasePrice / Number(formData.exchangeRate)) *(1 + prop.row.taxRate / 100) *(1 + prop.row.tariff / 100) *(1 - prop.row.discount / 100)) /prop.row.salePrice;
          var num = 1-(prop.row.customerCommision / 100)-(prop.row.purchasePrice*Number(formData.exchangeRate)*(1 + prop.row.tariff / 100))/(prop.row.salePrice/((1 + prop.row.taxRate / 100)/(1 - prop.row.discount / 100)))
          num = (Number(num) * 100).toFixed(2);
          prop.row.grossMargin = !isNaN(num) ? num : '';
          if (prop.row.quantity) {
            prop.row.taxAmount = (prop.row.salePrice * prop.row.quantity).toFixed(2);
          }
        }
        countGrossMargin()
      }
      function changeDiscountOrExchangeRate() {
        var xTable = saleQuotationFormProductTableRef.value!.getXTable();
        var newArr = [...xTable.data];
        if (newArr.length > 0) {
          formData.exchangeRate = formData.exchangeRate == '' || formData.exchangeRate === null || !formData.exchangeRate ? 1 : formData.exchangeRate;
          newArr.map((item) => {
            item.discount = formData.custumerDiscount == '' || formData.custumerDiscount === null || !formData.custumerDiscount ? 0 : formData.custumerDiscount;
            item.tariff = item.tariff == '' || item.tariff === null || !item.tariff ? 0 : item.tariff;
            item.customerCommision = item.customerCommision == '' || item.customerCommision === null || !item.customerCommision ? 0 : item.customerCommision;
            item.intermediatorCommission =item.intermediatorCommission == '' || item.intermediatorCommission === null || !item.intermediatorCommission? 0: item.intermediatorCommission;
            //汇率默认为1
            var num =(item.purchasePrice * Number(formData.exchangeRate)*(1 + item.tariff / 100))/(1 - item.grossMargin / 100 - item.customerCommision / 100)*(1 + item.taxRate / 100)/(1 -item.discount / 100)
            item.salePrice = !isNaN(num) ? num.toFixed(2) : '';
            if (item.quantity) {
              item.taxAmount = (item.salePrice * item.quantity).toFixed(2);
            }
            // }
          });
          saleQuotationFormProductTable.dataSource = newArr;
          countGrossMargin()
        }
      }
      function setSonList(){
        SetSonListRef.value.getTable()
      }
      function setSonListFiled(value){
        var xTable = (saleQuotationFormProductTableRef.value!.getXTable()).data
        if(xTable.length>0){
          xTable.map(item=>{
            item.grossMargin = value.numericalValue
          })
        }
        saleQuotationFormProductTable.dataSource =[...xTable]
        changeDiscountOrExchangeRate()
      }
      function countGrossMargin(){
        var customerCommisionAll = 0,
        platformCommisionAll=0,
        salePriceAll=0,
        purchasePriceAll=0
        var xTable = (saleQuotationFormProductTableRef.value!.getXTable()).data
        xTable.map(item=>{
          customerCommisionAll +=(Number(item.customerCommision)/ 100)*Number(item.taxAmount)
          platformCommisionAll +=(Number(item.intermediatorCommission)/ 100)*Number(item.taxAmount)
          salePriceAll+=Number(item.taxAmount)
          purchasePriceAll+=Number(item.purchaseAmount)
        })
        formData.grossMarginHead = (salePriceAll-customerCommisionAll-platformCommisionAll-(purchasePriceAll/Number(formData.exchangeRate)))/salePriceAll
        formData.grossMarginHead =(Number( formData.grossMarginHead)*100).toFixed(2)
      }
      async function getLinkOptionsArr(customerId){
        var obj = await LinkOption({id:customerId})
        linkOption.value = obj
        if(obj.lenght!==0&&typeof obj === 'undefined'){
           formData.liaisonId = obj[0].id
          formData.liaisonInfo = obj[0].name
        }
       
      }
      function onChangeLiaison(data){
        if(data&&data!==undefined){
          formData.liaisonId = data.key
          formData.liaisonInfo = data.label[0].children
        }else{
          formData.liaisonId = ''
          formData.liaisonInfo = ''
        }
        
      }
      return {
        saleQuotationFormShipTableRef,
        saleQuotationFormShipTable,
        saleQuotationFormProductTableRef,
        saleQuotationFormProductTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        SelectShipSModalRef,
        add,
        edit,
        formRef,
        selectShip,
        addShip,
        addProduct,
        BaseShipArchiveAccessoriesListRef,
        viewAccessory,
        handleDelete,
        handleDelete1,
        selectProducts,
        SelectPrpductModalRef,
        SelectProjectModalRef,
        ViewHistoryQuotationModalRef,
        SelectSupplierQuotationRef,
        onSearchProject,
        addProject,
        getOptiom,
        classOption,
        getCustomerOptions,
        customerOption,
        quotationPeriod,
        onChangequotationPeriod,
        chooseSupplier,
        changeDelivertTime,
        viewHistory,
        baseUrl,
        VersionDetail,
        queryVersonHistoryData,
        addProductFromSupplier,
        notAllowEdit,
        changeValues,
        getRowRate,
        changeDiscountOrExchangeRate,
        changeExchangeRate,
        setSonList,
        SetSonListRef,
        setSonListFiled,
        linkOption,
        getLinkOptionsArr,
        onChangeLiaison
      };
    },
  });
</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>
