<template>
  <div class="koi-flex">
    <KoiCard>
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true">
        <el-form-item label="部门名称" prop="deptName">
          <el-input
            placeholder="请输入部门名称"
            v-model="searchParams.deptName"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleTreeList"
          ></el-input>
        </el-form-item>
        <el-form-item label="部门状态" prop="status">
          <el-select
            placeholder="请选择部门状态"
            v-model="searchParams.status"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleTreeList"
          >
            <el-option
              v-for="dict in koiDicts.sys_normal_disable"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain v-throttle="handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-debounce="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <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="handleTreeList"></KoiToolbar>
      </el-row>

      <div class="h-20px"></div>
      <!-- 数据表格 -->
      <el-table
        v-if="refreshTreeTable"
        v-loading="loading"
        border
        :data="tableList"
        @selection-change="handleSelectionChange"
        row-key="deptId"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        empty-text="暂时没有数据哟"
      >
        <el-table-column label="序号" prop="id" width="80px" align="center" type="index"></el-table-column>
        <el-table-column label="部门名称" prop="deptName" align="left" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="负责人" prop="leader" width="120px" align="center"></el-table-column>
        <el-table-column label="联系电话" prop="phone" width="120px" align="center"></el-table-column>
        <el-table-column label="邮箱" prop="email" width="230px" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="部门状态" prop="status" width="100px" align="center">
          <template #default="scope">
            <KoiTag :tagOptions="koiDicts.sys_normal_disable" :value="scope.row.status"></KoiTag>
          </template>
        </el-table-column>
        <el-table-column label="显示顺序" prop="orderNum" width="100px" align="center"></el-table-column>
        <el-table-column label="备注" prop="remark" width="180px" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180px" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template #default="{ row }">
            <el-tooltip content="新增" placement="top">
              <el-button
                type="primary"
                icon="Plus"
                circle
                plain
                @click="handleAdd(row)"
                v-auth="['system:dept:add']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button
                type="primary"
                icon="Edit"
                circle
                plain
                @click="handleUpdate(row)"
                v-auth="['system:dept:edit']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                type="danger"
                icon="Delete"
                circle
                plain
                @click="handleDelete(row)"
                v-auth="['system:dept:remove']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 添加 OR 修改 -->
      <KoiDialog
        ref="koiDialogRef"
        :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: 12 }" :xs="{ span: 24 }">
                <el-form-item label="上级部门" prop="parentId">
                  <el-tree-select
                    v-model="form.parentId"
                    :data="cascaderOptions"
                    check-strictly
                    :render-after-expand="false"
                    :props="defaultProps"
                    style="width: 220px"
                  />
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="部门状态" prop="status">
                  <el-select v-model="form.status" placeholder="请选择部门状态" style="width: 260px">
                    <el-option label="启用" value="0" />
                    <el-option label="停用" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="部门名称" prop="deptName">
                  <el-input v-model="form.deptName" placeholder="请输入部门名称" clearable />
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="负责人" prop="leader">
                  <el-input v-model="form.leader" placeholder="请输入部门负责人" clearable />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="手机号码" prop="phone">
                  <el-input v-model="form.phone" placeholder="请输入手机号码" clearable maxlength="11" />
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }" class="p-l-10px">
                <el-form-item label="邮箱地址" prop="email">
                  <el-input v-model="form.email" placeholder="请输入邮箱地址" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }">
                <el-form-item label="显示排序" prop="orderNum">
                  <el-input-number v-model="form.orderNum" style="width: 260px" clearable />
                </el-form-item>
              </el-col>
              <el-col :sm="{ span: 12 }" :xs="{ span: 24 }" class="p-l-10px">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" placeholder="请输入备注" clearable />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </KoiDialog>
    </KoiCard>
  </div>
</template>

<script setup lang="ts" name="dept">
import { nextTick, ref, reactive, onMounted } from "vue";
import { koiNoticeSuccess, koiNoticeError, koiMsgError, koiMsgWarning, koiMsgBox, koiMsgInfo } from "@/utils/koi.ts";
import { handleTree } from "@/utils/index.ts";
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api/system/dept/index.ts";
import {useKoiDict} from "@/hooks/dicts";

const { koiDicts } = useKoiDict(["sys_normal_disable"])
// 表格加载动画Loading
const loading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 表格数据
const tableList = ref<any>([]);

// 查询参数
const searchParams = ref({
  deptName: "",
  status: ""
});
const defaultProps = {
  children: "children",
  label: "deptName",
  value: "deptId"
};

/** 重置搜索参数 */
const resetSearchParams = () => {
  searchParams.value = {
    deptName: "",
    status: ""
  };
};

/** 搜索 */
const handleSearch = () => {
  console.log("搜索");
  handleTreeList();
};

/** 重置 */
const resetSearch = () => {
  console.log("重置搜索");
  resetSearchParams();
  handleTreeList();
};

/** 树形表格查询 */
const handleTreeList = async () => {
  loading.value = true
  const res = await listDept(searchParams.value)
  if(res.code === 200) {
    tableList.value = handleTree(res.data, "deptId");
    loading.value = false
  } else {
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

onMounted(() => {
  // 获取表格数据
  handleTreeList();
});

const ids = ref([]); // 选择数组
const single = ref<boolean>(true); // 非单个禁用
const multiple = ref<boolean>(true); // 非多个禁用

/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  // console.log(selection);
  ids.value = selection.map((item: any) => item.id);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

// 重新渲染表格状态
const refreshTreeTable = ref(true);
const cascaderOptions = ref([])

/** 添加 */
const handleAdd = (row) => {
  // 重置表单
  resetForm();
  // 打开对话框
  koiDialogRef.value.koiOpen();
  koiNoticeSuccess("添加");
  // 标题
  title.value = "部门添加";
  if (row) {
    form.value.parentId = row.deptId;
  }
  cascaderOptions.value = tableList.value
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 打开对话框
  koiDialogRef.value.koiOpen();
  koiNoticeSuccess("修改");
  // 重置表单
  resetForm();
  // 标题
  title.value = "部门修改";
  const id = row.deptId
  if (id == null || id == "") {
    koiMsgError("请选择需要修改的数据");
  }
  const res = await getDept(id)
  if (res.code == 200) {
    form.value = res.data
    cascaderOptions.value = tableList.value
  }
};

// 添加 OR 修改对话框Ref
const koiDialogRef = ref();
// 标题
const title = ref("部门管理");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  deptId: "",
  parentId: "",
  deptName: "",
  orderNum: "",
  leader: "",
  phone: "",
  email: "",
  status: "0"
});

/** 清空表单数据 */
const resetForm = () => {
  // 等待 DOM 更新完成
  nextTick(() => {
    if (formRef.value) {
      // 重置该表单项，将其值重置为初始值，并移除校验结果
      formRef.value.resetFields();
    }
  });
  form.value = {
    deptId: "",
    parentId: "",
    deptName: "",
    orderNum: "",
    leader: "",
    phone: "",
    email: "",
    status: "0"
  };
};

/** 表单规则 */
const rules = reactive({
  deptId: [{ required: true, message: "请输入部门编号", trigger: "blur" }],
  deptName: [{ required: true, message: "请输入部门名字", trigger: "blur" }],
  parentId: [{ required: true, message: "请选择上级部门", trigger: "blur" }],
  status: [{ required: true, message: "请输入选择部门状态", trigger: "blur" }],
  leader: [{ required: true, message: "请输入负责人名字", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号码", trigger: "blur" }],
  orderNum: [{ 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) {
      if (form.value.deptId != null && form.value.deptId != "") {
          const res = await updateDept(form.value);
          if(res.code === 200) {
            koiNoticeSuccess("修改成功");
            confirmLoading.value = false;
            koiDialogRef.value.koiQuickClose();
            resetForm();
            handleTreeList();
          } else {
            confirmLoading.value = false;
            koiNoticeError("修改失败，请刷新重试");
          }
      } else {
          const res = await addDept(form.value);
          if(res.code === 200) {
            koiNoticeSuccess("添加成功");
            confirmLoading.value = false;
            koiDialogRef.value.koiQuickClose();
            resetForm();
            handleTreeList();
          } else {
            confirmLoading.value = false;
            koiNoticeError("添加失败，请刷新重试");
          }
      }
    } else {
      koiMsgError("验证失败，请检查填写内容");
      confirmLoading.value = false;
    }
  });
};

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

/** 删除 */
const handleDelete = (row: any) => {
  const id = row.deptId;
  if (id == null || id == "") {
    koiMsgWarning("请选择需要删除的数据");
    return;
  }
  koiMsgBox("您确认需要删除部门名称[" + row.deptName + "]么？")
    .then(async () => {
      const res = await delDept(id);
      if(res.code === 200) {
        koiNoticeSuccess("删除成功");
        handleTreeList()
      } else {
        koiMsgError(res.msg);
      }
    })
    .catch(() => {

    });
};
</script>

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