import React, {Component} from 'react';
import './index.scss';
import {HeaderBar} from '@/common';
import {http, getParam} from '@/utils';
import QRCode from 'qrcode';
import { Toast} from 'antd-mobile';

class SharePoster extends Component {
    constructor(props) {
        super(props)
        this.state = {
            codeSrc: '',
            billSrc: '',         // 图片链接
            imgUrl: '',
            smallListImg: [],  // 小图片地址
            smallactive: 0,  // 小图选中标记
            distPrice: '',  // 分销价格
            name: '',       // 用户姓名
            bgImage: []          // 背景图
        }
    }

    componentDidMount() {
        this.getCodeWe();
        http.get(`${API.home}/m/dist/posters/${getParam('courseId')}/${getParam('uid')}`).then((res) => {
            console.log(res);
            if (res.data.code === 200) {
                this.setState({
                    imgUrl: res.data.data.avatar,
                    smallListImg: res.data.data.list,
                    distPrice: res.data.data.dist_course,
                    bgImage: res.data.data.list,
                    name: res.data.data.username
                })
                this.initCanvas(this.state.bgImage, 0)
            } else {
                Toast.info(res.data.msg, 2)
            }
        })
    }

    // 初始化海报
    initCanvas = (imgList, index) => {
        let _this = this;
        let imgSrc1 = imgList[index].poster;
        let $width = 450;
        let $height = 800;
        let avatarWidth = 50    // imgList[index].poster_width    // 头像宽度
        let avatarHeight = 50   // imgList[index].poster_height     // 头像高度
        let avatarPositionX = (imgList[index].header_position_x * $width)  // 头像x轴位置
        let avatarPositionY = (imgList[index].header_position_y * $height)   // 头像Y轴位置

        let qrCodePositionX = imgList[index].qr_code_x * $width // 二维码x轴位置
        let qrCodePositionY = imgList[index].qr_code_y * $height  // 二维码y轴位置
        let qrCodeWidth = (imgList[index].qr_code_width * $width)      // 二维码宽度
        let qrCodeHeight = (imgList[index].qr_code_height * $height) - avatarHeight / 2     // 二维码高度

        let qrCodeLink = `https://m.julyedu.com/detail?id=${getParam('courseId')}&dist_code${getParam('dist_code')}`

        var canvas = document.getElementById("canvas"),
            context = canvas.getContext("2d");
        console.log(_this);
        _this.getBase64(imgSrc1)
        // 背景图片合成
            .then((img) => {
                let bgImage = new Image();
                bgImage.src = img;
                let qrCodeImg = document.getElementById('qrcode');
                let ua = navigator.userAgent.toLowerCase();
                // Android终端
                let isAndroid = ua.indexOf('Android') > -1 || ua.indexOf('Adr') > -1;
                // Ios终端
                let isiOS = !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
                if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                    qrCodeImg = document.getElementById('qrcode');
                } else if (/(Android)/i.test(navigator.userAgent)) {
                    //Android终端
                    qrCodeImg = document.getElementById('qrcode');

                }

                bgImage.setAttribute('crossOrigin', 'anonymous');
                bgImage.onload = function () {
                    context.drawImage(bgImage, 0, 0, 450, 800);
                    context.drawImage(qrCodeImg, 320, 685, 100, 100);
                    context.fillStyle = imgList[index].username_color;
                    context.font = "16px serif";
                    context.fillText('@' + _this.state.name, (avatarPositionX + avatarWidth) + 20, (avatarPositionY + avatarHeight / 2));
                    context.font = "14px serif";
                    context.fillText('正在学习该课程', (avatarPositionX + avatarWidth) + 20, (avatarPositionY + avatarHeight / 2) + 20);
                    context.restore();
                }

            })
            // 头像生成
            .then(() => {
                _this.getBase64(_this.state.imgUrl)
                    .then((img) => {
                        let bgImage = new Image();
                        bgImage.src = img;
                        bgImage.setAttribute('crossOrigin', 'anonymous');
                        bgImage.setAttribute('border-Radius', '50%');
                        bgImage.onload = function () {
                            _this.imgPosition(context, bgImage, avatarPositionX, avatarPositionY, 24);
                            context.drawImage(bgImage, avatarPositionX, avatarPositionY, 48, 48);
                            context.restore();
                            _this.setState({
                                billSrc: _this.convertCanvasToImage(canvas)
                            })

                        }
                    })

            })
    }
    children = (curEle, tagName) => {
        var nodeList = curEle.childNodes;
        var ary = [];
        if (/MSIE(6|7|8)/.test(navigator.userAgent)) {
            for (var i = 0; i < nodeList.length; i++) {
                var curNode = nodeList[i];
                if (curNode.nodeType === 1) {
                    ary[ary.length] = curNode;
                }
            }
        } else {
            ary = Array.prototype.slice.call(curEle.children);
        }

        // 获取指定子元素
        if (typeof tagName === "string") {
            for (var k = 0; k < ary.length; k++) {
                curEle = ary[k];
                if (curEle.nodeName.toLowerCase() !== tagName.toLowerCase()) {
                    ary.splice(k, 1);
                    k--;
                }
            }
        }

        return ary;
    }

    // 合成图片位置
    imgPosition = (ctx, img, x, y, r) => {
        ctx.save();
        var d = 2 * r;
        var cx = x + r;
        var cy = y + r;
        ctx.beginPath();
        ctx.arc(cx, cy, r, 0, 2 * Math.PI);
        ctx.clip();
    }

    // 获取二维码
    getCodeWe() {
        let _this = this
        let qrCodeLink = `https://m.julyedu.com/detail?id=${getParam('courseId')}&dist_code=${getParam('dist_code')}`
        return new Promise(resolve => {
            QRCode.toDataURL(qrCodeLink, {}, function (err, url) {
                _this.setState({
                    codeSrc: url
                })
            })
            /*
                        let qrcode = new QRCode(document.getElementById('qrcode'), {
                            text: qrCodeLink,
                            width: 160,
                            height: 160,
                            colorDark: "#000000", // 生成的二维码的深色部分
                            colorLight: "#ffffff", //生成二维码的浅色部分
                        })
            */
            resolve()
        })
    }

    // 图片路径转成base64
    getBase64(img) {
        let _this = this;
        return new Promise(resolve => {
            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)
                resolve(base64)
            }
            image.onerror = function () {
                let timeStamp = +new Date();
                _this.getBase64(img + '?' + timeStamp);
            }
        })

    }

    // 图片路径放入canvas转成base64
    getBase64Image = (img) => {
        let canvas = document.createElement("canvas");
        canvas.width = img.width;
        canvas.height = img.height;

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

    // canvas转换成img图片
    convertCanvasToImage = (canvas) => {
        let image = new Image();
        image.src = canvas.toDataURL("image/png");
        return image;
    }

    // 小图切换
    squareClick = (index) => {
        this.setState({
            smallactive: index
        });
        this.initCanvas(this.state.bgImage, index);
    }

    render() {
        const { distPrice={}, smallListImg=[], smallactive } = this.state;
        return (
            <div className='share-poster'>
                <HeaderBar 
                    title='生成专属海报' 
                    arrow={true} 
                    cart={false}
                />
                <div className="total-container">
                    <div className='placard-img-container' id='imgWrapper'>
                        <img src={this.state.billSrc.src} alt="" />
                    </div>
                    <img 
                        src={this.state.codeSrc} 
                        alt="" 
                        id='qrcode' 
                        className='placard-code'
                    />
                    <canvas 
                        id='canvas' 
                        width='450' 
                        height='800'
                        className={this.state.billSrc === '' ? '' : 'hide'}
                    />
                </div>
                <div className='placard-desc'>
                    <span className='placard-sharetxt'>
                        长按保存海报分享给好友，每有一人通过您的分享购买该课程，您可以
                        {
                            distPrice.count_type === 0 &&
                            <span className='placard-price'>
                                获得{distPrice.first_level_tip}元的佣金奖励。
                            </span>
                        }
                        {
                            distPrice.count_type === 1 &&
                            <span className='placard-price'>
                                获得成交金额的{distPrice.first_level_scale}%作为佣金奖励。
                            </span>
                        }
                    </span>
                </div>
                <div className='placard-swiper'>
                    <ul className='placard-list'>
                        {
                            smallListImg.length > 0 && smallListImg.map((item, index) => {
                                return (
                                    <li 
                                        onClick={this.squareClick.bind(this, index)} 
                                        key={index}
                                        className={smallactive === index ? 'active' : ''}
                                    >
                                        <img src={item.square} alt="" />
                                    </li>
                                );
                            })
                        }
                    </ul>
                </div>
            </div>
        );
    }
}

export default SharePoster;
