import { getRaceAll, postSubscribe, getMyRace, getRaceJoin } from '../../../../service/match';
import {
  $,
  setBg,
  setBack,
  writeLocalStorage,
  readLocalstorage
} from '../../../../util/utils'
import { isLogin } from '../../../../util/login'
class matchScene extends scene {
    constructor(scope) {
        super(scope);
        this.nowTime = '';
    }

    onCreate(data) {
        this.setContentView(require('../../../../res/tpl/match/match.tpl'), data, 'match', {
            containerId: 'root'
        }, () => {
            setBg('#403C94');
            setBack(false, '.52');
            const type = data.type;
            this.grade = readLocalstorage('class');
            this.checkoutTab(type)
        });
    }
    onOK(e) {
        const flag = e.target.con.attributes['data-event'].nodeValue;
        switch (flag) {
            case 'back':
                this.hideScene();
                break;
            case 'ranking':
                this.showScene(require('./rankingScene'), {
                    raceId: e.target.con.dataset.id || ''
                });
                break;
            case 'subscribe':
                if (e.target.con.innerHTML !== '已预约') {
                    postSubscribe({
                        raceId: e.target.con.dataset.id
                    }).success(res => {
                        e.target.con.innerHTML = '已预约';
                        const numberbox = e.target.con.parentNode.parentNode.querySelector('.course_match_sign_up span');
                        numberbox.innerHTML = numberbox.innerHTML * 1 + 1;
                    })
                }
                break;
            case 'joinRanking':
                 // console.log(e.target.con.dataset)
                if (e.target.con.dataset.join === 'true') {
                    this.submitRecord(e.target.con.dataset.id).then(res => {
                        this.showScene(require('./matchDialogScene.js'), {
                            bg: 'assets/match/baogao_bg.png',
                            type: 'report',
                            reportCon: res,
                            raceId: e.target.con.dataset.id
                        })
                    })
                    return
                }
                postSubscribe({
                    raceId: e.target.con.dataset.id
                }).success(res => {
                    this.showScene(require('./answerScene.js'), {
                        raceId: e.target.con.dataset.id
                    })
                })

                break;
            case 'whole':
                this.checkoutTab('whole')
                break;
            case 'my':
                this.checkoutTab('my')
                break;
            case 'goTo':
                this.scrollTo(this.goToLength);
                break;
            case 'errorbook':
                this.showScene(require('./errorbookScene.js'), {
                    type: '2'
                });
                break;
            case 'details':
                this.showScene(require('./detailsScene.js'), {
                    raceId: e.target.con.dataset.id
                });
                break;
            // default:
            //     break;
        }
    }
    onResume(data) {
        console.log(data)
        setBack(false, '.52');
        setBg('#403C94');
        const type = readLocalstorage('type')
        this.checkoutTab(type)
    }
    scrollTo(index) {
        document.querySelector('.match_container').scrollTo(index * 960,0)
    }
    getData() {
        return new Promise((resolve, reject) => {
            getRaceAll(this.grade).success(res => {
                const data = res.data;
                this.nowTime = data.now;
                data.todayRace = this.deformationArr(data.todayRace)
                data.futureRace = this.deformationArr(data.futureRace)
                data.historyRace = this.deformationArr(data.historyRace)
                data.tomorrowRace = this.deformationArr(data.tomorrowRace)
                resolve(data)
            }).fail(error => {
                reject();
            })
        })
    }
    getMyData() {
        return new Promise((resolve, reject) => {
            getMyRace(this.grade).success(res => {
                const data = res.data;
                this.nowTime = data.now;
                data.todayRace = this.deformationArr(data.todayRace)
                data.futureRace = this.deformationArr(data.futureRace)
                data.historyRace = this.deformationArr(data.historyRace)
                data.tomorrowRace = this.deformationArr(data.tomorrowRace)
                resolve(data)
            }).fail(error => {
                reject();
            })
        })
    }
    /**
     * 格式化数组
     * data格式化的数组Array
     * num 几个数组元素为一组number
    */
    deformationArr(data, num) {
        const newArr = [];
        num = num || 2;
        data.forEach(item => {
            const race = item.race
            const startDate = new Date(race.startTime).toLocaleDateString().slice(5).replace('/', '月');
            const startTime = new Date(race.startTime).toTimeString().slice(0, 5);
            const endTime = new Date(race.endTime).toTimeString().slice(0, 5);
            if(race.startTime < new Date() < race.endTime) {

            }
            race.join = (new Date(race.startTime) * 1 < this.nowTime) &&  (this.nowTime < new Date(race.endTime) * 1);
            race.time = startDate + '日 ' + startTime + '-' +endTime;
        })
        while(data.length > 0) {
            newArr.push(data.splice(0, num));
        }
        return newArr;
    }
    /**
     * 封装切换的渲染方法
     */
    selectRender({
        historyRace,
        todayRace,
        tomorrowRace,
        futureRace
    }) {
        $('.match_container').innerHTML = '';
        // 历史
        this.createDom(historyRace, '');
        // 今天
        this.createDom(todayRace, 'now');
        // 明天
        this.createDom(tomorrowRace, 'tomorrow');
        // 最近
        this.createDom(futureRace, 'lately');
        this.moye.root.reRender();
        this.goToLength = historyRace.length;
        this.scrollTo(historyRace.length);
        isLogin()
    }
    createDom(data, type) {
        if(data.length > 0) {
            data.forEach((item, index) => {
                const matchContainerChildren = document.createElement('div');
                matchContainerChildren.className = 'match_container_children';
                const matchContainerDetailBox = document.createElement('div');
                matchContainerDetailBox.className = 'match_container_detail_box';
                let str = '';
                item.forEach(childIt => {
                    /** 按钮展示 */
                    let btn = '';
                    let number = ''
                    if (type) {
                        if (childIt.race.join) {
                            btn = `<div class="btn ranking_btn" data-event="joinRanking" data-id="${childIt.race.id}" data-join="${childIt.join}" fe-role="Widget">立即参赛</div>`
                        } else if(childIt.subscribe) {
                            btn = `<div class="btn ranking_btn" style="background: #52C755;">已预约</div>`
                        } else {
                            btn = `<div class="btn ranking_btn" style="background: #52C755;" data-id="${childIt.race.id}" data-event="subscribe" fe-role="Widget">一键预约</div>`
                        }
                        number = `<span>${childIt.race.subscribeAmount || 0}</span>`
                    } else {
                        btn = `<div class="btn ranking_btn" data-id="${childIt.race.id}" data-event="ranking" fe-role="Widget">排行榜</div>`
                        number = childIt.race.subscribeAmount || 0
                    }
                    str+=`
                    <div class="match_container_detail ${type ? 'now' : 'history'}">
                        <img class="img_icon" src="${childIt.race.icon}"/>
                        <div class="course_match">
                            <span class="course_match_title">${childIt.race.title}</span>
                            <span class="course_match_date">${childIt.race.time}</span>
                            <span class="course_match_sign_up">${number}&nbsp报名</span>
                            <div class="course_btn">
                                <div class="btn detail_btn" data-id="${childIt.race.id}" data-event="details" fe-role="Widget">查看详情</div>
                                ${btn}
                            </div>
                        </div>
                    </div>
                    `
                })
                matchContainerDetailBox.innerHTML = str;
                if (type && index === 0) {
                    const matchContainerIcon = document.createElement('img');
                    matchContainerIcon.src = `assets/match/${type}.png`;
                    matchContainerIcon.className = 'match_container_icon';
                    matchContainerChildren.appendChild(matchContainerIcon);
                }
                matchContainerChildren.appendChild(matchContainerDetailBox)
                $('.match_container').appendChild(matchContainerChildren);
                /* 占位行 */
                if(index === data.length -1 ){
                    let placeDiv = document.createElement('div');
                    placeDiv.className = 'place-right'
                    $('.match_container').appendChild(placeDiv);
                }
            })
        }
    }
    // 提交本次记录
    submitRecord(raceId) {
        return new Promise((resolve, reject) => {
            getRaceJoin(raceId).success(res => {
                resolve(res.data)
            })
        })

    }
    // 切换
    checkoutTab(type) {
        if (type === 'whole') {
            $('.table').classList.add('whole_match_focus')
            $('.table').classList.remove('my_match_focus')
            writeLocalStorage('type', 'whole')
            this.getData().then((data) => {
                this.selectRender(data)
            })
        } else {
            $('.table').classList.remove('whole_match_focus')
            $('.table').classList.add('my_match_focus')
            writeLocalStorage('type', 'my')
            this.getMyData().then((data) => {
                this.selectRender(data)
            });
        }
    }
}

module.exports = matchScene;