import { DataManager } from '../../libs/tw/manager/DataManager';
import { NetManager } from '../../libs/tw/manager/NetManager';
import { Buried } from '../../libs/tw/util/Buried';
import { GDispatcher } from '../../libs/tc/util/GDispatcher';
import { ModuleTypes } from "../types/sceneTypes";
import Panel from "../views/Panel";
import GameConst from '../GameConst';
import ItemRenderder from './ItemRenderer';
import PanelCtrl from '../ctrls/panelCtrl';
import Scene from '../views/Scene';
import SceneCtrl from '../ctrls/sceneCtrl';
import Msg from '../alert/Msg';
export default class CalendarScene extends Scene {
    get skinKey() { return 'Calendar' }

    public bg: eui.Image;
    public pigA: eui.Image;
    public pigB: eui.Image;
    public pigC: eui.Image;
    public pigP: eui.Image;
    public joinDayCount: eui.Label;
    public joinDayTxt: eui.Label;
    public acmDayTxt: eui.Label;
    public acmDayCount: eui.Label;
    public currPigCheck: eui.Image;
    public ruleBtn: eui.Image;
    public backBtn: eui.Button;
    public recordTitle: eui.Label;
    public scroll: eui.Scroller;
    public group: eui.Group;
    public list: eui.List;

    public adoptedPigs: any[] = [];
    public pigAId: number = null;
    public pigBId: number = null;
    public pigCId: number = null;

    //埋点
    private exposures = {};//complete1  going2  notStarted3   p1 p2 p3

    start() {
        egret.Tween.removeAllTweens();

        this.percentWidth = 100;
        this.percentHeight = 100;
        // 初始化埋点信息
        this.initBuired();

        // 更新养成潮猪状态
        // if (!DataManager.ins.getData('getAllPetsInfo')) {
        GameConst.getAllPetsInfo(window['CFG'].activityId, (success) => {
            // if (success) {
            setTimeout(() => {

                this.updatePetsStatus();
            }, 20)
            // }
        });
        // } else {
        //     setTimeout(() => {

        //         this.updatePetsStatus();
        //     }, 20)
        // }

        // 更新日历
        if (!DataManager.ins.signInfoData) {
            NetManager.ins.getSignInfo((success) => {
                if (success) {
                    setTimeout(() => {

                        this.updateCalendar();
                    }, 20)
                }
            }, window['signActivityId']);  //注意确认
        } else {
            setTimeout(() => {

                this.updateCalendar();
            }, 20)
        }

    }

    updatePetsStatus() {
        //颜色矩阵数组
        let colorMatrix = [
            0.3, 0.6, 0, 0, 0,
            0.3, 0.6, 0, 0, 0,
            0.3, 0.6, 0, 0, 0,
            0, 0, 0, 1, 0
        ];
        let colorFlilter = new egret.ColorMatrixFilter(colorMatrix);
        this.pigA.filters = [colorFlilter];
        this.pigB.filters = [colorFlilter];
        this.pigC.filters = [colorFlilter];
        console.log(DataManager.ins.getData('getAllPetsInfo'));
        if (DataManager.ins.getData('getAllPetsInfo') && DataManager.ins.getData('getAllPetsInfo').data) {

            DataManager.ins.getData('getAllPetsInfo').data.forEach(pig => {
                // this.adoptedPigs.push(pig.identifier);
                switch (pig.identifier) {
                    case 'wastonA':
                        this.pigAId = pig.petId;
                        this.pigA.filters = [];
                        this.pigA.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_pigA, this);
                        if (pig.petLevel >= 14) {
                            let check = new eui.Image();
                            check.source = `cal_check_png`;
                            check.x = 180;
                            check.y = 185;
                            this.addChild(check);
                            //已养成埋点
                            var dpm = Buried.connectDpm(40, 10, 1);
                            var dcm = Buried.connectDcm(230, window['skinID'], 1);
                            this.exposures["p1"] = Buried.createExposure(dpm, dcm);
                            NetManager.ins.showLog(this.exposures["p1"]);
                        } else {
                            //正在养成
                            var dpm = Buried.connectDpm(40, 10, 2);
                            var dcm = Buried.connectDcm(230, window['skinID'], 1);
                            this.exposures["p1"] = Buried.createExposure(dpm, dcm);
                            NetManager.ins.showLog(this.exposures["p1"]);
                        }
                        break;
                    case 'wastonB':
                        this.pigBId = pig.petId;
                        this.pigB.filters = [];
                        this.pigB.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_pigB, this);
                        if (pig.petLevel >= 14) {
                            let check = new eui.Image();
                            check.source = `cal_check_png`;
                            check.x = 340;
                            check.y = 185;
                            this.addChild(check);
                            //已养成埋点
                            var dpm = Buried.connectDpm(40, 10, 1);
                            var dcm = Buried.connectDcm(230, window['skinID'], 2);
                            this.exposures["p2"] = Buried.createExposure(dpm, dcm);
                            NetManager.ins.showLog(this.exposures["p2"]);
                        } else {
                            //正在养成
                            var dpm = Buried.connectDpm(40, 10, 2);
                            var dcm = Buried.connectDcm(230, window['skinID'], 2);
                            this.exposures["p2"] = Buried.createExposure(dpm, dcm);
                            NetManager.ins.showLog(this.exposures["p2"]);
                        }
                        break;
                    case 'wastonC':
                        this.pigCId = pig.petId;
                        this.pigC.filters = [];
                        this.pigC.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_pigC, this);
                        if (pig.petLevel >= 14) {
                            let check = new eui.Image();
                            check.source = `cal_check_png`;
                            check.x = 490;
                            check.y = 185;
                            this.addChild(check);
                            //已养成埋点
                            var dpm = Buried.connectDpm(40, 10, 1);
                            var dcm = Buried.connectDcm(230, window['skinID'], 3);
                            this.exposures["p3"] = Buried.createExposure(dpm, dcm);
                            NetManager.ins.showLog(this.exposures["p3"]);
                        } else {
                            //正在养成
                            var dpm = Buried.connectDpm(40, 10, 2);
                            var dcm = Buried.connectDcm(230, window['skinID'], 3);
                            this.exposures["p3"] = Buried.createExposure(dpm, dcm);
                            NetManager.ins.showLog(this.exposures["p3"]);
                        }
                        break;
                }
            });
        }

        //剩下的未开始养的猪
        if (this.pigA.filters.length) {
            var dpm = Buried.connectDpm(40, 10, 3);
            var dcm = Buried.connectDcm(230, window['skinID'], 1);
            this.exposures["p1"] = Buried.createExposure(dpm, dcm);
            NetManager.ins.showLog(this.exposures["p1"]);
        }
        if (this.pigB.filters.length) {
            var dpm = Buried.connectDpm(40, 10, 3);
            var dcm = Buried.connectDcm(230, window['skinID'], 2);
            this.exposures["p2"] = Buried.createExposure(dpm, dcm);
            NetManager.ins.showLog(this.exposures["p2"]);
        }
        if (this.pigC.filters.length) {
            var dpm = Buried.connectDpm(40, 10, 3);
            var dcm = Buried.connectDcm(230, window['skinID'], 3);
            this.exposures["p3"] = Buried.createExposure(dpm, dcm);
            NetManager.ins.showLog(this.exposures["p3"]);
        }
    }

    updateCalendar() {
        console.log(DataManager.ins.signInfoData.signInfoVO);
        if (DataManager.ins.signInfoData.signInfoVO) {
            if (GameConst.stage.stageHeight > 1600) {
                this.scroll.height = 815;
            } else {
                // 考虑投放渠道为微信  实际列表高度略低于开发高度 暂将高度 760 改为 660
                this.scroll.height = 660 / 1624 * GameConst.stage.stageHeight;
            }
            let firstSignDate = DataManager.ins.signInfoData.signInfoVO.firstSignDate;
            var time = new Date(firstSignDate);
            var hours = time.getHours();
            var minutes = time.getMinutes();
            var seconds = time.getSeconds();
            var newTime = firstSignDate - (hours * 3600 + minutes * 60 + seconds) * 1000;

            let nowDate = Date.now();
            // let joinDayCount = Math.ceil((nowDate - firstSignDate) / (3600 * 24 * 1000));
            let joinDayCount = Math.ceil((nowDate - newTime) / (3600 * 24 * 1000));

            this.joinDayCount.text = `${joinDayCount}`;
            this.acmDayCount.text = `${DataManager.ins.signInfoData.signInfoVO.acmDay}`

            let signedMap = [];
            for (let item in DataManager.ins.signInfoData.signInfoVO.monthSignedMap) {
                let nItem = {}
                nItem['year'] = item.split('-')[0];
                nItem['month'] = item.split('-')[1];
                nItem['day'] = item.split('-')[2];
                nItem['timestamp'] = new Date(`${item.split('-')[0]}-${item.split('-')[1]}-${item.split('-')[2]}`).getTime();
                signedMap.push(nItem);
                // item['scopeOrigin'] = item['scopeOrigin'] || item.scope;
            };
            console.log(signedMap)
            signedMap.sort(this.ownSort);

            this.list.useVirtualLayout = false;
            this.list.itemRenderer = ItemRenderder;
            const ac = new eui.ArrayCollection(signedMap);
            this.list.dataProvider = ac;
        }

    }
    ownSort(a, b) {
        //通过比较ab对象的timestamp 来确认返回的是0还是大于0的数
        if (Number(a.timestamp) <= Number(b.timestamp)) {
            //如果a对象的timestamp小于并等于b对象，那么a对象就应该b对象的前面，所以返回0
            return 1;
        } else {
            //如果b.timestamp要小于a.timestamp,那么b对象应该在a对象的前面，所以返回大于0的数字
            return -1;
        }
    }

    // 初始化埋点信息
    initBuired() {
        // Buried.init();

        // let loadingDpmOut = Buried.connectDpm(110, 10, 1); // 点击埋点   
        // let loadingDcmOut = Buried.connectDcm(202, 0, 0); // 曝光埋点
        // this.loadingExposure = Buried.createExposure(loadingDpmOut, loadingDcmOut);

        // NetManager.ins.showLog(this.loadingExposure);
    }


    // 侦听事件
    initEvents() {
        super.initEvents();
        this.ruleBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ruleBtn, this);
        this.backBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_backBtn, this);
    }

    removeEvents() {
        super.removeEvents();
        this.ruleBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_ruleBtn, this);
        this.backBtn.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTap_backBtn, this);
    }

    onTap_pigA() {
        //点击埋点
        NetManager.ins.clickLog(this.exposures["p1"])

        console.log('pigA')
        // 切换运动猪
        if (this.pigAId) {
            GameConst.getPetInfo(this.pigAId, (success) => {
                if (success) {
                    window["currentPigData"] = {
                        "petId": this.pigAId,
                        "vipLevel": DataManager.ins.getData('getPetInfo').data.vipLevel,
                        "identifier": "wastonA",
                        "alredyReward": DataManager.ins.getData('getPetInfo').data.alredyReward,
                        "loveValue": DataManager.ins.getData('getPetInfo').data.loveValue,
                        "petLevel": DataManager.ins.getData('getPetInfo').data.petLevel,
                        "usingToys": DataManager.ins.getData('getPetInfo').data.usingToys
                    }
                    SceneCtrl.instance.change(ModuleTypes.PLAY_SCENE, { isBack: true });
                } else {
                    // 切换失败
                    let data = { msg: '切换宠物失败，请您稍后重试~', title: '很遗憾', type: 'tips' }
                    PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, data)
                }
            })
        } else {
            let data = { msg: '您尚未领养该只宠物~', title: '很遗憾', type: 'tips' }
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, data)
        }
    }

    onTap_pigB() {
        //点击埋点
        NetManager.ins.clickLog(this.exposures["p2"])

        console.log('pigB')
        // 切换臭美猪
        console.log(this.pigBId);

        if (this.pigBId) {
            GameConst.getPetInfo(this.pigBId, (success) => {
                if (success) {
                    window["currentPigData"] = {
                        "petId": this.pigBId,
                        "vipLevel": DataManager.ins.getData('getPetInfo').data.vipLevel,
                        "identifier": "wastonB",
                        "alredyReward": DataManager.ins.getData('getPetInfo').data.alredyReward,
                        "loveValue": DataManager.ins.getData('getPetInfo').data.loveValue,
                        "petLevel": DataManager.ins.getData('getPetInfo').data.petLevel,
                        "usingToys": DataManager.ins.getData('getPetInfo').data.usingToys
                    }
                    SceneCtrl.instance.change(ModuleTypes.PLAY_SCENE, { isBack: true });
                } else {
                    // 切换失败
                    let data = { msg: '切换宠物失败，请您稍后重试~', title: '很遗憾', type: 'tips' }
                    PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, data)
                }
            })
        } else {
            let data = { msg: '您尚未领养该只宠物~', title: '很遗憾', type: 'tips' }
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, data)
        }
    }

    onTap_pigC() {

        //点击埋点
        NetManager.ins.clickLog(this.exposures["p3"])

        console.log('pigC')
        // 切换社会猪
        if (this.pigCId) {
            GameConst.getPetInfo(this.pigCId, (success) => {
                if (success) {
                    window["currentPigData"] = {
                        "petId": this.pigCId,
                        "vipLevel": DataManager.ins.getData('getPetInfo').data.vipLevel,
                        "identifier": "wastonC",
                        "alredyReward": DataManager.ins.getData('getPetInfo').data.alredyReward,
                        "loveValue": DataManager.ins.getData('getPetInfo').data.loveValue,
                        "petLevel": DataManager.ins.getData('getPetInfo').data.petLevel,
                        "usingToys": DataManager.ins.getData('getPetInfo').data.usingToys
                    }
                    SceneCtrl.instance.change(ModuleTypes.PLAY_SCENE, { isBack: true });
                } else {
                    // 切换失败
                    let data = { msg: '切换宠物失败，请您稍后重试~', title: '很遗憾', type: 'tips' }
                    PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, data)
                }
            })
        } else {
            let data = { msg: '您尚未领养该只宠物~', title: '很遗憾', type: 'tips' }
            PanelCtrl.instance.show(ModuleTypes.MSG_PANEL, data)
        }
    }

    // 规则按钮
    onTap_ruleBtn() {
        SceneCtrl.instance.change(ModuleTypes.RULE_SCENE);
    }

    // 返回按钮
    onTap_backBtn() {
        SceneCtrl.instance.change(ModuleTypes.PLAY_SCENE);
    }

    // format(shijianchuo) {
    //     //shijianchuo是整数，否则要parseInt转换
    //     var time = new Date(shijianchuo);
    //     var y = time.getFullYear();
    //     var m = time.getMonth() + 1;
    //     var d = time.getDate();
    //     var h = time.getHours();
    //     var mm = time.getMinutes();
    //     var s = time.getSeconds();
    //     return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
    // }

}