import React from 'react';
import { Select, Tooltip } from 'antd';
import DataSet from "@antv/data-set";
import { Chart as G2Chart } from '@antv/g2';
import {
  G2,
  Chart,
  Geom,
  Axis,
  Tooltip as G2Tooltip,
  Coord,
  Label,
  Legend,
  View,
  Guide,
  Shape,
  Facet,
  Util
} from "bizcharts";
import moment from 'moment'
import Service from "@/common/js/service";
import User from '@/common/js/user';
import './Home.less';

const Option = Select.Option;

class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      scheduleType: 'LIVE',
      list: [],
      dataList: [],
      incCustomerNum: 0,
      incLiveCourseNum: 0,
      incVideoCourseNum: 0,
      liveCourseNum: 0,
      totalCustomerNum: 0,
      videoCourseNum: 0,
      pictureCourseNum: 0,
      timeRange: '7',
      studyTimeRange: '7',
      completeNum: 0,
      unfinishedNum: 0,
    }
    this._chart = null;
  }

  componentDidMount() {
    this.getPanelInfo();
    this.getStudyInfo();
    this.getHotCourse();
    this.getTrainingInfo();
  }

  getTrainingInfo() {
    Service.Hades('public/hades/planOverview', { storeId: User.getStoreId() }).then((res) => {
      if (res.success) {
        this.setState(res.result)
      }
    });
  }

  getHotCourse() {
    const { timeRange, scheduleType } = this.state;
    const data = {
      hotNum: 5,
      scheduleType,
      storeId: User.getStoreId(),
      timeRange,
    }
    Service.Hades('public/courseCloud/hotCourse', data).then((res) => {
      if (res.success) {
        this.setState({
          list: res.result
        })
      }
    })
  }

  getStudyInfo() {
    const { studyTimeRange } = this.state;
    Service.Hades('public/hades/studyInfo', { storeId: User.getStoreId(), timeRange: studyTimeRange }).then((res) => {
      if (res.success) {
        const dataList = res.result.map(item => ({
          time: moment(item.dateline).format('MM-DD'),
          studyNum: item.studyNum,
          studyTime: Math.round(item.studyTime / 6) / 10,
        }))
        this.createChart(dataList);
      }
    });
  }

  getPanelInfo() {
    Service.Hades('public/hades/storePanelInfo', { storeId: User.getStoreId() }).then((res) => {
      if (res.success) {
        this.setState({
          examNum: res.result.examNum,
          incCustomerNum: res.result.incCustomerNum,
          incExamNum: res.result.incExamNum,
          incLiveCourseNum: res.result.incLiveCourseNum,
          incVideoCourseNum: res.result.incVideoCourseNum,
          incPictureCourseNum: res.result.incPictureCourseNum,
          incOfflineCourseNum: res.result.incOfflineCourseNum,
          incTrainingPlanNum: res.result.incTrainingPlanNum,
          liveCourseNum: res.result.liveCourseNum,
          totalCustomerNum: res.result.totalCustomerNum,
          videoCourseNum: res.result.videoCourseNum,
          pictureCourseNum: res.result.pictureCourseNum,
          offlineCourseNum: res.result.offlineCourseNum,
          trainingPlanNum: res.result.trainingPlanNum,
        })
      }
    })
  }

  showNumber(index) {
    switch (index) {
      case 0:
        return 'https://image.xiaomaiketang.com/xm/D64QhNn74S.png';
      case 1:
        return 'https://image.xiaomaiketang.com/xm/Qfib4mnGJT.png';
      case 2:
        return 'https://image.xiaomaiketang.com/xm/8jKXHyrDaG.png';
    
      default:
        return 'https://image.xiaomaiketang.com/xm/D64QhNn74S.png';
    }
  }
  
  createChart = (data) => {
    if (!this._chart) {
      this._chart = new G2Chart({
        container: 'chart-id',
        forceFit: true,
        height: 290,
        padding: [48, 64]
      })
    }
		this._chart.clear();
		this._chart.source(data, {
			studyTime: {
				formatter: (val) => {
          return val
				},
        tickCount: 5,
			},
			time: {
				formatter: (val) => {
          return `${val}`
				},
			},
			studyNum: {
				formatter: (val) => {
          return val
				},
				tickCount: 5,
			}
		});
		this._chart.axis('time', {
			label: {
				offset: 20,
				textStyle: {
					fill: '#666666',
					fontSize: 14
				}
			},
			line: {
				stroke: '#E8E8E8'
			},
			tickLine: {
				stroke: '#E8E8E8'
			}
		})
		this._chart.axis('submitCount', {
			label: {
				textStyle: {
					fill: '#666666',
					fontSize: 14
				}
			}
		})
		this._chart.axis('studyTime', {
			label: {
				textStyle: {
					fill: '#666666',
					fontSize: 14
				}
			}
		})
		this._chart.line().position('time*studyNum').color('#2966FF').tooltip('time*studyNum', function( time, studyNum){
			return {
				name: '学习人数',
				value: studyNum + '人'
			}
		});
		this._chart.line().position('time*studyTime').color('#FFBB54').tooltip('time*studyTime', function( time, studyTime){
			return {
				name: '人均学习时长',
				value: studyTime + '分钟'
			}
		});

		this._chart.legend(false);
		this._chart.tooltip({
			 containerTpl: '<div class="g2-tooltip" style="background: #fff !important;">'
    + '<div class="g2-tooltip-title" style="margin:10px 0;"></div>'
    + '<ul class="g2-tooltip-list"></ul></div>', // tooltip 容器模板
		itemTpl: '<li data-index={index}><span style="background-color:{color};width:8px;height:8px;border-radius:50%;display:inline-block;margin-right:8px;"></span>{name}<span style="display: inline-block; float: right; margin-left: 30px;">{value}</span></li>', // tooltip 每项记录的默认模板
		})
		this._chart.render();
	}

  render() {
    const {
      examNum,
      incExamNum,
      list,
      incCustomerNum,
      incLiveCourseNum,
      incVideoCourseNum,
      incPictureCourseNum,
      liveCourseNum,
      totalCustomerNum,
      videoCourseNum,
      pictureCourseNum,
      timeRange,
      scheduleType,
      studyTimeRange,
      trainingPlanNum,
      incTrainingPlanNum,
      unfinishedNum,
      completeNum,
      planCustomerNum,
      incOfflineCourseNum,
      offlineCourseNum,
    } = this.state;
    const data = [
      {
        item: '已完成培训',
        count: completeNum,
      }, {
        item: '未完成培训',
        count: unfinishedNum,
      }
    ];
    const { DataView } = DataSet;
    const { Html } = Guide;
    const sum = data[0].count + data[1].count;
    const dv = new DataView();
    sum && dv.source(data).transform({
      type: "percent",
      field: "count",
      dimension: "item",
      as: "percent"
    });
    const cols = {
      percent: {
        formatter: val => {
          val = val * 100 + "%";
          return val;
        }
      }
    };
    return (
      <div className="home-page">
        <div className="home-tip">
          <div className="content">
            <span className="icon iconfont" style={{color:"#FF4F4F",marginRight:"8px"}}>&#xe61d;</span>温馨提示：企业使用人数已达上限，将无法新增员工、学员，如需增加人数限制，请联系小麦企学院服务平台。
            <div className="renew-btn">立即续费
            <div className="renew-popover">
            <div class="popover-arrow"><span class="-popover-arrow-content"></span></div>
              <div className="qrcode">
                <img src="https://image.xiaomaiketang.com/xm/HPTEsZf5DQ.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>
            </div>
          </div>
        </div>
        <div className="data-wrap">
          <div className="home-title">数据概况</div>
          <div className="data-box">
          <div className="data-item">
            <div className="header">
              <img className="header-icon" src="https://image.xiaomaiketang.com/xm/wAaFtjeRsM.png" />
              <span className="header-word">学员总数 (人)</span>
            </div>
            <div className="data-number">{totalCustomerNum}</div>
            <div className="data-footer">
              <span className="footer-word">本月新增</span>
              {incCustomerNum > 0 &&
                <span className="icon iconfont">&#xe635;</span>
              }
              <span className="footer-number">{incCustomerNum}</span>
            </div>
          </div>
          <div className="data-item course-data">
            <div className="header">
              <img className="header-icon" src="https://image.xiaomaiketang.com/xm/jPrRhw8EMF.png" />
              <span className="header-word">课程总数 (个)</span>
            </div>
            <div className="data-number">{videoCourseNum + liveCourseNum + pictureCourseNum}</div>
            <div className="course-box">
              <div className="course-item">
                <div className="course-title">直播课</div>
                <div className="data">
                  <span className="course-number">{liveCourseNum}</span>
                  <span className="course-word">本月新增</span>
                  {incLiveCourseNum > 0 &&
                    <span className="icon iconfont">&#xe635;</span>
                  }
                  <span className="add-number">{incLiveCourseNum}</span>
                </div>
              </div>
              <div className="course-item">
                <div className="course-title">视频课</div>
                <div className="data">
                  <span className="course-number">{videoCourseNum}</span>
                  <span className="course-word">本月新增</span>
                  {incVideoCourseNum > 0 &&
                    <span className="icon iconfont">&#xe635;</span>
                  }
                  <span className="add-number">{incVideoCourseNum}</span>
                </div>
              </div>
              <div className="course-item">
                <div className="course-title">图文课</div>
                <div className="data">
                  <span className="course-number">{pictureCourseNum}</span>
                  <span className="course-word">本月新增</span>
                  {incPictureCourseNum > 0 &&
                    <span className="icon iconfont">&#xe635;</span>
                  }
                  <span className="add-number">{incPictureCourseNum}</span>
                </div>
              </div>
              <div className="course-item">
                <div className="course-title">线下课</div>
                <div className="data">
                  <span className="course-number">{offlineCourseNum}</span>
                  <span className="course-word">本月新增</span>
                  {incOfflineCourseNum > 0 &&
                    <span className="icon iconfont">&#xe635;</span>
                  }
                  <span className="add-number">{incOfflineCourseNum}</span>
                </div>
              </div>
            </div>
          </div>
          <div className="data-item">
            <div className="header">
              <img className="header-icon" src="https://image.xiaomaiketang.com/xm/jZf3GNY5tY.png" />
              <span className="header-word">培训计划总数 (个)</span>
            </div>
            <div className="data-number">{trainingPlanNum}</div>
            <div className="data-footer">
              <span className="footer-word">本月新增</span>
              {incTrainingPlanNum > 0 &&
                <span className="icon iconfont">&#xe635;</span>
              }
              <span className="footer-number">{incTrainingPlanNum}</span>
            </div>
          </div>

          <div className="data-item">
            <div className="header">
              <img className="header-icon" src="https://image.xiaomaiketang.com/xm/3CfrPs23Re.png" />
              <span className="header-word">考试总数 (个)</span>
            </div>
            <div className="data-number">{examNum}</div>
            <div className="data-footer">
              <span className="footer-word">本月新增</span>
              {incExamNum > 0 &&
                <span className="icon iconfont">&#xe635;</span>
              }
              <span className="footer-number">{incExamNum}</span>
            </div>
          </div>
        </div>
        </div>
        <div className="study-wrap">
          <div className="home-title">学习概况</div>
            <div className="study-box">
            <div className="study-item">
              <div className="study-title">课程学习排行榜</div>
              <div className="study-header">
                <div className="study-tab">
                  <span 
                    className={`tab${scheduleType === 'LIVE' ? ' selected' : ''}`}
                    onClick={() => this.setState({ scheduleType: 'LIVE' }, () => this.getHotCourse())}
                  >直播课</span>
                  <span 
                    className={`tab${scheduleType === 'VOICE' ? ' selected' : ''}`}
                    onClick={() => this.setState({ scheduleType: 'VOICE' }, () => this.getHotCourse())}
                  >视频课</span>
                  <span 
                    className={`tab${scheduleType === 'PICTURE' ? ' selected' : ''}`}
                    onClick={() => this.setState({ scheduleType: 'PICTURE' }, () => this.getHotCourse())}
                  >图文课</span>
                </div>
                <div className="study-select">
                  <span className="select-word">（{moment().subtract(timeRange - 1, 'day').format('MM.DD')} ~ {moment().format('MM.DD')}）</span>
                  <Select
                    style={{ width: 88 }}
                    value={timeRange}
                    onChange={(value) => {
                      this.setState({ timeRange: value }, () => this.getHotCourse());
                    }}
                  >
                    <Option value="7">近7天</Option>
                    <Option value="15">近15天</Option>
                    <Option value="30">近30天</Option>
                  </Select>
                </div>
              </div>
              {_.isEmpty(list) ?
                <div className="study-empty">
                  <img src="https://image.xiaomaiketang.com/xm/52dmait5Bx.png" />
                  <div>暂无课程上榜</div>
                </div>
                : list.map((item, index) => (
                  <div className={`table-item${index % 2 ? '' : ' odd'}`} key={item.id}>
                    {index < 3 ?
                      <span className="table-number"><img src={this.showNumber(index)} className="table-image" /></span>
                      : <span className="table-number">{index + 1}</span>
                    }
                    <div className="table-data">
                      <div className="table-name">
                        <Tooltip title={item.courseName}>
                          {item.courseName}
                        </Tooltip>
                      </div>
                      <div className="table-tag">{item.categoryName}</div>
                    </div>
                    <span className="table-study">{item.studyNum || 0}人已学习</span>
                  </div>
                  ))
              }
            </div>
            <div className="study-item">
            <div className="study-title">培训计划完成情况
               <Tooltip overlayClassName="data-plan-tooltip" title="若某人加入多个培训计划，则需完成所有已加入的培训计划后，才视为已完成培训">
                <span className="iconfont icon">&#xe61d;</span>
               </Tooltip>
               <span className="tip">(本月)</span>
            </div>
            {(unfinishedNum || completeNum) ?
              <div
                className="left-graph-container"
                id="mountNode"
                style={{ width: '100%', marginLeft: '-20%', marginTop: -30 }}
                ref={e => e && (this.width = e.clientWidth)}
              >
                {this.width && <div>
                  <Chart
                    height={400}
                    width={this.width}
                    data={dv}
                    scale={cols}
                    padding={20}
                  >
                    <Coord type={"theta"} radius={0.75} innerRadius={0.6} />
                    <Axis name="percent" />
                    <G2Tooltip
                      showTitle={false}
                      itemTpl="<li><span style=&quot;background-color:{color};&quot; class=&quot;g2-tooltip-marker&quot;></span>{name}: {value}</li>"
                    />
                    <Guide>
                      <Html
                        position={['50%', "50%"]}
                        html={`<div style="color:#8c8c8c;font-size:14px;text-align: center;width: ${this.width}px;"><span style="color:#333;font-size:20px">${planCustomerNum}人</span><br>新增培训人数</div>`}
                        alignX="middle"
                        alignY="middle"
                      />
                    </Guide>
                    <Geom
                      type="intervalStack"
                      position="percent"
                      color={['item', ['#FFBB54', '#2966FF']]}
                      tooltip={[
                        "item*percent",
                        (item, percent) => {
                          percent = Math.round(percent * 100) + "%";
                          return {
                            name: item,
                            value: percent,
                          };
                        }
                      ]}
                      style={{
                        lineWidth: 1,
                        stroke: "#fff"
                      }}
                    >
                    </Geom>
                  </Chart>
                </div>
              }
              </div>
              : <div className="circle-box">
                <div className="big-circle">
                  <div className="small-circle">
                    <div className="tip-box">
                      <div style={{ color: '#333', fontSize: '20px', marginBottom: 4 }}>{planCustomerNum}人</div>
                      <div style={{ color: '#999' }}>新增培训人数</div>
                    </div>
                  </div>
                </div>
              </div>
            }
            <div className="circle-tip unfinished">
              <div className="spot"></div>
              <div className="number">{unfinishedNum}人</div>
              <div className="word">未完成培训</div>
            </div>
            <div className="circle-tip finished">
              <div className="spot"></div>
              <div className="number">{completeNum}人</div>
              <div className="word">完成培训</div>
            </div>
          </div>
          </div>
        </div>
        <div className="study-chart">
          <div className="study-title">学习人数与时长
            <div className="study-select">
              <span className="select-word">（{moment().subtract(studyTimeRange - 1, 'day').format('MM.DD')} ~ {moment().format('MM.DD')}）</span>
              <Select
                style={{ width: 88 }}
                value={studyTimeRange}
                onChange={(value) => {
                  this.setState({ studyTimeRange: value }, () => this.getStudyInfo());
                }}
              >
                <Option value="7">近7天</Option>
                <Option value="15">近15天</Option>
                <Option value="30">近30天</Option>
              </Select>
            </div>
          </div>
          <div className="chart-tip">
            <div>学习人数(人)
              <Tooltip title="参与任意课程进行学习的人数">
                <span className="iconfont icon">&#xe61d;</span>
              </Tooltip>
            </div>
            <div>人均学习时长(分钟)</div>
          </div>
          <div id="chart-id"></div>
          <div className="chart-bottom-tip">
            <div className="tip-item" style={{ marginRight: 100 }}><span className="student-dot"></span>学习人数</div>
            <div className="tip-item"><span className="time-dot"></span>人均学习时长</div>
          </div>
        </div>
      </div>
    )
  }
}

export default Home;