<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form v-bind="formItemLayout" name="SelectQuotationFormForm" ref="formRef">
          <a-row>
            <a-col :span="12">
							<a-form-item label="选定单号(bill code)" v-bind="validateInfos.billCode" id="SelectQuotationFormForm-billCode" name="billCode">
								<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="SelectQuotationFormForm-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="询价项目(inquiry project)" v-bind="validateInfos.projectName" id="SelectQuotationFormForm-projectName" name="projectName">
								<a-input-search v-model:value="formData.projectName" placeholder="请输入询价项目(inquiry project)"  allow-clear enter-button="Search" @search="onSearchProject"></a-input-search>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="优先级(priority)" v-bind="validateInfos.priority" id="SelectQuotationFormForm-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="SelectQuotationFormForm-productionClass" name="productionClass">
								<ApiSelect
                    :api="ClassList"
                    showSearch
                    v-model:value="formData.productionClass"
                    :filterOption="false"
                    resultField="records"
                    labelField="name"
                    valueField="id"
                    :params='{pageSize:-1}'
                    disabled
                  />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="机型(model)" v-bind="validateInfos.model" id="SelectQuotationFormForm-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="SelectQuotationFormForm-maker" name="maker">
								<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="选定备注(selection notes)" v-bind="validateInfos.selectionNotes" id="SelectQuotationFormForm-selectionNotes" name="selectionNotes">
								<a-input v-model:value="formData.selectionNotes" placeholder="请输入选定备注备注(selection notes)"  allow-clear AutoComplete="off"></a-input>
							</a-form-item>
						</a-col> 
            <a-col :span="12">
							<a-form-item label="附件(attachs)" v-bind="validateInfos.attachs" id="SelectQuotationFormForm-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="SelectQuotationFormProduct" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="SelectQuotationFormProductTableRef"
          :loading="SelectQuotationFormProductTable.loading"
          :columns="SelectQuotationFormProductTable.columns"
          :dataSource="SelectQuotationFormProductTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          asyncRemove
          >
          <template #selectionSupplier="props">
            <a-select v-model:value="props.row.selectionSupplier" style="width: 100%;" @change="selectSupplier(props)" allowClear>
              <a-select-option v-for="item in supplierList" :key="item.value" >{{ item.label }}</a-select-option>
            </a-select>
          </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="SelectQuotationFormShip" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="SelectQuotationFormShipTableRef"
          :loading="SelectQuotationFormShipTable.loading"
          :columns="SelectQuotationFormShipTable.columns"
          :dataSource="SelectQuotationFormShipTable.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-tab-pane tab="采购报价单选定 - 供应商报价明细(supplier quotation details)" key="SupplierQuotationDetails" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="SupplierQuotationDetailsTableRef"
          :loading="SupplierQuotationDetailsTable.loading"
          :columns="SupplierQuotationDetailsTable.columns"
          :dataSource="SupplierQuotationDetailsTable.dataSource"
          :rowKey="record => record.childId"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          asyncRemove
          >
          </j-vxe-table>
      </a-tab-pane>
      <a-tab-pane tab="采购报价单选定 - 供应商汇总金额(supplier summary amount)" key="SupplierSummaryAmount" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="SupplierSummaryAmountTableRef"
          :loading="SupplierSummaryAmountTable.loading"
          :columns="SupplierSummaryAmountTable.columns"
          :dataSource="SupplierSummaryAmountTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          asyncRemove
          >
          </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
    <BaseShipArchiveAccessoriesModal ref="BaseShipArchiveAccessoriesListRef"></BaseShipArchiveAccessoriesModal>
    <SelectProjectModal ref="SelectProjectModalRef" @selectProject="addProject"></SelectProjectModal>
  </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 { SelectQuotationFormShippTable, SelectQuotationFormProductListByMainId, queryDataById, saveOrUpdate,ClassList } from '../SelectionQuotationForm.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {SelectQuotationFormShipTableCloumn, SelectQuotationFormProductColumns,SupplierQuotationColumns,SupplierSummaryAmountColumns} from '../SelectionQuotationForm.data';
  import BaseShipArchiveAccessoriesModal from '../../../publicComponents/BaseShipArchiveAccessoriesModal.vue';
  import SelectProjectModal from '../../../publicComponents/SelectProjectModal.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 { Form ,message} from 'ant-design-vue';
  import moment from 'moment';
  const useForm = Form.useForm;
  export default defineComponent({
    name: "SelectQuotationFormForm",
    components:{
      JVxeTable,
			JFormContainer,
      BaseShipArchiveAccessoriesModal,
      JUpload,
      SelectProjectModal,
      JDictSelectTag,
      JSelectInput,
      ApiSelect
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      const loading = ref(false);
      const formRef = ref();
      var SelectProjectModalRef = ref()
      const SelectQuotationFormShipTableRef = ref();
      const SelectQuotationFormShipTable = reactive<Record<string, any>>({
        loading: false,
        columns: SelectQuotationFormShipTableCloumn,
        dataSource: []
      });
      const SelectQuotationFormProductTableRef = ref();
      const SupplierQuotationDetailsTableRef = ref();
      const SupplierSummaryAmountTableRef = ref();
      const SelectQuotationFormProductTable = reactive<Record<string, any>>({
        loading: false,
        columns: SelectQuotationFormProductColumns,
        dataSource: []
      });
      const SupplierQuotationDetailsTable = reactive<Record<string, any>>({
        loading: false,
        columns: SupplierQuotationColumns,
        dataSource: []
      });
      const SupplierSummaryAmountTable = reactive<Record<string, any>>({
        loading: false,
        columns: SupplierSummaryAmountColumns,
        dataSource: []
      });
      var BaseShipArchiveAccessoriesListRef = ref();
      var supplierList = ref([]);
      const activeKey = ref('SelectQuotationFormProduct');
      const formData = reactive<Record<string, any>>({
        id: '',
        status: undefined,
        delFlag: undefined,
        submit: '',   
        billDate: moment(new Date()).format('YYYY-MM-DD'),   
        billCode: '',   
        inquiryProject: '',   
        projectName:'',       
        priority: '',   
        productionClass: '',   
        model: '',   
        maker: '',
        selectionNotes:'',
        attachs:'',
        sourceId:''
      });

      //表单验证
      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}},
      };

      // 表单禁用
      const disabled = computed(()=>{
        if(props.formBpm === true){
          if(props.formData.disabled === false){
            return false;
          }else{
            return true;
          }
        }
        return props.formDisabled;
      });
      function add() {
        resetFields();
        SelectQuotationFormShipTable.dataSource = [];
        SelectQuotationFormProductTable.dataSource = [];
        SupplierQuotationDetailsTable.dataSource = []
        SupplierSummaryAmountTable.dataSource = []
        activeKey.value = 'SelectQuotationFormProduct'
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const SelectQuotationFormShipDataList = await SelectQuotationFormShippTable(row['id']);
        SelectQuotationFormShipTable.dataSource = [...SelectQuotationFormShipDataList];
        const SelectQuotationFormProductDataList = await SelectQuotationFormProductListByMainId(row['id']);
        SelectQuotationFormProductTable.dataSource = [...SelectQuotationFormProductDataList];
        getSupplierQuotationDetail(formData.inquiryProject)
        getSupplierSummaryAmount(formData.inquiryProject)
      }

      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, {
        'purQuotationSelectionShip': SelectQuotationFormShipTableRef,
        'purQuotationSelectionProduct': SelectQuotationFormProductTableRef,
      });

      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 mainData = await getFormData();
        const subData = await getSubFormAndTableData();
        const values = Object.assign({}, dbData, mainData, subData);
        const isUpdate = values.id ? true : false
        await saveOrUpdate(values, isUpdate);
        //关闭弹窗
        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 handleDelete1(prop) {
        var newArray = [...SelectQuotationFormProductTable.dataSource]
        newArray.splice(prop.rowIndex, 1)
        SelectQuotationFormProductTable.dataSource = newArray  
      }
      async function addProject(data) {
        if(data.length!==0){
           formData.inquiryProject = data[0].id
           formData.projectName = data[0].code
           await getShipDetail(data[0].id)
           await getSupplierQuotationDetail(data[0].id)
           await getSupplierSummaryAmount(data[0].id)
        }else{
          formData.inquiryProject = ''
          formData.projectName = ''
        }
        
      }
      async function getShipDetail(id){
          let params = {projectId:id}
          await defHttp.get({url:'/purCode/purInquiryForm/getPurInquiryFormByProject',params}, { isTransformResponse: false }).then(res=>{
            if(res!==''){
              formData.priority = res.priority
              formData.productionClass = res.productionClass
              formData.model = res.model
              formData.maker = res.maker
              SelectQuotationFormShipTable.dataSource = res.purInquiryFormShipList
              res.purInquiryFormProductList.map(item=>{
                item.sourceCode= item.headCode
                item.sourceId= item.id
              })
              formData.sourceId = res.purInquiryFormProductList[0].headCodes
              SelectQuotationFormProductTable.dataSource = res.purInquiryFormProductList
            }else if(res==''){
              message.warning('当前项目还没有报价')
            }
          })
      }
      async function getSupplierQuotationDetail(id){
          let params = {quotationProject:id}
          await defHttp.get({url:'/purCode/purPurchaseQuotation/supplierQuotationDetails',params}, { isTransformResponse: false }).then(res=>{
            if(res){
              SupplierQuotationDetailsTable.dataSource=res.result.records
              supplierList.value= []
              res.result.records.map(item=>{
                 supplierList.value.push({label:item.suppilerName,value:item.quotationSuppiler})
              })
              supplierList.value = supplierList.value.filter((item, index, self) => {
                return index === self.findIndex(obj => obj.value === item.value && obj.label === item.label);
              });

            }
          })
      }
      function getSupplierSummaryAmount(id){
          let params = {quotationProject:id}
          defHttp.get({url:'/purCode/purPurchaseQuotation/supplierQuotationTotal',params}, { isTransformResponse: false }).then(res=>{
            if(res){
              SupplierSummaryAmountTable.dataSource=res.result.records
            }
          })
      }
            
      function viewAccessory(prop){
        BaseShipArchiveAccessoriesListRef.value.getTable(prop.row)
      }
      function onSearchProject(){
        SelectProjectModalRef.value.getTable()
      }
      function selectSupplier(prop){
        SupplierQuotationDetailsTable.dataSource.map(item=>{
          if(item.productCode==prop.row.productCode&&item.quotationSuppiler==prop.row.selectionSupplier){
            var arr = [...SelectQuotationFormProductTable.dataSource]
            arr.map((event,index)=>{
              if(prop.rowIndex==index){
                if(prop.rowIndex==index){
                  item.sourceCode=event.sourceCode
                  item.sourceId=event.sourceId
                  item.sourceId2=item.id
                  arr[index]={...item}
                  arr[index].selectionSupplier=item.quotationSuppiler
                  arr[index].deliveryTime=item.childDeliveryTime
                }
              }              
            })
            SelectQuotationFormProductTable.dataSource = [...arr]
          }
        })
      }
      return {
        SelectQuotationFormShipTableRef,
        SelectQuotationFormShipTable,
        SelectQuotationFormProductTableRef,
        SelectQuotationFormProductTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
        BaseShipArchiveAccessoriesListRef,
        viewAccessory,
        handleDelete1,
        SelectProjectModalRef,
        onSearchProject,
        addProject,
        SupplierQuotationDetailsTableRef,
        SupplierQuotationDetailsTable,
        SupplierSummaryAmountTableRef,
        SupplierSummaryAmountTable,
        supplierList,
        selectSupplier,
        ClassList
      }
    }
  });
</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>
