/*
 * @Description:
 * @Author: zangsuyun
 * @Date: 2021-03-16 10:18:31
 * @LastEditors: fusanqiasng
 * @LastEditTime: 2021-05-28 15:55:14
 * @Copyright: © 2020 杭州杰竞科技有限公司 版权所有
 */

import React from 'react'
import { Table, message, Input, Button } from 'antd'
import { PageControl } from '@/components'
import CourseService from '@/domains/course-domain/CourseService'
import User from '@/common/js/user'
// import './WatchDataModal.less';
import dealTimeDuration from '../../course-manage/utils/dealTimeDuration'

import KnowledgeAPI from '@/data-source/knowledge/request-api'
const { Search } = Input

class WatchDataModal extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      dataSource: [],
      size: 10,
      query: {
        current: 1,
      },
      totalCount: 0,
    }
  }
  componentDidMount() {
    this.handleFetchDataList()
  }

  // 获取观看视频数据列表
  handleFetchDataList = () => {
    const { query, size, totalCount } = this.state
    const { id, type } = this.props

    const params = {
      ...query,
      size,
      id,
      storeId: User.getStoreId(),
    }
    type === 'FOLDER'
      ? KnowledgeAPI.queryPageKnowledgeFolderWatchInfo(params).then((res) => {
          const { result = {} } = res
          const { records = [], total = 0 } = result
          this.setState({
            dataSource: records,
            totalCount: Number(total),
          })
        })
      : KnowledgeAPI.queryPageKnowledgeMediaCourseWatchInfo(params).then((res) => {
          const { result = {} } = res
          const { records = [], total = 0 } = result
          this.setState({
            dataSource: records,
            totalCount: Number(total),
          })
        })
  }

  handleChangNickname = (value) => {
    const isPhone = (value || '').match(/^\d+$/)
    const { query } = this.state
    if (isPhone) {
      query.phone = value
      query.nickName = null
    } else {
      query.nickName = value
      query.phone = null
    }
    query.current = 1
    this.setState({
      query,
    })
  }

  onShowSizeChange = (current, size) => {
    if (current == size) {
      return
    }
    this.setState(
      {
        size,
      },
      () => {
        this.handleFetchDataList()
      }
    )
  }

  // 请求表头
  parseColumns = () => {
    const { type } = this.props
    const columns = [
      {
        title: '观看学员',
        key: 'name',
        dataIndex: 'name',
      },
      {
        title: '手机号',
        key: 'phone',
        dataIndex: 'phone',
      },
      {
        title: '观看者类型',
        key: 'userRole',
        dataIndex: 'userRole',
      },
      {
        title: '首次观看时间',
        key: 'firstWatch',
        dataIndex: 'firstWatch',
        render: (val) => {
          return formatDate('YYYY-MM-DD H:i', val)
        },
      },
    ]
    if (type === 'VOICE' || type === 'PICTURE') {
      columns.push({
        title: '观看时长',
        key: 'watchDuration',
        dataIndex: 'watchDuration',
        render: (val) => {
          return <span>{val ? dealTimeDuration(val) : '00:00:00'}</span>
        },
      })
    }
    if (type === 'PICTURE') {
      columns.push({
        title: '学习进度',
        key: 'progress',
        dataIndex: 'progress',
        render: (val) => {
          return val === 100 ? '已完成' : <span>{val + '%'}</span>
        },
      })
    }
    return columns
  }

  handleExportV5 = () => {
    const { query } = this.state
    const { id, type } = this.props

    const params = {
      ...query,
      knowledgeId: id,
      storeId: User.getStoreId(),
    }
    switch (type) {
      case 'FOLDER':
        KnowledgeAPI.exportFolderLearnSync(params).then((res) => {
          if (res.result) {
            const dom = document.getElementById('load-data')
            dom.setAttribute('href', res.result)
            dom.click()
          } else {
            message.error('导出失败')
          }
        })
        break
      case 'VOICE':
        KnowledgeAPI.exportVideoLearnSync(params).then((res) => {
          if (res.result) {
            const dom = document.getElementById('load-data')
            dom.setAttribute('href', res.result)
            dom.click()
          } else {
            message.error('导出失败')
          }
        })
        break
      case 'PICTURE':
        KnowledgeAPI.exportPicLearnSync(params).then((res) => {
          if (res.result) {
            const dom = document.getElementById('load-data')
            dom.setAttribute('href', res.result)
            dom.click()
          } else {
            message.error('导出失败')
          }
        })
        break
      default:
        break
    }
  }

  render() {
    const { size, dataSource, totalCount, query } = this.state
    return (
      <div className='watch-data'>
        <a download id='load-data' style={{ position: 'absolute', left: '-10000px' }}></a>
        <div className='search-container'>
          <Search
            placeholder='搜索学员姓名/手机号'
            style={{ width: 200 }}
            onChange={(e) => {
              this.handleChangNickname(e.target.value)
            }}
            onSearch={() => {
              this.handleFetchDataList()
            }}
            enterButton={<span className='icon iconfont'>&#xe832;</span>}
          />
        </div>
        <div className='filter'>
          <Button
            style={{ height: 32, margin: '16px auto 13px 0' }}
            onClick={_.debounce(
              () => {
                if (!dataSource.length) {
                  message.warning('暂无数据可导出')
                  return
                }
                this.handleExportV5()
              },
              500,
              true
            )}>
            导出
          </Button>
        </div>
        <div>
          <Table rowKey={(record) => record.id} dataSource={dataSource} columns={this.parseColumns()} pagination={false} bordered />
          {dataSource.length > 0 && (
            <div className='box-footer'>
              <PageControl
                current={query.current - 1}
                pageSize={size}
                total={totalCount}
                size='small'
                toPage={(page) => {
                  const _query = { ...query, current: page + 1 }
                  this.setState(
                    {
                      query: _query,
                    },
                    () => {
                      this.handleFetchDataList()
                    }
                  )
                }}
                onShowSizeChange={this.onShowSizeChange}
              />
            </div>
          )}
        </div>
      </div>
    )
  }
}

export default WatchDataModal
