<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="queryFormRef" :inline="true" :model="queryParams" label-position="left" label-width="130px">
            <el-form-item label="管理机构" prop="manageCom">
              <el-select v-model="queryParams.manageCom" placeholder="请输入管理机构" clearable @change="manageComChangeQury">
                <template #header>
                  <el-input v-model="likeName" placeholder="可根据机构编码或名称模糊查询" @input="filterByManageCom"></el-input>
                </template>
                <el-option
                  v-for="dict in filteredManagecom"
                  :key="dict.dictValue"
                  :label="dict.dictValue + '-' + dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="收款银行账号" prop="receivingBankAccount">
              <el-select v-model="queryParams.receivingBankAccount" clearable placeholder="请输入收款银行账号">
                <template #header>
                  <el-input v-model="likeCollName" placeholder="可根据银行账号模糊查询" @input="filterByCollBankName"></el-input>
                </template>
                <el-option
                  v-for="dict in filteredListCollBank"
                  :key="dict.bankAccount"
                  :label="dict.bankAccount"
                  :value="dict.bankAccount"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="客户账户名称" prop="payerName">
              <el-input
                v-model="queryParams.payerName"
                clearable
                placeholder="请输入客户账户名称"
                maxlength="100"
                show-word-limit
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="虚拟户编码" prop="virtualAccount">
              <el-input
                v-model="queryParams.virtualAccount"
                clearable
                placeholder="请输入虚拟户编码"
                maxlength="50"
                show-word-limit
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="到账日期" prop="arrivalDate">
              <el-date-picker
                v-model="dateRange"
                end-placeholder="结束日期"
                range-separator="-"
                start-placeholder="开始日期"
                type="daterange"
                value-format="YYYY-MM-DD"
                style="width: 240px"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="缴费方式" prop="paymentMethod">
              <el-select v-model="queryParams.paymentMethod" clearable 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-form-item label="是否委托专户" prop="isEntrust">
              <el-select v-model="queryParams.isEntrust" clearable 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-form-item label="特殊收费类型" prop="specType">
              <el-select v-model="queryParams.specType" clearable 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-form-item label="申请状态" prop="approvalStatus">
              <el-select v-model="queryParams.approvalStatus" clearable placeholder="申请状态">
                <el-option v-for="dict in bls_temp_approval_state" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-row>
              <el-form-item>
                <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['bls:charges:add']" type="primary" plain icon="Plus" @click="handleAdd()">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="chargesList" @row-dblclick="handleRowDblclick">
        <el-table-column align="center" type="selection" width="50" />
        <el-table-column align="center" label="客户账户名称" prop="payerName" show-overflow-tooltip width="150" />
        <el-table-column align="center" label="客户开户行" prop="payerBank" show-overflow-tooltip width="120">
          <template #default="scope">
            <dict-tag :options="sys_bank_code" :value="scope.row.payerBank" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="付款人银行账号" prop="payerBankAccount" show-overflow-tooltip width="150" />
        <el-table-column align="center" label="是否委托专户" prop="isEntrust" show-overflow-tooltip width="120">
          <template #default="scope">
            <dict-tag :options="sys_yes_no" :value="scope.row.isEntrust" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="金额" prop="amount" show-overflow-tooltip width="150" />
        <el-table-column align="center" label="收款银行账号" prop="receivingBankAccount" show-overflow-tooltip width="200" />
        <el-table-column align="center" label="收款银行名称" prop="receivingBankName" show-overflow-tooltip width="120">
          <template #default="scope">
            <dict-tag :options="sys_bank_code" :value="scope.row.receivingBankName" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="到账日期" prop="arrivalDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.arrivalDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="申请状态" prop="approvalStatus">
          <template #default="scope">
            <dict-tag :options="bls_temp_approval_state" :value="scope.row.approvalStatus" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="对账码" prop="reconciliationCode" show-overflow-tooltip width="150" />
        <el-table-column align="center" label="虚拟户编码" prop="virtualAccount" show-overflow-tooltip width="150" />
        <el-table-column align="center" label="备注" prop="remark" show-overflow-tooltip width="350" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button
                v-if="scope.row.approvalStatus === '-2'"
                v-hasPermi="['bls:charges:query']"
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                >编辑</el-button
              >
            </el-tooltip>
            <el-tooltip content="查看" placement="top">
              <el-button
                v-if="scope.row.approvalStatus != '-2'"
                v-hasPermi="['bls:charges:query']"
                link
                type="primary"
                icon="View"
                @click="handleUpdate(scope.row)"
                >查看</el-button
              >
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNum" :total="total" @pagination="getList" />
    </el-card>
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="90%" top="5vh" append-to-body class="scrollbar">
      <el-card shadow="hover">
        <el-form ref="chargesFormRef" :model="form" :rules="rules" :inline="true" label-width="130px" label-position="left">
          <!-- 隐藏信息 -->
          <el-row>
            <el-form-item v-if="false" label="暂收费ID" prop="temporaryChargeId">
              <el-input v-model="form.temporaryChargeId" placeholder="请输入付款金额" clearable />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="管理机构" prop="manageCom">
              <el-select v-model="form.manageCom" clearable placeholder="请输入管理机构" @change="manageComChangeForm">
                <template #header>
                  <el-input v-model="likeName" placeholder="可根据机构编码或名称模糊查询" @input="filterByManageCom"></el-input>
                </template>
                <el-option
                  v-for="dict in filteredManagecom"
                  :key="dict.dictValue"
                  :label="dict.dictValue + '-' + dict.dictLabel"
                  :value="dict.dictValue"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否委托专户" prop="isEntrust">
              <el-select v-model="form.isEntrust" clearable placeholder="是否委托专户" @change="isEntrustForm">
                <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-form-item label="收款银行账号" clearable prop="receivingBankAccount">
              <el-select v-model="form.receivingBankAccount" placeholder="请输入收款银行账号" @change="bankAccountChangeForm">
                <template #header>
                  <el-input v-model="likeCollName" placeholder="可根据银行账号模糊查询" @input="filterByCollBankName"></el-input>
                </template>
                <el-option
                  v-for="dict in filteredListCollBank"
                  :key="dict.bankAccount"
                  :label="dict.bankAccount"
                  :value="dict.bankAccount"
                ></el-option>
              </el-select>
              <!--              <el-select v-model="form.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-row>
          <el-row>
            <el-form-item label="客户账户名称" prop="payerName">
              <el-input v-model="form.payerName" placeholder="请输入客户账户名称" maxlength="100" show-word-limit clearable />
            </el-form-item>
            <el-form-item label="客户开户行" prop="payerBank">
              <el-select v-model="form.payerBank" clearable 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="form.payerBankAccount" placeholder="请输入客户银行账户" maxlength="50" show-word-limit clearable />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="付款金额" prop="amount">
              <el-input-number v-model="form.amount" placeholder="请输入付款金额" :precision="2" clearable style="width: 230px" />
            </el-form-item>
            <el-form-item label="虚拟户编码" prop="virtualAccount" style="margin-left: 10px">
              <el-input v-model="form.virtualAccount" placeholder="请输入虚拟户编码" maxlength="6" show-word-limit clearable />
            </el-form-item>
            <el-form-item label="到账日期" prop="arrivalDate">
              <el-date-picker
                v-model="form.arrivalDate"
                clearable
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择过期时间"
                style="width: 240px"
                :disabled-date="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="缴费方式" prop="paymentMethod">
              <el-select v-model="form.paymentMethod" clearable placeholder="请输入缴费方式">
                <el-option
                  v-for="dict in sys_rec_method.filter((dict) => dict.value !== '01')"
                  :key="dict.value"
                  :label="dict.value + '-' + 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="form.reconciliationCode" placeholder="请输入银行记账码" maxlength="50" disabled show-word-limit clearable />
            </el-form-item>
<!--            <el-row>
              <el-form-item label="电E金服" prop="isEfinance">
                <el-radio-group v-model="form.isEfinance">
                  <el-radio label="1">是</el-radio>
                  <el-radio label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-row>-->
          </el-row>
          <el-row>
            <el-form-item label="缴费项目" prop="chargItems">
              <el-input v-model="form.chargItems" placeholder="请输入缴费项目" clearable />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="是否特殊收费" clearable prop="isSpec">
              <el-switch
                v-model="form.isSpec"
                size="large"
                active-value="Y"
                inactive-value="N"
                active-text="是"
                inactive-text="否"
                @change="handleFromIsSpecChange()"
              />
            </el-form-item>
            <el-form-item v-if="form.isSpec === 'Y'" label="特殊收费类型" prop="specType" style="margin-left: 140px">
              <el-select v-model="form.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="form.remark"
                :rows="4"
                style="width: 440px"
                type="textarea"
                maxlength="500"
                show-word-limit
                placeholder="请输入备注信息"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-row>
          <el-form-item>
            <el-button v-hasPermi="['bls:charges:add']" type="primary" icon="Search" @click="handleAddCharges">保存</el-button>
            <el-button
              v-if="form.approvalStatus === '-2'"
              v-hasPermi="['bls:charges:approval']"
              type="primary"
              icon="Position"
              @click="handleApprovalCharges"
              >提交</el-button
            >
            <el-button
              v-if="form.approvalStatus === '-2'"
              v-hasPermi="['bls:charges:applayfail']"
              type="danger"
              icon="Close"
              @click="handleRevertedCharges"
              >作废</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </el-dialog>
  </div>
</template>
<script setup name="ChargesIndex" lang="ts">
import { ChargesQuery, ChargesVO } from '@/api/bls/charges/types';
import { addCharges, applayfail, approvalCharges, editCharges, failCharges, getCharges, getCollBank, listCharges } from '@/api/bls/charges';
import { pickerOptions } from '@/utils/date';
import { queryManageCom } from '@/api/bls/cache';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const chargesList = ref<ChargesVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const likeName = ref('');
const filteredManagecom = ref([]);
const sys_managecom = ref([]);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);

const manageComCollBank = ref([]);
const ListCollBank = ref([]);
const filteredListCollBank = ref([]);
const likeCollName = ref('');

const queryFormRef = ref<ElFormInstance>();
const chargesFormRef = ref<ElFormInstance>();

// 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 { bls_temp_approval_state } = toRefs<any>(proxy?.useDict('bls_temp_approval_state'));
const initFormData = {
  temporaryChargeId: undefined,
  manageCom: undefined,
  temporaryChargeNumber: undefined,
  bankSerialNumber: undefined,
  payerName: undefined,
  payerBank: undefined,
  payerBankAccount: undefined,
  amount: undefined,
  paymentMethod: undefined,
  receivingBankAccount: undefined,
  receivingBankName: undefined,
  arrivalDate: undefined,
  reconciliationCode: '000000',
  matchingStatus: undefined,
  matchingBalance: undefined,
  approvalStatus: undefined,
  excessPaymentAmount: undefined,
  virtualAccount: undefined,
  isEntrust: undefined,
  remark: undefined,
  isSpec: undefined,
  specType: undefined,
  chargItems: undefined,
  isEfinance: '0'
};
const data = reactive<PageData<ChargesQuery, any>>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    temporaryChargeNumber: undefined,
    bankSerialNumber: undefined,
    payerName: undefined,
    payerBank: undefined,
    payerBankAccount: undefined,
    amount: undefined,
    paymentMethod: undefined,
    receivingBankAccount: undefined,
    receivingBankName: undefined,
    arrivalDate: undefined,
    matchingStatus: undefined,
    matchingBalance: undefined,
    approvalStatus: undefined,
    excessPaymentAmount: undefined,
    manageCom: undefined,
    isEntrust: undefined,
    isSpec: undefined,
    specType: undefined,
    params: {}
  },
  form: {
    ...initFormData
  },
  rules: {
    manageCom: [{ required: true, message: '管理机构不能为空', trigger: 'blur' }],
    receivingBankAccount: [{ required: true, message: '收款银行账号不能为空', trigger: 'blur' }],
    payerName: [{ required: true, validator: validatePayerName, trigger: 'blur' }],
    payerBank: [{ required: true, 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' }],
    virtualAccount: [{ validator: checkVirtualAccount, trigger: 'blur' }]
  }
});

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

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

/** 查询团体暂收费列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCharges(proxy?.addDateRange(queryParams.value, dateRange.value));
  chargesList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
// 新增双击事件处理函数
const handleRowDblclick = (row: ChargesVO) => {
  handleUpdate(row); // 复用查看逻辑
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};

const handleIsSpecChange = () => {
  if (queryParams.value.isSpec === 'N') {
    queryParams.value.specType = undefined;
  }
};

const handleFromIsSpecChange = () => {
  if (form.value.isSpec === 'N') {
    form.value.specType = undefined;
  }
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '新增暂收费';
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  chargesFormRef.value?.resetFields();
  //重置模糊查询内容，模糊查询内容在form表单中也使用
  likeCollName.value = undefined;
  likeName.value = undefined;
  filteredListCollBank.value = ListCollBank.value;
  manageComCollBank.value = ListCollBank.value;
  filteredManagecom.value = sys_managecom.value;
};

const handleAddCharges = () => {
  chargesFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      let res;
      if (form.value.temporaryChargeId == null) {
        res = await addCharges(form.value);
      } else {
        res = await editCharges(form.value);
      }

      if (res.code == 200) {
        Object.assign(form.value, res.data);
        proxy?.$modal.msgSuccess('保存成功');
      }
    } else {
      proxy?.$modal.msgError(res.msg || '保存失败,请检查数据是否正确');
    }
  });
};

const handleApprovalCharges = () => {
  chargesFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      const res = await approvalCharges(form.value);
      if (res.code == 200) {
        proxy?.$modal.msgSuccess('提交审核成功');
        dialog.visible = false;
        await getList();
      }
    }
  });
};

const handleRevertedCharges = async () => {
  await proxy?.$modal.confirm('是否要作废银行流水号为' + form.value.bankSerialNumber + '的数据?');
  const temporaryChargeIds = [form.value.temporaryChargeId];
  const res = await applayfail(temporaryChargeIds);
  if (res.code == 200) {
    proxy?.$modal.msgSuccess('作废成功');
    dialog.visible = false;
    getList();
  }
};

const handleUpdate = async (row) => {
  reset();
  const _id = row?.temporaryChargeId;
  const res = await getCharges(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '查看暂收费';
};

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

function checkPayerBankAccount(rule, value, callback) {
  if (form.value.paymentMethod !== '03' && (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 ((form.value.paymentMethod == '01' || form.value.paymentMethod == '02') && (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 if (value <= 0) {
    callback(new Error('金额需大于0'));
  } 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 validatePayerName(rule, value, callback) {
  if (!value) {
    return callback(new Error('客户账户名称不能为空'));
  }
  if (/\s/.test(value)) {
    return callback(new Error('客户账户名称不能包含空格'));
  }
  // 检查是否为纯数字
  if (/^\d+$/.test(value)) {
    return callback(new Error('客户账户名称不能为纯数字'));
  }
  callback();
}

function checkVirtualAccount(rule, value, callback) {
  if (form.value.isEntrust && form.value.isEntrust === 'Y' && (value == null || value == '')) {
    return callback(new Error('委托专户，虚拟户编码不能为空'));
  }
  if (form.value.isEntrust && form.value.isEntrust === 'N' && value != null && value != '') {
    return callback(new Error('非委托专户，虚拟户编码必须为空'));
  }
  // 当存在 isEntrust 且虚拟户编码不为空时，进行 6 位数字校验
  if (form.value.isEntrust && value != null && value !== '') {
    // 使用正则表达式检查是否为 6 位数字
    const inputValue = String(value).trim();
    const regex = /^\d{6}$/;
    if (!regex.test(inputValue)) {
      return callback(new Error('虚拟户必须为 6 位数字'));
    }
  }
  callback();
}

/** 模糊查询 */
const filterByManageCom = () => {
  if (likeName.value) {
    filteredManagecom.value = sys_managecom.value.filter((item) => {
      return item.dictLabel.includes(likeName.value) || item.dictValue.includes(likeName.value);
    });
  } else {
    filteredManagecom.value = sys_managecom.value;
  }
};

/**
 * 初始化银行列表
 */
const initCollBank = async () => {
  const res = await getCollBank();
  if (res.code == 200) {
    ListCollBank.value = res.data;
    filteredListCollBank.value = res.data;
    manageComCollBank.value = res.data;
  }
};

/** 模糊查询 */
const filterByCollBankName = () => {
  if (manageComCollBank.value === ListCollBank.value) {
    if (likeCollName.value) {
      filteredListCollBank.value = ListCollBank.value.filter((item) => {
        return item.bankAccount.includes(likeCollName.value);
      });
    } else {
      filteredListCollBank.value = ListCollBank.value;
    }
  } else {
    if (likeCollName.value) {
      filteredListCollBank.value = manageComCollBank.value.filter((item) => {
        return item.bankAccount.includes(likeCollName.value);
      });
    } else {
      filteredListCollBank.value = manageComCollBank.value;
    }
  }
};

const manageComChangeForm = () => {
  form.value.receivingBankAccount = undefined;
  if (form.value.isEntrust && form.value.isEntrust === 'Y') {
    filteredListCollBank.value = ListCollBank.value.filter((item) => {
      return item.isEntrust === 'Y';
    });
  } else {
    if (form.value.manageCom) {
      let _manageCom = '86';
      if (form.value.manageCom.length >= 4) {
        _manageCom = form.value.manageCom.slice(0, 4);
      }
      manageComCollBank.value = ListCollBank.value.filter((item) => {
        return item.manageCom.includes(_manageCom);
      });
      if (manageComCollBank.value.length > 0) {
        filteredListCollBank.value = manageComCollBank.value;
      }
    }
  }
  proxy.$refs.chargesFormRef.validateField('manageCom');
};

const manageComChangeQury = () => {
  queryParams.value.receivingBankAccount = undefined;
  if (queryParams.value.manageCom) {
    let _manageCom = '86';
    if (queryParams.value.manageCom.length >= 4) {
      _manageCom = queryParams.value.manageCom.slice(0, 4);
    }
    manageComCollBank.value = ListCollBank.value.filter((item) => {
      return item.manageCom.includes(_manageCom);
    });
    filteredListCollBank.value = manageComCollBank.value;
  }
};

const bankAccountChangeForm = () => {
  proxy.$refs.chargesFormRef.validateField('receivingBankAccount');
};

const isEntrustForm = () => {
  if (form.value.isEntrust && form.value.isEntrust === 'Y') {
    filteredListCollBank.value = ListCollBank.value.filter((item) => {
      return item.isEntrust === 'Y';
    });
  } else {
    manageComChangeForm();
  }
};
const getCache = async () => {
  const res = await queryManageCom();
  if (res.code == 200) {
    sys_managecom.value = res.data;
    filteredManagecom.value = sys_managecom.value;
  }
};

onMounted(() => {
  getList();
  getCache();
  initCollBank();
});
</script>

<style scoped lang="scss"></style>
