<script lang="ts">
export default {
  name: 'help'
};
</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 Editor from '@/components/WangEditor/index.vue';
import {
  helpManage,
  addHelpManage,
  updateHelpManage,
  delHelpManage,
  stickTopHelp,
  helpDown,
  helpCategoryList
} from '@/api/cms';
import {
  HelpQueryParam,
  HelpItem,
  HelpFormData,
  HelpCategoryItem
} from '@/types/api/cms';

const emit = defineEmits(['adClick']);
const dataTableRef = ref(ElTable);
const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const state = reactive({
  loading: true,
  ids: [],
  single: true,
  multiple: true,
  queryParams: {
    pageNo: 1,
    pageSize: 15,
    categoryCode: '',
    lang: ''
  } as HelpQueryParam,
  list: [] as HelpItem[],
  total: 0,
  isCreate: false,
  dialog: {
    title: '',
    visible: false
  },
  formData: {} as HelpFormData,
  categoryOptions: [] as HelpCategoryItem[],
  rules: {
    title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    categoryCode: [{ required: true, message: '请选择分类', trigger: 'change' }],
    lang: [{ required: true, message: '请选择语言', trigger: 'change' }]
  }
});

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

function handleQuery() {
  emit('adClick', {});
  state.loading = true;
  helpManage(state.queryParams).then(({ data }) => {
    state.list = data.content;
    state.total = data.totalElements;
    state.loading = false;
  });
}

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

function handleAdd() {
  state.dialog = {
    title: '添加帮助',
    visible: true
  };
  state.isCreate = true;
  formData.value.id = 0;
  formData.value.title = "";
  formData.value.imgUrl = "";
  formData.value.lang = "zh_CN";
  formData.value.status = 0;
  formData.value.sysHelpClassification = 0;
  formData.value.categoryCode = "";
  formData.value.sort = 1;
  formData.value.author = "";
  formData.value.content = "";
  formData.value.createTime = "";
}

/**
 * 提交新增/编辑
 */
function submitFormData() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (state.formData.id) {
        updateHelpManage(state.formData).then(() => {
          ElMessage.success('修改成功');
          cancel();
          handleQuery();
          loading.value = false;
        });
      } else {
        addHelpManage(state.formData).then(() => {
          cancel();
          ElMessage.success('添加成功');
          handleQuery();
          loading.value = false;
        });
      }
    }
  });
}

/**
 * 取消
 */
function cancel() {
  dialog.value.visible = false;
  formData.value.id = 0;
  formData.value.title = "";
  formData.value.imgUrl = "";
  formData.value.lang = "";
  formData.value.status = 0;
  formData.value.sysHelpClassification = 0;
  formData.value.categoryCode = "";
  formData.value.sort = 0;
  formData.value.author = "";
  formData.value.content = "";
  formData.value.createTime = "";
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
}

/**
 *  删除
 */
function handleDelete() {
  const ids = [state.ids].join(',');
  ElMessageBox.confirm('确认删除已选中的' + state.ids.length + '条数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  .then(() => {
    delHelpManage({ ids: ids }).then(() => {
      ElMessage.success('删除成功');
      handleQuery();
    });
  })
  .catch(() => ElMessage.info('已取消删除'));
}

/**
 * 查看 / 编辑
 * @param row 
 */
const viewEdit = (row: any) => {
  state.dialog = {
    title: '查看/编辑',
    visible: true
  };
  state.isCreate = false;
  formData.value.id = row.id;
  formData.value.title = row.title;
  formData.value.status = row.status;
  formData.value.sysHelpClassification = row.sysHelpClassification;
  formData.value.categoryCode = row.categoryCode || '';
  formData.value.content = row.content;
  formData.value.sort = row.sort;
  formData.value.lang = row.lang;
  formData.value.createTime = row.createTime;
}

/**
 * 置顶
 * @param row 
 */
const setTop = (row: any) => {
  stickTopHelp({ id: row.id }).then((res: any) => {
    if (!res.code) {
      ElMessage.success(res.message);
      handleQuery();
    } else {
      ElMessage.error(res.message);
    }
  })
}

/**
 * 取消置顶
 * @param row 
 */
const cancelTop = (row: any) => {
  helpDown({ id: row.id }).then((res: any) => {
    if (!res.code) {
      ElMessage.success(res.message);
      handleQuery();
    } else {
      ElMessage.error(res.message);
    }
  })
}

// 加载分类选项
function loadCategories() {
  helpCategoryList().then(({ data }: any) => {
    state.categoryOptions = data.data || data;
  });
}

// 根据 code 查找分类中文名
function getCategoryName(code: string): string {
  const found = state.categoryOptions.find((c: HelpCategoryItem) => c.code === code);
  return found ? found.nameZh : (code || '-');
}

onMounted(() => {
  loadCategories();
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="queryFormRef" :model="queryParams" :inline="true">
      <el-form-item label="分类">
        <el-select v-model="queryParams.categoryCode" placeholder="全部分类" clearable style="width:160px" @change="handleQuery">
          <el-option v-for="item in categoryOptions" :key="item.code" :label="item.nameZh" :value="item.code" />
        </el-select>
      </el-form-item>
      <el-form-item label="语言">
        <el-select v-model="queryParams.lang" placeholder="全部语言" clearable style="width:130px" @change="handleQuery">
          <el-option label="中文" value="zh_CN" />
          <el-option label="English" value="en_US" />
          <el-option label="日语" value="ja_JP" />
          <el-option label="韩语" value="ko_KR" />
          <el-option label="中文繁体" value="zh_HK" />
        </el-select>
      </el-form-item>
      <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"
      highlight-current-row
      border
      >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" prop="id" min-width="80" align="center" />
      <el-table-column label="标题" prop="title" min-width="180" align="center" />
      <el-table-column label="分类" prop="categoryCode" min-width="120" align="center">
        <template #default="scope">
          <span>{{ getCategoryName(scope.row.categoryCode) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="语言" prop="lang" min-width="100" align="center">
        <template #default="scope">
          <span v-if="scope.row.lang=='en_US'">English</span>
          <span v-else-if="scope.row.lang=='ja_JP'">日语</span>
          <span v-else-if="scope.row.lang=='ko_KR'">韩语</span>
          <span v-else-if="scope.row.lang=='de_DE'">德语</span>
          <span v-else-if="scope.row.lang=='fr_FR'">法语</span>
          <span v-else-if="scope.row.lang=='it_IT'">意大利</span>
          <span v-else-if="scope.row.lang=='es_ES'">西班牙</span>
          <span v-else-if="scope.row.lang=='zh_HK'">中文繁体</span>
          <span v-else>中文</span>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="sort" min-width="80" align="center" />
      <el-table-column label="显示" prop="status" min-width="80" align="center">
        <template #default="scope">
          <span v-if="scope.row.status==0">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column label="置顶" prop="isTop" min-width="80" align="center">
        <template #default="scope">
          <span v-if="scope.row.isTop==0">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" prop="createTime" min-width="160" align="center" />
      <el-table-column label="操作" align="center" width="280" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click.stop="viewEdit(scope.row)">查看 / 编辑</el-button>
          <el-button type="danger" size="small" @click.stop="setTop(scope.row)">置顶</el-button>
          <el-button type="danger" size="small" @click.stop="cancelTop(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="800px"
      destroy-on-close
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="创建时间" prop="createTime" v-if="!isCreate">
          <el-input v-model="formData.createTime" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryCode">
          <el-select v-model="formData.categoryCode" placeholder="请选择分类" style="width:240px">
            <el-option
              v-for="item in categoryOptions"
              :key="item.code"
              :label="item.nameZh"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="1" :max="100" />
        </el-form-item>
        <el-form-item label="广告语言" prop="lang">
          <el-radio-group v-model="formData.lang">
            <el-radio label="zh_CN">中文</el-radio>
            <el-radio label="en_US">English</el-radio>
            <el-radio label="ja_JP">日语</el-radio>
            <el-radio label="ko_KR">韩语</el-radio>
            <el-radio label="de_DE">德语</el-radio>
            <el-radio label="fr_FR">法语</el-radio>
            <el-radio label="it_IT">意大利</el-radio>
            <el-radio label="es_ES">西班牙</el-radio>
            <el-radio label="zh_HK">繁体</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="广告状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="0">显示</el-radio>
            <el-radio :label="1">不显示</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label-width="0" prop="content">
          <editor v-model="formData.content" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFormData">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
