<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="90px"
    >
      <el-form-item label="报告编号" prop="reportNo">
        <el-input
          v-model="queryParams.reportNo"
          placeholder="请输入报告编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-180px"
        />
      </el-form-item>
      <el-form-item label="罪犯编号" prop="prisonerNo">
        <el-input
          v-model="queryParams.prisonerNo"
          placeholder="请输入罪犯编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-140px"
        />
      </el-form-item>
      <el-form-item label="模板" prop="templateId">
        <el-select
          v-model="queryParams.templateId"
          placeholder="请选择模板"
          clearable
          class="!w-160px"
        >
          <el-option
            v-for="item in templateOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择"
          clearable
          class="!w-110px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.PRISON_REPORT_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="评估日期" prop="evaluationDate">
        <el-date-picker
          v-model="queryParams.evaluationDate"
          type="daterange"
          value-format="YYYY-MM-DD"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openCreateDialog"
          v-hasPermi="['prison:evaluation-report:report:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新建报告
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['prison:evaluation-report:report:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 报告列表 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="报告编号" prop="reportNo" width="180" align="center" />
      <el-table-column label="罪犯信息" min-width="180">
        <template #default="{ row }">
          <div class="prisoner-info">
            <el-avatar :size="32">{{ row.prisonerName?.charAt(0) }}</el-avatar>
            <div class="prisoner-detail">
              <span class="name">{{ row.prisonerName }}</span>
              <span class="no">{{ row.prisonerNo }}</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="模板" prop="templateName" width="150" />
      <el-table-column label="评估日期" prop="evaluationDate" width="120" align="center" />
      <el-table-column label="风险等级" prop="riskLevel" width="100" align="center">
        <template #default="{ row }">
          <el-tag v-if="row.riskLevel" :type="getRiskLevelType(row.riskLevel)" size="small">
            {{ getRiskLevelLabel(row.riskLevel) }}
          </el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status" width="100" align="center">
        <template #default="{ row }">
          <dict-tag :type="DICT_TYPE.PRISON_REPORT_STATUS" :value="row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建人" prop="creator" width="100" align="center" />
      <el-table-column label="创建时间" prop="createTime" width="180" align="center" />
      <el-table-column label="操作" width="220" fixed="right" align="center">
        <template #default="{ row }">
          <el-button
            link
            type="primary"
            @click="handleView(row)"
          >
            <Icon icon="ep:view" /> 查看
          </el-button>
          <el-button
            v-if="row.status === 1 || row.status === 4"
            link
            type="primary"
            @click="handleEdit(row)"
            v-hasPermi="['prison:evaluation-report:report:update']"
          >
            <Icon icon="ep:edit" /> 编辑
          </el-button>
          <el-button
            v-if="row.status === 1"
            link
            type="warning"
            @click="handleSubmit(row.id)"
            v-hasPermi="['prison:evaluation-report:report:update']"
          >
            提交
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(row.id)"
            v-hasPermi="['prison:evaluation-report:report:delete']"
          >
            <Icon icon="ep:delete" /> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 创建报告弹窗 -->
  <CreateReportDialog ref="createDialogRef" @success="getList" />

  <!-- 报告详情弹窗 -->
  <ReportDetailDialog ref="detailDialogRef" />
</template>

<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import download from '@/utils/download'
import { EvaluationReportApi, EvaluationReport, EvaluationTemplateApi } from '@/api/prison/evaluation'
import CreateReportDialog from './CreateReportDialog.vue'
import ReportDetailDialog from './ReportDetailDialog.vue'

defineOptions({ name: 'EvaluationReport' })

const router = useRouter()
const message = useMessage()
const { t } = useI18n()

const loading = ref(false)
const exportLoading = ref(false)
const list = ref<EvaluationReport[]>([])
const total = ref(0)
const ids = ref<number[]>([])
const templateOptions = ref<{ id: number; name: string }[]>([])

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  reportNo: undefined,
  prisonerNo: undefined,
  templateId: undefined,
  status: undefined,
  evaluationDate: undefined as string[] | undefined
})
const queryFormRef = ref()

/** 获取风险等级类型 */
const getRiskLevelType = (level: number): string => {
  const map: Record<number, string> = {
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return map[level] || 'info'
}

/** 获取风险等级标签 */
const getRiskLevelLabel = (level: number): string => {
  const map: Record<number, string> = {
    1: '低风险',
    2: '中风险',
    3: '高风险'
  }
  return map[level] || '-'
}

/** 获取报告列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await EvaluationReportApi.getReportPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 获取模板列表 */
const getTemplateList = async () => {
  const data = await EvaluationTemplateApi.getEnabledTemplateList()
  templateOptions.value = data.map((item: any) => ({ id: item.id, name: item.name }))
}

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

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: EvaluationReport[]) => {
  ids.value = selection.map((item) => item.id)
}

/** 打开创建报告弹窗 */
const createDialogRef = ref()
const openCreateDialog = () => {
  createDialogRef.value?.open()
}

/** 查看报告 */
const detailDialogRef = ref()
const handleView = (row: EvaluationReport) => {
  detailDialogRef.value?.open(row.id)
}

/** 编辑报告 */
const handleEdit = (row: EvaluationReport) => {
  router.push({
    path: '/prison/evaluation-mgmt/report/edit',
    query: { id: row.id }
  })
}

/** 提交审核 */
const handleSubmit = async (id: number) => {
  try {
    await message.confirm('确定要提交该报告进行审核吗？')
    await EvaluationReportApi.submitReport(id)
    message.success('提交成功')
    getList()
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await EvaluationReportApi.deleteReport(id)
    message.success(t('common.delSuccess'))
    getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await EvaluationReportApi.exportReportExcel(queryParams)
    download.excel(data, '评估报告.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 */
onMounted(() => {
  getList()
  getTemplateList()
})
</script>

<style lang="scss" scoped>
.prisoner-info {
  display: flex;
  align-items: center;
  gap: 10px;

  .prisoner-detail {
    display: flex;
    flex-direction: column;

    .name {
      font-weight: 500;
      color: var(--el-text-color-primary);
    }

    .no {
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }
}
</style>
