<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="入库单号(bill code)" 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 v-model:value="formData.projectName" placeholder="请输入项目(project)" disabled allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="供应商(supplier)" v-bind="validateInfos.supplierName"  id="SaleOrderForm-supplierName" name="supplierName">
								<a-input v-model:value="formData.supplierName" placeholder="请输入" disabled allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="发货方式(delivery)" v-bind="validateInfos.delivery" id="SaleOrderForm-delivery" name="delivery">
                <JDictSelectTag v-model:value="formData.delivery" placeholder="请选择" dictCode="delivery_methods" 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">
								<a-input v-model:value="formData.productionClass" placeholder="请输入"  allow-clear disabled ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="机型(model)" v-bind="validateInfos.model" id="SaleOrderForm-model" name="model">
                <a-input v-model:value="formData.model" placeholder="请输入"  allow-clear disabled ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="厂家(maker)" v-bind="validateInfos.maker"  id="SaleOrderForm-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="货位(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"></a-input>
							</a-form-item>
						</a-col>   
            <a-col :span="12">
							<a-form-item label="到货详情(arrival details)" v-bind="validateInfos.arrivalDetails"  id="PuechaseInquiryFormForm-attachs" name="arrivalDetails" >
								<a :href="baseUrl+formData.arrivalDetails">{{formData.arrivalDetails}}</a>
							</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="purInAbnormalShip" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="purInAbnormalShipTableRef"
          :loading="purInAbnormalShipTable.loading"
          :columns="purInAbnormalShipTable.columns"
          :dataSource="purInAbnormalShipTable.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="入库明细(stock in details)" key="stockIn" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="stockInTableRef"
          :loading="stockInTable.loading"
          :columns="stockInTable.columns"
          :dataSource="stockInTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          asyncRemove
          >
          </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
    <BaseShipArchiveAccessoriesModal ref="BaseShipArchiveAccessoriesModalRef"></BaseShipArchiveAccessoriesModal>
  </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 { queryPurInAbnormalFormShip, querystockInByMainId, queryDataById} from '../purInAbnormalForm.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {purInAbnormalShipColumns, stockInColumns} from '../purInAbnormalForm.data';
  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 { Form, message } from 'ant-design-vue';
  import { useGlobSetting } from '/@/hooks/setting';
  import moment from 'moment';
  const useForm = Form.useForm;
  export default defineComponent({
    name: "purInAbnormalForm",
    components:{
      JVxeTable,
			JFormContainer,
      JUpload,
      JDictSelectTag,
      BaseShipArchiveAccessoriesModal,
    },
    props:{
      formDisabled:{
        type: Boolean,
        default: false
      },
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    },
    emits:['success'],
    setup(props, {emit}) {
      const { domainUrl } = useGlobSetting();
      const baseUrl = domainUrl + '/sys/common/static/';
      const loading = ref(false);
      const formRef = ref();
      const purInAbnormalShipTableRef = ref();
      const BaseShipArchiveAccessoriesModalRef = ref();
      const purInAbnormalShipTable = reactive<Record<string, any>>({
        loading: false,
        columns: purInAbnormalShipColumns,
        dataSource: []
      });
      const stockInTableRef = ref();
      const stockInTable = reactive<Record<string, any>>({
        loading: false,
        columns: stockInColumns,
        dataSource: []
      });
      const activeKey = ref('purInAbnormalShip');
      const formData = reactive<Record<string, any>>({
        id: '',
        status: undefined,
        delFlag: undefined,
        sourceCode:'',
        billCode:'',
        billDate: moment(new Date()).format('YYYY-MM-DD'),   
        project: '', 
        projectName:'',  
        supplier:"",
        supplierName:'',
        delivery: '',   
        productionClass: '',   
        model:'',   
        maker: '',
        goodsAllocation:'',
        warehouse:'',
        notes:'',
        attachs:'',
        arrivalDetails:'',
        typr:'1'
      });
      //表单验证
      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: 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();
        purInAbnormalShipTable.dataSource = [];
        stockInTable.dataSource = [];
        activeKey.value = 'purInAbnormalShip'
      }
      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const purInAbnormalShipDataList = await queryPurInAbnormalFormShip(row['id']);
        purInAbnormalShipTable.dataSource = [...purInAbnormalShipDataList];
        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, {
        'storePurchaseInShip': purInAbnormalShipTableRef,
        'storePurchaseInDetails': 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() {
        if( formData.sourceCode==''){
          message.error('请添加入库明细！');
        }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)
      }
      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }
      return {
        purInAbnormalShipTableRef,
        purInAbnormalShipTable,
        stockInTableRef,
        stockInTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
        BaseShipArchiveAccessoriesModalRef,
        viewAccessory,
        baseUrl
      }
    }
  });
</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>
