import { PageContainer } from "@/components";
import { FC, useEffect, useState } from "react";
import {
  AddDeptModal,
  AddGroupModal,
  AllocationOfDataModal,
  AllocationOfIndexModal,
} from "../components";
import { Pane } from "./components/Pane";
import { Button, Table, Tag } from "antd";
import { DageTableActions } from "@dage/pc-components";
import {
  deleteManageRoleDeptApi,
  deleteManageRoleGroupApi,
  getManageRoleDeptListApi,
  getManageRoleGroupListApi,
} from "@/api";
import { useParams } from "react-router-dom";
import {
  ASS_INDEX_TYPE,
  IManageDeptItem,
  IManageRoleGroupItem,
  PUBLISH_ENUM,
  YES_OR_NO,
} from "@/types";
import style from "../index.module.scss";

const SettingRole: FC = () => {
  const params = useParams();
  const [addDeptVisible, setAddDeptVisible] = useState(false);
  const [addGroupVisible, setAddGroupVisible] = useState(false);
  const [allocationOfDataVisible, setAllocationOfDataVisible] = useState(false);
  const [allocationOfIndexVisible, setAllocationOfIndexVisible] =
    useState(false);
  const [deptLoading, setDeptLoading] = useState(false);
  const [deptList, setDeptList] = useState<IManageDeptItem[]>([]);
  const [groupLoading, setGroupLoading] = useState(false);
  const [groupList, setGroupList] = useState<IManageRoleGroupItem[]>([]);
  const [checkedItem, setCheckedItem] = useState<null | IManageDeptItem>(null);
  const [checkedGroup, setCheckedGroup] = useState<null | IManageRoleGroupItem>(
    null
  );

  // 获取责任部门列表
  const getDeptList = async () => {
    try {
      setDeptLoading(true);
      const data = await getManageRoleDeptListApi(params.id as string);
      setDeptList(data);
    } finally {
      setDeptLoading(false);
    }
  };

  // 获取评定组列表
  const getGroupList = async () => {
    try {
      setGroupLoading(true);
      const data = await getManageRoleGroupListApi(params.id as string);
      // fake array
      setGroupList(Array.isArray(data) ? data : Boolean(data) ? [data] : []);
    } finally {
      setGroupLoading(false);
    }
  };

  const handleEdit = (item: IManageDeptItem) => {
    setCheckedItem(item);
    setAddDeptVisible(true);
  };

  const handleDelete = async (id: number) => {
    await deleteManageRoleDeptApi(id);
    getDeptList();
  };

  const handleAllocationData = (item: IManageDeptItem) => {
    setCheckedItem(item);
    setAllocationOfDataVisible(true);
  };

  const handleAllocationIndex = (item: IManageDeptItem) => {
    setCheckedItem(item);
    setAllocationOfIndexVisible(true);
  };

  const handleDeleteGroup = async (id: number) => {
    await deleteManageRoleGroupApi(id);
    getGroupList();
  };

  useEffect(() => {
    getDeptList();
    getGroupList();
  }, []);

  return (
    <PageContainer title="设置角色">
      <Pane
        title="责任部门"
        required
        tips="负责填报指标或上传资料的部门或组织"
        onAdd={() => setAddDeptVisible(true)}
      >
        <Table
          rowKey="id"
          dataSource={deptList}
          loading={deptLoading}
          className="cus-table gray"
          columns={[
            {
              title: "部门名称",
              align: "center",
              dataIndex: "name",
            },
            {
              title: "博物馆级别",
              align: "center",
              dataIndex: "levelMuseum",
            },
            {
              title: "组别说明",
              align: "center",
              dataIndex: "remark",
            },
            {
              title: "自评权限",
              align: "center",
              render: (item: IManageDeptItem) => {
                return item.isSelf === YES_OR_NO.YES ? "是" : "否";
              },
            },
            {
              title: "主管",
              align: "center",
              dataIndex: "leaderName",
            },
            {
              title: "操作",
              align: "center",
              render: (item: IManageDeptItem) => {
                return (
                  <DageTableActions
                    renderBefore={
                      <>
                        <Button
                          type="text"
                          className={style.button}
                          onClick={handleAllocationData.bind(undefined, item)}
                        >
                          分配资料
                        </Button>
                        <Button
                          type="text"
                          className={style.button}
                          onClick={handleAllocationIndex.bind(undefined, item)}
                        >
                          分配指标
                        </Button>
                      </>
                    }
                    showDelete={Number(params.status) === PUBLISH_ENUM.PENDING}
                    onEdit={handleEdit.bind(undefined, item)}
                    onDelete={handleDelete.bind(undefined, item.id)}
                  />
                );
              },
            },
          ]}
        />
      </Pane>

      <Pane
        title="评定组"
        required
        hideAddBtn={Boolean(groupList.length)}
        tips="负责评定责任部门填报结果的人员"
        style={{ marginTop: 40 }}
        onAdd={() => setAddGroupVisible(true)}
      >
        <Table
          rowKey="id"
          className="cus-table gray"
          dataSource={groupList}
          loading={groupLoading}
          columns={[
            {
              title: "用户",
              align: "center",
              render: (item: IManageRoleGroupItem) => {
                const arr = item.userName.split(",") ?? [];
                return (
                  <>
                    {arr.map((i) => (
                      <Tag key={i}>{i}</Tag>
                    ))}
                  </>
                );
              },
            },
            {
              title: "操作",
              align: "center",
              render: (item) => {
                return (
                  <DageTableActions
                    onEdit={() => {
                      setCheckedGroup(item);
                      setAddGroupVisible(true);
                    }}
                    onDelete={handleDeleteGroup.bind(undefined, item.id)}
                  />
                );
              },
            },
          ]}
        />
      </Pane>

      {/* 设置责任部门 */}
      <AddDeptModal
        item={checkedItem}
        assessId={params.id as string}
        open={addDeptVisible}
        onOk={getDeptList}
        onCancel={() => {
          setAddDeptVisible(false);
          setCheckedItem(null);
        }}
      />

      {/* 设置评定组 */}
      <AddGroupModal
        checkedItem={checkedGroup}
        assessId={params.id as string}
        open={addGroupVisible}
        onOk={getGroupList}
        onCancel={() => {
          setAddGroupVisible(false);
        }}
      />

      {/* 分配资料 */}
      <AllocationOfDataModal
        item={checkedItem}
        deptList={deptList}
        assessId={params.id as string}
        open={allocationOfDataVisible}
        onOk={getDeptList}
        onCancel={() => {
          setAllocationOfDataVisible(false);
          setCheckedItem(null);
        }}
      />

      {/* 分配指标 */}
      <AllocationOfIndexModal
        type={params.type as ASS_INDEX_TYPE}
        item={checkedItem}
        assessId={params.id as string}
        open={allocationOfIndexVisible}
        deptList={deptList}
        onOk={getDeptList}
        onCancel={() => {
          setAllocationOfIndexVisible(false);
          setCheckedItem(null);
        }}
      />
    </PageContainer>
  );
};

export default SettingRole;
