<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form v-bind="formItemLayout" name="purPaymnetRequest" ref="formRef">
          <a-row>
            <a-col :span="12">
							<a-form-item label="申请单编号(bill code)" v-bind="validateInfos.billCode" id="purPaymnetRequest-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="purPaymnetRequest-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="供应商(supplier)" v-bind="validateInfos.supplier" id="purPaymnetRequest-supplier" name="supplier">
                <ApiSelect
                  :api="listSupplier"
                  showSearch
                  v-model:value="formData.supplier"
                  :filterOption="false"
                  resultField="records"
                  labelField="name"
                  valueField="id"
                  :params='{pageSize:-1}'
                  @change="changeSupplier"
                />
              </a-form-item>
            </a-col>
						<a-col :span="12">
							<a-form-item label="预计付款日期(expected payment date)" v-bind="validateInfos.expectedPaymentDate" id="purPaymnetRequest-expectedPaymentDate" name="expectedPaymentDate">
                <a-date-picker placeholder="请选择预计付款日期(expected payment date)"  v-model:value="formData.expectedPaymentDate"  value-format="YYYY-MM-DD"   style="width: 100%"  allow-clear />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="收款人(payee)" v-bind="validateInfos.payee" id="purPaymnetRequest-payee" name="payee">
                <a-input v-model:value="formData.payee" placeholder="" AutoComplete="off"></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="开户行(opening bank)" v-bind="validateInfos.openingBank" id="purPaymnetRequest-openingBank" name="openingBank">
                <a-input v-model:value="formData.openingBank" placeholder="请输入"  allow-clear AutoComplete="off"></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="银行账号(bank account)" v-bind="validateInfos.bankAccount" id="purPaymnetRequest-bankAccount" name="bankAccount">
                <a-input v-model:value="formData.bankAccount" placeholder="请输入"  allow-clear AutoComplete="off"></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="银行代码(swift code)" v-bind="validateInfos.swiftCode" id="purPaymnetRequest-swiftCode" name="swiftCode">
                <a-input v-model:value="formData.swiftCode" placeholder="请输入"  allow-clear AutoComplete="off"></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="币种(currency)" v-bind="validateInfos.currency" id="purPaymnetRequest-currency" name="currency">
                <JDictSelectTag v-model:value="formData.currency" placeholder="请选择" dictCode="currency" style="width: 100%;"/>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="备注(notes)" v-bind="validateInfos.notes" id="purPaymnetRequest-notes" name="notes">
								<a-input v-model:value="formData.notes" placeholder="请输入备注(notes)"  allow-clear AutoComplete="off"></a-input>
							</a-form-item>
						</a-col>
            <a-col :span="12">
							<a-form-item label="委托收款证明(entrusted certificate)" v-bind="validateInfos.collectionCertificate"  name="collectionCertificate" >
                  <JUpload v-model:value="formData.collectionCertificate"></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="采购付款申请 - 付款明细(payment details)" key="paymentDetails" :forceRender="true">
        <a-button type="primary"  style="margin-right: 1%;margin-bottom: 1%;" @click="selectOrder"> 选择采购订单(select purchase order)</a-button>
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="paymentDetailsTableRef"
          :loading="paymentDetailsTable.loading"
          :columns="paymentDetailsTable.columns"
          :dataSource="paymentDetailsTable.dataSource"
          :height="340"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          asyncRemove
          @valueChange="changeValues"
          >
            <template #action="props">
                  <a-popconfirm title="确定删除吗？" @confirm="handleDelete1(props)">
                    <a>删除(delete)</a>
                  </a-popconfirm>
              </template>
              <template #viewDetail="props">
                    <a>查看(view)</a>
              </template>
              <template #invoice="props">
                <JUpload v-model:value="props.row.invoice"></JUpload>
              </template>
          </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
    <SelectPurchaseOrderModal ref="SelectPurchaseOrderModalRef" @selectPurchaseOrder="addDetailList"></SelectPurchaseOrderModal>
  </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 { listSupplier,queryPaymentDetailListByMainId,queryDataById, saveOrUpdate } from '../purPaymentRequestForm.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import { paymentDetailColumns} from '../purPaymentRequest.data';
  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 { ApiSelect } from '/@/components/Form';
  import { JDictSelectTag} from '/@/components/Form';
  import { Form,message } 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: "purPaymentRequestForm",
    components:{
      JVxeTable,
			JFormContainer,
      JUpload,
      JDictSelectTag,
      SelectPurchaseOrderModal,
      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();
      const SelectPurchaseOrderModalRef = ref()
      const paymentDetailsTableRef = ref();
      const paymentDetailsTable = reactive<Record<string, any>>({
        loading: false,
        columns: paymentDetailColumns,
        dataSource: []
      });
      const activeKey = ref('paymentDetails');
      var notAllowEdit = ref(false);
      const formData = reactive<Record<string, any>>({
        id: '',
        status: undefined,
        delFlag: undefined,
        sourceCode:'',
        billDate: moment(new Date()).format('YYYY-MM-DD'),   
        billCode: '',   
        supplier: '',   
        supplierName: '',   
        expectedPaymentDate: '',   
        payee: '',   
        openingBank: '',   
        bankAccount: '',   
        swiftCode: '',   
        currency: '',   
        notes:'',   
        collectionCertificate:''      
      });

      //表单验证
      const validatorRules = reactive({
      });
      const {resetFields, validate, validateInfos} = useForm(formData, validatorRules, {immediate: false});
      const dbData = {};
      const formItemLayout = {
        labelCol: {xs: {span: 24}, sm: {span: 8}},
        wrapperCol: {xs: {span: 24}, sm: {span: 13}},
        labelCol1: {xs: {span: 24}, sm: {span: 8}},
        wrapperCol1: {xs: {span: 24}, sm: {span: 13}},
      };

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

      
      //新增方法
      function add() {
        resetFields();
        paymentDetailsTable.dataSource = [];
        activeKey.value = 'paymentDetails'
        notAllowEdit.value = false
      }
      //编辑方法
      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        const paymentDetailsDataList = await queryPaymentDetailListByMainId(row['id']);
        paymentDetailsTable.dataSource = [...paymentDetailsDataList];
        notAllowEdit.value=true
      }
      //获取主表
      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, {
        'purPaymentRequestDetails': paymentDetailsTableRef,
      });
      //获取表单信息
      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();
        if(!subData.purPaymentRequestDetailsList||subData.purPaymentRequestDetailsList.lenght==0){
          message.warning('请添加付款明细')
        }else{
          
          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 handleDelete1(prop) {
        var newArray = [...paymentDetailsTable.dataSource]
        newArray.splice(prop.rowIndex, 1)
        paymentDetailsTable.dataSource = newArray  
        // if( paymentDetailsTable.dataSource.length!==0){
        //   var arr = []
        //   paymentDetailsTable.dataSource.map(item=>{
        //     if(item.sourceId){
        //       arr.push(item.sourceId)
        //     } 
        //   })
        //   if(arr.length==0){
        //     formData.sourceCode=''
        //     notAllowEdit.value=false
        //   }
        // }else{
        //    formData.sourceCode=''
        //    notAllowEdit.value=false
        // }
      }
      function changeValues(prop){
        
      }
      function selectOrder(){
        SelectPurchaseOrderModalRef.value.getTableFromPurPayRequestForm()
      }
      function addDetailList(data){
        data.map(item=>{
          item.sourceId = item.childId
          item.purchaseCode =  item.billCode
          item.purchaseId =  item.id
          item.orderMoney =  item.taxAmount
        })
        var arrSonFormDelivery = data.concat(paymentDetailsTable.dataSource)
        paymentDetailsTable.dataSource=arrSonFormDelivery     
      }
      async function changeSupplier(value){
        var param={id:value}
        var result=await listSupplier(param)     
        formData.supplierName =result.records[0].name
      }
      return {
        listSupplier,
        paymentDetailsTableRef,
        paymentDetailsTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
        handleDelete1,
        notAllowEdit,
        changeValues,
        SelectPurchaseOrderModalRef,
        selectOrder,
        addDetailList,
        changeSupplier
      }
    }
  });
</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>
