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: "学院管理员",
  CloudOperator: '运营师',
};

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,
      createStoreList:[],
      joinStoreList:[]
    };
  }

  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;
    if (!enterpriseId) return null;
    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) || list[0] || {};
        User.setStoreId(mainStore.id);
        User.setStoreUserId(mainStore.storeUserId);
      }
      const createStoreList =  list.filter((item)=>{
        return item.userRole === 'StoreManager'
      })
      const joinStoreList =   list.filter((item)=>{
        return item.userRole !== 'StoreManager'
      })
      this.setState({createStoreList:createStoreList,joinStoreList:joinStoreList})
    });
  }
  checkCollege(item, bool) {
    const data = {
      storeId: item.id,
    }
    Service.Hades('public/hades/whetherStartLiveCourse', data).then((res) => {
      if (res.result) {
        Modal.warning({
          title: '停用失败',
          content: '当前学院有正在上课的直播课，请课程结束后再进行操作。',
          icon: <span className="icon iconfont default-confirm-icon">&#xe6f4;</span>,
          okText: '我知道了',
        })
      } else {

        Modal.confirm({
          title: '确定停用吗？',
          content: '停用学院，所有学院相关信息不可使用，学员无法继续学习，请谨慎操作！',
          icon: <span className="icon iconfont default-confirm-icon">&#xe6f4;</span>,
          onOk: () => {
            this.changeCollege(item, bool);
          },
          okText: '停用',
          cancelText: '取消',
        })
      }
    })
  }

  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({identifier:User.getIdentifier()}).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,
      createStoreList,
      joinStoreList
    } = 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/fe4NCjr7XF.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>
            <div className="title-box">
              <span className="title">我创建的({createStoreList.length})</span>
              {isAdmin && <span className="text">最多可创建10个企学院，您还能创建{10 - createStoreList.length}个</span>}
            </div>
            <div className="college-list">
              {createStoreList.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);
                    User.setStoreUserId(item.storeUserId);
                    window.currentStoreUserInfo.storeId = item.id;
                    window.currentStoreUserInfo.storeUserId = item.storeUserId;
                    window.RCHistory.push('/home')
                  }}
                >
                  <div className="header">
                    <img className="image" src={item.logo || "https://image.xiaomaiketang.com/xm/fe4NCjr7XF.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'  &&
                      <span
                        className="control-button"
                        onClick={(e) => {
                          e.preventDefault();
                          e.stopPropagation();
                          User.setStoreId(item.id);
                          User.setStoreUserId(item.storeUserId);
                          window.currentStoreUserInfo.storeId = item.id;
                          window.currentStoreUserInfo.storeUserId = item.storeUserId;
                          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();
                          this.checkCollege(item, false);
                        }}
                      >{item.state === 'VALID' ? '停用' : '已停用'}</span>
                    }
                    <span
                      className="control-button disable-button"
                      onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        this.changeCollege(item, true);
                      }}
                    >启用</span>
                  </div>
                </div>
              ))}
              {createStoreList.length < 10 && isAdmin &&
                <div
                  className="college-create"
                  onClick={() => {
                    window.RCHistory.push('/college-manage/create')
                  }}
                >
                  <span className="create-word">+ 创建企学院</span>
                </div>
              }
            </div>
          </div>
          { joinStoreList.length > 0 && 
          <div className="join-container">
            <div className="title-box">
              <span className="title">我加入的({joinStoreList.length})</span>
            </div>
            <div className="college-list">
              {joinStoreList.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);
                    User.setStoreUserId(item.storeUserId);
                    window.currentStoreUserInfo.storeId = item.id;
                    window.currentStoreUserInfo.storeUserId = item.storeUserId;
                    window.RCHistory.push('/home')
                  }}
                >
                  <div className="header">
                    <img className="image" src={item.logo || "https://image.xiaomaiketang.com/xm/fe4NCjr7XF.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);
                          User.setStoreUserId(item.storeUserId);
                          window.currentStoreUserInfo.storeId = item.id;
                          window.currentStoreUserInfo.storeUserId = item.storeUserId;
                          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();
                          this.checkCollege(item, false);
                        }}
                      >{item.state === 'VALID' ? '停用' : '已停用'}</span>
                    }
                    <span
                      className="control-button disable-button"
                      onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        this.changeCollege(item, true);
                      }}
                    >启用</span>
                  </div>
                </div>
              ))}
            </div>
          </div>
          }
        </div>
        
      </div>
    )
  }
}