<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" clearable placeholder="请输入管理机构">
                <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="payeeName">
              <el-input v-model="queryParams.payeeName" clearable placeholder="请输入收款人姓名" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="收款人银行账号" prop="bankAccount">
              <el-input v-model="queryParams.bankAccount" clearable placeholder="请输入付款人银行账号" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="实付号" prop="businessReceiptNumber">
              <el-input v-model="queryParams.businessPaymentNumber" clearable placeholder="请输入实收号" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="保单号" prop="policyNumber">
              <el-input v-model="queryParams.policyNumber" clearable placeholder="请输入保单号" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="业务号" prop="businessNumber">
              <el-input v-model="queryParams.businessNumber" clearable placeholder="请输入业务号" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="数据来源" prop="fromSystem">
              <el-select v-model="queryParams.fromSystem" clearable placeholder="请输入数据来源">
                <el-option v-for="dict in sys_from_system" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="应付日期">
              <el-date-picker
                v-model="dateRangeRece"
                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="amount">
              <el-input v-model="amountBigen" clearable style="width: 40%" />
              <div style="margin: 0 10px">-</div>
              <el-input v-model="amountEnd" clearable style="width: 40%" />
            </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">
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="payablesList" highlight-current-row @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="50" />
        <el-table-column v-if="false" align="center" label="支付id" prop="payablesId" show-overflow-tooltip />
        <el-table-column align="center" label="实付号" prop="businessPaymentNumber" show-overflow-tooltip width="150px" />
        <el-table-column align="center" label="数据来源" prop="fromSystem" show-overflow-tooltip width="150px">
          <template #default="scope">
            <dict-tag :options="sys_from_system" :value="scope.row.fromSystem" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="机构" prop="manageCom" show-overflow-tooltip width="150px">
          <template #default="scope">
            <dict-tag :options="sys_managecom" :value="scope.row.manageCom" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="收款人名称" prop="payeeName" show-overflow-tooltip width="200px" />
        <el-table-column align="center" label="收款人开户行" prop="bankCode" show-overflow-tooltip width="150px">
          <template #default="scope">
            <dict-tag :options="sys_bank_code" :value="scope.row.bankCode" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="收款人银行账号" prop="bankAccount" show-overflow-tooltip width="250px" />
        <el-table-column align="center" label="应付日期" prop="payableDate" width="150">
          <template #default="scope">
            <span>{{ parseTime(scope.row.payableDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <!--        <el-table-column align="center" label="保单号" prop="policyNumber" show-overflow-tooltip width="200px" />-->
        <el-table-column align="center" label="业务号" prop="businessNumber" show-overflow-tooltip width="200px" />
        <el-table-column align="center" label="金额" prop="amount" show-overflow-tooltip width="150px" />
      </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>
      <el-form ref="formRef" :model="form" :rules="rules" :inline="true" label-position="left" label-width="130px">
        <el-form-item>
          <el-button v-hasPermi="['bls:payables:singlepay']" icon="Check" type="primary" @click="handleSinglePay">发起支付</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script setup name="PayablesAduit" lang="ts">
import { PayablesVO } from '@/api/bls/payables/types';
import { listPayables, singlePay } from '@/api/bls/payables';
import {queryManageCom} from "@/api/bls/cache";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const dateRangeRece = ref<[DateModelType, DateModelType]>(['', '']);
const amountBigen = ref<number | null>(null);
const amountEnd = ref<number | null>(null);
const amountRange = ref<[number | null, number | null]>([null, null]);

const queryFormRef = ref<ElFormInstance>();
const formRef = ref<ElFormInstance>();
const payablesList = ref<PayablesVO[]>([]);

const { sys_managecom } = toRefs<any>(proxy?.useDict('sys_managecom'));
const { sys_bank_code } = toRefs<any>(proxy?.useDict('sys_bank_code'));
const { bls_payables_aduit } = toRefs<any>(proxy?.useDict('bls_payables_aduit'));
const { sys_from_system } = toRefs<any>(proxy?.useDict('sys_from_system'));
const { bls_transfer_status, sys_common_status, bls_transit_status } = toRefs<any>(
  proxy?.useDict('bls_transfer_status', 'sys_common_status', 'bls_transit_status')
);
const likeName = ref('');
const filteredManagecom = ref([]);
const sys_managecomCache = ref([]);
const ids = ref<Array<string | number>>([]);
const single = ref(false);
const initFormData = {};

const data = reactive({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    manageCom: undefined,
    appntName: undefined,
    bankAccount: undefined,
    businessReceiptNumber: undefined,
    policyNumber: undefined,
    businessNumber: undefined,
    fromSystem: undefined,
    chargeType: undefined,
    chargeStatus: undefined,
    paymentMethod: undefined,
    inTransitStatus: '0',
    paymentStatus: '0',
    params: {}
  },
  rules: {}
});

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

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

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

const getList = async () => {
  loading.value = true;
  queryParams.value = proxy?.addDateRange(queryParams.value, dateRangeRece.value, 'Rece');
  if (!checkAmount()) {
    loading.value = false;
    return;
  }
  amountRange.value = [amountBigen.value, amountEnd.value];
  queryParams.value = proxy?.addDateRange(queryParams.value, amountRange.value, 'Amount');
  const res = await listPayables(queryParams.value);
  payablesList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const checkAmount = () => {
  const regex = /^\d+(\.\d{1,2})?$/;
  const fields = [
    { name: 'amountBigen', value: amountBigen.value },
    { name: 'amountEnd', value: amountEnd.value }
  ];
  for (const field of fields) {
    if (field.value && !regex.test(String(field.value))) {
      proxy?.$modal.msgError(`${field.name} 金额只能为数字且最多2位小数`);
      return false;
    }
  }
  if (amountBigen.value && amountEnd.value && amountBigen.value > amountEnd.value) {
    proxy?.$modal.msgError('开始金额不能大于终止金额');
    return false;
  }
  return true;
};
/** 模糊查询 */
const filterByManageCom = () => {
  if (likeName.value) {
    filteredManagecom.value = sys_managecomCache.value.filter((item) => {
      return item.dictLabel.includes(likeName.value) || item.dictValue.includes(likeName.value);
    });
  } else {
    filteredManagecom.value = sys_managecomCache.value;
  }
};


/** 多选框选中数据 */
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.payablesId);
  single.value = selection.length > 0;
};

const handleSinglePay = async () => {
  if (ids.value.length === 0) {
    proxy.$modal.msgError('请选中要支付的记录');
    return;
  }
  await proxy.$modal.confirm('确定要将选中的数据直接推送资金系统吗？');
  loading.value = true;
  try {
    const res = await singlePay({ ids: ids.value });
    if (res.code === 200) {
      proxy.$modal.msgSuccess('推送成功');
      await getList();
    }
  } finally {
    loading.value = false;
  }
};

const getCache = async () => {
  const res = await queryManageCom();
  if (res.code == 200) {
    sys_managecomCache.value = res.data;
    filteredManagecom.value = sys_managecomCache.value;
  }
};

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

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