import React, {Component} from 'react'
import {HeaderBar} from '@/common'
import {http} from '@/utils'
import './index.scss'
import QRCode from 'qrcode'
import html2canvas from 'html2canvas'
import scoreIconL from '@assets/image/score_icon-l.png'
import scoreIconR from '@assets/image/score_icon-r.png'
import scoreReportBg from '@assets/image/scoreReport_bg.png'
import {connect} from "react-redux"

@connect(state => ({
        user: state.user,
    }),
)
class scoreReport extends Component {

    constructor(props) {
        super(props)
        this.state = {
            tab: ['当前成绩', '今日最佳', '本月最佳'],
            cutIndex: 0,
            myRankList: '',
            imgUrl: '',
            codeSrc: '',
            avatar_file: ''
        }
    }

    componentDidMount() {
        this.getCodeWe()
        this.handleFetchInfo(0)
    }

    shouldComponentUpdate(nextProps, nextState, nextContext) {
        if (this.props.user.data.avatar!==nextProps.user.data.avatar) {
            this.getCanvas()
            return false
        }
      return true
    }


    getCanvas() {
        let _this = this
        var canvas2 = document.createElement("canvas")
        let _canvas = document.getElementsByClassName('score-list')[0]
        var w = parseInt(window.getComputedStyle(_canvas).width)
        var h = parseInt(window.getComputedStyle(_canvas).height)
        var scale = window.devicePixelRatio
        canvas2.width = w * scale
        canvas2.height = h * scale

        var context = canvas2.getContext("2d")
        context.scale(1, 1)
        html2canvas(document.getElementsByClassName('score-list')[0], {canvas: canvas2}).then(function (canvas) {
            //document.body.appendChild(canvas);

            let imgUrl = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream")
            _this.setState({
                imgUrl: imgUrl,
            })
        })
    }

// 获取二维码
    getCodeWe() {
        let _this = this
        let qrCodeLink = `${API.m}/ai-test`
        return new Promise(resolve => {
            QRCode.toDataURL(qrCodeLink, {}, function (err, url) {
                _this.setState({
                    codeSrc: url,
                })
            })
            resolve()
        })
    }

    handleFetchInfo = (index) => {
        http.get(`${API.home}/sys/at/user_score/${index}`).then(res => {
            const {code, data} = res.data
            if (code === 200) {
                const {user, history} = this.props
                if (user.hasError) {
                    history.push('/passport')
                    return
                }

                this.setState({
                    myRankList: data
                })

                let avatar = this.props.user && this.props.user.data.avatar
                this.getBase64(avatar)
                setTimeout(() => {
                    this.getCanvas()
                },500)
            }
        })
    }


    getBase64Image = (img) => {
        var canvas = document.createElement("canvas")
        canvas.width = img.width
        canvas.height = img.height

        var ctx = canvas.getContext("2d")
        ctx.drawImage(img, 0, 0, img.width, img.height)
        var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase()
        var dataURL = canvas.toDataURL("image/" + ext)
        return dataURL
    }

    getBase64 = (img) => {
        let base64 = null
        let image = new Image()
        let timeStamp = +new Date()
        image.setAttribute('crossOrigin', 'anonymous')
        image.src = img + '?' + timeStamp
        image.onload = () => {
            base64 = this.getBase64Image(image)
            this.setState({
                avatar_file: base64,
            })
        }
        image.onerror = () => {
            console.log('onerror')
            let timeStamp = +new Date()
            this.getBase64(img + '?' + timeStamp)
        }
    }


    change = (index) => {
        this.setState({
            cutIndex: index,
        })
        this.handleFetchInfo(index)
    }


    render() {
        const {tab, cutIndex, myRankList, codeSrc, imgUrl, avatar_file} = this.state
        return (
            <div className={'score-content'}>
                <HeaderBar
                    title='成绩报告'
                    arrow={true}
                    home={false}
                />
                <div className={'score-report'}>
                    <ul className={'tab-list'}>
                        {
                            tab.map((item, index) => {
                                return (
                                    <li key={index} className={cutIndex === index ? 'active' : ''}
                                        onClick={() => this.change(index)}>{item}</li>
                                )
                            })
                        }
                    </ul>

                    <div className="score-list-box">

                        <div className={'score-list'} style={{backgroundImage: `url(${scoreReportBg})`}}>
                            <div className="title">
                                <img src={scoreIconL} alt=""/>
                                成绩报告
                                <img src={scoreIconR} alt=""/>
                            </div>

                            <table border="0" cellSpacing="0" cellPadding="0">
                                <thead>
                                <tr>
                                    <td>分数</td>
                                    <td>用时</td>
                                    <td>{cutIndex === 0 && '最终'}排名</td>
                                </tr>
                                </thead>
                                <tbody>
                                {
                                    myRankList.r_id !== 0 &&
                                    <tr className={'has'}>
                                        <td>{myRankList.score}分</td>
                                        <td>{myRankList.cost_time}</td>
                                        <td className={'rank'}>{myRankList.rank}</td>
                                    </tr>
                                }
                                {
                                    myRankList.r_id == 0 &&
                                    <tr>
                                        <td>-</td>
                                        <td>-</td>
                                        <td>-</td>
                                    </tr>
                                }

                                </tbody>
                            </table>

                            <div className="comment text-overflow-4">
                                <img className={'avatar_file'} src={avatar_file} alt=""/>
                                {myRankList && myRankList.title && myRankList.title.comment}
                            </div>

                            <div className="code">
                                <img src={codeSrc} alt=""/>
                                <p>AI水平测试</p>
                            </div>
                        </div>


                        <img className={'imgUrl'} src={imgUrl} alt=""/>
                    </div>

                    <div className="tip">长按图片分享给好友，或保存后分享到朋友圈</div>

                </div>
            </div>
        )
    }
}


export default scoreReport