import BreadTit from "@/components/BreadTit";
import { RootState } from "@/store";
import {
  addRoleAPI,
  delRoleAPI,
  getRoleInfoAPI,
  getRoleListAPI,
  roleEditStatusAPI,
} from "@/store/action/system";
import {
  Button,
  Checkbox,
  Input,
  Modal,
  Popconfirm,
  Switch,
  Table,
} from "antd";
import TextArea from "antd/es/input/TextArea";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { useDispatch, useSelector } from "react-redux";
import styles from "./index.module.scss";
import classNames from "classnames";
import "../System1/index.css";
import { MessageFu } from "@/utils/message";

function System2() {
  const dispatch = useDispatch();

  // 从仓库中获取权限数据
  const roleInfo = useSelector(
    (state: RootState) => state.systemStore.roleInfo
  );
  const roleArr = useSelector((state: RootState) => state.systemStore.roleArr);

  // 筛选和分页
  const [tableSelect, setTableSelect] = useState({
    searchKey: "",
    pageSize: 10,
    pageNum: 1,
  });

  // 账号的输入
  const nameTime = useRef(-1);
  const nameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    clearTimeout(nameTime.current);
    nameTime.current = window.setTimeout(() => {
      setTableSelect({ ...tableSelect, searchKey: e.target.value, pageNum: 1 });
    }, 500);
  };
  useEffect(() => {
    dispatch(getRoleListAPI(tableSelect));
  }, [dispatch, tableSelect]);

  // 点击新增或者编辑按钮
  const addRole = useCallback(
    async (id?: any) => {
      if (id) {
        const res: any = await getRoleInfoAPI(id);
        const roleInfo = res.data.role;
        const roleArr = res.data.permission;
        dispatch({ type: "system/getRoleInfo", payload: roleInfo });
        dispatch({ type: "system/getRoleArr", payload: roleArr });
        setRoleDesc(roleInfo.roleDesc);
        setRoleName(roleInfo.roleName);
        editRef.current = "edit";
      } else {
        // 清空仓库角色信息
        dispatch({ type: "system/getRoleInfo", payload: {} });
        setRoleDesc("");
        setRoleName("");
        // 初始化权限信息
        dispatch({
          type: "system/getRoleArr",
          payload: [
            {
              id: 100,
              name: "藏品登记",
              authority: false,
              children: [
                { name: "编辑", authority: false, id: 102 },
                { name: "删除", authority: false, id: 103 },
                { name: "审核", authority: false, id: 105 },
              ],
            },
            {
              id: 200,
              name: "臧品总账",
              authority: false,
              children: [
                { name: "编辑", authority: false, id: 202 },
                { name: "移库", authority: false, id: 205 },
              ],
            },
            {
              id: 300,
              name: "入库管理",
              authority: false,
              children: [
                { name: "编辑", authority: false, id: 302 },
                { name: "删除", authority: false, id: 303 },
                { name: "审核", authority: false, id: 305 },
              ],
            },
            {
              id: 400,
              name: "出库管理",
              authority: false,
              children: [
                { name: "编辑", authority: false, id: 402 },
                { name: "删除", authority: false, id: 403 },
                { name: "审核", authority: false, id: 405 },
                { name: "归还", authority: false, id: 406 },
              ],
            },
            {
              id: 500,
              name: "臧品修改",
              authority: false,
              children: [
                { name: "删除", authority: false, id: 503 },
                { name: "审核", authority: false, id: 505 },
              ],
            },
            {
              id: 600,
              name: "臧品注销",
              authority: false,
              children: [
                { name: "编辑", authority: false, id: 602 },
                { name: "删除", authority: false, id: 603 },
                { name: "审核", authority: false, id: 605 },
              ],
            },
            {
              id: 700,
              name: "库房设置",
              authority: false,
              children: [
                { name: "编辑", authority: false, id: 702 },
                { name: "删除", authority: false, id: 703 },
              ],
            },
            {
              id: 800,
              name: "臧品移库",
              authority: false,
              children: [
                { name: "删除", authority: false, id: 803 },
                { name: "审核", authority: false, id: 805 },
              ],
            },
          ],
        });
        editRef.current = "add";
      }
      setOpen(true);
    },
    [dispatch]
  );
  // 点击删除
  const delOne = useCallback(
    async (id: number) => {
      const res: any = await delRoleAPI(id);
      if (res.code === 0) {
        MessageFu.success("删除成功!");
        // 重新发请求更新页面
        dispatch(getRoleListAPI(tableSelect));
      }
    },
    [dispatch, tableSelect]
  );

  // ---------关于表格

  // 切换表格中的启用停用状态
  const isEnabledClickFu = useCallback(
    async (val: boolean, id: number) => {
      const isDisable = val ? 1 : 0;
      const res: any = await roleEditStatusAPI(id, isDisable);
      if (res.code === 0) dispatch(getRoleListAPI(tableSelect));
    },
    [dispatch, tableSelect]
  );

  // 页码变化
  const paginationChange = (pageNum: number, pageSize: number) => {
    setTableSelect({ ...tableSelect, pageNum, pageSize });
  };
  const results = useSelector(
    (state: RootState) => state.systemStore.tableList
  );
  const columns = useMemo(() => {
    return [
      {
        title: "角色名称",
        dataIndex: "roleName",
      },
      {
        title: "描述",
        dataIndex: "roleDesc",
      },
      {
        title: "成员数量",
        dataIndex: "count",
      },

      {
        title: "状态",
        render: (item: any) => (
          <Switch
            checkedChildren="启用"
            unCheckedChildren="停用"
            checked={item.isEnabled === 1}
            onChange={(val) => isEnabledClickFu(val, item.id)}
            disabled={item.roleKey && item.roleKey.includes("sys_")}
          />
        ),
      },

      {
        title: "操作",
        render: (item: any) => (
          <>
            <Button type="text" danger onClick={() => addRole(item.id)}>
              {item.roleKey && item.roleKey.includes("sys_") ? "查看" : "编辑"}
            </Button>
            {item.roleKey && item.roleKey.includes("sys_") ? null : (
              <>
                <Popconfirm
                  title="确定删除吗?"
                  okText="确定"
                  cancelText="取消"
                  onConfirm={() => delOne(item.id)}
                >
                  <Button type="text" danger>
                    删除
                  </Button>
                </Popconfirm>
              </>
            )}
          </>
        ),
      },
    ];
  }, [addRole, delOne, isEnabledClickFu]);

  // --------关于弹窗
  const [open, setOpen] = useState(false);
  const editRef = useRef("add");

  // 角色名称
  const [roleName, setRoleName] = useState("");
  // 描述
  const [roleDesc, setRoleDesc] = useState("");

  // 权限第一级的改变
  const checkOneFu = useCallback(
    (val: boolean, id: number) => {
      const data = roleArr.map((v: any) => {
        return {
          ...v,
          authority: v.id === id ? val : v.authority,
        };
      });
      dispatch({ type: "system/getRoleArr", payload: data });
    },
    [dispatch, roleArr]
  );
  // 权限的第二级改变
  const checkTowFu = useCallback(
    (val: boolean, id1: number, id2: number) => {
      const data = [...roleArr];
      data.forEach((v) => {
        if (v.id === id1) {
          v.children.forEach((v2: any) => {
            if (v2.id === id2) v2.authority = val;
          });
        }
      });
      dispatch({ type: "system/getRoleArr", payload: data });
    },
    [dispatch, roleArr]
  );

  // 点击提交
  const btnOkFu = useCallback(async () => {
    if (roleName === "") return MessageFu.warning("角色名称不能为空!");
    const txt = roleDesc.replaceAll(" ", "").replaceAll("\n", "");
    if (txt === "") return MessageFu.warning("描述不能为空!");
    const resources = [] as any;
    roleArr.forEach((v: any) => {
      if (v.authority) resources.push(v.id);
      v.children.forEach((v2: any) => {
        if (v2.authority) resources.push(v2.id);
      });
    });
    const obj = {
      ...roleInfo,
      roleName,
      roleDesc,
      resources,
    };
    const res: any = await addRoleAPI(obj);
    if (res.code === 0) {
      MessageFu.success("操作成功!");
      setOpen(false);
      // 重新发请求更新页面
      dispatch(getRoleListAPI(tableSelect));
    }
  }, [dispatch, roleArr, roleDesc, roleInfo, roleName, tableSelect]);

  return (
    <div className={styles.System2}>
      <div className="breadTit">
        <BreadTit>
          <div className="breadTitRow active">角色管理</div>
        </BreadTit>
      </div>
      <div className="objectSonMain">
        <div className="tableSelectBox">
          <div className="row">
            <span>角色名：</span>
            <Input
              maxLength={10}
              style={{ width: 150 }}
              placeholder="请输入"
              allowClear
              onChange={(e) => nameChange(e)}
            />
          </div>
          <div className="row">
            <Button type="primary" onClick={() => addRole()}>
              新增角色
            </Button>
          </div>
        </div>
        {/* 表格主体 */}
        <div className="tableMain">
          <Table
            scroll={{ y: 480 }}
            dataSource={results.list}
            columns={columns}
            rowKey="id"
            pagination={{
              showQuickJumper: true,
              position: ["bottomCenter"],
              showSizeChanger: true,
              current: tableSelect.pageNum,
              pageSize: tableSelect.pageSize,
              total: results.total,
              onChange: paginationChange,
            }}
          />
        </div>
      </div>
      {/* 点击新增或者编辑出来的弹窗 */}
      <Modal
        wrapClassName="systemUser systemRole"
        destroyOnClose
        open={open}
        title={
          editRef.current === "add"
            ? "新增角色"
            : roleInfo.roleKey && roleInfo.roleKey.includes("sys_")
            ? "查看角色"
            : "编辑角色"
        }
        onCancel={() => setOpen(false)}
        footer={
          [] // 设置footer为空，去掉 取消 确定默认按钮
        }
      >
        <div
          className={classNames(
            "systemTit",
            roleInfo.roleKey && roleInfo.roleKey.includes("sys_")
              ? "looksystem"
              : ""
          )}
        >
          <div className="systemTitRow">
            <div className="bs">*</div>
            <div className="lable">角色名称：</div>
            <Input
              maxLength={15}
              showCount
              style={{ width: 600 }}
              placeholder="请输入"
              value={roleName}
              onChange={(e) => setRoleName(e.target.value.trim())}
            />
          </div>
          <div className="systemTitRow">
            <div className="bs bs2">*</div>
            <div className="lable">描述：</div>
            <TextArea
              style={{ width: 600 }}
              value={roleDesc}
              onChange={(e) => setRoleDesc(e.target.value)}
              rows={3}
              placeholder="请输入"
              showCount
              maxLength={255}
            />
          </div>
          <div className="systemTitRow systemTitRow2">
            <div className="lable">权限设置：</div>
            <div className="powerBox">
              {roleArr.map((v: any) => (
                <div className="powerBoxRow" key={v.id}>
                  <span className="label">{v.name}：</span>
                  <Checkbox
                    className="oneCheck"
                    checked={v.authority}
                    onChange={(e) => checkOneFu(e.target.checked, v.id)}
                  >
                    启用
                  </Checkbox>
                  {v.children.map((v2: any) => (
                    <Checkbox
                      checked={v2.authority}
                      onChange={(e) =>
                        checkTowFu(e.target.checked, v.id, v2.id)
                      }
                      disabled={!v.authority}
                      key={v2.id}
                    >
                      {v2.name}
                    </Checkbox>
                  ))}
                </div>
              ))}
              {roleInfo.id === 1 ? (
                <div className="powerBoxRow">
                  <span className="label">系统管理：</span>
                  <Checkbox className="oneCheck" defaultChecked={true}>
                    启用
                  </Checkbox>
                </div>
              ) : null}
            </div>
          </div>

          <br />
          <div className="systemTitBtn">
            <Button type="primary" onClick={btnOkFu}>
              提交
            </Button>
            &emsp;
            <Button onClick={() => setOpen(false)}>取消</Button>
          </div>
        </div>
      </Modal>
    </div>
  );
}

const MemoSystem2 = React.memo(System2);

export default MemoSystem2;
