// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import { getSprNodeByUrl, playLocalAudio, setSprNodeMaxLen } from "./JJ_page_homework_util";

const { ccclass, property } = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Node)
    scrollView: cc.Node = null;

    @property(cc.Node)
    svItem: cc.Node = null;

    @property(cc.Node)
    homeworkFinishPage: cc.Node = null;

    // @property(cc.Node)
    // frontPage: cc.Node = null;

    redPointCallback;

    // onLoad () {}

    async onEnable() {
        await this.initData();
        this.initView();
    }

    async start() {
        // await this.initData();
        // this.initView();
    }

    dateData;
    itemData;
    async initData() {
      
        this.svItem.opacity = 0;

        const homeworkData = await this.getHomeworkData();

        this.dateData = this.getNotFinishData(homeworkData);

        if (this.redPointCallback) {
            this.redPointCallback(this.dateData && this.dateData.length > 0);
            this.redPointCallback = null;
        }

    }

    initView() {
        this.initListView();
    }


    getNotFinishData(homeworkData) {
       
        const rows = homeworkData?.data?.rows || [];
        const newArr = rows.filter(it => {

            return it.courses.find(subIt => {
                return !subIt.is_finished
            })
        })

        return newArr;
    }

    async getHomeworkData() {

        // return {
        //     "code": 200,
        //     "msg": "success",
        //     "data": {
        //         "rows": [{
        //             "id": 3,
        //             "class_time": "2020-08-04",
        //             "courses": [{
        //                 "id": 1365,
        //                 "name": "我的第一份作业",
        //                 "cover": "http://staging-teach.cdn.ireadabc.com/3a0875f3-74b2-4f28-b8e4-7d9d4c9b383d.png",
        //                 "df_ispayment": 0,
        //                 "is_finished": 0,
        //                 "score": 100,
        //                 "type": "dfzx_zx_audio",
        //                 "url": "http://staging-teach.cdn.ireadabc.com/d108d5d06105fda0526059a3e372f926.mp3",
        //                 "article": "OA点击率费计算机的份上",
        //                 "picUrl": "http://staging-teach.cdn.ireadabc.com/1c9a510039065355e8f2402227cf8ef0.png"
        //             }, {
        //                 "id": 1407,
        //                 "name": "我的第二份作业",
        //                 "cover": "http://staging-teach.cdn.ireadabc.com/9804bd70-1c3a-4f03-adec-f4f959302b42.png",
        //                 "df_ispayment": 0,
        //                 "is_finished": 1,
        //                 "score": 100,
        //                 "type": "dfzx_zx_audio",
        //                 "url": "http://staging-teach.cdn.ireadabc.com/d108d5d06105fda0526059a3e372f926.mp3",
        //                 "article": "ABCABCABCABC",
        //                 "picUrl": "http://staging-teach.cdn.ireadabc.com/37aabef9ddf04d24a5206cbf350e6fa0.png"
        //             }]
        //         }, {
        //             "id": 4,
        //             "class_time": "2020-08-03",
        //             "courses": [{
        //                 "id": 1365,
        //                 "name": "我的第一份作业",
        //                 "cover": "http://staging-teach.cdn.ireadabc.com/3a0875f3-74b2-4f28-b8e4-7d9d4c9b383d.png",
        //                 "df_ispayment": 0,
        //                 "is_finished": 0,
        //                 "score": 0,
        //                 "type": "dfzx_zx_audio",
        //                 "url": "http://staging-teach.cdn.ireadabc.com/d108d5d06105fda0526059a3e372f926.mp3",
        //                 "article": "OA点击率费计算机的份上",
        //                 "picUrl": "http://staging-teach.cdn.ireadabc.com/1c9a510039065355e8f2402227cf8ef0.png"
        //             }]
        //         }, {
        //             "id": 5,
        //             "class_time": "2020-08-04",
        //             "courses": [{
        //                 "id": 1365,
        //                 "name": "我的第一份作业",
        //                 "cover": "http://staging-teach.cdn.ireadabc.com/3a0875f3-74b2-4f28-b8e4-7d9d4c9b383d.png",
        //                 "df_ispayment": 0,
        //                 "is_finished": 1,
        //                 "score": 100,
        //                 "type": "dfzx_zx_audio",
        //                 "url": "http://staging-teach.cdn.ireadabc.com/d108d5d06105fda0526059a3e372f926.mp3",
        //                 "article": "OA点击率费计算机的份上",
        //                 "picUrl": "http://staging-teach.cdn.ireadabc.com/1c9a510039065355e8f2402227cf8ef0.png"
        //             }, {
        //                 "id": 1407,
        //                 "name": "我的第二份作业",
        //                 "cover": "http://staging-teach.cdn.ireadabc.com/9804bd70-1c3a-4f03-adec-f4f959302b42.png",
        //                 "df_ispayment": 0,
        //                 "is_finished": 0,
        //                 "score": 100,
        //                 "type": "dfzx_zx_audio",
        //                 "url": "http://staging-teach.cdn.ireadabc.com/d108d5d06105fda0526059a3e372f926.mp3",
        //                 "article": "ABCABCABCABC",
        //                 "picUrl": "http://staging-teach.cdn.ireadabc.com/37aabef9ddf04d24a5206cbf350e6fa0.png"
        //             }]
        //         }],
        //         "total": 3,
        //         "displayCount": 10,
        //         "pageNum": 1,
        //         "start": 0,
        //         "end": 3,
        //         "currentPage": 1
        //     },
        //     "token": "xxx"
        // }

        const page = '1';
        const items_count = 30;
        const data = await global.middleLayer.asyncCallNetworkApiGetNew(`/api/app_source/v1/student/homeworks/page/${page}`, {items_count});
        console.log('getHomeworkData data: ', data);
        if (data.code != 200) {
            global.middleLayer.showTips(data.msg);
            return;
        }
        return data;
    }



    async initListView() {

        const svNode = this.scrollView;

        const view = cc.find("view", svNode);
        view.width = svNode.width;
        view.height = svNode.height;


        if (this.dateData.length == 0) {
            this.showEmptyIcon();
        } else {
            this.hideEmptyIcon();
        }

        if (this.dateData.length == 0) {
            const sv = svNode.getComponent(cc.ScrollView);
            const content = sv.content;
            content.removeAllChildren();
            return;
        }

        const itemArr = this.getItemArr(this.dateData);

        const sv = svNode.getComponent(cc.ScrollView);
        this.initScrollViewItemCol(sv, itemArr, 1);

    }

    showEmptyIcon() {
        const emptyIcon = cc.find("empty_icon", this.node);
        emptyIcon.active = true;
    }

    hideEmptyIcon() {
        const emptyIcon = cc.find("empty_icon", this.node);
        emptyIcon.active = false;
    }


    getItemArr(dataArr) {
        const itemArr = [];
        for (let i = 0; i < dataArr.length; i++) {

            const data = dataArr[i];

            const itemNode = cc.instantiate(this.svItem);
            itemNode.opacity = 255;
            itemNode.active = true
            itemNode['data'] = data;

            const svNode = cc.find("itemList", itemNode);
            const svItem = cc.find("view/content/item", svNode)
            const dataList = data.courses// [{}, {}, {}, {},{}, {}, {}, {}]
            this.initSubListView(svNode, svItem, dataList);


            const label = cc.find("title/time_label", itemNode).getComponent(cc.Label);
            // label.string = this.formatDate(new Date());

            const {class_time} = data;
            label.string = this.formatDate( new Date(class_time) );

            // getSprNodeByUrl(data.cover, (spr) => {

            // const sprNode = spr.node;
            // const picLayer = cc.find("mask/pic_layer", itemNode);
            // picLayer.addChild(sprNode);

            // setSprNodeMaxLen(sprNode, picLayer.width, picLayer.height);
            // })

            // cc.find("title_label", itemNode).getComponent(cc.Label).string = data.name;

            // itemNode.addComponent(cc.Button);
            // itemNode.on("click", () => {
            // global.middleLayer.backPageNode = this.node;
            // global.middleLayer.loadOnlineCourseWare(data.id, null, (flag)=>{
            //     this.node.active=!flag
            // });
            // })

            itemArr.push(itemNode);
        }
        return itemArr;
    }

    formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1并且补零
        const day = String(date.getDate()).padStart(2, '0'); // 补零
      
        return `${month}月${day}日`;
    }

    initScrollViewItemRow(sv, itemArr, row = 1) {

        sv.scrollToTop();
        const content = sv.content;
        content.width = sv.node.width;
        content.height = sv.node.height;
        content.removeAllChildren();

        const tempH = content.height / row;
        const disY = tempH * 0.95;
        const baseY = (row - 1) * 0.5 * disY;
        let rowCount = 0;

        const disX = 40;
        const baseX = itemArr[0].width / 2 * itemArr[0].scaleX + disX/2;
        let colCount = 0;

        let lastX = baseX;

        for (let i = 0; i < itemArr.length; i++) {

            const item = itemArr[i];

            item.x = lastX + disX;
            item.y = baseY - rowCount * disY;

            lastX = item.x + item.width * item.scale;

            content.addChild(itemArr[i]);

            const tempW = Math.abs(item.x + disX + item.width / 2 * item.scale);
            content.width = lastX - item.width / 2 * item.scaleX + disX * 2;

            rowCount++;
            if (rowCount >= row) {
                rowCount = 0;
                colCount++;
            }
        }
    }

    initScrollViewItemCol(sv, itemArr, col = 1) {

        sv.scrollToTop();
        const content = sv.content;
        content.width = sv.node.width;
        content.height = sv.node.height;
        content.removeAllChildren();

        const tempW = content.width / col;
        const disX = tempW * 0.95 //1.05;
        const baseX = -(col - 1) * 0.5 * disX;
        let colCount = 0;



        if (itemArr.length <= 0) return

        const disY = 80 // this._mapScaleMin;
        const topOffY = 50;
        const baseY = -itemArr[0].height / 2 * itemArr[0].scaleY - disY + topOffY;
        let rowCount = 0;
        for (let i = 0; i < itemArr.length; i++) {

            const item = itemArr[i];
            item.x = baseX + colCount * disX;
            item.y = baseY - rowCount * ((item.height + disY) * item.scaleY);
            content.addChild(itemArr[i]);

            const tempH = Math.abs(item.y - disY - item.height / 2 * item.scale);
            content.height = tempH;

            colCount++;
            if (colCount >= col) {
                colCount = 0;
                rowCount++;
            }
        }
    }

    async initSubListView(svNode, svItem, dataList) {

        
        const view = cc.find("view", svNode);
        view.width = svNode.width;
        view.height = svNode.height;

        if (dataList.length == 0) {
            const sv = svNode.getComponent(cc.ScrollView);
            const content = sv.content;
            content.removeAllChildren();
            return;
        }

        const itemArr = this.getSubItemArr(dataList, svItem);

        const sv = svNode.getComponent(cc.ScrollView);
        this.initScrollViewItemRow(sv, itemArr, 1);
    }

    checkShowLock() {

        if (!global.userInfo.expire_date) {
            return false;
        }

        const expireTime = new Date( global.userInfo.expire_date ).getTime();
        const curTime = new Date().getTime();
        if (curTime >= expireTime) {
            return true;
        }

        return false;
    }

    getSubItemArr(dataArr, svItem) {

        const isShowLockLayer = this.checkShowLock();
        const itemArr = [];
        for (let i = 0; i < dataArr.length; i++) {

            const data = dataArr[i];

            const itemNode = cc.instantiate(svItem);
            itemNode.active = true
            itemNode['data'] = data;


            const picUrl = data.cover
            getSprNodeByUrl(picUrl, (spr) => {
                const picNode = cc.find("bg/pic_bg", itemNode);
                spr.node.parent = cc.find("mask_bg", picNode);
                setSprNodeMaxLen(spr.node, picNode.width, picNode.height, true);
            })


            const lockLayer = cc.find("bg/lock_layer", itemNode);
            if (isShowLockLayer && data.df_ispayment) {
                lockLayer.active = true;
            }


            const notDone = cc.find("bg/icon_notdone", itemNode);
            if (data.is_finished) {
                notDone.active = false;
            } else {
                notDone.active = true;
            }

            const richtext = cc.find("bg/richtext", itemNode).getComponent(cc.RichText);
            richtext.string = data.name
            

            // getSprNodeByUrl(data.cover, (spr) => {

            // const sprNode = spr.node;
            // const picLayer = cc.find("mask/pic_layer", itemNode);
            // picLayer.addChild(sprNode);

            // setSprNodeMaxLen(sprNode, picLayer.width, picLayer.height);
            // })

            // cc.find("title_label", itemNode).getComponent(cc.Label).string = data.name;

            itemNode.addComponent(cc.Button);
            itemNode.on("click", () => {
                if (lockLayer.active) {
                    this.showVipTipLayer();
                    return;
                }
                global.middleLayer.backPageNode = this.node;

                console.log(' item data: ' , data);

                global.middleLayer.setCurHomeworkData(data.homework_id, data.id);
                global.middleLayer.loadOnlineCourseWare(data.id, null, (flag)=>{
                    this.node.active=!flag
                    // this.frontPage.active = !flag;
                });
            })

            itemArr.push(itemNode);
        }
        return itemArr;
    }


    showHomeworkFinishPage() {
        this.homeworkFinishPage.active = true;
        this.node.active = false;
        playLocalAudio('btn');
    }

    showVipTipLayer() {
        const layer = cc.find("vip_tip_layer", this.node);
        layer.active = true;
        playLocalAudio('btn');
    }

    hideVipTipLayer() {
        const layer = cc.find("vip_tip_layer", this.node);
        layer.active = false;
        playLocalAudio('btn');
    }

    

    getRedPoint(callback) {
        if (!this.dateData) {
            this.redPointCallback = callback;    
            this.initData();
        } else {
            callback(this.dateData && this.dateData.length > 0)
        }
    }

    exitGame() {
        global?.middleLayer?.exitGame();
    }


    // update (dt) {}
}
