var cityList = require('../data/city');
var cityIncomeList = require('../data/cityIncome');
var GameModule = require('../utils/GameModule');
const GameNotificationKey = require('../utils/GameEnum').GameNotificationKey;
const DWTool = require("../utils/DWTool");
const CityMapApi = require('../net/CityMapApi');

const CityState = {
    lock: 0,
    dev: 1,
    unlock: 2
}

cc.Class({
    extends: cc.Component,

    properties: {

        scrollView: cc.ScrollView,
        view: cc.Node,
        mapbg: cc.Node,
        content: cc.Node,
        cityItemPrefab: cc.Prefab,

        myMoneyLayout: cc.Node,
        coinNode: cc.Node,
        coinSkeleton: sp.Skeleton,
        myMoneyLabel: cc.Label,
        moneyCatNode: cc.Node,
        moneyCatSkeleton: sp.Skeleton,
        backNode: cc.Node,

        myCompanyNode: cc.Node,
        companyText: cc.RichText,
        incomeText: cc.RichText,

        progressBar: cc.ProgressBar,
        currentIncomeLabel: cc.Label,

        // airplane: cc.Node,

        coinPrefab: cc.Prefab,

        topBg: cc.Node,

        grossIncome: {
            get: function () {
                return this._grossIncome;
            },
            set: function (value) {
                this._grossIncome = value;
                this.myMoneyLabel.string = DWTool.coinParse(this._grossIncome);
            }
        },

    },

    onLoad() {

        this.moneyCatNode.on(cc.Node.EventType.TOUCH_END, _.debounce(() => {
            this.showCollectAnim(50);
        }, 1000, true), this);

        this.cityScriptList = [];

        let scaleSize = cc.view.getVisibleSize().height / this.scrollView.node.height;

        this.view.height = this.scrollView.node.height = this.node.height = cc.view.getVisibleSize().height;

        // this.scrollView.node.height = this.view.height = cc.view.getVisibleSize().height;

        // this.topBg.y = this.topBg.y * scaleSize;

        this.myMoneyLayout.y = scaleSize * this.myMoneyLayout.y;
        this.moneyCatNode.y = scaleSize * this.moneyCatNode.y;
        this.backNode.y = scaleSize * this.backNode.y;

        this.myCompanyNode.y = scaleSize * this.myCompanyNode.y;
        this.myCompanyNode.active = false;

        for (let i = 0; i < cityList.length; i++) {
            let cityInfo = cityList[i];
            // if (cityInfo.id < Global.devCityId) {
            //     cityInfo.state = CityState.unlock;
            // } else if (cityInfo.id === Global.devCityId) {
            //     cityInfo.state = CityState.dev;
            // } else {
            //     cityInfo.state = CityState.lock;
            // }

            let item = cc.instantiate(this.cityItemPrefab);
            item.x = i % 2 === 0 ? 110 : -110;
            item.on(cc.Node.EventType.TOUCH_END, () => {
                if (cityInfo.id <= Global.devCityId) {
                    this.gameFSM.visitcity(cityInfo.id);
                }
            }, this);
            let cityScript = item.getComponent('CityItem');
            // cityScript.init(cityInfo);
            this.content.addChild(item);
            this.cityScriptList.push(cityScript);
        }
    },

    init(game) {
        this.game = game
        this.gameFSM = game.gameFSM

        console.log(this.gameFSM);
    },

    show(move, devCityId) {
        if (devCityId) {
            this.devCityId = devCityId;
        } else {
            this.devCityId = Global.devCityId;
        }
        this.node.x = 400;
        this.node.active = true;
        let finish = cc.callFunc(() => {
            if (move) {
                this._showMoveAnimation();
            }
        });
        this.node.runAction(cc.sequence(cc.moveTo(0.3, 0, 0).easing(cc.easeBackOut()), finish));

        let totalIncomeSpeed = 0;

        for (let i = 0; i < cityList.length; i++) {
            let cityInfo = cityList[i];
            let cityScript = this.cityScriptList[i];
            let incomeSpeed = 0;
            if (cityInfo.id < this.devCityId) {
                cityInfo.state = CityState.unlock;
                incomeSpeed = cityIncomeList[i].income;
                totalIncomeSpeed += incomeSpeed;
                this.incomeMax = cityIncomeList[i].incomeLimit;
            } else if (cityInfo.id === this.devCityId) {
                cityInfo.state = CityState.dev;
            } else {
                cityInfo.state = CityState.lock;
            }

            cityScript.init(cityInfo, incomeSpeed);
        }

        if (move) {
            this.myCompanyNode.active = false;
            this.moneyCatNode.active = false;
            this.backNode.active = false;

        } else {
            this.myCompanyNode.active = false;
            this.moneyCatNode.active = true;
            this.backNode.active = true;

            this.moneyCatSkeleton.setAnimation(0, 'maomi', true);

            // let totalIncomeSpeed = 0;

            // for (let i = 0; i < cityList.length; i++) {
            //     let cityInfo = cityList[i];
            //     let cityScript = this.cityScriptList[i];
            //     let incomeSpeed = 0;
            //     if (cityInfo.id < this.devCityId) {
            //         cityInfo.state = CityState.unlock;
            //         incomeSpeed = cityIncomeList[i].income;
            //         totalIncomeSpeed += incomeSpeed;
            //         this.incomeMax = cityIncomeList[i].incomeLimit;
            //     } else if (cityInfo.id === this.devCityId) {
            //         cityInfo.state = CityState.dev;
            //     } else {
            //         cityInfo.state = CityState.lock;
            //     }

            //     cityScript.init(cityInfo, incomeSpeed);
            // }

            CityMapApi.getMapInfo(
                (response) => {
                    this.income = response.cityIncomeTime * totalIncomeSpeed / 1000;
                    this._setProgressbar();
                }
                , (code, msg) => {

                });

            this.myMoneyLabel.string = GameModule.userInfo.grossIncomeLabel.string;
        }
    },

    _setProgressbar() {
        if (this.income > this.incomeMax) {
            this.income = this.incomeMax;
        }
        this.currentIncomeLabel.string = DWTool.coinParse(this.income);
        this.progressBar.progress = this.income / this.incomeMax * this.progressBar.totalLength;
    },

    _showMoveAnimation() {
        for (let i = 0; i < this.cityScriptList.length; i++) {
            let cityInfo = cityList[i];
            if (cityInfo.id == this.devCityId) {
                let lastCity = this.cityScriptList[i];
                let currentCity = this.cityScriptList[i + 1];

                var lastPosition = this.getPositionInView(lastCity.node);
                let scrollOffset = this.scrollView.getScrollOffset().y - lastPosition.y + 200;
                let scrollTime = Math.abs(Math.round(scrollOffset / 50) * 0.1);
                this.scrollView.scrollToOffset(cc.v2(0, scrollOffset), scrollTime);
                this.scheduleOnce(() => {
                    this.startMoveAnimation(lastCity, currentCity);
                    this.scrollView.vertical = false;
                }, scrollTime);
            }
        }
    },

    startMoveAnimation(lastCity, currentCity) {
        let self = this;
        lastCity.showFinishAnimation(() => {
            currentCity.setState(CityState.dev);
            self.scrollView.vertical = true;
            self.scheduleOnce(() => {
                self.gameFSM.visitcity(this.devCityId);
            }, 1);
        });
    },

    getPositionInView(item) { // get item position in scrollview's node space
        let worldPos = item.parent.convertToWorldSpaceAR(item.position);
        let viewPos = this.scrollView.node.convertToNodeSpaceAR(worldPos);
        return viewPos;
    },

    // airplaneAnimation(position1, position2, cb) {
    //     var angle = this.getAngle(position1, position2);
    //     this.airplane.setRotation(angle);
    //     this.airplane.setPosition(position1);
    //     let end = cc.callFunc(cb, this);
    //     this.airplane.runAction(cc.sequence(cc.moveTo(3, position2), end));
    // },

    close() {
        this.gameFSM.historyBack();
    },

    getAngle(p1, p2) {
        // 直角的边长
        var x = p2.x - p1.x;
        var y = p2.y - p1.y;
        // 斜边长
        var z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
        // 余弦
        var cos = y / z;
        // 弧度
        var radina = Math.acos(cos);
        // 角度
        var angle = 180 / (Math.PI / radina);
        if (x < 0) {
            angle = - angle;
        }
        return angle;
    },

    showCollectAnim(colNums) {

        if (this.income > 0) {

            this.moneyCatSkeleton.setAnimation(0, 'maomi_hit', false);
            this.moneyCatSkeleton.setCompleteListener(() => {
                this.moneyCatSkeleton.setAnimation(0, 'maomi', true);
            })
            GameModule.userInfo.grossIncome += this.income * 10000;
            this.grossIncome = GameModule.userInfo.grossIncome;
            this.income = 0;
            this._setProgressbar();

            CityMapApi.reportCityIncome().then(() => {

            });

            let canvasNode = cc.find("Canvas");
            let coinNode = this.coinNode;
            let grossCoinPos = coinNode.convertToWorldSpace(cc.v2(coinNode.width / 2, coinNode.height / 2));

            let pos = this.moneyCatNode.convertToWorldSpace(cc.v2(this.moneyCatNode.width / 2, this.moneyCatNode.height / 2 - 80));

            // let colNums = 5
            let vSize = cc.view.getVisibleSize();
            let target = cc.v2(grossCoinPos.x - vSize.width / 2, grossCoinPos.y - vSize.height / 2);

            let i = 0;
            let runSt = setInterval(() => {
                if (i == colNums) {
                    clearInterval(runSt)
                } else {
                    let ranX = (Math.random() - 0.5) * 2 * 8;
                    let ranY = (Math.random() - 0.5) * 2 * 3;

                    let newCoin = cc.instantiate(this.coinPrefab);
                    let posX = pos.x - vSize.width / 2;
                    let posY = pos.y - vSize.height / 2;

                    canvasNode.addChild(newCoin)

                    newCoin.x = posX + ranX * 15;
                    newCoin.y = posY + 30 + ranY * 15;
                    newCoin.active = true;

                    newCoin = newCoin.getComponent("LevelHomeCoin")
                    newCoin.initAnim()

                    let cbNotiStart = cc.callFunc(() => {
                        this.coinSkeleton.setAnimation(0, 'jinbi_huoqu2', false);
                    })

                    let cbDestroy = cc.callFunc(() => {
                        newCoin.node.destroy();
                    })

                    let act = cc.sequence(cc.moveTo(1, target), cbDestroy, cbNotiStart)

                    newCoin.node.runAction(act.easing(cc.easeIn(2.1)));

                    i++
                }
            }, 25);
        }

    },
});
