import { getRoleInfoByIdAPI, roleSaveAPI } from "@/store/action/C2Role";

import { Button, Checkbox, Input, Modal, Popconfirm } from "antd";
import React, { useCallback, useEffect, useState } from "react";
import classNames from "classnames";
import "./index.css";
import { AddRoleType, PermissionsAPIType, RoleTableType } from "@/types";
import { MessageFu } from "@/utils/message";
const { TextArea } = Input;

type Props = {
  id: any;
  closePage: () => void;
  upTableList: () => void;
  addTableList: () => void;
};

function RoleAdd({ id, closePage, upTableList, addTableList }: Props) {
  // 角色名称
  const [roleName, setRoleName] = useState("");

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

  // 页面权限的选择
  const [list, setList] = useState<PermissionsAPIType[]>([
    {
      id: 100,
      name: "数据统计",
      authority: true,
      children: [{ id: 110, name: "热度统计", authority: true }],
    },
    {
      id: 200,
      name: "内容管理",
      authority: true,
      children: [
        { id: 220, name: "场景管理", authority: true },
        { id: 230, name: "馆藏管理", authority: true },
        { id: 240, name: "万物墙管理", authority: true },
        { id: 250, name: "弹幕管理", authority: true },
        { id: 260, name: "题库管理", authority: true },
        { id: 270, name: "智能导览管理", authority: true },
      ],
    },
  ]);

  const checkChangeFu = useCallback(
    (checked: boolean, id: number) => {
      const newList = [...list];
      newList.forEach((v1) => {
        v1.children?.forEach((v2) => {
          if (v2.id === id) v2.authority = checked;
        });
      });

      setList(newList);
    },
    [list]
  );

  const getRoleInfoByIdFu = useCallback(async (id: number) => {
    const res = await getRoleInfoByIdAPI(id);
    const info: RoleTableType = res.data.role;
    const authPageArr: PermissionsAPIType[] = res.data.permission;
    setRoleName(info.roleName);
    setRoleDesc(info.roleDesc);
    setList(authPageArr);
  }, []);
  // 如果是编辑
  useEffect(() => {
    if (id) getRoleInfoByIdFu(id);
  }, [getRoleInfoByIdFu, id]);

  // 点击提交
  const btnOkFu = useCallback(async () => {
    if (roleName === "") return MessageFu.warning("请输入角色名称!");

    let temp1 = true;

    const resources: number[] = [];

    list.forEach((v1) => {
      v1.children?.forEach((v2) => {
        if (v2.authority) {
          temp1 = false;
          resources.push(v2.id);
        }
      });
    });

    if (temp1) return MessageFu.warning("至少勾选一个页面权限!");

    const obj: AddRoleType = {
      id: id ? id : null,
      resources,
      roleDesc: roleDesc,
      roleName: roleName,
    };
    const res: any = await roleSaveAPI(obj);

    if (res.code === 0) {
      MessageFu.success(id ? "编辑成功!" : "新增成功!");
      closePage();
      if (id) addTableList();
      else upTableList();
    }
  }, [addTableList, closePage, id, list, roleDesc, roleName, upTableList]);

  return (
    <Modal
      wrapClassName="roleAdd"
      destroyOnClose
      open={true}
      title={id ? (id === 1 ? "查看角色" : "编辑角色") : "新增角色"}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className={classNames("roleAddMain", id === 1 ? "lookRole" : "")}>
        <div className="row">
          <span className="bs rowSpan">角色名称：</span>
          <div className="inputBox">
            <Input
              maxLength={8}
              value={roleName}
              onChange={(e) => setRoleName(e.target.value.replace(/\s+/g, ""))}
              showCount
              placeholder="请输入内容"
            />
          </div>
        </div>

        <div className="row">
          <span className="rowSpan">角色描述：</span>
          <div className="inputBox">
            <TextArea
              rows={4}
              placeholder="请输入内容"
              maxLength={100}
              showCount
              value={roleDesc}
              onChange={(e) => setRoleDesc(e.target.value.replace(/\s+/g, ""))}
            />
          </div>
        </div>

        {list.map((v1) => (
          <div className="row" key={v1.id}>
            <span className="rowSpan">
              <span>*</span> {v1.name}：
            </span>
            <div className="inputBox inputBoxCheck">
              {v1.children!.map((v2) => (
                <Checkbox
                  className="rowCheck"
                  key={v2.id}
                  checked={v2.authority}
                  onChange={(e) => checkChangeFu(e.target.checked, v2.id)}
                >
                  {v2.name}
                </Checkbox>
              ))}
            </div>
          </div>
        ))}

        {id === 1 ? (
          <div className="row">
            <span className="rowSpan">
              <span>*</span>系统管理：
            </span>
            <div className="inputBox inputBoxCheck">
              <Checkbox className="rowCheck" defaultChecked={true}>
                用户管理
              </Checkbox>
              <Checkbox className="rowCheck" defaultChecked={true}>
                角色管理
              </Checkbox>
              <Checkbox className="rowCheck" defaultChecked={true}>
                操作日志
              </Checkbox>
            </div>
          </div>
        ) : null}

        <div className="roleAddButton">
          {id !== 1 ? (
            <>
              <Button type="primary" onClick={btnOkFu}>
                提交
              </Button>
              &emsp;
              <Popconfirm
                title="放弃编辑后，信息将不会保存!"
                okText="放弃"
                cancelText="取消"
                onConfirm={closePage}
              >
                <Button>取消</Button>
              </Popconfirm>
            </>
          ) : (
            <Button onClick={closePage}>关闭</Button>
          )}
        </div>
      </div>
    </Modal>
  );
}

const MemoRoleAdd = React.memo(RoleAdd);

export default MemoRoleAdd;
