<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" class="mb-6">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="信用规则名称" prop="ruleName">
              <el-input
                v-model="queryParams.ruleName"
                placeholder="请输入信用规则名称"
                clearable
                @keyup.enter="handleRuleQuery"
              />
            </el-form-item>
            <el-form-item label="规则创建时间" prop="ruleCreateTime" style="width: 330px">
              <el-date-picker
                clearable
                v-model="queryParams.ruleCreateTime"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleRuleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetRuleQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 信用规则列表 -->
        <el-card shadow="never" class="mb-10">
          <template #header>
            <h3>信用规则列表</h3>
          </template>
          <el-table v-loading="loadingRule" :data="ruleList" style="width: 100%">
            <el-table-column
              v-for="{ label, prop, align, minWidth } in ruleHeaders"
              :key="prop"
              :label="label"
              :prop="prop"
              :align="align || 'center'"
              :min-width="minWidth || '100px'"
            >
              <template #default="{ row }">
                <span v-if="prop === 'eachScore'">
                  {{ row[prop] < 0 ? row[prop] : '+' + row[prop] }}
                </span>
                <span v-else>
                  {{ row[prop] || '-' }}
                </span>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="rulePage.total > 0"
            :total="rulePage.total"
            v-model:page="rulePage.pageNum"
            v-model:limit="rulePage.pageSize"
            @pagination="getRuleList"
          />
        </el-card>

        <!-- 信用等级列表 -->
        <el-card shadow="never">
          <template #header>
            <h3>信用等级列表</h3>
          </template>
          <el-table v-loading="loadingLevel" :data="levelList" style="width: 100%">
            <el-table-column
              v-for="{ label, prop, align, minWidth } in levelHeaders"
              :key="prop"
              :label="label"
              :prop="prop"
              :align="align || 'center'"
              :min-width="minWidth || '100px'"
            >
              <template #default="{ row }">
                <span v-if="prop === 'personSum'" class="grade-num" @click="goToDetail(row)">
                  {{ row.personSum || '0' }}
                </span>
                <span v-else-if="prop === 'gradeInterval'">
                  {{ row.creditSectionLe }} - {{ row.creditSectionGe }}
                </span>
                <span v-else>{{ row[prop] || '-' }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

      </div>
    </transition>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onActivated, getCurrentInstance } from 'vue';
import { getRuleList as fetchRuleList, getLevelList as fetchLevelList } from '@/api/credit/rule';

const { proxy } = getCurrentInstance() as any;

const showSearch = ref(true);
const queryFormRef = ref();

const ruleList = ref<any[]>([]);
const levelList = ref<any[]>([]);

const loadingRule = ref(false);
const loadingLevel = ref(false);

const queryParams = ref({
  ruleName: '',
  ruleCreateTime: [] as string[],
});

const rulePage = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});

const ruleHeaders = [
  { label: '信用规则名称', prop: 'ruleName' },
  { label: '信用分奖惩', prop: 'eachScore' },
  { label: '规则创建时间', prop: 'createTime' },
  { label: '规则到期时间', prop: 'expireTime' },
];

const levelHeaders = [
  { label: '信用等级名称', prop: 'creditName' },
  { label: '对应信用分区间', prop: 'gradeInterval' },
  { label: '信用等级包含人数', prop: 'personSum' },
];

// 获取信用规则列表（带分页和搜索）
const getRuleList = async () => {
  loadingRule.value = true;
  const [startTime, endTime] = queryParams.value.ruleCreateTime || [];
  try {
    const res = await fetchRuleList({
      ruleName: queryParams.value.ruleName,
      startTime: startTime || '',
      endTime: endTime || '',
      pageNum: rulePage.value.pageNum,
      pageSize: rulePage.value.pageSize,
    });
    ruleList.value = res.data || [];
    rulePage.value.total = res.data.length || 0; // 如果接口无total字段用length替代
  } finally {
    loadingRule.value = false;
  }
};

// 获取信用等级列表（无分页）
const getLevelList = async () => {
  loadingLevel.value = true;
  try {
    const res = await fetchLevelList();
    levelList.value = res.data || [];
  } finally {
    loadingLevel.value = false;
  }
};

// 搜索信用规则
const handleRuleQuery = () => {
  rulePage.value.pageNum = 1;
  getRuleList();
};

// 重置搜索条件
const resetRuleQuery = () => {
  queryFormRef.value?.resetFields();
  handleRuleQuery();
};

// 点击信用等级人数跳转
const goToDetail = (row: any) => {
  proxy?.$router.push({
    path: '/credit/list',
    query: { credtieGe: row.creditSectionLe, crediteLe: row.creditSectionGe },
  });
};

onMounted(() => {
  getRuleList();
  getLevelList();
});
onActivated(() => {
  getRuleList();
  getLevelList();
});
</script>

<style scoped lang="scss">
.grade-num {
  color: var(--el-color-primary);
  cursor: pointer;
}
</style>
