import dayjs from "dayjs";
import editForm from "../components/form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import { cloneDeep } from "@pureadmin/utils";
import type { DepartmentInfo } from "types/system";
import { usePublicHooks } from "../../hooks";
import {
  deleteDepartmentAPI,
  getDepartmentListAPI,
  postAddDepartmentAPI,
  putUpdateDepartmentAPI
} from "@/api/system";

export const useDepartment = () => {
  const form = reactive({
    /**部门ID */
    id: "",
    /**部门名称 */
    name: "",
    /**附属部门ID */
    parent_id: "",
    /**部门负责人 */
    principal: "",
    /**部门电话 */
    phone: "",
    /**部门邮件 */
    email: "",
    /**备注 */
    remark: "",
    /**排序 */
    sort: 0,
    /**状态 */
    status: ""
  });
  /**
   * 表单Ref
   */
  const formRef = ref();
  /**
   * 数据列表
   */
  const dataList = ref<DepartmentInfo[]>([]);
  /**
   * 加载状态
   */
  const loading = ref(true);
  /**
   * 标签样式
   */
  const { tagStyle } = usePublicHooks();
  /**
   * 表格列设置
   */
  const columns: TableColumnList = [
    {
      label: "部门名称",
      prop: "name",
      width: 180,
      align: "left"
    },
    {
      label: "排序",
      prop: "sort",
      minWidth: 70
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.status)}>
          {row.status === 1 ? "启用" : "停用"}
        </el-tag>
      )
    },
    {
      label: "创建时间",
      minWidth: 200,
      prop: "create_time",
      formatter: ({ create_time }) =>
        dayjs(create_time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "修改时间",
      minWidth: 200,
      prop: "update_time",
      formatter: ({ update_time }) =>
        dayjs(update_time).format("YYYY-MM-DD HH:mm:ss")
    },
    {
      label: "备注",
      prop: "remark",
      minWidth: 320
    },
    {
      label: "操作",
      fixed: "right",
      width: 230,
      slot: "operation"
    }
  ];
  /**
   * 初次查询
   */
  const onSearch = async () => {
    loading.value = true;
    const res = await getDepartmentListAPI({
      page: 1,
      pageSize: 9999,
      ...form
    });
    if (res.success) {
      dataList.value = handleTree(res.data.result, "id", "parent_id"); // 处理成树结构
    }
    setTimeout(() => {
      loading.value = false;
    }, 500);
  };

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };
  const formatHigherOptions = treeList => {
    // 根据返回数据的status字段值判断追加是否禁用disabled字段，返回处理后的树结构，用于上级部门级联选择器的展示（实际开发中也是如此，不可能前端需要的每个字段后端都会返回，这时需要前端自行根据后端返回的某些字段做逻辑处理）
    if (!treeList || !treeList.length) return;
    const newTreeList = [];
    for (let i = 0; i < treeList.length; i++) {
      treeList[i].disabled = treeList[i].status === 0 ? true : false;
      formatHigherOptions(treeList[i].children);
      newTreeList.push(treeList[i]);
    }
    return newTreeList;
  };
  const openDialog = (title = "新增", row?: DepartmentInfo) => {
    addDialog({
      title: `${title}部门`,
      props: {
        formInline: {
          higherOptions: formatHigherOptions(cloneDeep(dataList.value)),
          id: row?.id ?? "",
          parent_id: row?.parent_id ?? "",
          name: row?.name ?? "",
          principal: row?.principal ?? "",
          phone: row?.phone ?? "",
          email: row?.email ?? "",
          sort: row?.sort ?? 0,
          status: row?.status ?? 1,
          remark: row?.remark ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () =>
        h(editForm, {
          formInline: {
            higherOptions: formatHigherOptions(cloneDeep(dataList.value)),
            id: row?.id ?? "",
            parent_id: row?.parent_id ?? "",
            name: row?.name ?? "",
            principal: row?.principal ?? "",
            phone: row?.phone ?? "",
            email: row?.email ?? "",
            sort: row?.sort ?? 0,
            status: row?.status ?? 1,
            remark: row?.remark ?? ""
          },
          ref: formRef
        }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as DepartmentInfo;
        function chores() {
          message(`您${title}了部门名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async (valid: any) => {
          if (valid) {
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              const res = await postAddDepartmentAPI(curData);
              if (res.success) {
                chores();
              } else {
                message(`添加失败！`, {
                  type: "error"
                });
                done();
              }
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              const res = await putUpdateDepartmentAPI(curData, row.id);
              if (res.success) {
                chores();
              } else {
                message(`修改失败！`, {
                  type: "error"
                });
                done();
              }
            }
          }
        });
      }
    });
  };
  /**
   * 删除部门
   */
  const handleDelete = async (row: DepartmentInfo) => {
    const res = await deleteDepartmentAPI(row.id);
    if (res.code === 200) {
      message(`您删除了部门：${row.name}及其附属部门`, { type: "success" });
      onSearch();
    } else {
      message(`删除失败！`, {
        type: "error"
      });
    }
  };

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    dataList,
    columns,
    onSearch,
    resetForm,
    openDialog,
    handleDelete
  };
};
