<template>
  <a-spin :spinning="loading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form v-bind="formItemLayout" name="commissionPayRequest" ref="formRef">
          <a-row>
            <a-col :span="12">
              <a-form-item label="申请单编号(bill code)" v-bind="validateInfos.billCode" id="commissionPayRequest-billCode" name="billCode">
                <a-input v-model:value="formData.billCode" placeholder="自动生成" disabled />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="申请日期(bill date)" v-bind="validateInfos.billDate" id="commissionPayRequest-billDate" name="billDate">
                <a-date-picker placeholder="请选择" 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="返佣类型(commission type)"
                v-bind="validateInfos.commissionType"
                id="commissionPayRequest-commissionType"
                name="commissionType"
              >
                <JDictSelectTag v-model:value="formData.commissionType" placeholder="请选择" dictCode="commission_type" style="width: 100%" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="收款人(payee)" v-bind="validateInfos.payee" id="commissionPayRequest-payee" name="payee">
                <ApiSelect
                  :api="listPayee"
                  showSearch
                  v-model:value="formData.payee"
                  :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="预计付款日期(expected payment date)"
                v-bind="validateInfos.expectedPaymentDate"
                id="commissionPayRequest-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="币种(currency)" v-bind="validateInfos.currency" id="commissionPayRequest-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="开户行(opening bank)" v-bind="validateInfos.openingBank" id="commissionPayRequest-openingBank" name="openingBank">
                <a-input v-model:value="formData.openingBank" placeholder="请输入" allow-clear AutoComplete="off" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="银行账号(bank account)" v-bind="validateInfos.bankAccount" id="commissionPayRequest-bankAccount" name="bankAccount">
                <a-input v-model:value="formData.bankAccount" placeholder="请输入" allow-clear AutoComplete="off" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="银行代码(swift code)" v-bind="validateInfos.swiftCode" id="commissionPayRequest-swiftCode" name="swiftCode">
                <a-input v-model:value="formData.swiftCode" placeholder="请输入" allow-clear AutoComplete="off" />
              </a-form-item>
            </a-col>

            <a-col :span="12">
              <a-form-item label="备注(notes)" v-bind="validateInfos.notes" id="commissionPayRequest-notes" name="notes">
                <a-input v-model:value="formData.notes" placeholder="请输入备注(notes)" allow-clear AutoComplete="off" />
              </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" :disabled="disabled">
          选择销售订单(select sale order)</a-button
        >
        <j-vxe-table
          :keep-source="true"
          resizable
          ref="paymentDetailsTableRef"
          :loading="paymentDetailsTable.loading"
          :columns="paymentDetailsTable.columns"
          :dataSource="paymentDetailsTable.dataSource"
          :disabled="disabled"
          :rowNumber="true"
          :rowSelection="true"
          asyncRemove
        >
          <template #action="props">
            <a-popconfirm title="确定删除吗？" @confirm="handleDelete1(props)" v-if="!disabled">
              <a>删除(delete)</a>
            </a-popconfirm>
          </template>
        </j-vxe-table>
      </a-tab-pane>
    </a-tabs>
    <SelectSaleOrderModal ref="SelectSaleOrderModalRef" @select-sale-order-mian="addDetailList" />
  </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 { queryPaymentDetailListByMainId, queryDataById, saveOrUpdate, listPayee } from '../commissionPayRequestForm.api';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import { paymentDetailColumns } from '../commissionPayRequestList.data';
  import SelectSaleOrderModal from '../../../publicComponents/SelectSaleOrderMianModal.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 moment from 'moment';
  const useForm = Form.useForm;
  export default defineComponent({
    name: 'CommissionPayRequestForm',
    components: {
      JVxeTable,
      JFormContainer,
      JUpload,
      JDictSelectTag,
      SelectSaleOrderModal,
      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 SelectSaleOrderModalRef = ref();
      const paymentDetailsTableRef = ref();
      const paymentDetailsTable = reactive<Record<string, any>>({
        loading: false,
        columns: paymentDetailColumns,
        dataSource: [],
      });
      const activeKey = ref('paymentDetails');
      const formData = reactive<Record<string, any>>({
        id: '',
        status: undefined,
        delFlag: undefined,
        sourceCode: '',
        billDate: moment(new Date()).format('YYYY-MM-DD'),
        billCode: '',
        commissionType: '',
        payee: '',
        expectedPaymentDate: '',
        currency: '',
        openingBank: '',
        bankAccount: '',
        swiftCode: '',
        notes: '',
      });

      //表单验证
      const validatorRules = reactive({
        payee: [{ required: true, message: '请选择付款人(select payee)' }],
        currency: [{ required: true, message: '请选择币种(select currency)' }],
      });
      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';
      }
      //编辑方法
      async function edit(row) {
        //主表数据
        await queryMainData(row.id);
        const paymentDetailsDataList = await queryPaymentDetailListByMainId(row['id']);
        paymentDetailsTable.dataSource = [...paymentDetailsDataList];
      }
      //获取主表
      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, {
        purCommissionRequestDetails: 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() {
        var xTable = paymentDetailsTableRef.value!.getXTable();
        if (xTable.data.length == 0) {
          message.warning('请添加付款明细');
        } else {
          paymentDetailsTableRef.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];
          });
        }
      }

      /**
       * 值改变事件触发-树控件回调
       * @param key
       * @param value
       */
      function handleFormChange(key, value) {
        formData[key] = value;
      }
      //产品明细-删除行
      async function handleDelete1(prop) {
        var xTable = paymentDetailsTableRef.value!.getXTable();
        var newArray = [...xTable.data];
        newArray.splice(prop.rowIndex, 1);
        paymentDetailsTable.dataSource = newArray;
      }
      function selectOrder() {
        SelectSaleOrderModalRef.value.getTableFormCommissionPayment();
      }
      function addDetailList(data) {
        var billCodeArr = [];
        data.map((item) => {
          item.sourceId = item.id;
          item.saleCode = item.billCode;
          billCodeArr.push(item.billCode);
          item.saleId = item.id;
          item.orderMoney = item.orderMoney;
          item.id = undefined;
        });
		
		if (formData.sourceCode !== '') {
		  formData.sourceCode = formData.sourceCode + ',' + billCodeArr.join(',');
		} else {
		  formData.sourceCode = billCodeArr.join(',');
		}
		
        var xTable = paymentDetailsTableRef.value!.getXTable();
        var arrSonFormDelivery = xTable.data.concat(data);
        paymentDetailsTable.dataSource = arrSonFormDelivery;
      }
      return {
        paymentDetailsTableRef,
        paymentDetailsTable,
        validatorRules,
        validateInfos,
        activeKey,
        loading,
        formData,
        setFieldsValue,
        handleFormChange,
        formItemLayout,
        disabled,
        getFormData,
        submitForm,
        add,
        edit,
        formRef,
        handleDelete1,
        SelectSaleOrderModalRef,
        selectOrder,
        addDetailList,
        listPayee,
      };
    },
  });
</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>
