<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-if="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" v-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" 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="appntName">
                <el-input v-model="queryParams.appntName" placeholder="请输入投保人名称" clearable />
              </el-form-item>
              <el-form-item label="保单号" prop="policyNumber">
                <el-input v-model="queryParams.policyNumber" placeholder="请输入保单号" clearable />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="业务类型" prop="businessType">
                <el-select v-model="queryParams.businessType" clearable placeholder="请输入业务类型">
                  <el-option v-for="dict in bls_business_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="业务号码" prop="businessNumber">
                <el-input v-model="queryParams.businessNumber" placeholder="请输入业务号码" clearable />
              </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-row>
            <el-row>
              <el-form-item label="匹配日期">
                <el-date-picker
                  v-model="dateRange"
                  value-format="YYYY-MM-DD"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
            </el-row>
            <el-form>
              <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @query-table="getMatchList"></right-toolbar>
        </el-row>
      </template>
      <el-row>
        <div style="margin-bottom: 5px; margin-left: 10px">
          <h4>待审核保费匹配信息</h4>
        </div>
        <el-table v-loading="matchLoading" :data="matchList" highlight-current-row @current-change="handleCurrentChange">
          <el-table-column label="机构" align="center" prop="manageCom" width="150" 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="matchId" width="150" show-overflow-tooltip />
          <el-table-column label="投保人名称" align="center" prop="appntName" width="150" show-overflow-tooltip />
          <el-table-column label="应收金额" align="center" prop="receivableAmount" width="150" show-overflow-tooltip />
          <el-table-column label="实收金额" align="center" prop="actualReceivedAmount" width="150" show-overflow-tooltip />
          <el-table-column label="溢交金额" align="center" prop="overpaidAmount" width="150" show-overflow-tooltip />
          <el-table-column label="匹配日期" align="center" prop="matchDate" width="150" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ parseTime(scope.row.matchDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <pagination
        v-show="matchTotal > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="matchTotal"
        @pagination="getMatchList"
      />
      <el-row style="margin-top: 20px">
        <div style="margin-bottom: 5px; margin-left: 10px" v-if="tempShowSearch">
          <h4>团体财务实收数据</h4>
        </div>
        <el-table v-if="tempShowSearch" v-loading="tempLoading" :data="tempList">
          <el-table-column label="核对码" align="center" prop="reconciliationCode" 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="payerBank" width="150" 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="amount" width="150" show-overflow-tooltip />
          <el-table-column label="匹配余额" align="center" prop="matchingBalance" width="150" show-overflow-tooltip />
          <el-table-column label="到账日期" align="center" prop="arrivalDate" width="150" show-overflow-tooltip >
            <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="150" show-overflow-tooltip />
          <el-table-column label="缴费项目" align="center" prop="chargItems" width="150" show-overflow-tooltip />
        </el-table>
      </el-row>
      <el-form ref="monitoringFormRef" v-if="tempShowSearch" :inline="true" :model="monitoringForm" label-position="left" label-width="130px" style="margin-top: 20px">
        <el-form-item label="匹配余额总金额" prop="tempTotlAmount">
          <el-input v-model="monitoringForm.tempTotlAmount" readonly />
        </el-form-item>
        <el-form-item label="其中团体暂收总金额" prop="tempTotlAmount">
          <el-input v-model="monitoringForm.tempGrpTotlAmount" readonly />
        </el-form-item>
        <el-form-item label="其中个人暂收总金额" prop="tempTotlAmount">
          <el-input v-model="monitoringForm.tempPersonTotlAmount" readonly />
        </el-form-item>
      </el-form>
      <el-row style="margin-top: 20px">
        <div style="margin-bottom: 5px; margin-left: 10px" v-if="policyShowSearch">
          <h4>团体缴费匹配对应业务应收数据</h4>
        </div>
        <el-table v-if="policyShowSearch" v-loading="policyLoading" :data="policyList">
          <el-table-column label="保单号" align="center" prop="policyNumber" width="150" show-overflow-tooltip />
          <el-table-column label="业务类型" align="center" prop="businessType" width="150" show-overflow-tooltip >
            <template #default="scope">
              <dict-tag :options="bls_business_type" :value="scope.row.businessType" />
            </template>
          </el-table-column>
          <el-table-column label="业务号码" align="center" prop="businessNumber" width="150" show-overflow-tooltip />
          <el-table-column label="投保人名称" align="center" prop="appntName" width="150" show-overflow-tooltip />
          <el-table-column label="实际交款人" align="center" prop="actualPayer" width="150" show-overflow-tooltip />
          <el-table-column label="交款人账号" align="center" prop="payerBankAccount" width="150" show-overflow-tooltip />
          <el-table-column label="业务日期" align="center" prop="businessDate" width="150" show-overflow-tooltip >
            <template #default="scope">
              <span>{{ parseTime(scope.row.businessDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="应收金额" align="center" prop="receivableAmount" width="150" show-overflow-tooltip />
        </el-table>
      </el-row>

      <el-form ref="monitoringFormRef" v-if="policyShowSearch" :inline="true" :model="monitoringForm" label-position="left" label-width="130px" style="margin-top: 20px">
        <el-form-item label="保费总金额" prop="policyTotlAmount">
          <el-input v-model="monitoringForm.policyTotlAmount" readonly />
        </el-form-item>
      </el-form>

      <el-row style="margin-top: 20px">
        <div style="margin-bottom: 5px; margin-left: 10px" v-if="policyShowSearch && personList.length > 0">
          <h4>个人缴费匹配对应业务应收数据</h4>
        </div>
        <el-table v-if="policyShowSearch && personList.length > 0" v-loading="policyLoading" :data="personList">
          <el-table-column label="保单号" align="center" prop="policyNumber" width="150" show-overflow-tooltip />
          <el-table-column label="业务类型" align="center" prop="businessType" width="150" show-overflow-tooltip >
            <template #default="scope">
              <dict-tag :options="bls_business_type" :value="scope.row.businessType" />
            </template>
          </el-table-column>
          <el-table-column label="业务号码" align="center" prop="businessNumber" width="150" show-overflow-tooltip />
          <el-table-column label="业务日期" align="center" prop="businessDate" width="150" show-overflow-tooltip >
            <template #default="scope">
              <span>{{ parseTime(scope.row.businessDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="应收金额" align="center" prop="receivableAmount" width="150" show-overflow-tooltip />
          <el-table-column label="缴费项目" align="center" prop="chargItems" width="150" show-overflow-tooltip />
        </el-table>
      </el-row>

      <el-form ref="monitoringFormRef" v-if="personShowSearch" :inline="true" :model="monitoringForm" label-position="left" label-width="130px" style="margin-top: 20px">
        <el-form-item label="保费总金额" prop="policyTotlAmount">
          <el-input v-model="monitoringForm.personTotlAmount" readonly />
        </el-form-item>
      </el-form>

      <el-row style="margin-top: 20px">
        <div style="margin-bottom: 5px; margin-left: 10px" v-if="policyShowSearch && transferList.length > 0">
          <h4>内部转账信息</h4>
        </div>
        <el-table v-if="policyShowSearch && transferList.length > 0" v-loading="policyLoading" :data="transferList">
          <el-table-column label="付费业务流水号" align="center" prop="paymentBusinessNumber" width="150" show-overflow-tooltip />
          <el-table-column label="付费业务类型" align="center" prop="paymentType" width="150" show-overflow-tooltip />
          <el-table-column label="付费业务金额" align="center" prop="paymentAmount" width="150" show-overflow-tooltip />
          <el-table-column label="内转金额" align="center" prop="transferAmount" width="150" show-overflow-tooltip />
        </el-table>
      </el-row>

      <el-form ref="monitoringFormRef" :inline="true" :model="monitoringForm" v-if="policyShowSearch && transferList.length > 0" label-position="left" label-width="130px" style="margin-top: 20px">
        <el-form-item label="内部转账总金额"  prop="transferTotlAmount">
          <el-input v-model="monitoringForm.transferTotlAmount" readonly />
        </el-form-item>
      </el-form>

      <el-row style="margin-top: 20px">
        <div style="margin-bottom: 5px; margin-left: 10px" v-if="policyShowSearch && attachmentList.length > 0">
          <h4>附件信息</h4>
        </div>
        <el-table v-if="policyShowSearch && attachmentList.length > 0" v-loading="policyLoading" :data="attachmentList">
          <el-table-column v-if="false" label="附件ossid" align="center" prop="ossId" width="150" show-overflow-tooltip />
          <el-table-column label="附件名称" align="center" prop="fileName" width="150" show-overflow-tooltip />
          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-tooltip content="下载附件" placement="top">
                <el-button v-hasPermi="['bls:match:download']" link type="primary" icon="View" @click="handleDownLoad(scope.row)">下载附件</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-row>

    </el-card>
    <el-card shadow="hover">
      <el-form v-model="auditForm" label-width="130px" label-position="left">
        <el-form-item label="审核结论描述" prop="auditReason">
          <el-input v-model="auditForm.auditReason" type="textarea" style="width: 290px" maxlength="500" show-word-limit :rows="4" placeholder="请输入审核结论描述" clearable />
        </el-form-item>
        <el-button v-hasPermi="['bls:match:auditpass']" icon="Check" type="primary" @click="handlePass">审核通过</el-button>
        <el-button v-hasPermi="['bls:match:auditfail']" icon="CloseBold" type="danger" @click="handleFail">审核不通过</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script setup name="Matches" lang="ts">
import { MatchVO } from '@/api/bls/match/matchtypes';
import { MatchPolicyVO } from '@/api/bls/match/matchpolicytypes';
import { failMatch, listDetail, listMatch, passMatch } from '@/api/bls/match';
import { parseTime } from '@/utils/ruoyi';
import { ChargesVO } from '@/api/bls/charges/types';
import { to } from 'await-to-js';
import { failCharges } from '@/api/bls/charges';
import {queryManageCom} from "@/api/bls/cache";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const showSearch = ref(true);
const { sys_managecom } = toRefs<any>(proxy?.useDict('sys_managecom'));
const { sys_bank_code } = toRefs<any>(proxy?.useDict('sys_bank_code'));
const { sys_from_system } = toRefs<any>(proxy?.useDict('sys_from_system'));
const { bls_business_type } = toRefs<any>(proxy?.useDict('bls_business_type'));

const matchLoading = ref(false);
const matchList = ref<MatchVO[]>([]);
const matchTotal = ref(0);

const policyShowSearch = ref(false);
const policyLoading = ref(false);
const policyList = ref<MatchPolicyVO[]>([]);

const tempShowSearch = ref(false);
const tempLoading = ref(false);
const tempList = ref<ChargesVO[]>([]);

const transferList = ref([]);
const attachmentList = ref([]);
//个人缴费部分
const personShowSearch = ref(false);
const personList = ref([]);
//个人缴费暂收费匹配部分
const personTempList = ref([]);

const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const monitoringFormRef = ref<ElFormInstance>();
const selectRow = ref([]);

const likeName = ref('');
const filteredManagecom = ref([]);
const sys_managecomCache = ref([]);
const monitoringData = reactive({
  monitoringForm: {
    policyTotlAmount: undefined,
    tempTotlAmount: undefined,
    transferTotlAmount: undefined,
    personTotlAmount: undefined,
    tempGrpTotlAmount: undefined,
    tempPersonTotlAmount: undefined
  }
});
const { monitoringForm } = toRefs(monitoringData);

const data = reactive<SinglePageData<ChargesQuery>>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    manageCom: undefined,
    appntName: undefined,
    contNo: undefined,
    businessType: undefined,
    businessNumber: undefined,
    fromSystem: undefined
  },
  rules: {}
});
const { queryParams, rules } = toRefs(data);

const auditFormData = reactive({
  auditForm: {
    auditReason: undefined
  }
});
const { auditForm } = toRefs(auditFormData);


/** 搜索按钮操作 */
const handleQuery = () => {
  getMatchList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  // 重置表单字段
  queryFormRef.value?.resetFields();

  // 重置日期范围
  dateRange.value = ['', ''];

  // 重置分页参数
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    manageCom: undefined,
    appntName: undefined,
    contNo: undefined,
    businessType: undefined,
    businessNumber: undefined,
    fromSystem: undefined
  };

  // 重新获取数据
  handleQuery();
};

/** 查询团体暂收费列表 */
const getMatchList = async () => {
  matchLoading.value = true;
  restDetail();
  try {
    const res = await listMatch(proxy?.addDateRange(queryParams.value, dateRange.value));
    matchList.value = res.rows;
    matchTotal.value = res.total;
  } finally {
    matchLoading.value = false;
  }
};

const handleCurrentChange = async (row: MatchVO | null) => {
  selectRow.value = row;
  restDetail();
  if (row) {
    const _matchId = row.matchId;
    matchLoading.value = true;
    const res = await listDetail(row.matchId);
    policyList.value = res.data.policyvoList;
    tempList.value = res.data.tempvoList;
    transferList.value = res.data.transferList;
    attachmentList.value = res.data.attachmentList;
    personList.value = res.data.personList;
    policyShowSearch.value = true;
    tempShowSearch.value = true;
    matchLoading.value = false;
    Object.assign(monitoringForm.value, res.data.totlData);
  } else {
    policyList.value = [];
    tempList.value = [];
    transferList.value = [];
    attachmentList.value = [];
    personList.value = [];
    monitoringForm.value.policyTotlAmount = undefined;
    monitoringForm.value.tempTotlAmount = undefined;
    monitoringForm.value.transferTotlAmount = undefined;
  }
};

const restDetail = () => {
  policyShowSearch.value = false;
  tempShowSearch.value = false;
  policyList.value = [];
  tempList.value = [];
  transferList.value = [];
  attachmentList.value = [];
  monitoringForm.value.policyTotlAmount = undefined;
  monitoringForm.value.tempTotlAmount = undefined;
  monitoringForm.value.transferTotlAmount = undefined;
};

const handleAudit = async (action: 'pass' | 'fail', message: string) => {
  if (selectRow.value.length === 0) {
    ElMessage.error('请选择要审批的保费匹配数据');
    return;
  }
  if (action === 'fail' && !auditForm.value.auditReason) {
    proxy?.$modal.msgError('请在审核结论描述处输入拒绝原因');
    return;
  }

  try {
    const [err] = await to(ElMessageBox.confirm(`是否要${message}投保人"${selectRow.value.appntName}"的保费匹配数据？`));
    if (!err) {
      await (action === 'pass' ? passMatch : failMatch)(selectRow.value.matchId, auditForm.value.auditReason);
      await getMatchList();
      ElMessage.success(`${message}成功！`);
      auditAfter();
    }
  } catch (error) {

  } finally {
  }
};

const handleDownLoad = (row) => {
  proxy?.$download.oss(row.ossId);
};



const handlePass = () => handleAudit('pass', '审批通过');
const handleFail = () => handleAudit('fail', '拒绝');

const auditAfter = () => {
  selectRow.value = [];
  policyList.value = [];
  tempList.value = [];
  policyShowSearch.value = false;
  tempShowSearch.value = false;
};


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

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

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