<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryParamsRef" :model="queryParams" :rules="rules" :inline="true" label-width="130px" label-position="left">
            <el-row>
              <el-form-item label="管理机构" prop="manageCom">
                <el-select v-model="queryParams.manageCom" placeholder="请输入管理机构">
                  <el-option v-for="dict in sys_managecom" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="收款银行账号" prop="receivingBankAccount">
                <el-select v-model="queryParams.receivingBankAccount" placeholder="请输入收款银行账号">
                  <el-option v-for="dict in receiv_bank_accno" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="客户账户名称" prop="payerName">
                <el-input v-model="queryParams.payerName" placeholder="请输入客户账户名称" clearable />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="付款人开户行" prop="payerBank">
                <el-select v-model="queryParams.payerBank" placeholder="请输入付款人开户行">
                  <el-option v-for="dict in sys_bank_code" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="付款人银行账号" prop="payerBankAccount">
                <el-input v-model="queryParams.payerBankAccount" placeholder="请输入付款人银行账号" clearable />
              </el-form-item>
              <el-form-item label="付款金额" prop="amount">
                <el-input v-model="queryParams.amount" placeholder="请输入付款金额" clearable />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="银行流水号" prop="bankSerialNumber">
                <el-input v-model="queryParams.bankSerialNumber" placeholder="请输入银行流水号" clearable />
              </el-form-item>
              <el-form-item label="到账日期" prop="arrivalDate">
                <el-date-picker
                  v-model="queryParams.arrivalDate"
                  clearable
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请选择过期时间"
                  style="width: 240px"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="缴费方式" prop="paymentMethod">
                <el-select v-model="queryParams.paymentMethod" placeholder="请输入缴费方式">
                  <el-option v-for="dict in sys_rec_method" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="银行记账码" prop="reconciliationCode">
                <el-input v-model="queryParams.reconciliationCode" placeholder="请输入银行记账码" clearable />
              </el-form-item>
              <el-form-item label="是否委托专户" prop="isEntrust">
                <el-select v-model="queryParams.isEntrust" placeholder="是否委托专户">
                  <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="是否特殊收费" prop="isSpec">
                <el-switch v-model="queryParams.isSpec" size="large" active-value="Y" inactive-value="N" active-text="是" inactive-text="否" @change="handleIsSpecChange()"/>
              </el-form-item>
              <el-form-item v-if="queryParams.isSpec === 'Y'" label="特殊收费类型" prop="specType" style="margin-left: 140px">
                <el-select v-model="queryParams.specType" placeholder="特殊收费类型">
                  <el-option v-for="dict in bfs_spec_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="备注" prop="remark">
                <el-input v-model="queryParams.remark" :rows="4" style="width: 440px" type="textarea" placeholder="请输入备注信息" clearable>
                </el-input>
              </el-form-item>
            </el-row>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleAdd">录入</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
  </div>
</template>

<script setup name="Charges" lang="ts">
import { ChargesQuery } from '@/api/bls/charges/types';
import { addCharges } from '@/api/bls/charges/index';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { sys_managecom } = toRefs<any>(proxy?.useDict('sys_managecom'));
const { receiv_bank_accno } = toRefs<any>(proxy?.useDict('receiv_bank_accno'));
const { sys_bank_code } = toRefs<any>(proxy?.useDict('sys_bank_code'));
const { sys_rec_method } = toRefs<any>(proxy?.useDict('sys_rec_method'));
const { sys_yes_no } = toRefs<any>(proxy?.useDict('sys_yes_no'));
const { bfs_spec_type } = toRefs<any>(proxy?.useDict('bfs_spec_type'));
const queryParamsRef = ref<ElFormInstance>();
const showSearch = ref(true);

const data = reactive<SinglePageData<ChargesQuery>>({
  queryParams: {
    manageCom: undefined,
    temporaryChargeNumber: undefined,
    bankSerialNumber: undefined,
    payerName: undefined,
    payerBank: undefined,
    payerBankAccount: undefined,
    amount: undefined,
    paymentMethod: undefined,
    receivingBankAccount: undefined,
    //todo 修改映射逻辑
    receivingBankName: '103',
    arrivalDate: undefined,
    reconciliationCode: undefined,
    matchingStatus: undefined,
    matchingBalance: undefined,
    //默认待审批状态
    approvalStatus: '0',
    excessPaymentAmount: undefined,
    isEntrust: undefined,
    remark: undefined
  },
  rules: {
    manageCom: [{ required: true, message: '管理机构不能为空', trigger: 'blur' }],
    receivingBankAccount: [{ required: true, message: '收款银行账号不能为空', trigger: 'blur' }],
    payerName: [{ required: true, message: '客户账户名称不能为空', trigger: 'blur' }],
    payerBank: [
      {
        validator: checkPayerBank,
        trigger: 'blur'
      }
    ],
    payerBankAccount: [
      {
        validator: checkPayerBankAccount,
        trigger: 'blur'
      },
      {
        pattern: /^[0-9-]+$/,
        message: '付款人银行账号只能输入数字',
        trigger: 'blur'
      }
    ],
    amount: [
      { required: true, message: '付款金额不能为空', trigger: 'blur' },
      { validator: checkOnlyNumbers, trigger: 'blur' },
      { validator: checkNonNegative, trigger: 'blur' },
      { validator: checkTwoDecimals, trigger: 'blur' }
    ],
    bankSerialNumber: [{ validator: checkBankSerialNumber, trigger: 'blur' }],
    arrivalDate: [{ required: true, message: '到账日期不能为空', trigger: 'blur' }],
    paymentMethod: [{ required: true, message: '缴费方式不能为空', trigger: 'blur' }],
    reconciliationCode: [
      { required: true, message: '银行记账码不能为空', trigger: 'blur' },
      {
        validator: checkReconciliationCode,
        message: '银行记账码不能录入特殊字符',
        trigger: 'blur'
      }
    ],
    isEntrust: [{ required: true, message: '是否委托专户不能为空', trigger: 'blur' }]
  }
});

const { queryParams, rules } = toRefs(data);

function checkPayerBank(rule, value, callback) {
  if (queryParams.value.paymentMethod !== '1' && (value == null || value == '')) {
    callback(new Error('付款人开户行不能为空'));
  } else {
    callback(); // 验证通过
  }
}

function checkPayerBankAccount(rule, value, callback) {
  if (queryParams.value.paymentMethod !== '1' && (value == null || value == '')) {
    callback(new Error('付款人银行账号不能为空'));
  } else {
    callback(); // 验证通过
  }
}

function checkNonNegative(rule, value, callback) {
  if (value < 0) {
    callback(new Error('金额不能为负数'));
  } else {
    callback();
  }
}

function checkTwoDecimals(rule, value, callback) {
  const regex = /^\d+(\.\d{1,2})?$/;
  if (!regex.test(value)) {
    callback(new Error('金额最多保留两位小数'));
  } else {
    callback();
  }
}

function checkBankSerialNumber(rule, value, callback) {
  if (queryParams.value.paymentMethod == '4' && (value == null || value == '')) {
    callback(new Error('缴费方式为银行转账，银行流水号不能为空'));
  } else {
    const specialCharsRegex = /^[A-Za-z0-9]+$/;
    if (value && !specialCharsRegex.test(value)) {
      callback(new Error('银行流水号不能包含特殊字符'));
    }
    callback();
  }
}

function checkOnlyNumbers(rule, value, callback) {
  const regex = /^-?\d+(\.\d{1,2})?$/;
  if (isNaN(Number(value))) {
    callback(new Error('金额只能为数字'));
  } else {
    callback();
  }
}

function checkReconciliationCode(rule, value, callback) {
  if (!value) {
    callback(new Error('银行记账码不能为空'));
    return;
  }
  const specialCharsRegex = /^[A-Za-z0-9]+$/;
  if (!specialCharsRegex.test(value)) {
    callback(new Error('银行记账码不能包含特殊字符'));
  } else {
    callback(); // 必须调用这个表示验证通过
  }
}

function handleAdd() {
  queryParamsRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      await addCharges(queryParams.value);
      proxy?.$modal.msgSuccess('操作成功');
      clearFrom();
    }
  });
}

function clearFrom() {
  queryParamsRef.value?.resetFields();
}

function handleIsSpecChange() {
  if (queryParams.value.isSpec === 'N') {
    queryParams.value.specType = undefined;
  }
}
</script>
