<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form v-bind="formItemLayout" name="SaleInquiryFormForm" ref="formRef">
          <a-row>
            <a-col :span="12">
							<a-form-item label="询价单号(bill code)" v-bind="validateInfos.billCode" id="SaleInquiryFormForm-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="SaleInquiryFormForm-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="SaleInquiryFormForm-inquiryProject" name="inquiryProject">
								<a-input-search v-model:value="formData.projectName" placeholder="请选择询价项目(inquiry project)" readonly  allow-clear enter-button="Search" @search="onSearchProject"></a-input-search>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="询价客户(inquiry customer)" v-bind="validateInfos.inquiryCustomer" id="SaleInquiryFormForm-inquiryCustomer" name="inquiryCustomer">
                <JSelectInput   v-model:value="formData.inquiryCustomer"  placeholder="请选择" :options="customerOption" disabled></JSelectInput>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="询价平台(inquiry platform)" v-bind="validateInfos.inquiryPlatform" id="SaleInquiryFormForm-inquiryPlatform" name="inquiryPlatform">
                <JDictSelectTag v-model:value="formData.inquiryPlatform" placeholder="请选择" dictCode="inquiry_platform"/>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="客户询价单号(customer inquiry number)" v-bind="validateInfos.customerInquiryNumber" id="SaleInquiryFormForm-customerInquiryNumber" name="customerInquiryNumber">
								<a-input v-model:value="formData.customerInquiryNumber" placeholder="请输入客户询价单号(customer inquiry number)"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="客户询价日期(customer inquiry time)" v-bind="validateInfos.inquiryTime" id="SaleInquiryFormForm-inquiryTime" name="inquiryTime">
								<a-date-picker placeholder="请选择客户询价日期(customer inquiry time)"  v-model:value="formData.inquiryTime"  value-format="YYYY-MM-DD"  style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="询价有效期(inquiry period)" v-bind="validateInfos.inquiryPeriodEnd" id="SaleInquiryFormForm-inquiryPeriodEnd" name="inquiryPeriodEnd">
                <a-range-picker v-model:value="inquiryPeriod" :format="['YYYY-MM-DD','YYYY-MM-DD']"  @change="onChangeInquiryPeriod" style="width: 100%" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="优先级(priority)" v-bind="validateInfos.priority" id="SaleInquiryFormForm-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="SaleInquiryFormForm-productionClass" name="productionClass">
                <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="SaleInquiryFormForm-model" name="model">
                <JDictSelectTag 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="SaleInquiryFormForm-maker" name="maker">
								<a-input v-model:value="formData.maker" placeholder="请输入厂家(maker)"  allow-clear AutoComplete="off"></a-input>
							</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-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="业务员(salesman)" v-bind="validateInfos.salesman" id="SaleInquiryFormForm-salesman" name="salesman">
								<a-input v-model:value="formData.salesmanName" placeholder=""  allow-clear disabled></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="采购询价组(procurement inquiry team)" v-bind="validateInfos.inquiryTeam" id="SaleInquiryFormForm-inquiryTeam" name="inquiryTeam">
                <JSelectDept v-model:value="formData.inquiryTeam" :multiple="false"/>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="质量等级(quality grade)" v-bind="validateInfos.inquiryTeam" id="SaleInquiryFormForm-inquiryTeam" name="inquiryTeam">
                <JDictSelectTag v-model:value="formData.qualityGradeHead" placeholder="请选择" dictCode="quality_grade" @change="handleChangeQualityGrade"/>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="询价备注(inquiry notes)" v-bind="validateInfos.inquiryNotes" id="SaleInquiryFormForm-inquiryNotes" name="inquiryNotes">
								<a-input v-model:value="formData.inquiryNotes" placeholder="请输入询价备注(inquiry 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="SaleInquiryFormForm-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="saleInquiryFormProduct" :forceRender="true">
        <a-button type="primary" @click="selectProducts" style="margin-right: 1%;margin-bottom: 1%;"> 选择产品(select product)</a-button>
        <a-button type="primary" @click="setNeed" style="margin-right: 1%;"> 设置需要船检证书(set need ship inspection certificate)</a-button>
        <a-button type="primary" @click="setNotNeed"> 设置不需要船检证书(set need not ship inspection certificate)</a-button>
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="saleInquiryFormProductTableRef"
          :loading="saleInquiryFormProductTable.loading"
          :columns="saleInquiryFormProductTable.columns"
          :dataSource="saleInquiryFormProductTable.dataSource"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          asyncRemove
          :maxHeight="340"
          >
          <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="saleInquiryFormShip" :forceRender="true">
        <a-button type="primary" @click="selectShip"> 选择船(select ship)</a-button>
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="saleInquiryFormShipTableRef"
          :loading="saleInquiryFormShipTable.loading"
          :columns="saleInquiryFormShipTable.columns"
          :dataSource="saleInquiryFormShipTable.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"></SelectShipSModal>
    <BaseShipArchiveAccessoriesModal ref="BaseShipArchiveAccessoriesListRef"></BaseShipArchiveAccessoriesModal>
    <SelectPrpductModal ref="SelectPrpductModalRef" @selectProduct="addProduct"></SelectPrpductModal>
    <SelectProjectModal ref="SelectProjectModalRef" @selectProject="addProject"></SelectProjectModal>
  </a-spin>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, computed, toRaw} from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useValidateAntFormAndTable } from '/@/hooks/system/useJvxeMethods';
  import { querySaleInquiryFormShipListByMainId, querySaleInquiryFormProductListByMainId, queryDataById, saveOrUpdate } from '../SaleInquiryForm.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {saleInquiryFormShipColumns, saleInquiryFormProductColumns} from '../SaleInquiryForm.data';
  import SelectShipSModal from '../../../publicComponents/SelectShipSModal.vue';
  import BaseShipArchiveAccessoriesModal from '../../../publicComponents/BaseShipArchiveAccessoriesModal.vue';
  import SelectPrpductModal from '../../../publicComponents/SelectPrpductModal.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} from '/@/components/Form';
  import JSelectInput from '/@/components/Form/src/jeecg/components/JSelectInput.vue';
  import JSelectDept from '/@/components/Form/src/jeecg/components/JSelectDept.vue';
  import { Form } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import moment from 'moment';
  const userStore = useUserStore();
  const useForm = Form.useForm;
  export default defineComponent({
    name: "SaleInquiryFormForm",
    components:{
      JVxeTable,
			JFormContainer,
      SelectShipSModal,
      BaseShipArchiveAccessoriesModal,
      SelectPrpductModal,
      JUpload,
      SelectProjectModal,
      JDictSelectTag,
      JSelectInput,
      JSelectDept
    },
    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 SelectPrpductModalRef = ref()
      var SelectProjectModalRef = ref()
      var inquiryPeriod = ref([])
      const saleInquiryFormShipTableRef = ref();
      const saleInquiryFormShipTable = reactive<Record<string, any>>({
        loading: false,
        columns: saleInquiryFormShipColumns,
        dataSource: []
      });
      const saleInquiryFormProductTableRef = ref();
      const saleInquiryFormProductTable = reactive<Record<string, any>>({
        loading: false,
        columns: saleInquiryFormProductColumns,
        dataSource: []
      });
      var SelectShipSModalRef = ref();
      var BaseShipArchiveAccessoriesListRef = ref();
      const activeKey = ref('saleInquiryFormProduct');
      var customerOption =ref([]);
      const formData = reactive<Record<string, any>>({
        id: '',
        status: undefined,
        delFlag: undefined,
        otherStatus: '',   
        billDate: moment(new Date()).format('YYYY-MM-DD'),   
        billCode: '',   
        inquiryProject: '',   
        projectName:"",
        inquiryCustomer: '', 
        customerName:'',  
        inquiryPlatform: '',   
        customerInquiryNumber: '',   
        inquiryPeriodEnd: '',   
        inquiryPeriodBegin: '',     
        priority: '',   
        productionClass: '',   
        model: '',   
        maker: '',   
        saleDepartment: '',   
        saleDepartmentName: '',   
        salesman: '',   
        salesmanName: '',   
        inquiryTeam: '',   
        attachs: '',   
        inquiryNotes: '',  
        inquiryTime:moment(new Date()).format('YYYY-MM-DD') ,
        qualityGradeHead:'',
      });

      //表单验证
      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();
        saleInquiryFormShipTable.dataSource = [];
        saleInquiryFormProductTable.dataSource = [];
        activeKey.value = 'saleInquiryFormProduct'
        getCustomerOptions()
        inquiryPeriod.value = []
        formData.salesman=userStore.getUserInfo.username;
        formData.salesmanName=userStore.getUserInfo.realname;
        formData.saleDepartment = userStore.getUserInfo.orgCode
        formData.saleDepartmentName = userStore.getUserInfo.orgName
      }

      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const saleInquiryFormShipDataList = await querySaleInquiryFormShipListByMainId(row['id']);
        saleInquiryFormShipTable.dataSource = [...saleInquiryFormShipDataList];
        const saleInquiryFormProductDataList = await querySaleInquiryFormProductListByMainId(row['id']);
        saleInquiryFormProductTable.dataSource = [...saleInquiryFormProductDataList];
        getCustomerOptions()
        inquiryPeriod.value[0]=formData.inquiryPeriodBegin?moment(formData.inquiryPeriodBegin):''
        inquiryPeriod.value[1]=formData.inquiryPeriodEnd?moment(formData.inquiryPeriodEnd):''
      }

      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, {
        'saleInquiryFormShip': saleInquiryFormShipTableRef,
        'saleInquiryFormProduct': saleInquiryFormProductTableRef,
      });

      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);
        console.log('表单提交数据', values)
        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 handleDelete(prop) {
        var newArray = [...saleInquiryFormShipTable.dataSource]
        newArray.splice(prop.rowIndex, 1)
        saleInquiryFormShipTable.dataSource = newArray 
      }
      async function handleDelete1(prop) {
        var newArray = [...saleInquiryFormProductTable.dataSource]
        newArray.splice(prop.rowIndex, 1)
        saleInquiryFormProductTable.dataSource = newArray  
      }
      function selectShip(){
        SelectShipSModalRef.value.getTable()
      }
      function addShip(data){
        data.map(item=>item.shipowner = item.relateCustomer)
        var arr = data.concat(saleInquiryFormShipTable.dataSource)
        saleInquiryFormShipTable.dataSource=arr        
        
      }
      function addProduct(data){
        data.map(item=>{
          item.productClass = item.classId_dictText
          item.productCode = item.code
          item.unit = item.measurementUnit
          item.productId = item.id
          item.qualityGrade = formData.qualityGradeHead!==''?formData.qualityGradeHead:''
        })
        var arrProduct = saleInquiryFormProductTable.dataSource.concat(data)
        saleInquiryFormProductTable.dataSource=arrProduct      
      }
      function addProject(data) {
        if(data.length==0){
          formData.inquiryProject = ''
          formData.projectName = ''
        }else{
          formData.inquiryProject = data[0].id
          formData.projectName = data[0].code
          formData.inquiryCustomer =data[0].customerId
          formData.customerName =data[0].customerId_dictText
          customerOption.value.map(item=>{
            if(item.value==data[0].customerId){
              formData.priority =item.priority
            }
          })
        }
        
      }
      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
                })
              })
            }
          })
      }
      function viewAccessory(prop){
        BaseShipArchiveAccessoriesListRef.value.getTable(prop.row)
      }
      function selectProducts(){
        SelectPrpductModalRef.value.getTable()
      }
      function setNeed(){
        const values = saleInquiryFormProductTableRef.value.getSelectionData()        
        values.map(item=>{
          saleInquiryFormProductTable.dataSource.map(event=>{
            if(item.id == event.id){
              event.needShip = 1
            }
          })
          const xTable = saleInquiryFormProductTableRef.value!.getXTable();//关键代码 如果不更新 重新加载表格即可
          xTable.loadData(saleInquiryFormProductTable.dataSource)

        })
      }
      function setNotNeed(){
        const values = saleInquiryFormProductTableRef.value.getSelectionData()        
        values.map(item=>{
          saleInquiryFormProductTable.dataSource.map(event=>{
            if(item.id == event.id){
              event.needShip = 0
            }
          })
          const xTable = saleInquiryFormProductTableRef.value!.getXTable();//关键代码 如果不更新 重新加载表格即可
          xTable.loadData(saleInquiryFormProductTable.dataSource)

        })
      }
      function onSearchProject(){
        SelectProjectModalRef.value.getTable('allowAdd')
      }
      function onChangeInquiryPeriod(data){
        inquiryPeriod.value = data
        formData.inquiryPeriodBegin = data[0].format('YYYY-MM-DD')
        formData.inquiryPeriodEnd = data[1].format('YYYY-MM-DD')
      }
      function handleChangeQualityGrade(data){
        var xTable = saleInquiryFormProductTableRef.value!.getXTable();//关键代码 如果不更新 重新加载表格即可
        xTable.data.map(item=>{
          item.qualityGrade = data
        })
        saleInquiryFormProductTable.dataSource = xTable.data
      }
      return {
        saleInquiryFormShipTableRef,
        saleInquiryFormShipTable,
        saleInquiryFormProductTableRef,
        saleInquiryFormProductTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        SelectShipSModalRef,
        add,
        edit,
        formRef,
        selectShip,
        addShip,
        addProduct,
        BaseShipArchiveAccessoriesListRef,
        viewAccessory,
        handleDelete,
        handleDelete1,
        selectProducts,
        setNeed,
        setNotNeed,
        SelectPrpductModalRef,
        SelectProjectModalRef,
        onSearchProject,
        addProject,
        getCustomerOptions,
        customerOption,
        inquiryPeriod,
        onChangeInquiryPeriod,
        handleChangeQualityGrade
      }
    }
  });
</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>
