import React from 'react';
import Service from "@/common/js/service";
import BaseService from "@/domains/basic-domain/baseService";
import User from "@/common/js/user";
import { LIVE_SHARE } from "@/domains/course-domain/constants";
import moment from 'moment';
import { Modal, message } from 'antd';
import './CollegeManagePage.less';

const roleMap = {
  CloudManager: "管理员",
  CloudLecturer: "讲师",
  StoreManager: "学院管理员",
};

export default class CollegeManagePage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      avatar: 'https://image.xiaomaiketang.com/xm/rJeQaZxtc7.png',
      name: '',
      list: [],
      enterpriseId: User.getEnterpriseId(),
      isAdmin: false,
    };
  }

  componentDidMount() {
    this.getStoreList();
    this.getEnterpriseUser();
  }
  
  getEnterpriseUser() {
    const { enterpriseId } = this.state;
    const params = {
      enterpriseId,
      userId: User.getUserId(),
    }
    BaseService.getEnterpriseUser(params).then((res) => {
      const { name, avatar, isAdmin } = res.result;
      this.setState({ name, avatar, isAdmin })
    });
  }

  getStoreList() {
    const { enterpriseId } = this.state;
    const params = {
      enterpriseId,
      userId: User.getUserId(),
    };
    Service.Hades('public/customerHades/getStoreListUser', params).then((res) => {
      const list = res.result;
      if (!User.getStoreId()) {
        const mainStore = _.find(list, item => item.mainStore) || {};
        User.setStoreId(mainStore.id);
        User.setStoreUserId(mainStore.storeUserId);
      }
      this.setState({ list })
    });
  }

  changeCollege(item, bool) {
    const data = {
      storeId: item.id,
      userId: User.getUserId(),
      enableState: bool ? 'YES' : 'NO',
    }
    Service.Hades('public/hades/updateStateStore', data).then((res) => {
      if (res.success) {
        message.success(bool ? '启用成功' : '停用成功');
        this.getStoreList();
      }
    })
  }

  handleLogout() {
    BaseService.logout({}).then((res) => {
      User.removeUserId();
      User.removeToken();
      User.removeEnterpriseId();
      User.clearUserInfo();
      const htmlUrl = `${LIVE_SHARE}store/index?id=${User.getCustomerStoreId()||User.getStoreId()}&userId=${User.getUserId()}&from=work_weixin`;
      window.location.href = htmlUrl;
    });
  }

  render() {
    const {
      name,
      avatar,
      list,
      isAdmin,
    } = this.state;
    return (
      <div className="college-manage-page">
        <div className="college-header">
          <div className="box">
            <img className="box-image" src="https://image.xiaomaiketang.com/xm/JDjBDAPDwD.png" />
            <div className="user">
              <img className="image" src={avatar} />
              <span className="name">{name}</span>
              <span
                className="logout"
                onClick={() => {
                  Modal.confirm({
                    title: "你确定要退出登录吗？",
                    content: "退出后，需重新登录",
                    icon: (
                      <span className="icon iconfont default-confirm-icon">&#xe839; </span>
                    ),
                    okText: "退出登录",
                    cancelText: "点错了",
                    onOk: () => {
                      this.handleLogout();
                    },
                  });
                }}
              >退出登录</span>
            </div>
          </div>
        </div>
        <div className="college-box">
          <div className="user">
            <img className="image" src={avatar} />
            <span className="name">{name}</span>
          </div>
          <div className="title-box">
            <span className="title">企学院 ({list.length})</span>
            {isAdmin && <span className="text">最多可创建10个企学院，您还能创建{10 - list.length}个</span>}
          </div>
          <div className="college-list">
            {list.map((item) => (
              <div
                key={item.id}
                className={`college-item${item.state === 'VALID' ? '' : ' disabled'}${item.userRole === 'StoreManager' ? ' enabled' : ''}`}
                onClick={() => {
                  if (item.state !== 'VALID') {
                    message.warning('学院已停用，请启用后使用或联系学院管理员');
                    return null;
                  };
                  User.setStoreId(item.id);
                  window.RCHistory.push('/home')
                }}
              >
                <div className="header">
                  <img className="image" src={item.logo || "https://image.xiaomaiketang.com/xm/JDjBDAPDwD.png"} />
                  <span className="tag">{roleMap[item.userRole]}</span>
                </div>
                <div className="title">{item.storeName}</div>
                <div className="time">{moment(item.createTime).format('YYYY-MM-DD HH:mm')}</div>
                <div className="control-box">
                  {item.userRole === 'StoreManager' && item.state === 'VALID' && !item.mainStore &&
                    <span
                      className="control-button"
                      onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        User.setStoreId(item.id);
                        window.RCHistory.push('/college-info')
                      }}
                    >编辑</span>
                  }
                  {((item.userRole === 'StoreManager' && !item.mainStore) || item.state !== 'VALID') &&
                    <span
                      className="control-button"
                      onClick={(e) => {
                        if (item.state !== 'VALID') return null;
                        e.preventDefault();
                        e.stopPropagation();
                        Modal.confirm({
                          title: '确定停用吗？',
                          content: '禁用学院，所有学院相关信息不可使用，用户无法继续学习，请谨慎操作！',
                          icon: <span className="icon iconfont default-confirm-icon">&#xe6f4;</span>,
                          onOk: () => {
                            this.changeCollege(item, false);
                          },
                          okText: '停用',
                          cancelText: '取消',
                        })
                      }}
                    >{item.state === 'VALID' ? '停用' : '已停用'}</span>
                  }
                  <span
                    className="control-button disable-button"
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      this.changeCollege(item, true);
                    }}
                  >启用</span>
                </div>
              </div>
            ))}
            {list.length < 10 && isAdmin &&
              <div
                className="college-create"
                onClick={() => {
                  window.RCHistory.push('/college-manage/create')
                }}
              >
                <span className="create-word">+ 创建企学院</span>
              </div>
            }
          </div>
        </div>
      </div>
    )
  }
}