<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" v-loading="loading" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :rules="rules" :inline="true" label-width="80px">
            <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="fromSystem">
              <el-select v-model="queryParams.fromSystem" clearable placeholder="请输入保单管理机构">
                <el-option v-for="dict in sys_from_system" :key="dict.value" :label="dict.value + '-' + dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="场景编码" prop="finCostIdList">
              <el-select v-model="queryParams.finCostIdList" multiple clearable placeholder="请选择场景编码">
                <template #header>
                  <el-input v-model="likeFinItemName" placeholder="可根据场景编码或名称模糊查询" @input="filterByCostIdName"></el-input>
                </template>
                <el-option
                  v-for="option in filteredFinItemList"
                  :key="option.costId"
                  :label="option.costId + '-' + option.costName"
                  :value="option.costId"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="对账日期" prop="dateRange">
              <el-date-picker
                v-model="queryParams.dateRange"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                clearable
                style="width: 240px"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="对账状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择对账状态" clearable>
                <el-option v-for="dict in bfs_reconciliation_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </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-button icon="Download" v-hasPermi="['bfs:reconciliation:TotolExport']"  type="success" @click="handleTotolExport">汇总导出</el-button>
                <el-button icon="Download" v-hasPermi="['bfs:reconciliation:ErrorExport']"  type="success" @click="handleErrorExport">导出失败明细</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="never">
      <el-table v-loading="loading" :data="reconciliationList">
        <el-table-column v-if="false" label="id" align="center" prop="id" />
        <el-table-column label="错误描述" align="center" prop="errDes" width="230px" show-overflow-tooltip />
        <el-table-column label="来源系统" align="center" prop="fromSystem">
          <template #default="scope">
            <dict-tag :options="sys_from_system" :value="scope.row.fromSystem" />
          </template>
        </el-table-column>
        <el-table-column label="对账日期" align="center" prop="recDate" width="100px">
          <template #default="scope">
            <span>{{ parseTime(scope.row.recDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="数据类型" align="center" prop="dataType">
          <template #default="scope">
            <dict-tag :options="bfs_rec_datatype" :value="scope.row.dataType" />
          </template>
        </el-table-column>
        <el-table-column label="业务批次号" align="center" prop="batchno" width="200px" show-overflow-tooltip> </el-table-column>
        <el-table-column label="业务场景编码" align="center" prop="bussType" width="100px" show-overflow-tooltip> </el-table-column>
        <el-table-column label="团单号" align="center" prop="policyNo" width="200px" show-overflow-tooltip> </el-table-column>
        <el-table-column label="业务号码" align="center" prop="businessNo" width="200px" show-overflow-tooltip> </el-table-column>
        <el-table-column label="业务渠道" align="center" prop="channelCode" width="100px"> </el-table-column>
        <el-table-column label="险种编码" align="center" prop="productCode" width="100px"> </el-table-column>
        <el-table-column label="总金额" align="center" prop="amount" width="100px"> </el-table-column>
        <el-table-column label="交易日期" align="center" prop="businessDate" width="100px">
          <template #default="scope">
            <span>{{ parseTime(scope.row.businessDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button v-hasPermi="['bfs:reconciliation:detailList']" link type="primary" icon="Edit" @click="handleDetail(scope.row)">查看详情</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
  </div>
</template>
<script setup name="BFSReconciliation" lang="ts">
import { getReconciliationList } from '@/api/bfs/reconciliation';
import { parseTime } from '@/utils/ruoyi';
import { getCacheList } from '@/api/bfs/busnessQury/costBalance';
import {queryManageCom} from "@/api/bfs/cache";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { bfs_reconciliation_status } = toRefs<any>(proxy?.useDict('bfs_reconciliation_status'));
const { sys_managecom } = toRefs<any>(proxy?.useDict('sys_managecom'));
const { sys_from_system } = toRefs<any>(proxy?.useDict('sys_from_system'));
const { bfs_rec_datatype } = toRefs<any>(proxy?.useDict('bfs_rec_datatype'));
const showSearch = ref(true);
const loading = ref(false);
const total = ref(0);
const likeName = ref('');
const filteredManagecom = ref([]);
const likeFinItemName = ref('');
const finItemList = ref([]);
const filteredFinItemList = ref([]);
const sys_managecomCache = ref([]);

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dateRange: undefined,
    status: undefined,
    manageCom: undefined,
    fromSystem: undefined,
    finCostIdList: undefined,
    params: {}
  },
  rules: {
    dateRange: [{ required: true, message: '对账日期不能为空', trigger: 'blur' }]
  }
});
const { queryParams, rules } = toRefs(data);
const reconciliationList = ref([]);
const queryFormRef = ref<ElFormInstance>();
const getList = () => {
  queryFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      const res = await getReconciliationList(proxy?.addDateRange(queryParams.value, queryParams.value.dateRange));
      //  console.log(res);
      reconciliationList.value = res.rows;
      total.value = res.total;
      loading.value = false;
    }
  });
};

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

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

const handleDetail = (row: any) => {
  proxy.$router.push({
    path: `/bfs/reconciliation/detail`,
    query: {
      recId: row.id
    }
  });
};

const getCache = async () => {
  const res = await getCacheList();
  finItemList.value = res.data.costIdList;
  filteredFinItemList.value = finItemList.value;
};

const filterByCostIdName = () => {
  if (likeFinItemName.value) {
    filteredFinItemList.value = finItemList.value.filter((item) => {
      return item.costId.includes(likeFinItemName.value) || item.costName.includes(likeFinItemName.value);
    });
  } else {
    filteredFinItemList.value = finItemList.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 handleTotolExport = () => {
  proxy?.download(
    'bfs/reconciliation/totolExport',
    {
      ...queryParams.value
    },
    `汇总导出_${new Date().getTime()}.xlsx`
  );
};

const handleErrorExport = () => {
  proxy?.download(
    'bfs/reconciliation/errorExport',
    {
      ...queryParams.value
    },
    `失败明细_${new Date().getTime()}.xlsx`
  );
};

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

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

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