import { useState, useEffect, useMemo } from "react";
import { Outlet, useLocation, history } from "umi";
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  BarChartOutlined,
  ProfileOutlined,
  ReloadOutlined,
  StockOutlined,
  FundOutlined,
  FundProjectionScreenOutlined,
  TeamOutlined,
  ToolOutlined,
  CloudUploadOutlined
} from "@ant-design/icons";
import {
  Avatar,
  Button,
  Flex,
  Layout,
  Menu,
  Space,
  theme,
  Dropdown,
  Tooltip,
  Form,
  Input,
  Modal,
  message
} from "antd";
import { getUserInfo, updatePassword } from '@/apis/user';
import useUserStore from '@/stores/useUserStore';
import useCurrentExam from '@/stores/useCurrentExam';
import { judgeLeader } from '@/utils/permission';
import avatarSrc from "@/assets/image/avatar.png";
import "./index.less";

const { Header, Sider, Content } = Layout;

const HomePage = () => {
  const { username = '' } = localStorage.getItem("userInfo") ? JSON.parse(localStorage.getItem('userInfo')) : {};
  const { examName } = useCurrentExam();
  const location = useLocation();
  const [collapsed, setCollapsed] = useState(false);
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();

  const [defaultSelectedKey, setDefaultSelectedKey] = useState();

  const [filteredMenu, setFilteredMenu] = useState([]);


  const [isShowTitle, setIsShowTitle] = useState('');
  const [roleType, setRoleType] = useState();

  const { setUser } = useUserStore();


  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();

  const [isAdmin, setIsAdmin] = useState(false);
  const [disabled, setDisabled] = useState(false);


  const backMenuItems = [
    {
      key: "/home/system/data",
      icon: <CloudUploadOutlined />,
      label: "数据导入",
    },
    {
      key: "/home/system/account",
      icon: <TeamOutlined />,
      label: "账号管理",
      children: [
        {
          key: "/home/system/account/admin",
          label: "创建账号",
        },
        {
          key: "/home/system/account/access",
          label: "权限设置",
        },
        // {
        //   key: "/home/system/setup/school",
        //   label: "学校设置",
        // },
      ],

    },
    {
      key: "/home/system/setup",
      icon: <ToolOutlined />,
      label: "系统设置",
      children: [
        {
          key: "/home/system/setup/subject",
          label: "学科设置",
        },
        {
          key: "/home/system/setup/district",
          label: "区县设置",
        },
        {
          key: "/home/system/setup/school",
          label: "学校设置",
        },
      ],
    },
  ];


  const computedDropdownMenuItems = useMemo(() => {
    const originalMenu = [

      {
        key: "1",
        label: (
          <a onClick={() => {
            setOpen(true);
          }}>修改密码</a>
        ),
      },
      {
        key: "3",
        label: (
          <a onClick={() => {
            history.push("/login");
            localStorage.removeItem('access');
          }}>退出账号</a>
        ),
      },
    ];
    return originalMenu;

  }, [isAdmin]);



  const computedMenuItems = () => {
    if (localStorage.getItem('menuType') === "MIDDLE_GROUND") {
      return filteredMenu;
    }
    return backMenuItems;
  }


  // 根据接口返回值

  // useEffect(() => {

  //   setCollapsed(()=>{
  //     return judgeLeader(roleType)
  //   });
  // }, [roleType]);




  const computedRole = useMemo(() => {
    if (roleType === 0) {
      return '教师';
    }
    if (roleType === 1) {
      return '教研员';
    }
    if (roleType === 2) {
      return '校长';
    }
    if (roleType === 3) {
      return '院长';
    }
    if (roleType === 4) {
      return '局长';
    }
  }, [roleType]);


  function filterMenuItems(menuItems, menuList) {
    return menuItems
      .map((item) => {
        // 检查当前项是否有权限
        const hasAccess = item.access === 'all' || menuList.includes(item.access) ||item.access === 'link';
        if (!hasAccess) return null;

        // 深拷贝当前项，避免修改原始数据
        const newItem = { ...item };

        // 递归处理子项
        if (newItem.children) {
          const filteredChildren = filterMenuItems(newItem.children, menuList);
          if (filteredChildren.length === 0) return null; // 子项为空则过滤父项
          newItem.children = filteredChildren;
        }

        return newItem;
      })
      .filter((item) => item !== null); // 过滤掉被标记为 null 的项
  }


  const menuItems = [
    {
      key: "/home/analysis",
      icon: <FundOutlined />,
      label: "分析报告",
      access: 20019,
    },
    // {
    //   key: "/home/statistics",
    //   icon: <BarChartOutlined />,
    //   label: "首页",
    //   access: 20020,
    // },
    // {
    //   key: "/home/backup",
    //   // icon: <BarChartOutlined />,
    //   label: "备份整体分析报告",
    //   access:'all',
    // },
    {
      key: "/home/template",
      icon: <FundProjectionScreenOutlined />,
      label: "模板管理",
      access: 20021,
    },
    {
      key: "/home/report",
      icon: <ProfileOutlined />,
      label: "当前考试",
      access: 20017,
      children: [
        {
          key: "/home/report/online",
          label: "上线情况分析",
          access: 20004,
        },
        {
          key: "/home/report/school",
          label: "学校对比分析",
          access: 20005,
        },
        {
          key: "/home/report/teacher",
          label: "教师群体分析",
          access: 20008,
        },
        {
          key: "/home/report/student",
          label: "学生群体分析",
          access: 20006,
        },
        {
          key: "/home/report/examDistribution",
          label: "选考分布分析",
          access: 20013,
        },
        {
          key: "/home/report/quality",
          label: "试卷质量分析",
          access: 'all',
        },
        {
          key: "/home/report/question",
          label: "学科小题分析",
          access: 20014,
        },
        {
          key: "/home/report/enowledgepoint",
          label: "学科知识点分析",
          access: 20015,
        },
      ],
    },
    {
      key: "/home/examination/comparison",
      icon: <StockOutlined />,
      label: "对比考试",
      access: 20018,
      children: [
        {
          key: "/home/online/comparison",
          label: (
            <Tooltip title="对比考试上线情况分析">
              <span>对比考试上线情况分析</span>
            </Tooltip>
          ),
          access: "all",
        },
        {
          key: "/home/ranking/comparison",
          label: (
            <Tooltip title="对比考试排名情况分析">
              <span>对比考试排名情况分析</span>
            </Tooltip>
          ),
          access: 20010,
        },
        {
          key: "/home/percentage/comparison",
          label: (
            <Tooltip title="对比考试百分比情况分析">
              <span>对比考试百分比情况分析</span>
            </Tooltip>
          ),
          access: 20011,
        },
        {
          key: "/home/params/comparison",
          label: "对比考试参数分析",
          label: (
            <Tooltip title="对比考试参数分析">
              <span>对比考试参数分析</span>
            </Tooltip>
          ),
          access: 20012,
        },
        {
          key: "/home/knowledge/comparison",
          label: "对比考试知识点分析",
          label: (
            <Tooltip title="对比考试知识点分析">
              <span>对比考试知识点分析</span>
            </Tooltip>
          ),
          access: 20016,
        },
      ],
    },
    {
      key: "https://exam.wxy100.com/tpLogin.do?mobile=13685755271&url=%2F%23!%2FtestCenter%2FexamList&aid=10500&sig=JBbUNdOXhagDOXpIY8id7zpSSKbeqaDWlNo8Qrym993HyDSNBZQUoQ06%2BRw9pa2d",
      label: (
        <Tooltip title="精准教学">
          <span>精准教学</span>
        </Tooltip>
      ),
      access: "link",
    },
  ];

  useEffect(() => {
    if (location.pathname) {
      setDefaultSelectedKey(location.pathname);
    }
  }, [location.pathname]);


  useEffect(() => {
    init();
  }, []);



  const init = async () => {
    try {
      const res = await getUserInfo();
      if (res?.code === 200) {
        const menuList = filterMenuItems(menuItems, res?.data?.menuList) || [];
        setUser(res?.data || {});
        setRoleType(res?.data?.userRoleType);
        localStorage.setItem('userRoleType', res?.data?.userRoleType)
        setFilteredMenu(menuList);
        setIsShowTitle(res?.data?.modelList?.includes(2100077));
        setIsAdmin(!!res?.data?.isAdmin);
        setCollapsed(() => {
          return judgeLeader(res?.data?.userRoleType);
        });
        if (res?.data?.resetPassword === 1) {
          setOpen(true);
          setDisabled(true);
        } else {
          setOpen(false);
          setDisabled(false);
        }
        return;
      }
      setFilteredMenu([]);

    } catch (error) {
      console.log(error, 'get-user-info-error');

    }
  };

  const handleMenuClick = (item) => {
    if(item?.item?.props.access === "link"){
      window.open(item?.key,'_blank');
      return;
    }
    
    setDefaultSelectedKey(item.key);
    history.push(item.key);
  };


  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      const res = await updatePassword({ password: values?.password, newPassword: values?.newPassword })
      if (res?.code === 200) {
        message.success('修改成功,请重新登录');
        setOpen(false);
        history.push('/login');
        return;
      }
      message.error(res?.msg);

    } catch (error) {
      console.log(error, 'error');
    }
  };


  const validatePassword = (_, value) => {
    const passwordRegex = /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!@#$%^&*]).{8,20}$/;
    
    if (!value) {
      return Promise.reject(new Error('密码要求至少8位以上，包含大写字母、小写字母、数字、特殊字符(!@#$%^&*等)'));
    }
    
    if (!passwordRegex.test(value)) {
      return Promise.reject(
        new Error('密码要求至少8位以上，包含大写字母、小写字母、数字、特殊字符(!@#$%^&*等)')
      );
    }
    
    return Promise.resolve();
  };

  return (
    <Layout className="layout">
      <Sider
        trigger={null}
        collapsible
        collapsed={collapsed}
        style={{ height: "100vh", backgroundColor: "#fff" }}
      >
        <div className="layout_title">
          {collapsed ? "学业" : "瑞安市学业大数据分析系统"}
        </div>
        <Menu
          onClick={handleMenuClick}
          mode="inline"
          selectedKeys={[defaultSelectedKey]}
          items={computedMenuItems()}
        />
      </Sider>
      <Layout>
        <Header
          style={{
            padding: "0 16px",
            background: colorBgContainer,
            boxSizing: "border-box",
            width: "100%",
          }}
        >
          <Flex justify="space-between" align="center">
            <Space>
              <Button
                type="text"
                icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                onClick={() => setCollapsed(!collapsed)}
                style={{
                  fontSize: "16px",
                  width: 64,
                  height: 64,
                }}
              />
              <Button
                type="text"
                icon={<ReloadOutlined />}
                onClick={() => history.go(0)}
                style={{
                  fontSize: "16px",
                  width: 64,
                  height: 64,
                }}
              />
              {
                (isShowTitle && location.pathname === '/home/analysis') ? (
                  <span style={{ color: "#333", fontSize: 24 }}>
                    欢迎您：{username}{computedRole}！请您审阅{examName}分析报告！
                  </span>
                ) : null
              }

            </Space>
            <Space align="center">
              {isAdmin ? (
                <>
                  {localStorage.getItem('menuType') === 'BACK_GROUND' ? <Button style={{ marginRight: 16 }} onClick={() => {
                    localStorage.setItem('menuType', 'MIDDLE_GROUND');

                    history.push(filteredMenu?.[0]?.key);
                  }}>前往中台</Button> : null}
                  {localStorage.getItem('menuType') === 'MIDDLE_GROUND' ? <Button style={{ marginRight: 16 }} onClick={() => {
                    localStorage.setItem('menuType', 'BACK_GROUND');
                    history.push('/home/system/data');
                  }}>前往后台</Button> : null}
                </>
              ) : null}
              <Dropdown
                menu={{
                  items: computedDropdownMenuItems
                }}
              >
                <Avatar size="large" src={avatarSrc} />
              </Dropdown>
            </Space>
          </Flex>
        </Header>
        <Content
          style={{
            boxSizing: "border-box",
            margin: "24px 16px",
            minHeight: 280,
            backgroundColor: colorBgContainer,
            borderRadius: borderRadiusLG,
            overflow: "auto",
          }}
        >
          <Outlet />
        </Content>
      </Layout>
      <Modal
        title="修改密码"
        open={open}
        centered
        maskClosable={false}
        closeIcon={false}
        destroyOnClose
        width={680}
        cancelButtonProps={{
          disabled,
        }}
        onCancel={() => {
          setOpen(false);
          form.resetFields();
        }}
        onOk={handleOk}
      >
        <Form
          name="basic"
          autoComplete="off"
          form={form}
          layout="vertical"
        >
          <Form.Item
            label="原密码"
            name="password"
            rules={[{ required: true, message: '请输入原密码!' }]}
          >
            <Input.Password allowClear placeholder="请输入原密码" />
          </Form.Item>
          <Form.Item
            label="新密码(密码要求至少8位以上，包含大写字母、小写字母、数字、特殊字符(!@#$%^&*等))"
            name="newPassword"
            rules={[{ required: true, message: '请输入新密码(密码要求至少8位以上，包含大写字母、小写字母、数字、特殊字符(!@#$%^&*等))' }, { validator: validatePassword },]}
          >
            <Input.Password allowClear placeholder="请输入新密码" />
          </Form.Item>
          <Form.Item
            label="确认新密码"
            name="confirmPassword"
            dependencies={['newPassword']}
            rules={[
              { required: true, message: '请再次输入新密码！' },
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (!value || getFieldValue('newPassword') === value) {
                    return Promise.resolve();
                  }
                  return Promise.reject(new Error('两次输入的密码不一致！'));
                },
              }),
            ]}
          >
            <Input.Password allowClear placeholder="请再次输入新密码" />
          </Form.Item>
        </Form>
      </Modal>
    </Layout>
  );
};

export default HomePage;
