import React, { useEffect, useState } from 'react';
import moment from "moment"
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 { Modal, message } from 'antd';
import { brandLogo } from '@/domains/brand/constants'
import './CollegeManagePage.less';
import storage from '@/common/js/storage';

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

function ExpirationPopover(props) {

  const [showType, setShowType] = useState(0); //0不显示，1剩余30天，2小于等于7天，3已过期

  useEffect(() => {
    if (props.surplusDayTime === 0) {
      //已过期
      let loginflag = storage.get("expiration_tip_login")
      if (loginflag === null || loginflag === "true") {
        //只有登陆进来的时候提示一次
        setShowType(3)
      }
      return
    }
    //即将过期
    if (props.surplusDayTime === 30 || props.surplusDayTime <= 7) {
      let daysflag = storage.get("expiration_tip" + User.getUserId() + "_days")
      if (daysflag === null || daysflag !== moment().format("YYYYMMDD")) {
        setShowType(2)
      }
    }
    // if (props.surplusDayTime === 30) {
    //   if (storage.get("expiration_tip"+User.getUserId()+"_thirty") == null || storage.get("expiration_tip"+User.getUserId()+"_thirty") === "true") {
    //     setShowType(1)
    //   }
    //   return
    // }
    // if (props.surplusDayTime <= 7) {
    //   let daysflag = storage.getObj("expiration_tip"+User.getUserId()+"_7day");
    //   if (!daysflag) {
    //     setShowType(2)
    //     return
    //   }
    //   if (daysflag[props.surplusDayTime - 1] === 0) {
    //     setShowType(2)
    //   }
    // }

  }, [props.endTime, props.surplusDayTime])

  function iknow() {
    storage.set("expiration_tip_login", false)
    storage.set("expiration_tip" + User.getUserId() + "_days", moment().format("YYYYMMDD"))
    /*
    if (props.surplusDayTime === 0 ) {
      //已过期
      storage.set("expiration_tip_login",false)
    } else if (props.surplusDayTime === 30) {
      storage.set("expiration_tip"+User.getUserId()+"_thirty",false)
    } else if (props.surplusDayTime <= 7) {
      let daysflag = [0,0,0,0,0,0,0]
      daysflag[props.surplusDayTime - 1] = 1
      storage.setObj("expiration_tip"+User.getUserId()+"_7day",daysflag)
    }
    */
    setShowType(0)
  }

  if (props.surplusDayTime > 30) {
    return ("")
  }
  return (
    <>
      {
        showType === 0 ? ("") : (
          <div className="expirationpopover">
            <div className="dialog">
              <div className="title">{props.surplusDayTime === 0 ? "服务已到期" : "服务到期提醒"}</div>
              {
                showType === 3 ? (
                  <div className="tip-text">当前企业购买的{`${window.brandName}`}服务已于<span style={{ color: "#FF4F4F" }}>{moment(props.endTime).format("YYYY-MM-DD HH:mm:ss")}</span>到期，到期后仍可访问，但功能不可使用，建议尽快续费购买哦~</div>
                ) : (
                  <div className="tip-text">当前企业购买的{`${window.brandName}`}服务 <span style={{ color: "#FF4F4F" }}>仅剩{props.surplusDayTime}天</span>（于<span>{moment(props.endTime).format("YYYY-MM-DD")}</span>到期），为了不影响使用，建议尽快续费购买哦~</div>
                )
              }

              <div className="qrcode">
                <img src="https://cdn.xiaomai5.com/qixueyuankehu.png" alt=""></img>
                <div className="des">微信/企业微信扫码咨询</div>
              </div>
              <div className="phone"><svg style={{ position: "relative", top: "2px", marginRight: "4px" }} viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="16" height="16"><path d="M512.651 3.78c-281.433 0-509.21 228.324-509.21 509.209 0 281.43 228.325 509.203 509.21 509.203 281.427 0 509.202-228.317 509.202-509.203 0.55-280.885-227.775-509.21-509.202-509.21z m198.205 743.553c-36.14 36.136-169.737 1.641-302.24-130.312-131.953-131.959-165.902-266.104-129.768-301.695 31.211-31.21 68.99-85.417 125.939-14.782 56.943 70.629 29.016 90.34-3.291 122.647-22.449 22.448 24.642 79.392 73.37 128.125 49.283 48.73 105.678 95.818 128.126 73.368 32.306-32.305 52.017-60.23 122.646-3.288 71.182 56.949 16.426 95.276-14.782 125.937z" p-id="4409" fill="#999999"></path></svg>
                咨询电话：19157875632</div>
              <div className="button" onClick={iknow}>我知道了</div>
            </div>
          </div>
        )
      }
    </>
  )
}

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: [],
      surplusDayTime: 365, //剩余天数
      endTime: 0, //有效截至时间
    };
  }

  componentDidMount() {
    this.getStoreList();
    this.getEnterpriseUser();
    this.getVersion()
  }

  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 })
    });
  }

  getVersion() {
    BaseService.getLesseeVersionMsg()
      .then(res => {
        User.setVersion(res.result)
        User.setExpirationTime(res.result.validEndTime)
        this.setState({
          surplusDayTime: res.result.stateEnum === "NO" ? 0 : res.result.surplusDayTime,
          endTime: res.result.validEndTime
        })
      })
  }

  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">
        <ExpirationPopover surplusDayTime={this.state.surplusDayTime} endTime={this.state.endTime} />
        <div className="college-header">
          <div className="box">
            <img className="box-image" src={brandLogo} />
            <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 || brandLogo} />
                    <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 || brandLogo} />
                      <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>
    )
  }
}