<script lang="ts">
export default {
  name: 'help-category'
};
</script>

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from 'vue';
import { ElTable, ElForm, ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Delete } from '@element-plus/icons-vue';
import {
  helpCategoryPageQuery,
  createHelpCategory,
  updateHelpCategory,
  deleteHelpCategory
} from '@/api/cms';
import { HelpCategoryItem, HelpCategoryFormData } from '@/types/api/cms';

const dataTableRef = ref(ElTable);
const dataFormRef = ref(ElForm);

const state = reactive({
  loading: true,
  ids: [] as number[],
  multiple: true,
  queryParams: { pageNo: 1, pageSize: 15 },
  list: [] as HelpCategoryItem[],
  total: 0,
  isCreate: false,
  dialog: { title: '', visible: false },
  formData: {
    code: '', nameZh: '', nameEn: '', scene: 'HELP', sort: 0, status: 1, remark: ''
  } as HelpCategoryFormData,
  rules: {
    code: [{ required: true, message: '请输入分类编码', trigger: 'blur' }],
    nameZh: [{ required: true, message: '请输入中文名称', trigger: 'blur' }],
    nameEn: [{ required: true, message: '请输入英文名称', trigger: 'blur' }],
    scene: [{ required: true, message: '请选择适用场景', trigger: 'change' }]
  }
});

const { loading, multiple, queryParams, list, total, isCreate, dialog, formData, rules } = toRefs(state);

function handleQuery() {
  state.loading = true;
  helpCategoryPageQuery(state.queryParams).then(({ data }: any) => {
    state.list = data.content || data.data?.records || [];
    state.total = data.totalElements || data.data?.total || 0;
    state.loading = false;
  });
}

function handleSelectionChange(selection: any) {
  state.ids = selection.map((item: any) => item.id);
  state.multiple = !selection.length;
}

function handleAdd() {
  state.dialog = { title: '新增分类', visible: true };
  state.isCreate = true;
  state.formData = { code: '', nameZh: '', nameEn: '', scene: 'HELP', sort: 0, status: 1, remark: '' };
}

function handleEdit(row: HelpCategoryItem) {
  state.dialog = { title: '编辑分类', visible: true };
  state.isCreate = false;
  state.formData = {
    id: row.id,
    code: row.code,
    nameZh: row.nameZh,
    nameEn: row.nameEn,
    scene: row.scene,
    sort: row.sort,
    status: row.status,
    remark: row.remark
  };
}

function submitFormData() {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) return;
    state.loading = true;
    const action = state.isCreate ? createHelpCategory : updateHelpCategory;
    action(state.formData).then(() => {
      ElMessage.success(state.isCreate ? '新增成功' : '修改成功');
      state.dialog.visible = false;
      handleQuery();
      state.loading = false;
    });
  });
}

function handleDelete() {
  ElMessageBox.confirm(`确认删除选中的 ${state.ids.length} 条记录?`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteHelpCategory({ ids: state.ids.join(',') }).then(() => {
      ElMessage.success('删除成功');
      handleQuery();
    });
  }).catch(() => ElMessage.info('已取消'));
}

onMounted(() => handleQuery());
</script>

<template>
  <div class="app-container">
    <el-form :inline="true">
      <el-form-item>
        <el-button type="success" :icon="Plus" @click="handleAdd">新增分类</el-button>
        <el-button type="danger" :icon="Delete" :disabled="multiple" @click="handleDelete">删除</el-button>
      </el-form-item>
    </el-form>

    <el-table
      ref="dataTableRef"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      border
      highlight-current-row
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" prop="id" width="80" align="center" />
      <el-table-column label="分类编码" prop="code" min-width="140" align="center" />
      <el-table-column label="中文名称" prop="nameZh" min-width="120" align="center" />
      <el-table-column label="英文名称" prop="nameEn" min-width="160" align="center" />
      <el-table-column label="适用场景" prop="scene" min-width="100" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.scene === 'HELP'" type="success">帮助中心</el-tag>
          <el-tag v-else-if="scope.row.scene === 'PROTOCOL'" type="warning">协议展示</el-tag>
          <el-tag v-else>{{ scope.row.scene }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort" width="80" align="center" />
      <el-table-column label="状态" prop="status" width="80" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" min-width="160" align="center" show-overflow-tooltip />
      <el-table-column label="操作" align="center" width="120" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-if="total > 0"
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="560px" destroy-on-close>
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="分类编码" prop="code">
          <el-input v-model="formData.code" placeholder="英文大写，如 PRIVACY" :disabled="!isCreate" />
        </el-form-item>
        <el-form-item label="中文名称" prop="nameZh">
          <el-input v-model="formData.nameZh" placeholder="如：隐私条款" />
        </el-form-item>
        <el-form-item label="英文名称" prop="nameEn">
          <el-input v-model="formData.nameEn" placeholder="如：Privacy Policy" />
        </el-form-item>
        <el-form-item label="适用场景" prop="scene">
          <el-select v-model="formData.scene" style="width:200px">
            <el-option label="帮助中心 (HELP)" value="HELP" />
            <el-option label="协议展示 (PROTOCOL)" value="PROTOCOL" />
            <el-option label="公告通知 (NOTICE)" value="NOTICE" />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" />
          <span style="margin-left:8px;color:#999;font-size:12px">越大越靠前</span>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" :rows="2" placeholder="说明该分类的用途" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitFormData">确 定</el-button>
        <el-button @click="dialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>
  </div>
</template>
