<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" :model="queryParams" :inline="true" label-width="130px" label-position="left">
            <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" placeholder="请输入客户账户名称" clearable @keyup.enter="handleQuery" />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="到账日期" prop="arrivalDate">
                <el-date-picker
                  v-model="dateRange"
                  value-format="YYYY-MM-DD"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="handleDateRangeChange"
                >
                </el-date-picker>
              </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.value + '-' + dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="银行记账码" prop="reconciliationCode">
                <el-input v-model="queryParams.reconciliationCode" placeholder="请输入银行记账码" clearable @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-row>
              <el-form-item label="状态" prop="paymentMethod">
                <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-form-item label="匹配状态" prop="matchingStatus">
                <el-select v-model="queryParams.matchingStatus" clearable placeholder="请输入匹配状态">
                  <el-option v-for="dict in bls_payment_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-form-item>
              <el-button type="primary" icon="Search" @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">
        <el-table-column label="管理机构" align="center" prop="manageCom" width="120" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="sys_managecom" :value="scope.row.manageCom" />
          </template>
        </el-table-column>
        <el-table-column label="暂收费流水号" align="center" prop="temporaryChargeNumber" width="150" show-overflow-tooltip />
        <el-table-column label="进账状态" align="center" prop="approvalStatus" width="100" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="bls_temp_approval_state" :value="scope.row.approvalStatus" />
          </template>
        </el-table-column>
        <el-table-column label="匹配状态" align="center" prop="matchingStatus" width="100" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="bls_payment_status" :value="scope.row.matchingStatus" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="缴费方式" prop="paymentMethod" width="120" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="sys_rec_method" :value="scope.row.paymentMethod" />
          </template>
        </el-table-column>
        <el-table-column label="客户开户行" align="center" prop="payerBank" width="120" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="sys_bank_code" :value="scope.row.payerBank" />
          </template>
        </el-table-column>
        <el-table-column label="客户银行账户" align="center" prop="payerBankAccount" width="150" show-overflow-tooltip />
        <el-table-column label="客户账户名称" align="center" prop="payerName" width="150" show-overflow-tooltip />
        <el-table-column label="金额" align="center" prop="amount" width="150" show-overflow-tooltip />
        <el-table-column label="当前使用金额" align="center" prop="useAmount" width="150" show-overflow-tooltip>
          <template #default="scope">
            {{ (scope.row.amount - scope.row.matchingBalance).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="余额" align="center" prop="matchingBalance" width="150" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="到账日期" align="center" prop="arrivalDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.arrivalDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收款银行账号" align="center" prop="receivingBankAccount" width="200" show-overflow-tooltip />
        <el-table-column label="收款银行名称" align="center" prop="receivingBankName" width="120" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="sys_bank_code" :value="scope.row.receivingBankName" />
          </template>
        </el-table-column>
        <el-table-column label="对账码" align="center" prop="reconciliationCode" width="150" show-overflow-tooltip />
        <el-table-column label="补录状态" align="center" prop="informationStatus" width="100" show-overflow-tooltip>
          <template #default="scope">
            <span :class="scope.row.informationStatus === '1' ? 'text-green-600' : 'text-amber-600'">
              {{ scope.row.informationStatus === '1' ? '已补' : '未补' }}
            </span>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <el-card shadow="never">
      <el-row>
        <el-button v-hasPermi="['bls:charges:queryexport']" type="success" icon="Download" @click="handleExport">导出数据</el-button>
      </el-row>
    </el-card>
  </div>
</template>

<script setup name="Charges" lang="ts">
import { ChargesVO, ChargesQuery } from '@/api/bls/charges/types';
import { parseTime } from '@/utils/ruoyi';
import { getCollBank, listCharges } 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 queryFormRef = ref<ElFormInstance>();
const chargesFormRef = ref<ElFormInstance>();
const likeName = ref('');
const filteredManagecom = ref([]);
const manageComCollBank = ref([]);
const ListCollBank = ref([]);
const filteredListCollBank = ref([]);
const likeCollName = ref('');
const sys_managecomCache = ref([]);

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 { bls_temp_approval_state } = toRefs<any>(proxy?.useDict('bls_temp_approval_state'));
const { bls_payment_status } = toRefs<any>(proxy?.useDict('bls_payment_status'));




const data = reactive<SinglePageData<ChargesQuery>>({
  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: undefined,
    excessPaymentAmount: undefined,
    manageCom: undefined,
    isEntrust: undefined,
    params: {}
  },
  rules: {}
});

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

/** 查询团体暂收费列表 */
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 handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.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/queryexport',
    {
      ...queryParams.value
    },
    `进账查询_${new Date().getTime()}.xlsx`
  );
};

// 计算属性用于动态设置 picker options
const handleDateRangeChange = (value: [string, string] | null) => {
  if (!value || !value[0] || !value[1]) return;

  const startDate = new Date(value[0]);
  const endDate = new Date(value[1]);

  const maxEndDate = new Date(startDate);
  maxEndDate.setDate(maxEndDate.getDate() + 365);

  if (endDate > maxEndDate) {
    proxy.$modal.msgError('结束日期不能超过开始日期一年以上');
    dateRange.value = ['', ''];
  }
};

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

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