<template>
  <div class="p-2">
    <!-- 统计卡片 -->
    <el-row :gutter="12" class="mb-[10px]">
      <el-col :span="6">
        <el-card shadow="hover" body-style="padding: 16px">
          <div class="stat-card">
            <el-icon class="stat-icon" style="color: #e6a23c"><Warning /></el-icon>
            <div>
              <div class="stat-num">{{ stats.pending || 0 }}</div>
              <div class="stat-label">待处理</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" body-style="padding: 16px">
          <div class="stat-card">
            <el-icon class="stat-icon" style="color: #f56c6c"><CircleCloseFilled /></el-icon>
            <div>
              <div class="stat-num" style="color: #f56c6c">{{ stats.urgent || 0 }}</div>
              <div class="stat-label">紧急预警</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" body-style="padding: 16px">
          <div class="stat-card">
            <el-icon class="stat-icon" style="color: #e6a23c"><Timer /></el-icon>
            <div>
              <div class="stat-num">{{ stats.hoursLow || 0 }}</div>
              <div class="stat-label">课时不足</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" body-style="padding: 16px">
          <div class="stat-card">
            <el-icon class="stat-icon" style="color: #f56c6c"><AlarmClock /></el-icon>
            <div>
              <div class="stat-num">{{ stats.expiring || 0 }}</div>
              <div class="stat-label">到期/过期</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <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">
            <el-form-item label="合同号" prop="contractNo">
              <el-input v-model="queryParams.contractNo" placeholder="合同号" clearable style="width: 180px" @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="类型" prop="alertType">
              <el-select v-model="queryParams.alertType" placeholder="预警类型" clearable style="width: 140px">
                <el-option v-for="opt in alertTypeOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="级别" prop="level">
              <el-select v-model="queryParams.level" placeholder="级别" clearable style="width: 120px">
                <el-option v-for="opt in alertLevelOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="处理状态" clearable style="width: 120px">
                <el-option v-for="opt in alertStatusOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
              </el-select>
            </el-form-item>
            <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="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:alert:handle']" type="primary" plain icon="RefreshRight" @click="handleScan">立即扫描</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['edu:alert:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" border :data="alertList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="级别" align="center" width="80">
          <template #default="scope">
            <el-tag :type="getLevelTag(scope.row.level)">{{ getLevelLabel(scope.row.level) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTag(scope.row.alertType)" effect="plain">{{ getTypeLabel(scope.row.alertType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="合同号" align="center" prop="contractNo" width="180" />
        <el-table-column label="学生ID" align="center" prop="studentId" width="90" />
        <el-table-column label="预警内容" align="center" prop="content" show-overflow-tooltip min-width="240" />
        <el-table-column label="状态" align="center" width="90">
          <template #default="scope">
            <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="处理时间" align="center" prop="handledAt" width="160">
          <template #default="scope">
            <span>{{ proxy.parseTime(scope.row.handledAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="生成时间" align="center" prop="createTime" width="160">
          <template #default="scope">
            <span>{{ proxy.parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center" class-name="small-padding fixed-width" fixed="right">
          <template #default="scope">
            <template v-if="scope.row.status === '0'">
              <el-tooltip content="处理" placement="top">
                <el-button v-hasPermi="['edu:alert:handle']" link type="success" icon="Check" @click="handleHandle(scope.row)"></el-button>
              </el-tooltip>
              <el-tooltip content="忽略" placement="top">
                <el-button v-hasPermi="['edu:alert:ignore']" link type="info" icon="RemoveFilled" @click="handleIgnore(scope.row)"></el-button>
              </el-tooltip>
            </template>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['edu:alert:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </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-dialog v-model="handleDialog.visible" :title="handleDialogTitle" width="460px" append-to-body>
      <el-form label-width="100px">
        <el-form-item label="预警内容">
          <span>{{ handleRow.content }}</span>
        </el-form-item>
        <el-form-item label="处理说明">
          <el-input v-model="handleForm.handleRemark" type="textarea" :rows="4" placeholder="请输入处理说明(如:已联系家长续费)" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button :type="handleDialog.type === 'handle' ? 'success' : 'info'" @click="submitHandle">{{ handleDialog.type === 'handle' ? '确认处理' : '确认忽略' }}</el-button>
        <el-button @click="handleDialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EduAlert" lang="ts">
import { listAlert, alertStats, handleAlert, ignoreAlert, delAlert, scanAlert } from '@/api/edu/alert';
import {
  AlertQuery,
  AlertVO,
  AlertHandleForm,
  alertTypeOptions,
  alertLevelOptions,
  alertStatusOptions
} from '@/api/edu/alert/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const alertList = ref<AlertVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const stats = ref<Record<string, number>>({});

const handleDialog = reactive<{ visible: boolean; title: string; type: string }>({ visible: false, title: '', type: 'handle' });
const handleRow = ref<AlertVO>({} as AlertVO);
const handleForm = reactive<AlertHandleForm>({ id: '', handleRemark: '' });

const data = reactive<PageData<any, AlertQuery>>({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentId: undefined,
    contractId: undefined,
    contractNo: '',
    alertType: '',
    level: '',
    status: '0',
    housekeeperId: undefined
  },
  rules: {}
});

const { queryParams } = toRefs(data);

const getTypeLabel = (val: string) => alertTypeOptions.find((o) => o.value === val)?.label || val;
const getTypeTag = (val: string) => alertTypeOptions.find((o) => o.value === val)?.elTagType || 'info';
const getLevelLabel = (val: string) => alertLevelOptions.find((o) => o.value === val)?.label || val;
const getLevelTag = (val: string) => alertLevelOptions.find((o) => o.value === val)?.elTagType || 'info';
const getStatusLabel = (val: string) => alertStatusOptions.find((o) => o.value === val)?.label || val;
const getStatusTag = (val: string) => alertStatusOptions.find((o) => o.value === val)?.elTagType || 'info';

const handleDialogTitle = computed(() => (handleDialog.type === 'handle' ? '处理预警' : '忽略预警'));

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  const res = await listAlert(queryParams.value);
  alertList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 查询统计 */
const getStats = async () => {
  const res = await alertStats();
  stats.value = res.data;
};

const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.status = '0';
  handleQuery();
};

const handleSelectionChange = (selection: AlertVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 处理预警 */
const handleHandle = (row: AlertVO) => {
  handleRow.value = row;
  handleForm.id = row.id;
  handleForm.handleRemark = '';
  handleDialog.type = 'handle';
  handleDialog.title = '处理预警';
  handleDialog.visible = true;
};

/** 忽略预警 */
const handleIgnore = (row: AlertVO) => {
  handleRow.value = row;
  handleForm.id = row.id;
  handleForm.handleRemark = '';
  handleDialog.type = 'ignore';
  handleDialog.title = '忽略预警';
  handleDialog.visible = true;
};

const submitHandle = async () => {
  if (handleDialog.type === 'handle') {
    await handleAlert({ ...handleForm });
    proxy?.$modal.msgSuccess('已标记为已处理');
  } else {
    await ignoreAlert({ ...handleForm });
    proxy?.$modal.msgSuccess('已忽略');
  }
  handleDialog.visible = false;
  await getList();
  await getStats();
};

/** 删除 */
const handleDelete = async (row?: AlertVO) => {
  const delIds = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除选中的预警记录？');
  await delAlert(delIds);
  await getList();
  await getStats();
  proxy?.$modal.msgSuccess('删除成功');
};

/** 立即扫描 */
const handleScan = async () => {
  await proxy?.$modal.confirm('确认立即扫描全部执行中合同？将生成课时/到期预警');
  loading.value = true;
  const res = await scanAlert();
  proxy?.$modal.msgSuccess(`扫描完成，新增预警 ${res.data} 条`);
  await getList();
  await getStats();
};

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

<style scoped>
.stat-card {
  display: flex;
  align-items: center;
  gap: 14px;
}
.stat-icon {
  font-size: 36px;
}
.stat-num {
  font-size: 24px;
  font-weight: 600;
  line-height: 1.2;
}
.stat-label {
  font-size: 13px;
  color: #909399;
}
</style>
