import React, { useEffect, useState } from 'react'
import { Select, Tooltip, Carousel, Popover } 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 HomeTip from './HomeTip'
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,
      weekVisitCustomerNum: 0,
      incWeekVisitCustomerNum: 0,
      courseNum: 0, //课程总数
      inCourseNum: 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,
          weekVisitCustomerNum: res.result.weekVisitCustomerNum,
          incWeekVisitCustomerNum: res.result.incWeekVisitCustomerNum,
          courseNum: res.result.videoCourseNum + res.result.liveCourseNum + res.result.pictureCourseNum + res.result.offlineCourseNum,
          inCourseNum: res.result.incLiveCourseNum + res.result.incVideoCourseNum + res.result.incPictureCourseNum + res.result.incOfflineCourseNum,
        })
      }
    })
  }

  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 {
      courseNum,
      inCourseNum,
      examNum,
      incExamNum,
      list,
      incCustomerNum,
      incLiveCourseNum,
      incVideoCourseNum,
      incPictureCourseNum,
      liveCourseNum,
      totalCustomerNum,
      videoCourseNum,
      pictureCourseNum,
      timeRange,
      scheduleType,
      studyTimeRange,
      trainingPlanNum,
      incTrainingPlanNum,
      unfinishedNum,
      completeNum,
      planCustomerNum,
      incOfflineCourseNum,
      offlineCourseNum,
      weekVisitCustomerNum,
      incWeekVisitCustomerNum,
    } = 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'>
        <HomeTip />
        <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' alt='' />
                <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 > 0 ? incCustomerNum : 0}</span>
              </div>
            </div>
            <div className='data-item'>
              <div className='header'>
                <img className='header-icon' src='https://image.xiaomaiketang.com/xm/nXYAHExPrX.png' alt='' />
                <span className='header-word'>学员周活跃 (人)</span>
              </div>
              <div className='data-number'>{weekVisitCustomerNum || 0}</div>
              <div className='data-footer'>
                <span className='footer-word'>本周新增</span>

                {incWeekVisitCustomerNum > 0 && <span className='icon iconfont'>&#xe635;</span>}
                <span className='footer-number'>{incWeekVisitCustomerNum > 0 ? incWeekVisitCustomerNum : 0}</span>
              </div>
            </div>

            <div className='data-item course-data'>
              <div className='header'>
                <img className='header-icon' src='https://image.xiaomaiketang.com/xm/jPrRhw8EMF.png' alt='' />
                <span className='header-word'>课程总数 (个)</span>
              </div>

              <div className='data-number'>{courseNum}</div>
              <div className='data-footer'>
                <span className='footer-word'>本月新增</span>
                {inCourseNum > 0 && <span className='icon iconfont'>&#xe635;</span>}
                <span className='footer-number'>{inCourseNum > 0 ? inCourseNum : 0}</span>
              </div>
              <div className='course-box'>
                <div className='course-item'>
                  <div className='course-title'>直播课</div>
                  <div className='data'>
                    <span className='course-number'>{liveCourseNum}</span>
                    {incLiveCourseNum > 0 && <span className='icon iconfont'>&#xe635;</span>}
                    <span className='add-number'>{incLiveCourseNum > 0 ? incLiveCourseNum : 0}</span>
                  </div>
                </div>
                <div className='course-item'>
                  <div className='course-title'>线上课</div>
                  <div className='data'>
                    <span className='course-number'>{videoCourseNum}</span>
                    {incVideoCourseNum > 0 && <span className='icon iconfont'>&#xe635;</span>}
                    <span className='add-number'>{incVideoCourseNum > 0 ? incVideoCourseNum : 0}</span>
                  </div>
                </div>
                <div className='course-item'>
                  <div className='course-title'>图文课</div>
                  <div className='data'>
                    <span className='course-number'>{pictureCourseNum}</span>
                    {incPictureCourseNum > 0 && <span className='icon iconfont'>&#xe635;</span>}
                    <span className='add-number'>{incPictureCourseNum > 0 ? incPictureCourseNum : 0}</span>
                  </div>
                </div>
                <div className='course-item'>
                  <div className='course-title'>线下活动</div>
                  <div className='data'>
                    <span className='course-number'>{offlineCourseNum}</span>
                    {incOfflineCourseNum > 0 && <span className='icon iconfont'>&#xe635;</span>}
                    <span className='add-number'>{incOfflineCourseNum > 0 ? incOfflineCourseNum : 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' alt='' />
                <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 > 0 ? incTrainingPlanNum : 0}</span>
              </div>
            </div>

            <div className='data-item'>
              <div className='header'>
                <img className='header-icon' src='https://image.xiaomaiketang.com/xm/3CfrPs23Re.png' alt='' />
                <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 > 0 ? incExamNum : 0}</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>
              <Choose>
                <When condition={_.isEmpty(list)}>
                  <div className='study-empty'>
                    <img src='https://image.xiaomaiketang.com/xm/52dmait5Bx.png' alt='' />
                    <div>暂无课程上榜</div>
                  </div>
                </When>
                <Otherwise>
                  {list.map((item, index) => (
                    <div className={`table-item${index % 2 ? '' : ' odd'}`} key={item.id}>
                      <Choose>
                        <When condition={index < 3}>
                          <span className='table-number'>
                            <img src={this.showNumber(index)} className='table-image' alt='' />
                          </span>
                        </When>
                        <Otherwise>
                          <span className='table-number'>{index + 1}</span>
                        </Otherwise>
                      </Choose>

                      <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>
                  ))}
                </Otherwise>
              </Choose>
            </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>
              <Choose>
                <When condition={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="background-color:{color};" class="g2-tooltip-marker"></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>
                </When>
                <Otherwise>
                  <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>
                </Otherwise>
              </Choose>

              <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
