<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-row>
              <el-form-item label="管理机构" prop="manageCom">
                <el-select v-model="queryParams.manageCom" clearable placeholder="请输入管理机构" @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-row>
            <el-row>

              <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="createTime">
                <el-date-picker
                  v-model="createDateRange"
                  type="daterange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  style="width: 240px"
                />
              </el-form-item>
            </el-row>
            <el-row>
              <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="reconciliationCode">
                <el-input v-model="queryParams.reconciliationCode" clearable placeholder="请输入银行记账码" maxlength="50" show-word-limit @keyup.enter="handleQuery" />
              </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-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-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="chargesList" @selection-change="handleSelectionChange" @row-dblclick="handleRowDblClick">
        <el-table-column align="center" type="selection" width="50" />
        <el-table-column align="center" label="缴费方式" prop="paymentMethod">
          <template #default="scope">
            <dict-tag :options="sys_rec_method" :value="scope.row.paymentMethod" />
          </template>
        </el-table-column>
        <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="amount" show-overflow-tooltip width="150" />
        <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="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <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="reconciliationCode" show-overflow-tooltip width="150" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button v-hasPermi="['bls:charges:query']"  link type="primary" icon="View" @click="handleView(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-card shadow="never">
      <el-row>
        <el-button v-hasPermi="['bls:charges:auditpass']" icon="Check" type="primary" @click="handlePass">审核通过 </el-button>
        <el-button v-hasPermi="['bls:charges:auditfail']" icon="CloseBold" type="danger" @click="handleFail">财务作废 </el-button>
<!--        <el-button icon="Download" type="success" @click="handleExport">导出数据</el-button>-->
      </el-row>
    </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" disabled 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="收款银行账号" disabled prop="receivingBankAccount">
              <el-select v-model="form.receivingBankAccount" disabled placeholder="请输入收款银行账号">
                <el-option v-for="dict in ListCollBank" :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="form.payerName" readonly placeholder="请输入客户账户名称" clearable />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="客户开户行" prop="payerBank">
              <el-select v-model="form.payerBank" disabled 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" readonly placeholder="请输入客户银行账户" clearable />
            </el-form-item>
            <el-form-item label="付款金额" prop="amount">
              <el-input-number v-model="form.amount" readonly placeholder="请输入付款金额" :precision="2" clearable style="width: 220px"/>
            </el-form-item>
          </el-row>
          <el-row>
            <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"
                readonly
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="缴费方式" prop="paymentMethod">
              <el-select v-model="form.paymentMethod" disabled placeholder="请输入缴费方式">
                <el-option v-for="dict in sys_rec_method" :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" readonly placeholder="请输入银行记账码" clearable />
            </el-form-item>
            <el-form-item label="是否委托专户" prop="isEntrust">
              <el-select v-model="form.isEntrust" disabled 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="virtualAccount" style="margin-left: 10px">
              <el-input v-model="form.virtualAccount" readonly clearable />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="缴费项目" prop="chargItems">
              <el-input v-model="form.chargItems" readonly placeholder="请输入缴费项目" clearable />
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="是否特殊收费" prop="isSpec">
              <el-switch
                v-model="form.isSpec"
                size="large"
                active-value="Y"
                inactive-value="N"
                active-text="是"
                inactive-text="否"
                disabled
              />
            </el-form-item>
            <el-form-item v-if="form.isSpec === 'Y'" label="特殊收费类型" prop="specType" style="margin-left: 140px">
              <el-select v-model="form.specType" disabled 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" readonly :rows="4" style="width: 440px" type="textarea" placeholder="请输入备注信息" clearable> </el-input>
            </el-form-item>
          </el-row>
          <el-form-item>
            <el-button v-hasPermi="['bls:charges:auditpass']" type="primary" icon="Search" @click="handlePassCharges">审核通过</el-button>
            <el-button v-hasPermi="['bls:charges:auditfail']" type="danger" icon="Close" @click="handleRevertedCharges">财务作废</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-dialog>
  </div>
</template>

<script lang="ts" name="Charges" setup>
import { ChargesQuery, ChargesVO } from '@/api/bls/charges/types';
import { parseTime } from '@/utils/ruoyi';
import { to } from 'await-to-js';
import {failCharges, getCharges, getCollBank, listCharges, passCharges} from '@/api/bls/charges/index';
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 total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const createDateRange = ref<[DateModelType, DateModelType]>(["", ""]);
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 manageComCollBank = ref([]);
const filteredListCollBank = ref([]);
const likeCollName = ref('');
const likeName = ref('');
const filteredManagecom = ref([]);
const ListCollBank = ref([]);


const initFormData = {
  temporaryChargeId: undefined,
  manageCom: undefined,
  temporaryChargeNumber: undefined,
  bankSerialNumber: undefined,
  payerName: undefined,
  payerBank: undefined,
  payerBankAccount: undefined,
  amount: undefined,
  paymentMethod: undefined,
  receivingBankAccount: undefined,
  arrivalDate: undefined,
  reconciliationCode: undefined,
  matchingStatus: undefined,
  matchingBalance: undefined,
  approvalStatus: undefined,
  excessPaymentAmount: undefined,
  isEntrust: undefined,
  remark: undefined,
  isSpec: undefined,
  specType: undefined,
  chargItems: undefined
};
const data = reactive<PageData<ChargesQuery>>({
  form: { ...initFormData },
  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,
    reconciliationCode: undefined,
    matchingStatus: undefined,
    matchingBalance: undefined,
    //审批状态为待审批
    approvalStatus: '0',
    excessPaymentAmount: undefined,
    manageCom: undefined,
    isEntrust: undefined,
    params: {}
  },
  rules: {}
});

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

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

/** 查询团体暂收费列表 */
const getList = async () => {
  loading.value = true;
  let params = proxy?.addDateRange(queryParams.value, dateRange.value);
  params = proxy?.addDateRange(params, createDateRange.value, "CreateTime");
  const res = await listCharges(params);
  chargesList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};
// 新增双击行处理方法
const handleRowDblClick = (row: ChargesVO) => {
  handleView(row);
};
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ["", ""];
  createDateRange.value = ["", ""]; // 清空创建时间范围
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ChargesVO[]) => {
  ids.value = selection.map((item) => item.temporaryChargeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

// /** 导出按钮操作 */
// const handleExport = () => {
//   proxy?.download(
//     'bls/charges/export',
//     {
//       ...queryParams.value
//     },
//     `charges_${new Date().getTime()}.xlsx`
//   );
// };

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  chargesFormRef.value?.resetFields();
};

const handleView = async (row: ChargesVO) => {
  reset();
  const _id = row?.temporaryChargeId;
  const res = await getCharges(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '查看暂收费';
};
// 新增双击事件处理函数
const handleRowDblclick = (row: ChargesVO) => {
  handleUpdate(row); // 复用查看逻辑
};

const handlePass = async (row?: ChargesVO) => {
  const temporaryChargeIds = row?.temporaryChargeId || ids.value;
  if (temporaryChargeIds.length == 0) {
    proxy?.$modal.msgError('请选择要审批的数据项');
    return;
  }
  const [err] = await to(proxy?.$modal.confirm('是否审核通过选中的数据项？') as any);
  if (!err) {
    await passCharges(temporaryChargeIds);
    await getList();
    proxy?.$modal.msgSuccess('审核通过成功！');
  }
};

const handlePassCharges = async () => {
  const temporaryChargeIds = [form.value.temporaryChargeId];
  if (temporaryChargeIds) {
    await proxy?.$modal.confirm('是否要审核通过?');
    const res = await passCharges(temporaryChargeIds);
    if (res.code == 200) {
      proxy?.$modal.msgSuccess('审核通过成功');
      dialog.visible = false;
      getList();
    }
  }
};

const handleFail = async (row?: ChargesVO) => {
  const temporaryChargeIds = row?.temporaryChargeId || ids.value;
  if (temporaryChargeIds.length == 0) {
    proxy?.$modal.msgError('请选择要作废的数据项');
    return;
  }
  const [err] = await to(proxy?.$modal.confirm('是否财务作废选中的数据项？') as any);
  if (!err) {
    await failCharges(temporaryChargeIds);
    await getList();
    proxy?.$modal.msgSuccess('财务作废成功！');
  }
};

const handleRevertedCharges = async () => {
  const temporaryChargeIds = [form.value.temporaryChargeId];
  if (temporaryChargeIds) {
    await proxy?.$modal.confirm('是否要作废数据?');
    const res = await failCharges(temporaryChargeIds);
    if (res.code == 200) {
      proxy?.$modal.msgSuccess('财务作废成功');
      dialog.visible = false;
      getList();
    }
  }
};

const manageComChangeQury = () => {
  if (queryParams.value.manageCom) {
    manageComCollBank.value = ListCollBank.value.filter((item) => {
      return item.manageCom.includes(queryParams.value.manageCom);
    });
    if (manageComCollBank.value.length > 0) {
      filteredListCollBank.value = manageComCollBank.value;
    }
  }
};

/** 模糊查询 */
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;
  }
  // filteredManagecom.value = sys_managecom.value;
};

/** 模糊查询 */
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 getCache = async () => {
  const res = await queryManageCom();
  if (res.code == 200) {
    sys_managecom.value = res.data;
    filteredManagecom.value = sys_managecom.value;
  }
};

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