<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="到货日期(arrival date)" v-bind="validateInfos.arrivalDate" :label-col="formItemLayout.labelCol1" :wrapper-col="formItemLayout.wrapperCol1" id="SaleOrderForm-arrivalDate" name="arrivalDate">
								<a-date-picker placeholder="请选择到货日期(arrival date)"  v-model:value="formData.arrivalDate"  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)" :disabled="notAllowEdit"  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.supplierName" :label-col="formItemLayout.labelCol1" :wrapper-col="formItemLayout.wrapperCol1" id="SaleOrderForm-supplierName" name="supplierName">
                <JSelectInput   v-model:value="formData.supplier"  placeholder="请选择" allow-clear  :options="supplierOption" @change="changeSupplier"></JSelectInput>
							</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" :label-col="formItemLayout.labelCol1" :wrapper-col="formItemLayout.wrapperCol1" id="SaleOrderForm-productionClass" name="productionClass">
								<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" :label-col="formItemLayout.labelCol1" :wrapper-col="formItemLayout.wrapperCol1" 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="发货方式(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="包装要求(package requirement)" v-bind="validateInfos.packagebRequirement" :label-col="formItemLayout.labelCol1" :wrapper-col="formItemLayout.wrapperCol1" id="SaleOrderForm-packagebRequirement" name="packagebRequirement">
								<a-input v-model:value="formData.packagebRequirement" placeholder="请输入包装要求(package requirement)"  allow-clear disabled></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="运单号(waybill number)" v-bind="validateInfos.waybillNumber" id="SaleOrderForm-waybillNumber" name="waybillNumber">
								<a-input v-model:value="formData.waybillNumber" placeholder="请输入运单号(waybill number)"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="收件人(recipient)" v-bind="validateInfos.recipient" :label-col="formItemLayout.labelCol1" :wrapper-col="formItemLayout.wrapperCol1" id="SaleOrderForm-recipient" name="recipient">
								<a-input v-model:value="formData.recipient" placeholder="请输入收件人(recipient)"  allow-clear disabled></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="收件人电话(recipient tel)" v-bind="validateInfos.recipientTel" id="SaleOrderForm-recipientTel" name="recipientTel">
								<a-input v-model:value="formData.recipientTel" placeholder="请输入收件人电话(recipient tel)"  allow-clear disabled></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="收件人地址(recipient address)" v-bind="validateInfos.recipientAddress" :label-col="formItemLayout.labelCol1" :wrapper-col="formItemLayout.wrapperCol1" id="SaleOrderForm-recipientAddress" name="recipientAddress">
								<a-input v-model:value="formData.recipientAddress" placeholder="请输入收件人地址(recipient address)"  allow-clear disabled></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">
								<a-input v-model:value="formData.warrantyTerms" placeholder="请输入质保条款(warranty terms)"  allow-clear disabled></a-input>
							</a-form-item>
						</a-col> 
            <a-col :span="12">
							<a-form-item label="采购部门(purchase department)" v-bind="validateInfos.purchaseDepartment" :label-col="formItemLayout.labelCol1" :wrapper-col="formItemLayout.wrapperCol1" id="SaleOrderForm-purchaseDepartment" name="purchaseDepartment">
								<a-input v-model:value="formData.purchaseDepartment" placeholder="请输入"  allow-clear disabled></a-input>
							</a-form-item>
						</a-col>   
            <a-col :span="12">
							<a-form-item label="采购员(purchasesman)" v-bind="validateInfos.purchaseman" id="SaleOrderForm-purchaseman" name="purchaseman">
								<a-input v-model:value="formData.purchaseman" placeholder="请输入采购员(salesman)"  allow-clear disabled ></a-input>
							</a-form-item>
						</a-col> 
            <a-col :span="12">
							<a-form-item label="发票/发货日期(delivery/invoice date)" v-bind="validateInfos.invoiceDate" :label-col="formItemLayout.labelCol1" :wrapper-col="formItemLayout.wrapperCol1" id="SaleOrderForm-invoiceDate" name="invoiceDate">
								<a-date-picker placeholder="请选择发票/发货日期(delivery/invoice date)"  v-model:value="formData.invoiceDate"  value-format="YYYY-MM-DD"  style="width: 100%"  allow-clear />
							</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" :label-col="formItemLayout.labelCol1" :wrapper-col="formItemLayout.wrapperCol1" id="PuechaseInquiryFormForm-arrivalDetails" name="arrivalDetails" >
								<JUpload v-model:value="formData.arrivalDetails"></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="ArriveGoodsFormShipFormShip" :forceRender="true">
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="ArriveGoodsFormShipTableRef"
          :loading="ArriveGoodsFormShipFormShipTable.loading"
          :columns="ArriveGoodsFormShipFormShipTable.columns"
          :dataSource="ArriveGoodsFormShipFormShipTable.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="到货单 - 到货明细(arrive details)" key="arriveDetailsFormProduct" :forceRender="true">
        <a-button type="primary" style="margin-right: 1%;margin-bottom: 1%;" @click="selectPurchaseOrderList"> 选择采购单(select purchase order)</a-button>
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="arriveDetailsFormProductTableRef"
          :loading="arriveDetailsFormProductTable.loading"
          :columns="arriveDetailsFormProductTable.columns"
          :dataSource="arriveDetailsFormProductTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          asyncRemove
          >
            <template #action="props">
              <a-popconfirm title="确定删除吗？" @confirm="handleDelete(props)">
                <a>删除(delete)</a>
              </a-popconfirm>
            </template>
          </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
    <SelectProjectModal ref="SelectProjectModalRef" @selectProject="addProject"></SelectProjectModal>
    <BaseShipArchiveAccessoriesModal ref="BaseShipArchiveAccessoriesModalRef"></BaseShipArchiveAccessoriesModal>
    <SelectPurchaseOrderModal ref="SelectPurchaseOrderModalRef" @selectPurchaseOrder="addAddiveGoods"></SelectPurchaseOrderModal>
  </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 { queryArriveGoodsShipTable, queryArriveGoodsDetailByMainId, queryDataById,ClassList, saveOrUpdate,Supplierlist} from '../ArriveGoodsForm.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import {ArriveGoodsFormShipColumns, ArriveGoodsDetailColumns} from '../ArriveGoodsForm.data';
  import SelectProjectModal from '../../../publicComponents/SelectProjectModal.vue';
  import BaseShipArchiveAccessoriesModal from '../../../publicComponents/BaseShipArchiveAccessoriesModal.vue';
  import SelectPurchaseOrderModal from '../../../publicComponents/SelectPurchaseOrderModal.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 {  ApiSelect, } from '/@/components/Form/index';
  import { Form, message } from 'ant-design-vue';
  import { useUserStore } from '/@/store/modules/user';
  import moment from 'moment';
  const useForm = Form.useForm;
  export default defineComponent({
    name: "SaleOrderForm",
    components:{
      JVxeTable,
			JFormContainer,
      JUpload,
      JDictSelectTag,
      JSelectInput,
      SelectProjectModal,
      BaseShipArchiveAccessoriesModal,
      SelectPurchaseOrderModal,
      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 ArriveGoodsFormShipTableRef = ref();
      const SelectProjectModalRef = ref()
      const BaseShipArchiveAccessoriesModalRef = ref();
      const SelectPurchaseOrderModalRef = ref();
      const ArriveGoodsFormShipFormShipTable = reactive<Record<string, any>>({
        loading: false,
        columns: ArriveGoodsFormShipColumns,
        dataSource: []
      });
      const arriveDetailsFormProductTableRef = ref();
      const arriveDetailsFormProductTable = reactive<Record<string, any>>({
        loading: false,
        columns: ArriveGoodsDetailColumns,
        dataSource: []
      });
      const activeKey = ref('ArriveGoodsFormShipFormShip');
      var notAllowEdit = ref(false);
      const formData = reactive<Record<string, any>>({
        id: '',
        status: undefined,
        delFlag: undefined,
        sourceCode:'',
        billCode:'',
        arrivalDate: moment(new Date()).format('YYYY-MM-DD'),   
        project: '', 
        projectName:'',  
        supplier:"",
        supplierName:'',
        priority: '',   
        productionClass: '',   
        model: '',   
        maker: '',
        delivery:'',
        waybillNumber:'',
        packagebRequirement:'',
        recipient:'',
        recipientTel:'',
        recipientAddress:'',
        warrantyTerms:'',
        purchaseDepartment:'',
        purchaseman:'',
        invoiceDate:'',
        notes:'',
        arrivalDetails:"",
      });
      var supplierOption = ref([]);
      //表单验证
      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();
        ArriveGoodsFormShipFormShipTable.dataSource = [];
        arriveDetailsFormProductTable.dataSource = [];
        activeKey.value = 'ArriveGoodsFormShipFormShip'
        formData.purchaseman=userStore.getUserInfo.username;
        formData.purchaseDepartment = userStore.getUserInfo.orgCode
        getSupplierOption()
      }
      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        //子表数据
        const ArriveGoodsFormShipFormShipDataList = await queryArriveGoodsShipTable(row['id']);
        ArriveGoodsFormShipFormShipTable.dataSource = [...ArriveGoodsFormShipFormShipDataList];
        const arriveDetailsFormProductDataList = await queryArriveGoodsDetailByMainId(row['id']);
        arriveDetailsFormProductTable.dataSource = [...arriveDetailsFormProductDataList];
        getSupplierOption()
        if(arriveDetailsFormProductTable.dataSource.length!==0){
          notAllowEdit.value = true
        }else{
          notAllowEdit.value = false
        }
      }

      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, {
        'purDeliveryNodeShip': ArriveGoodsFormShipTableRef,
        'purDeliveryNoteArrival': arriveDetailsFormProductTableRef,
      });

      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];
          });
        }
      }
      function onSearchProject(){
        SelectProjectModalRef.value.getTable()
      }
      function selectPurchaseOrderList(){
        SelectPurchaseOrderModalRef.value.getTable(formData)
      }
      function getShipList(id){
        let params = {id:id}
        let url = '/purCode/purOrder/queryPurOrderShipByMainId'
          defHttp.get({url:url,params}, { isTransformResponse: false }).then(res=>{
            if(res){
              ArriveGoodsFormShipFormShipTable.dataSource = res.result
            }
          })
      }
      function addProject(data){
        if(data.length==0){
          formData.project = ''
          formData.projectName = ''
        }else{
          formData.project = data[0].id
          formData.projectName = data[0].name
        }
        
      }
       //查看配件信息
       function viewAccessory(prop){
        BaseShipArchiveAccessoriesModalRef.value.getTable(prop.row)
      }
      //产品明细-删除行
      function handleDelete(prop) {
        var newArray = [...arriveDetailsFormProductTable.dataSource]
        newArray.splice(prop.rowIndex, 1)
        arriveDetailsFormProductTable.dataSource = newArray  
        if(arriveDetailsFormProductTable.dataSource.length!==0){
          notAllowEdit.value = true
        }else{
          notAllowEdit.value = false
        }        
      }
      function addAddiveGoods(data){
        data.map(item=>{
          item.model = item.childModel
          item.sourceId = item.childId
          item.orderQuantity=item.quantity
        })
        var arr = data.concat(arriveDetailsFormProductTable.dataSource)
        arriveDetailsFormProductTable.dataSource=arr  
        notAllowEdit.value=true
        formData.sourceCode =data[0].billCode
          formData.project = data[0].project
          formData.projectName = data[0].projectName
          formData.supplierName = data[0].supplierName
          formData.supplier= data[0].supplier
          formData.priority =data[0].priority
          formData.productionClass =data[0].productionClass
          formData.model =data[0].headModel
          formData.maker =data[0].maker
          formData.delivery = data[0].delivery
          formData.packagebRequirement = data[0].packagebRequirement
          formData.recipient = data[0].recipient
          formData.recipientTel = data[0].recipientTel
          formData.recipientAddress = data[0].recipientAddress
          getShipList(data[0].headId)
      }
      function getSupplierOption(){
        defHttp
            .get({ url: '/cuspCode/cuspSupplierProfile/list'}, { isTransformResponse: false })
            .then((res) => {
                if (res.success) {
                  supplierOption.value = []
                  res.result.records.forEach(element => {
                      var obj = {
                        label: element.name?element.name:'无名称请维护',
                        value: element.id?element.id:''
                      };
                      supplierOption.value.push( obj)
                  });    
                }
            })
            .finally(() => {
                // loading.value = false;
            });
      }
      function changeSupplier(prop){
        if(prop){
          supplierOption.value.map(item=>{
            if(item.value==prop){
              formData.supplierName = item.label
            }
          })
        }else{
          formData.supplier = ''
          formData.supplierName = ''
        }
      }
        
      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }
      return {
        ArriveGoodsFormShipTableRef,
        ArriveGoodsFormShipFormShipTable,
        arriveDetailsFormProductTableRef,
        arriveDetailsFormProductTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
        onSearchProject,
        SelectProjectModalRef,
        addProject,
        handleDelete,
        BaseShipArchiveAccessoriesModalRef,
        viewAccessory,
        notAllowEdit,
        SelectPurchaseOrderModalRef,
        selectPurchaseOrderList,
        addAddiveGoods,
        Supplierlist,
        changeSupplier,
        supplierOption,
        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>
