<template>
  <div class="p-2">
    <el-row :gutter="20">
      <el-col>
        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button v-hasPermi="['system:post:add']" type="primary" plain icon="Plus" @click="handleAdd">新增一级分类</el-button>
              </el-col>
            </el-row>
          </template>
          <el-table v-loading="loading" border :data="postList" :tree-props="{ children: 'children' }" row-key="id">
            <el-table-column label="分类名称" align="left" prop="name" />
            <el-table-column label="排序" align="center" prop="sort" />
            <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-tooltip content="添加子分类" placement="top" v-if="scope.row.parentId == 0 || scope.row.parentId == '0'">
                  <el-button v-hasPermi="['system:post:add']" link type="primary" icon="Plus" @click="handleAddChild(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="修改" placement="top">
                  <el-button v-hasPermi="['system:post:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                  <el-button v-hasPermi="['system:post:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 添加或修改岗位对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
          <el-form ref="postFormRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="上级分类" prop="name">
              <span v-if="form.parentId">{{ form.oneName }}</span>
              <span v-else>顶级分类</span>
            </el-form-item>
            <el-form-item label="分类名称" prop="name">
              <el-input v-model="form.name" autocomplete="off" />
            </el-form-item>
            <el-form-item label="排序" prop="level">
              <el-input v-model="form.sort" autocomplete="off" />
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="Post" lang="ts">
import { listPost, getPost, updatePost, addPost, delPost } from '@/api/system/category';
import { PostVO, PostForm, PostQuery } from '@/api/system/category/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

const postList = ref<PostVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<number | string>>([]);
const single = ref(true);
const multiple = ref(true);
const deptTreeRef = ref<ElTreeInstance>();
const postFormRef = ref<ElFormInstance>();
const queryFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: PostForm = {
  id: undefined,
  name: undefined,
  level: undefined,
  parentId: undefined,
  sort: undefined,
  type: undefined,
  oneName: undefined
};

const data = reactive<PageData<PostForm, PostQuery>>({
  form: { ...initFormData },
  queryParams: {
    current: 1,
    size: 10,
    id: '',
    name: undefined,
    parentId: undefined,
    sort: undefined,
    level: undefined,
    type: undefined
  },
  rules: {
    postName: [{ required: true, message: '岗位名称不能为空', trigger: 'blur' }],
    postCode: [{ required: true, message: '岗位编码不能为空', trigger: 'blur' }],
    deptId: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
    postSort: [{ required: true, message: '岗位顺序不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs<PageData<PostForm, PostQuery>>(data);

const handleAddChild = (row: PostForm) => {
  reset();
  form.value.parentId = row.id;
  form.value.oneName = row.name;
  dialog.visible = true;
  dialog.title = '添加' + row.name + ' 子分类';
};

/** 查询文章分类列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPost(queryParams.value);
  postList.value = res.data;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  postFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  if (queryParams.value.deptId) {
    queryParams.value.belongDeptId = undefined;
  }
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNum = 1;
  queryParams.value.deptId = undefined;
  deptTreeRef.value?.setCurrentKey(undefined);
  /** 清空左边部门树选中值 */
  queryParams.value.belongDeptId = undefined;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: PostVO[]) => {
  ids.value = selection.map((item) => item.postId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加分类';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: any) => {
  const postId = row.id;
  const res = await getPost(postId);
  Object.assign(form.value, res.data);
  console.log(form.value);
  dialog.visible = true;
  dialog.title = '修改分类';
};

/** 提交按钮 */
const submitForm = () => {
  postFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      form.value.id ? await updatePost(form.value) : await addPost(form.value);
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: any) => {
  const postIds = row.id;
  await proxy?.$modal.confirm('是否确认删除岗位编号为"' + row.id + '"的数据项？');
  await delPost(postIds);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

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