<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">
								<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">
								<a-input-search v-model:value="formData.projectName" placeholder="请输入项目(project)" readOnly AutoComplete="off"  allow-clear enter-button="Search" @search="onSearchProject"></a-input-search>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="供应商(supplier)" v-bind="validateInfos.supplier"  id="SaleOrderForm-supplier" name="supplier">
                <JSelect   v-model:value="formData.supplier" :get-option-url="supplierOption" :showField="showField" @change="changeSupplier"></JSelect>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="产品分类(production class)" v-bind="validateInfos.productionClass"  id="SaleOrderForm-productionClass" name="productionClass">
                  <ApiSelect
                      :api="ClassList"
                      showSearch
                      v-model:value="formData.productionClass"
                      :filterOption="true"
                      resultField="records"
                      labelField="name"
                      valueField="id"
                      :params='{pageSize:-1}'
                      optionFilterProp='label'
                  />
							</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"/>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="厂家(maker)" v-bind="validateInfos.maker"  id="SaleOrderForm-maker" name="maker">
								<JDictSelectTag v-model:value="formData.maker" placeholder="请选择" dictCode="factory"/>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="货位(goods allocation)" v-bind="validateInfos.goodsAllocation" id="SaleOrderForm-goodsAllocation" name="goodsAllocation">
                <JDictSelectTag v-model:value="formData.goodsAllocation" placeholder="请选择" dictCode="goods_allocation"/>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="仓库(warehouse)" v-bind="validateInfos.warehouse" id="SaleOrderForm-warehouse" name="warehouse">
                <JDictSelectTag v-model:value="formData.warehouse" placeholder="请选择" dictCode="warehouse"/>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="备注(notes)" v-bind="validateInfos.notes" id="SaleOrderForm-notes" name="notes">
								<a-input v-model:value="formData.notes" AutoComplete="off"></a-input>
							</a-form-item>
						</a-col>    
            <a-col :span="12">
							<a-form-item label="附件(attachs)" v-bind="validateInfos.attachs"  id="PuechaseInquiryFormForm-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="其他入库 - 船明细(ship details)" key="otherInShip" :forceRender="true">
        <a-button type="primary" style="margin-right: 1%;margin-bottom: 1%;" @click="selectShip"> 选择船(select ship)</a-button>
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="otherInShipTableRef"
          :loading="otherInShipTable.loading"
          :columns="otherInShipTable.columns"
          :dataSource="otherInShipTable.dataSource"
          :maxHeight="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          >
            <template #action="props" >
              <a  @click="viewAccessory(props)">查看配件信息(view accessory information)</a>
            </template>
          </j-vxe-table>
      </a-tab-pane>
      <a-tab-pane tab="其他入库 - 入库明细(arrive details)" key="stockIn" :forceRender="true">
        <a-button type="primary" style="margin-right: 1%;margin-bottom: 1%;" @click="selectProductList"> 选择产品(select product)</a-button>
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="stockInTableRef"
          :loading="stockInTable.loading"
          :columns="stockInTable.columns"
          :dataSource="stockInTable.dataSource"
          :maxHeight="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          asyncRemove
          >
            <template #action="props">
              <a-popconfirm title="确定删除吗？" @confirm="handleDelete(props)">
                <a>删除(delete)</a>
              </a-popconfirm>
              <!-- 逻辑不通暂时取消次功能 -->
              <!-- <a>复制(copy)</a> -->
            </template>
          </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
    <BaseShipArchiveAccessoriesModal ref="BaseShipArchiveAccessoriesModalRef"></BaseShipArchiveAccessoriesModal>
    <SelectPrpductModal ref="SelectPrpductModalRef" @selectProduct ='addProduct'></SelectPrpductModal>
    <SelectProjectModal ref="SelectProjectModalRef" @selectProject="addProject"></SelectProjectModal>
    <SelectShipSModal ref="SelectShipSModalRef" @select="addShip"></SelectShipSModal>
  </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 { queryOtherInFormShipFormShippTable, querystockInByMainId, queryDataById, saveOrUpdate,supplierOption,ClassList} from '../otherInForm.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {otherInShipColumns, stockInColumns} from '../otherInForm.data';
  import BaseShipArchiveAccessoriesModal from '../../../publicComponents/BaseShipArchiveAccessoriesModal.vue';
  import SelectPrpductModal from '../../../publicComponents/SelectPrpductModal.vue';
  import SelectProjectModal from '../../../publicComponents/SelectProjectModal.vue';
  import SelectShipSModal from '../../../publicComponents/SelectShipSModal.vue';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import JSelectInput from '/@/components/Form/src/jeecg/components/JSelectInput.vue';
  import { JDictSelectTag,ApiSelect,JSelect} from '/@/components/Form';
  import { Form, message } from 'ant-design-vue';
  import moment from 'moment';
  const useForm = Form.useForm;
  export default defineComponent({
    name: "otherInForm",
    components:{
      JVxeTable,
			JFormContainer,
      JUpload,
      JDictSelectTag,
      BaseShipArchiveAccessoriesModal,
      SelectProjectModal,
      SelectPrpductModal,
      SelectShipSModal,
      JSelectInput,
      ApiSelect,
      JSelect
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      const loading = ref(false);
      var showField = ref('currency+name');
      const formRef = ref();
      const SelectProjectModalRef = ref()
      const SelectPrpductModalRef = ref()
      const SelectShipSModalRef = ref();
      const otherInShipTableRef = ref();
      const BaseShipArchiveAccessoriesModalRef = ref();
      const otherInShipTable = reactive<Record<string, any>>({
        loading: false,
        columns: otherInShipColumns,
        dataSource: []
      });
      const stockInTableRef = ref();
      const stockInTable = reactive<Record<string, any>>({
        loading: false,
        columns: stockInColumns,
        dataSource: []
      });
      const activeKey = ref('otherInShip');
      const formData = reactive<Record<string, any>>({
        id: '',
        status: undefined,
        delFlag: undefined,
        billCode:'',
        billDate: moment(new Date()).format('YYYY-MM-DD'),   
        project: '', 
        projectName:'',  
        supplier:"",
        supplierName:'',   
        productionClass: '',   
        model:'',   
        maker: '',
        goodsAllocation:'',
        warehouse:'',
        notes:'',
        attachs:'',
      });
      //表单验证
      const validatorRules = reactive({
        projectName: [
          { required: true, message: '请选择项目(select project)' }
        ],
        supplier: [
          { required: true, message: '请选择供应商(select supplier)' }
        ],
        model: [
          { required: true, message: '请选择机型(model)' }
        ],
      });
      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: 7}},
        wrapperCol1: {xs: {span: 24}, sm: {span: 15}},
      };

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

      

      function add() {
        resetFields();
        otherInShipTable.dataSource = [];
        stockInTable.dataSource = [];
        activeKey.value = 'otherInShip'
      }
      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const otherInShipDataList = await queryOtherInFormShipFormShippTable(row['id']);
        otherInShipTable.dataSource = [...otherInShipDataList];
        const stockInDataList = await querystockInByMainId(row['id']);
        stockInTable.dataSource = [...stockInDataList];
      }

      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, {
        'storePurchaseOtherShip': otherInShipTableRef,
        'storePurchaseOtherDetails': stockInTableRef,
      });

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

      async function submitForm() {
        var xTable = stockInTableRef.value!.getXTable()
        if( xTable.data.length==0){
          message.error('请添加入库明细！');
        }else{
          stockInTableRef.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
              await saveOrUpdate(values, isUpdate);
              //关闭弹窗
              emit('success');
            }
          })
          
        }
      }
      
      function setFieldsValue(values) {
        if(values){
          Object.keys(values).map(k=>{
            formData[k] = values[k];
          });
        }
      }
       //查看配件信息
       function viewAccessory(prop){
        BaseShipArchiveAccessoriesModalRef.value.getTable(prop.row)
      }
      //入库明细-删除行
      function handleDelete(prop) {
        var xTable = stockInTableRef.value!.getXTable()
        var newArray = [...xTable.data]
        newArray.splice(prop.rowIndex, 1)
        stockInTable.dataSource = newArray      
      }
      function onSearchProject(){
        SelectProjectModalRef.value.getTable()
      }
      function addProject(data){
        if(data.lenght==0){
          formData.projectName = ''
          formData.projectName = ''
        }else{
          formData.project = data[0].id
          formData.projectName = data[0].code
        } 
      }
      function addProduct(data){
        data.map(item=>{
          item.productClass = item.classId_dictText
          item.productCode = item.code
          item.productId = item.id
          item.id = undefined
        })
        var xTable = stockInTableRef.value!.getXTable()
        var arrProduct = xTable.data.concat(data)
        stockInTable.dataSource=arrProduct  
      }
      function selectProductList(){
        SelectPrpductModalRef.value.getTable()
      }
      function selectShip(){
        SelectShipSModalRef.value.getTable()
      }
      function addShip(data){
        data.map(item=>{
          item.shipowner = item.relateCustomer
          item.shipId = item.id;
          item.id=undefined
        })
        var xTable = otherInShipTableRef.value!.getXTable()
        var arr = xTable.data.concat(data)
        otherInShipTable.dataSource=arr        
      }
      async function changeSupplier(prop){
        if(prop){
          var params={id:prop}
          var obj = await supplierOption(params)
          formData.supplierName = obj.records[0].name
        }else{
          formData.supplier = ''
          formData.supplierName = ''
        }
      }
      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }
      return {
        otherInShipTableRef,
        otherInShipTable,
        stockInTableRef,
        stockInTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
        handleDelete,
        BaseShipArchiveAccessoriesModalRef,
        viewAccessory,
        onSearchProject,
        SelectProjectModalRef,
        addProject,
        selectProductList,
        SelectPrpductModalRef,
        addProduct,
        selectShip,
        SelectShipSModalRef,
        addShip,
        changeSupplier,
        ClassList,
        supplierOption,
        showField
      }
    }
  });
</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>
