<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="订单编号(bill code)" v-bind="validateInfos.billCode" id="SaleOrderForm-billCode" name="billCode" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
								<a-input v-model:value="formData.billCode" placeholder="自动生成" disabled></a-input>
							</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" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
								<a-input-search v-model:value="formData.projectName" placeholder="请输入项目(project)" :disabled="notAllowEdit"  allow-clear enter-button="Search" AutoComplete="off" @search="onSearchProject"></a-input-search>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="客户(customer)" v-bind="validateInfos.customerName" id="SaleOrderForm-customerName" name="customerName">
                  <a-input   v-model:value="formData.customerName"  placeholder="请选择" allow-clear  disabled></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="中间人(intermediator)" v-bind="validateInfos.intermediator" id="SaleOrderForm-intermediator" name="intermediator" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
                  <a-input   v-model:value="formData.intermediatorName"  placeholder="请选择" allow-clear  disabled></a-input>
							</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" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
								<ApiSelect
                  :api="ClassList"
                  showSearch
                  v-model:value="formData.productionClass"
                  optionFilterProp="label"
                  resultField="records"
                  labelField="name"
                  valueField="id"
                  disabled
                />
							</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" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
								<a-input v-model:value="formData.maker" placeholder="请输入厂家(maker)"  allow-clear disabled></a-input>
							</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="汇率(exchange rate)" v-bind="validateInfos.exchangeRate" id="SaleOrderForm-exchangeRate" name="exchangeRate" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
								<a-input v-model:value="formData.exchangeRate" placeholder="请输入"  allow-clear AutoComplete="off"></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="交货条款(delivery term)" v-bind="validateInfos.deliveryTerms" id="SaleOrderForm-deliveryTerms" name="deliveryTerms">
                <JDictSelectTag v-model:value="formData.deliveryTerms" placeholder="请选择" dictCode="delivery_terms"/>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="付款条件(payment terms)" v-bind="validateInfos.paymentTerms" id="SaleOrderForm-paymentTerms" name="paymentTerms" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
                <JDictSelectTag v-model:value="formData.paymentTerms" placeholder="请选择" dictCode="payment_terms" disabled/>
							</a-form-item>
						</a-col>
            
            <a-col :span="12">
							<a-form-item label="交期(delivery time)" v-bind="validateInfos.deliveryTime" id="SaleOrderForm-deliveryTime" name="deliveryTime">
								<a-date-picker placeholder="请选择交期(delivery time)"  v-model:value="formData.deliveryTime"  value-format="YYYY-MM-DD" format="YYYY-MM-DD" @change="changeMainDeliveryTime" style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="发货方式(delivery)" v-bind="validateInfos.delivery" id="SaleOrderForm-delivery" name="delivery" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
                <JDictSelectTag v-model:value="formData.delivery" placeholder="请选择" dictCode="delivery_sale_order" />
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="交货地点(delivery address)" v-bind="validateInfos.deliveryAddress" id="SaleOrderForm-deliveryAddress" name="deliveryAddress">
                <a-input v-model:value="formData.deliveryAddress" placeholder="请输入" AutoComplete="off"/>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="开票抬头(invoice header)" v-bind="validateInfos.invoiceHeader" id="SaleOrderForm-invoiceHeader" name="invoiceHeader" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
                <a-input v-model:value="formData.invoiceHeader" placeholder="请输入" AutoComplete="off"/>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="开票地址(invoice address)" v-bind="validateInfos.invoiceAddress" id="SaleOrderForm-invoiceAddress" name="invoiceAddress" >
                <a-input v-model:value="formData.invoiceAddress" placeholder="请输入" AutoComplete="off"/>
							</a-form-item>
						</a-col>               
            <a-col :span="12">
							<a-form-item label="包装要求(package requirement)" v-bind="validateInfos.packagebRequirement" id="SaleOrderForm-packagebRequirement" name="packagebRequirement" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
								<a-input v-model:value="formData.packagebRequirement" placeholder="请输入包装要求(package requirement)"  allow-clear AutoComplete="off"></a-input>
							</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="是否出口(export)" v-bind="validateInfos.isExport" id="SaleOrderForm-isExport" name="isExport" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
                <JDictSelectTag v-model:value="formData.isExport" placeholder="请选择" dictCode="yes_or_no" AutoComplete="off"/>
							</a-form-item>
						</a-col> 
            <a-col :span="12">
							<a-form-item label="销售部门(sale department)" v-bind="validateInfos.saleDepartment" id="SaleOrderForm-saleDepartment" name="saleDepartment" >
								<a-input v-model:value="formData.saleDepartment" placeholder="请输入"  allow-clear disabled ></a-input>
							</a-form-item>
						</a-col>   
            <a-col :span="12">
							<a-form-item label="客户订单号(custormer order)" v-bind="validateInfos.customerOrder" id="SaleOrderForm-customerOrder" name="customerOrder" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
								<a-input v-model:value="formData.customerOrder" placeholder="请输入客户订单号(custormer order number)"  allow-clear AutoComplete="off"></a-input>
							</a-form-item>
						</a-col> 
            <a-col :span="12">
							<a-form-item label="业务员(salesman)" v-bind="validateInfos.salesman" id="SaleOrderForm-salesman" name="salesman" >
								<a-input v-model:value="formData.salesman" placeholder="请输入业务员(salesman)"  allow-clear disabled ></a-input>
							</a-form-item>
						</a-col>    
            <a-col :span="12">
							<a-form-item label="折后金额(converted amount)" v-bind="validateInfos.convertedAmount" id="SaleOrderForm-convertedAmount"  name="convertedAmount"  :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
								<a-input v-model:value="formData.convertedAmount" placeholder="请输入折后金额(converted amount)"  allow-clear disabled></a-input>
							</a-form-item>
						</a-col>  
            <a-col :span="12">
							<a-form-item label="折上折(double discount)" v-bind="validateInfos.doubleDiscount" id="SaleOrderForm-doubleDiscount" name="doubleDiscount">
								<a-input v-model:value="formData.doubleDiscount" placeholder="请输入折上折(double discount)"  allow-clear AutoComplete="off"></a-input>
							</a-form-item>
						</a-col>     
            <a-col :span="12">
							<a-form-item label="质保条款(warranty terms)" v-bind="validateInfos.warrantyTerms" id="SaleOrderForm-warrantyTerms" name="warrantyTerms" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
								<a-input v-model:value="formData.warrantyTerms" placeholder="请输入质保条款(warranty terms)"  allow-clear AutoComplete="off"></a-input>
							</a-form-item>
						</a-col> 
            <a-col :span="12">
							<a-form-item label="预付比例(advance ratio)" v-bind="validateInfos.advanceRatio" id="SaleOrderForm-advanceRatio" name="advanceRatio" >
								<a-input v-model:value="formData.advanceRatio" placeholder="请输入"  allow-clear AutoComplete="off"></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="备注(notes)" v-bind="validateInfos.notes" id="SaleOrderForm-notes" name="notes" :labelCol="formItemLayout.labelCol1" :wrapperCol="formItemLayout.wrapperCol1">
								<a-input v-model:value="formData.notes" AutoComplete="off"></a-input>
							</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"></JUpload>
							</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="SaleOrderFormShipFormProduct" :forceRender="true">
        <a-button type="primary" style="margin-right: 1%;margin-bottom: 1%;" @click="selectProductList"> 选择产品(select product)</a-button>
        <a-button type="primary"  style="margin-right: 1%;margin-bottom: 1%;" @click ="selectContractList"> 选择合同(select contract)</a-button>
        <a-button type="primary"  style="margin-right: 1%;margin-bottom: 1%;" @click ="selectQuotationList"> 选择报价单(select quotation)</a-button>
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="SaleOrderFormShipFormProductTableRef"
          :loading="SaleOrderFormShipFormProductTable.loading"
          :columns="SaleOrderFormShipFormProductTable.columns"
          :dataSource="SaleOrderFormShipFormProductTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          asyncRemove
          @valueChange="changeValues"
          >
            <template #action="props">
              <a-popconfirm title="确定删除吗？" @confirm="handleDelete(props)">
                <a>删除(delete)</a>
              </a-popconfirm>
            </template>
          </j-vxe-table>
      </a-tab-pane>
      <a-tab-pane tab="销售订单 - 船明细(ship details)" key="SaleOrderFormShipFormShip" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="SaleOrderFormShipFormShipTableRef"
          :loading="SaleOrderFormShipFormShipTable.loading"
          :columns="SaleOrderFormShipFormShipTable.columns"
          :dataSource="SaleOrderFormShipFormShipTable.dataSource"
          :height="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" @selectProduct ='addProduct'></SelectPrpductModal>
    <SelectContractModal ref="SelectContractModalRef" @selectContract="addContract"></SelectContractModal>
    <SelectQuotationModal ref="SelectQuotationModalRef" @selectQuotation="addQuotation"></SelectQuotationModal>
    <SelectProjectModal ref="SelectProjectModalRef" @selectProject="addProject"></SelectProjectModal>
    <BaseShipArchiveAccessoriesModal ref="BaseShipArchiveAccessoriesModalRef"></BaseShipArchiveAccessoriesModal>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw,nextTick} from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { querySaleOrderFormShipFormShippTable,ClassList, querySaleOrderFormProductListByMainId, queryDataById, saveOrUpdate,queryVersonHistoryById,querysaleVersonFormShipListByMainId, querySaleVersonProductListByMainId} from '../SaleOrderyForm.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {saleOrderShipColumns, saleOrderProductColumns} from '../SaleOrderForm.data';
  import SelectPrpductModal from '../../../publicComponents/SelectPrpductModal.vue';
  import SelectContractModal from '../../../publicComponents/SelectContractModal.vue';
  import SelectQuotationModal from '../../../publicComponents/SelectQuotationModal.vue';
  import SelectProjectModal from '../../../publicComponents/SelectProjectModal.vue';
  import BaseShipArchiveAccessoriesModal from '../../../publicComponents/BaseShipArchiveAccessoriesModal.vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import { JDictSelectTag} 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 {  ApiSelect, } from '/@/components/Form/index';
  import moment from 'moment';
import { InputNumberItem } from '/@/layouts/default/setting/components';
  const useForm = Form.useForm;
  export default defineComponent({
    name: "SaleOrderForm",
    components:{
      JVxeTable,
			JFormContainer,
      SelectPrpductModal,
      SelectContractModal,
      JUpload,
      JDictSelectTag,
      JSelectInput,
      SelectQuotationModal,
      SelectProjectModal,
      BaseShipArchiveAccessoriesModal,
      ApiSelect
    },
    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 SaleOrderFormShipFormShipTableRef = ref();
      const SelectPrpductModalRef = ref()
      const SelectContractModalRef = ref()
      const SelectQuotationModalRef = ref()
      const SelectProjectModalRef = ref()
      const BaseShipArchiveAccessoriesModalRef = ref();
      const SaleOrderFormShipFormShipTable = reactive<Record<string, any>>({
        loading: false,
        columns: saleOrderShipColumns,
        dataSource: []
      });
      const SaleOrderFormShipFormProductTableRef = ref();
      const SaleOrderFormShipFormProductTable = reactive<Record<string, any>>({
        loading: false,
        columns: saleOrderProductColumns,
        dataSource: []
      });
      const activeKey = ref('SaleOrderFormShipFormProduct');
      var notAllowEdit = ref(false);
      const formData = reactive<Record<string, any>>({
        id: '',
        status: undefined,
        delFlag: undefined,
        billCode:'',
        billDate: moment(new Date()).format('YYYY-MM-DD'),   
        project: '', 
        projectName:'',  
        customer:"",
        customerName:'',
        intermediator: '',        
        intermediatorName:'',   
        priority: '',   
        productionClass: '',   
        model: '',   
        maker: '',
        deliveryTerms:'',
        paymentTerms:'',
        delivery:'',
        deliveryTime: '',  
        deliveryAddress:'', 
        invoiceHeader:'', 
        invoiceAddress:'',
        warrantyPeriod: '',   
        isExport:'',
        packagebRequirement:'',
        saleDepartment:'',
        salesman:'',
        customerOrder:'',
        doubleDiscount:'',
        convertedAmount:'',
        warrantyTerms:'',
        advanceRatio:'',
        notes:'',
        attachs:'',
        sourceCode:'',
        sourceCode2:'',
        currency:'',
        exchangeRate:'',
        submit:undefined,
      });

      //表单验证
      const validatorRules = reactive({
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
      const dbData = {};
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 5}},
        wrapperCol: {xs: {span: 24}, sm: {span: 16}},
        labelCol1: {xs: {span: 24}, sm: {span: 6}},
        wrapperCol1: {xs: {span: 24}, sm: {span: 16}},
      };

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

      

      function add() {
        resetFields();
        SaleOrderFormShipFormShipTable.dataSource = [];
        SaleOrderFormShipFormProductTable.dataSource = [];
        activeKey.value = 'SaleOrderFormShipFormProduct'
        formData.salesman=userStore.getUserInfo.username;
        formData.saleDepartment = userStore.getUserInfo.orgCode
      }
      async function copy(data,id){
        //主表数据
        await queryMainData(id);
        formData.id = ''
        formData.billCode = ''
        //子表数据
        const SaleOrderFormShipFormShipDataList = await querySaleOrderFormShipFormShippTable(id);
        SaleOrderFormShipFormShipTable.dataSource = [...SaleOrderFormShipFormShipDataList];
        SaleOrderFormShipFormProductTable.dataSource = [...data];
        isSelect()
      }
      // 判断有没有参照的子表
      function isSelect(){
        var arrQuo = [],
            arrCon=[]
        if(SaleOrderFormShipFormProductTable.dataSource)
        SaleOrderFormShipFormProductTable.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 = ''
          notAllowEdit.value=true
        }else if(arrCon.length==0){
          formData.sourceCode2 = ''
          notAllowEdit.value=true
        }
      }
      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const SaleOrderFormShipFormShipDataList = await querySaleOrderFormShipFormShippTable(row['id']);
        SaleOrderFormShipFormShipTable.dataSource = [...SaleOrderFormShipFormShipDataList];
        const SaleOrderFormShipFormProductDataList = await querySaleOrderFormProductListByMainId(row['id']);
        SaleOrderFormShipFormProductTable.dataSource = [...SaleOrderFormShipFormProductDataList];
        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 querysaleVersonFormShipListByMainId(record.id);
        SaleOrderFormShipFormShipTable.dataSource = [...SaleOrderFormShipFormShipDataList];
        const SaleOrderFormShipFormProductDataList = await querySaleVersonProductListByMainId(record.id);
        SaleOrderFormShipFormProductTable.dataSource = [...SaleOrderFormShipFormProductDataList];
      }
      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, {
        'saleOrderShip': SaleOrderFormShipFormShipTableRef,
        'saleOrderProduct': SaleOrderFormShipFormProductTableRef,
      });

      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() {
        if(formData.sourceCode==''&&formData.sourceCode2==''){
          message.warning('请选择合同或报价单')
        }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 selectProductList(){
        SelectPrpductModalRef.value.getTable()
      }
      function selectContractList(){
        SelectContractModalRef.value.getTable(formData)
      }
      function selectQuotationList(){
        SelectQuotationModalRef.value.getTable(formData)
      }
      function onSearchProject(){
        SelectProjectModalRef.value.getTable()
      }
      function addProduct(data){
        data.map(item=>{
          item.productClass = item.classId_dictText
          item.productCode = item.code
          item.deliveryTime = formData.deliveryTime
          item.productId = item.id
        })
        var arrProduct = data.concat(SaleOrderFormShipFormProductTable.dataSource)
        SaleOrderFormShipFormProductTable.dataSource=arrProduct  
      }
      function addQuotation(data){
        var allDiscountPrice = 0
        data.map(item=>{
          item.model = item.childModel
          item.deliveryTime = formData.deliveryTime
          item.sourceId = item.childId
          item.sourceType  = 'Quo'+item.childId
          item.taxPrice = item.salePrice
          item.discountedPrice = (Number(item.taxPrice) *(1-Number(item.discount)/100))
          item.discountedAmount =Number(item.discountedPrice) *Number(item.quantity)
          item.discountedPrice =  (item.discountedPrice).toFixed(2)
          item.discountedAmount = (item.discountedAmount).toFixed(2)
          allDiscountPrice=allDiscountPrice+Number(item.discountedAmount)
        })
        var arrProduct = data.concat(SaleOrderFormShipFormProductTable.dataSource)
        notAllowEdit.value=true
        SaleOrderFormShipFormProductTable.dataSource=arrProduct  
        formData.sourceCode =data[0].billCode
        formData.convertedAmount=allDiscountPrice
        if(!formData.sourceCode2&&formData.sourceCode2==''){
          formData.project = data[0].quotationProject
          formData.projectName = data[0].quotationProjectName
          formData.customer =data[0].quotationCustomer
          formData.customerName =data[0].quotationCustomerName
          formData.priority =data[0].priority
          formData.productionClass =data[0].productionClass
          formData.model =data[0].headModel
          formData.maker =data[0].maker
          formData.currency =data[0].currency
          formData.paymentTerms =data[0].paymentTerms
          formData.intermediator =data[0].intermediator
          formData.intermediatorName =data[0].intermediatorName
          getShipList(data[0].headId,'quotation')
        }
      }
      function addContract(data){
        var allDiscountPrice = 0
         data.map(item=>{
            item.model = item.childModel
            item.deliveryTime = formData.deliveryTime
            item.sourceId = item.childId
            item.sourceType  = 'Con'+item.childId
            item.discountedPrice =Number(item.taxPrice)*(1-Number(item.discount)/100)
            item.discountedAmount =Number(item.discountedPrice) *Number(item.quantity)
            item.discountedPrice =  (item.discountedPrice).toFixed(2)
            item.discountedAmount = (item.discountedAmount).toFixed(2)
            allDiscountPrice=allDiscountPrice+Number(item.discountedAmount)
          })
          var arrProduct = data.concat(SaleOrderFormShipFormProductTable.dataSource)
          notAllowEdit.value=true
          SaleOrderFormShipFormProductTable.dataSource=arrProduct  
          formData.sourceCode2 =data[0].billCode
          formData.convertedAmount=allDiscountPrice
          if(!formData.sourceCode&&formData.sourceCode==''){
            formData.project = data[0].quotationProject
            formData.projectName = data[0].quotationProjectName
            formData.customer =data[0].quotationCustomer
            formData.customerName =data[0].quotationCustomerName
            formData.priority =data[0].priority
            formData.productionClass =data[0].productionClass
            formData.model =data[0].headModel
            formData.maker =data[0].maker
            formData.currency =data[0].currency
            formData.paymentTerms =data[0].paymentTerms
            formData.intermediator =data[0].intermediator
            formData.intermediatorName =data[0].intermediatorName
            getShipList(data[0].headId,'contract')
          }
          
      }
      function getShipList(id,status){
        let params = {id:id}
        let url = status=='quotation'?'/saleCode/saleQuotation/querySaleQuotationShipByMainId':'/saleCode/saleContract/querySaleContractShipByMainId'
          defHttp.get({url:url,params}, { isTransformResponse: false }).then(res=>{
            if(res){
              SaleOrderFormShipFormShipTable.dataSource = res.result
            }
          })
      }
      function addProject(data){
        formData.project = data[0].id
        formData.projectName = data[0].name
        formData.customer =data[0].customerId
        formData.customerName =data[0].customerId_dictText
      }
      function changeMainDeliveryTime(prop){
        if(SaleOrderFormShipFormProductTable.dataSource.length>0){
            var newArr = [...SaleOrderFormShipFormProductTable.dataSource]
            newArr.map(item=>{
              item.deliveryTime = prop
            })
            SaleOrderFormShipFormProductTable.dataSource = newArr
         }
      }
       //查看配件信息
       function viewAccessory(prop){
        BaseShipArchiveAccessoriesModalRef.value.getTable(prop.row)
      }
      //产品明细-删除行
      function handleDelete(prop) {
        var newArray = [...SaleOrderFormShipFormProductTable.dataSource]
        newArray.splice(prop.rowIndex, 1)
        SaleOrderFormShipFormProductTable.dataSource = newArray  
        isSelect()
      }
      function changeValues(prop){
        if(prop.col.key=='discountedPrice'&&prop.row.quantity&&prop.row.discountedPrice){
          prop.row.discountedAmount =  (prop.value*prop.row.quantity).toFixed(2)
          var arr=SaleOrderFormShipFormProductTableRef.value.getTableData()
          var allAmount = 0
          arr.map(item=>{
            allAmount = allAmount+Number(item.discountedAmount)
          })
          formData.convertedAmount=allAmount
        }
      }
      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }
      return {
        SaleOrderFormShipFormShipTableRef,
        SaleOrderFormShipFormShipTable,
        SaleOrderFormShipFormProductTableRef,
        SaleOrderFormShipFormProductTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        copy,
        formRef,
        selectProductList,
        SelectPrpductModalRef,
        addProduct,
        SelectContractModalRef,
        selectContractList,
        addContract,
        SelectQuotationModalRef,
        selectQuotationList,
        addQuotation,
        onSearchProject,
        SelectProjectModalRef,
        addProject,
        changeMainDeliveryTime,
        handleDelete,
        BaseShipArchiveAccessoriesModalRef,
        viewAccessory,
        VersionDetail,
        notAllowEdit,
        ClassList,
        changeValues
      }
    }
  });
</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;
  }
      
</style>
