<template>
  <div class="koi-flex">
    <KoiCard>
      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['system:role:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
      </el-row>

      <div class="h-20px"></div>
      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        border
        :data="tableList"
        empty-text="暂时没有数据哟"
      >
        <el-table-column label="ID" prop="id" width="80px" align="center" type="index"></el-table-column>
        <el-table-column
          label="类型名称"
          prop="type"
          width="180px"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template #default="{ row }">
            <el-tooltip content="修改" placement="top">
              <el-button
                type="primary"
                icon="Edit"
                circle
                plain
                @click="handleUpdate(row)"
                v-auth="['system:role:update']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                type="danger"
                icon="Delete"
                circle
                plain
                @click="handleDelete(row)"
                v-auth="['system:role:delete']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <div class="h-20px"></div>
      <!-- {{ searchParams.pageNo }} --- {{ searchParams.pageSize }} -->
      <!-- 分页 -->
      <el-pagination
        background
        v-model:current-page="searchParams.pageNo"
        v-model:page-size="searchParams.pageSize"
        :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleListPage"
        @current-change="handleListPage"
      />

      <!-- 添加 OR 修改 -->
      <KoiDialog ref="koiDrawerRef" :width="500" :height="100" :title="title" @koiConfirm="handleConfirm" @koiCancel="handleCancel" :loading="confirmLoading">
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="80px" status-icon>
            <el-row>
              <el-col :sm="{ span: 20 }" :xs="{ span: 24 }">
                <el-form-item label="类型名称" prop="roleName">
                  <el-input v-model="form.type" placeholder="请输入类型名称" clearable />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </KoiDialog>
    </KoiCard>
  </div>
</template>

<script setup lang="ts" name="postPage">
import { nextTick, ref, reactive, onMounted } from "vue";
import {
  koiMsgSuccess,
  koiNoticeSuccess,
  koiNoticeError,
  koiMsgError,
  koiMsgWarning,
  koiMsgBox,
  koiMsgInfo
} from "@/utils/koi.ts";
// @ts-ignore
import {getList,add,update,del } from "@/api/system/post/index.ts";

// 表格加载动画Loading
const loading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 表格数据
const tableList = ref<any>();
const total = ref(0);
// 查询参数
const searchParams = reactive({
  pageNo: 1, // 第几页
  pageSize: 10, // 每页显示多少条
});
/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选中条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await getList(searchParams);
    tableList.value = res.data;
    total.value = res.data.length;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试!");
  }
};
onMounted(() => {
  // 获取表格数据
  handleListPage();
});

/** 添加 */
const handleAdd = () => {
  // 打开抽屉
  koiDrawerRef.value.koiOpen();
  //koiMsgSuccess("添加🌻");
  // 重置表单
  resetForm();
  // 标题
  title.value = "新增类型";
  //form.value.postStatus = "0";
};
const postId = ref(0);
/** 修改 */
const handleUpdate =  (row) => {
  console.log(row);
  // 打开抽屉
  koiDrawerRef.value.koiOpen();
  // 重置表单
  resetForm();
  // 标题
  title.value = "岗位修改";
  postId.value = row.id;
  form.type=row.type;
  //console.log(postId);
  // 回显数据
  //handleEcho(postId);
};

// 添加 OR 修改抽屉Ref
const koiDrawerRef = ref();
// 标题
const title = ref("岗位类型管理");
// form表单Ref
const formRef = ref<any>();

// form表单
const form = reactive({
  type: "",
});

/** 清空表单数据 */
const resetForm = () => {
  form.type='';
};

/** 表单规则 */
const rules = reactive({
  postName: [{ required: true, message: "请输入岗位名字", trigger: "blur" }],
  postCode: [{ required: true, message: "请输入岗位编码", trigger: "blur" }],
  postStatus: [{ required: true, message: "请输入选择岗位状态", trigger: "blur" }]
});

// 确定按钮是否显示Loading
const confirmLoading = ref(false);

/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      console.log("表单ID", postId.value);
      if (postId.value != null && postId.value != 0) {
        try {
          form.id = postId.value;
          await update(form);
          koiNoticeSuccess("修改成功!");
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("修改失败，请刷新重试!");
        }
      } else {
        try {
          await add(form);
          koiNoticeSuccess("添加成功!");
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("添加失败，请刷新重试🌻");
        }
      }
    } else {
      koiMsgError("验证失败，请检查填写内容🌻");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDrawerRef.value.koiClose();
};

/** 删除 */
const handleDelete = (row: any) => {
  const id = row.id;
  if (id == null || id == "") {
    koiMsgWarning("请选中需要删除的数据!");
    return;
  }
  koiMsgBox("您确认需要删除[" + row.type + "]么？")
    .then(async () => {
      try {
        await del({id:id});
        handleListPage();
        koiNoticeSuccess("删除成功🌻");
      } catch (error) {
        console.log(error);
        handleListPage();
        koiNoticeError("删除失败，请刷新重试🌻");
      }
    })
    .catch(() => {
      koiMsgError("已取消🌻");
    });
};
</script>

<style lang="scss" scoped></style>
