import React from 'react';
import { Select, Tooltip } from 'antd';
import { Chart } from '@antv/g2';
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,
      timeRange: '7',
      studyTimeRange: '7',
    }
    this._chart = null;
  }

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

  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'),
          commentCount: item.studyNum,
          commentRate: item.studyTime,
        }))
        this.createChart(dataList);
      }
    });
  }

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

  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 Chart({
        container: 'chart-id',
        forceFit: true,
        height: 290,
        padding: [48, 64]
      })
    }
		this._chart.clear();
		this._chart.source(data, {
			commentRate: {
				formatter: (val) => {
          return val
				},
				// tickCount: 5,
			},
			time: {
				formatter: (val) => {
					if (val == 8) {
						return '7日外'
					} 
          return `${val}`
				},
				range: [0.06, 0.94]
			},
			commentCount: {
				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('commentRate', {
			label: {
				textStyle: {
					fill: '#666666',
					fontSize: 14
				}
			}
		})
		this._chart.line().position('time*commentCount').color('#5289FA').tooltip('time*commentCount', function( time, commentCount){
			return {
				name: '学习人数',
				value: commentCount
			}
		});
		this._chart.line().position('time*commentRate').color('#FFB714').tooltip('time*commentRate', function( time, commentRate){
			return {
				name: '人均学习时长',
				value: commentRate
			}
		});

		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} style="color: #333 !important"><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 {
      list,
      incCustomerNum,
      incLiveCourseNum,
      incVideoCourseNum,
      liveCourseNum,
      totalCustomerNum,
      videoCourseNum,
      timeRange,
      scheduleType,
      studyTimeRange,
    } = this.state;
    return (
      <div className="home-page">
        <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}</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">0</span>
                  <span className="course-word">本月新增</span>
                  {false &&
                    <span className="icon iconfont">&#xe635;</span>
                  }
                  <span className="add-number">0</span>
                </div>
              </div>
              <div className="course-item">
                <div className="course-title">线下课</div>
                <div className="data">
                  <span className="course-number">0</span>
                  <span className="course-word">本月新增</span>
                  {false &&
                    <span className="icon iconfont">&#xe635;</span>
                  }
                  <span className="add-number">0</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">0</div>
            <div className="data-footer">
              <span className="footer-word">本月新增</span>
              {false &&
                <span className="icon iconfont">&#xe635;</span>
              }
              <span className="footer-number">0</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">0</div>
            <div className="data-footer">
              <span className="footer-word">本月新增</span>
              {false &&
                <span className="icon iconfont">&#xe635;</span>
              }
              <span className="footer-number">0</span>
            </div>
          </div>
        </div>
        <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>
              </div>
              <div className="study-select">
                <span className="select-word">（{moment().subtract(timeRange, '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 ?
                    <img src={this.showNumber(index)} className="table-image" />
                    : <span className="table-number">{index + 1}</span>
                  }
                  <div className="table-data">
                    <Tooltip placement="topLeft" title={item.courseName}>
                      <div className="table-name">{item.courseName}</div>
                    </Tooltip>
                    <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 title="若某人加入多个培训计划，则需完成所有已加入的培训计划后，才视为已完成培训">
                <span className="iconfont icon">&#xe61d;</span>
               </Tooltip>
               <span className="tip">(本月)</span>
            </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 }}>0人</div>
                    <div style={{ color: '#999' }}>新增培训人数</div>
                  </div>
                </div>
              </div>
            </div>
            <div className="circle-tip unfinished">
              <div className="spot"></div>
              <div className="number">0人</div>
              <div className="word">未完成培训</div>
            </div>
            <div className="circle-tip finished">
              <div className="spot"></div>
              <div className="number">0人</div>
              <div className="word">完成培训</div>
            </div>
          </div>
        </div>
        <div className="study-chart">
          <div className="study-title">学习人数与时长
            <div className="study-select">
              <span className="select-word">（{moment().subtract(studyTimeRange, '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>
      </div>
    )
  }
}

export default Home;