import TemplateContainer from '@/pages/TemplateContainer';
import { UserInfo } from '@/services/services/user';
import { RedoOutlined } from '@ant-design/icons';
import { useModel } from '@umijs/max';
import { Avatar, Badge, Button, Card, Col, FloatButton, Input, message, Modal, Row, Spin, Tag } from 'antd';
import React, { useEffect, useState } from 'react';
import UserCenterUserInfo from './UserCenterUserInfo';
import UserCenterAgentMessage from './UserCenterAgentMessage';
import { useSoftStore } from '@/store/software';
import { SoftwareControl } from '@/services/services/software';
import UserSoftwareInfo from './UserSoftwareInfo';

const UserCenter: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [messageApi, messageHolder] = message.useMessage();
  const [modalApi, modalHolder] = Modal.useModal();
  const [badgeCount, setBadgeCount] = useState(0);
  const { setTopSpinTip, setTopSpinning } = useSoftStore();
  const [userAgentUserInfo, setUserAgentUserInfo] = useState<UserModel.UserAgentInfo>();

  useEffect(() => {
    if (initialState?.currentUser?.id) {
      // 初始化加载用户信息
      setTopSpinning(true);
      setTopSpinTip("正在获取用户信息。。。");
      UserInfo.GetUserInfo(initialState?.currentUser?.id).then(async (res) => {
        setInitialState({ ...initialState, currentUser: res });
        localStorage.setItem('userInfo', JSON.stringify(res));
        let agentInfo = await UserInfo.GetUserAgentInfo();
        setUserAgentUserInfo(agentInfo);
      }).catch((error) => {
        messageApi.error(error.message);
      }).finally(() => {
        setTopSpinning(false);
      })
      // 加载当前用户可申请的的软件控制权限
      SoftwareControl.GetUserSoftwareControlCount(initialState?.currentUser?.id).then((res) => {
        setBadgeCount(res);
      }).catch((error) => {
        messageApi.error(error.message);
      })
    }
  }, [])

  /**
   * 申请用户软件控制权限
   */
  async function ApplyUserSoftwareControlHandle() {
    let userID = initialState?.currentUser?.id;
    if (!userID) {
      messageApi.error("用户信息不存在");
      return;
    }
    // 重新获取用户关联信息
    const userCanApplyCount = await SoftwareControl.GetUserSoftwareControlCount(userID);
    if (userCanApplyCount <= 0) {
      messageApi.warning("您已经没有可申请的软件控制权限了");
      return;
    }
    // 开始调用申请接口
    setTopSpinning(true);
    setTopSpinTip("正在申请软件控制权限。。。");
    try {
      await SoftwareControl.ApplyUserSoftwareControl(userID);
      // 提示成功
      messageApi.success("申请成功");
      setBadgeCount(0);
    } catch (error: any) {
      messageApi.error(error.message);
    } finally {
      setTopSpinning(false);
    }
  }

  /**
   * 显示软件控制权限
   */
  async function ShowSoftwareControlHandle() {
    modalApi.info({
      title: "用户软件控制权限",
      content: <UserSoftwareInfo userId={initialState?.currentUser?.id} />,
      width: 800,
      footer: null,
      closable: true,
    });
  }

  function renderTitie() {
    return (
      <div style={{ display: 'flex' }}>
        <div style={{ marginRight: 10, display: 'flex', alignItems: 'center' }}>
          <Avatar style={{ backgroundColor: '#2982ff', verticalAlign: 'middle' }} size="large" gap={1} >
            {initialState?.currentUser?.userName?.substring(0, 1)}
          </Avatar>
        </div >
        <div style={{ margin: "20px" }}>
          <div style={{ display: "flex", alignItems: 'center' }}>
            <Tag bordered={false} color="blue">{"ID: " + initialState?.currentUser?.id}</Tag>
            <span>{initialState?.currentUser?.userName}</span>
          </div>
          <div>

            {initialState?.currentUser?.roleNames?.map((item: any) => {
              return <Tag bordered={false} color="green" key={item}>{item}</Tag>
            })}
          </div>
        </div>
      </div >
    )
  }

  return (
    <TemplateContainer navTheme={initialState?.settings?.navTheme ?? "realDark"} style={{ minWidth: 600 }}>
      <div>
        <Card hoverable title={renderTitie()} style={{ width: "100%" }}>
          <Row justify="start" wrap>
            <Col style={{ minWidth: 100 }} span={2}>
              <div>可激活总数</div>
              <strong style={{ fontSize: 24, color: "goldenrod" }}>{initialState?.currentUser?.allDeviceCount}</strong>
            </Col>
            <Col span={2} style={{ minWidth: 100 }}>
              <div>余换绑次数</div>
              <strong style={{ fontSize: 24, color: "goldenrod" }}>{initialState?.currentUser?.freeCount}</strong>
            </Col>
            <Col hidden={!initialState?.currentUser?.roleNames?.includes("Agent User")} span={2} style={{ minWidth: 100 }}>
              <div>代理分成</div>
              <strong style={{ fontSize: 24, color: "goldenrod" }}>{(initialState?.currentUser?.agentPercent ?? 0.5) * 100}%</strong>
            </Col>
            <Col span={2} style={{ minWidth: 100 }}>
              <div>
                <span>邀请码</span>
                <Button icon={<RedoOutlined />} style={{ marginLeft: 5 }} type="default" shape="circle" size='small'></Button>
              </div>
              <strong style={{ fontSize: 24, color: "goldenrod" }}>{initialState?.currentUser?.affiliateCode}</strong>
            </Col>
            <Col span={3} style={{ minWidth: 100 }}>
              <div>
                <span>软件控制权限</span>

              </div>
              {
                badgeCount > 0 ? <Badge count={badgeCount}>
                  <Button variant="filled" color="default" onClick={ApplyUserSoftwareControlHandle}> 申请</Button>
                </Badge> : <Button variant="filled" color="default" onClick={ApplyUserSoftwareControlHandle}> 申请</Button>
              }
              <Button color="primary" variant="filled" style={{ marginLeft: 10 }} onClick={ShowSoftwareControlHandle} > 查看</Button>
            </Col>
          </Row>
        </Card>
      </div>
      <div style={{ marginTop: 10 }}>
        <Row gutter={16}>
          <Col span={12}>
            <UserCenterUserInfo />
          </Col>
          <Col span={12}>
            <UserCenterAgentMessage userAgentUserInfo={userAgentUserInfo} setUserAgentUserInfo={setUserAgentUserInfo} />
          </Col>
        </Row>
      </div>
      {modalHolder}
      {messageHolder}
    </TemplateContainer>
  );
};

export default UserCenter;