import { ryw_Event } from "../../FrameWork/Event/EventEnum";
import EventMgr from "../../FrameWork/Event/EventMgr";

import User from "../../FrameWork/User/User";
import AppPlatform from "../../FrameWork/Util/AppPlatform";
import Common5 from "../../Platform/th/Common5";
import UiBase from "../GameBase/UiBase";
import TaskManager, { MainTaskIdEnum } from "../JuQingChat/TaskManager";

import BuyStockBox from "./BuyStockBox"
import SaleStockBox from "./SaleStockBox"
import StockManager from "./StockManager";

const {ccclass, property} = cc._decorator;
enum StockMarketType{
    StockMarket,
    MyStocks,
    TouTiao
}
enum StockRiskType{
    LowRisk,
    HighRisk
}
@ccclass
export default class Stock extends UiBase{
    @property(cc.Node)
    stockMarketNode:cc.Node = null
    @property(cc.Node)
    stockContent:cc.Node = null
    @property(cc.Node)
    stockItem:cc.Node = null

    @property(cc.Node)
    myStockNode:cc.Node = null
    @property(cc.Node)
    myStockContent:cc.Node = null
    @property(cc.Node)
    myStockItem:cc.Node = null


    @property(cc.Node)
    btn_buy:cc.Node = null

    @property(cc.Prefab)
    buyStockPrefab:cc.Prefab = null
    @property(cc.Prefab)
    saleStockPrefab:cc.Prefab = null
    @property(cc.Prefab)
    jinRongTouTiaoPrefab:cc.Prefab = null
    
    curStockRiskType:StockRiskType.HighRisk
    curStockMarketType:StockMarketType.StockMarket
    buyStockNode:cc.Node = null
    saleStockNode:cc.Node = null
    jinRongTouTiaoBox:cc.Node = null

        
    onLoad () {
        super.onLoad()

    }

    onDestroy(){
        super.onDestroy()
    }

    start(){
        EventMgr.onEvent_custom(ryw_Event.updateStockView,()=>{
            this.setStockMarketContent(this.curStockRiskType)
            this.setMyStockContent()
        },this)

        let stocksStorageConfig = User.getStocksData()
        if(stocksStorageConfig['巨富集团']){
            stocksStorageConfig['巨富集团']["curPrice"] = 1500
            User.setStocksData(stocksStorageConfig)
        }
 

        this.setStockMarketContent(StockRiskType.HighRisk)

        this.checkFinishTask()
    }
    //初始化股票市场
    setStockMarketContent(riskType){
        // console.log("初始化股票市场",riskType)
        
        this.curStockRiskType = riskType
        let riskStr = ""
        if(riskType == StockRiskType.LowRisk){
            riskStr= "低"
         
        }else if(riskType == StockRiskType.HighRisk){
            riskStr= "高"
        
       
        }

        this.stockContent.removeAllChildren()
        let stocksStorageConfig = User.getStocksData()

        //console.log(stocksStorageConfig,'stocksStorageConfig++++')


        let objLength = 0
        for(let key in stocksStorageConfig){
            if(stocksStorageConfig[key].riskAttributes == riskStr && (key == '巨富集团')){
                objLength++
                let childItem = cc.instantiate(this.stockItem)
                childItem.getChildByName("stockName").getComponent(cc.Label).string = key
                // childItem.getChildByName("price").getComponent(cc.Label).string = StockManager.handPrice(riskStr,stocksStorageConfig[key].curPrice)
                childItem.getChildByName("price").getComponent(cc.Label).string = Common5.getNumberChangeHanzi(stocksStorageConfig[key].curPrice,'1',1)+""
                childItem.getChildByName("rateOfRise").getComponent(cc.Label).string = stocksStorageConfig[key].curRate + "%"
                //涨跌颜色区分
                if(stocksStorageConfig[key].curRate < 0){
                    childItem.getChildByName("stockName").color = new cc.Color().fromHEX("#03A239")
                    childItem.getChildByName("price").color = new cc.Color().fromHEX("#03A239")
                    childItem.getChildByName("rateOfRise").color = new cc.Color().fromHEX("#03A239")
                }else{
                    childItem.getChildByName("stockName").color = new cc.Color().fromHEX("#D20D00")
                    childItem.getChildByName("price").color = new cc.Color().fromHEX("#D20D00")
                    childItem.getChildByName("rateOfRise").color = new cc.Color().fromHEX("#D20D00")
                }
                childItem.active = true
                childItem.getChildByName("btn_buy").attr({stockConfig:stocksStorageConfig[key]})
                this.stockContent.addChild(childItem)
                break
            }
        }

        let nameArray = []
        Object.keys(stocksStorageConfig).forEach(name => {  
            //console.log(name)
            if(name!='巨富集团'){
                nameArray.push(name)
            }
          
        });
        let count = nameArray.length;
        let i = 0
        this.schedule(() => {
            let key = nameArray[i]
            if(stocksStorageConfig[key].riskAttributes == riskStr){
                let childItem = cc.instantiate(this.stockItem)
                childItem.getChildByName("stockName").getComponent(cc.Label).string = key
                // childItem.getChildByName("price").getComponent(cc.Label).string = StockManager.handPrice(riskStr,stocksStorageConfig[key].curPrice)
                childItem.getChildByName("price").getComponent(cc.Label).string = Common5.getNumberChangeHanzi(stocksStorageConfig[key].curPrice,'1',1)+""
                childItem.getChildByName("rateOfRise").getComponent(cc.Label).string = stocksStorageConfig[key].curRate + "%"
                //涨跌颜色区分
                if(stocksStorageConfig[key].curRate < 0){
                    childItem.getChildByName("stockName").color = new cc.Color().fromHEX("#03A239")
                    childItem.getChildByName("price").color = new cc.Color().fromHEX("#03A239")
                    childItem.getChildByName("rateOfRise").color = new cc.Color().fromHEX("#03A239")
                }else{
                    childItem.getChildByName("stockName").color = new cc.Color().fromHEX("#D20D00")
                    childItem.getChildByName("price").color = new cc.Color().fromHEX("#D20D00")
                    childItem.getChildByName("rateOfRise").color = new cc.Color().fromHEX("#D20D00")
                }
                childItem.active = true
                childItem.getChildByName("btn_buy").attr({stockConfig:stocksStorageConfig[key]})
                this.stockContent.addChild(childItem)
            }
            i++
            
        }, 0, count-1, 0)

        
    }
    
    //股市-我的股票toggle
    onSocketMarketTypeToggle(event,customData){
        //Common5.playEffect("sound/按键点击")
        if(this.curStockMarketType == customData){
            return
        }
        this.changeMarketAndMyStock(customData)
    }
    //切换股市和我的股票
    changeMarketAndMyStock(marketType){
        this.curStockMarketType = marketType
        //股市
        if(marketType == StockMarketType.StockMarket){
            // console.log("点击股市")
        
       
            this.stockMarketNode.active = true
            this.myStockNode.active = false
    
            this.btn_buy.active = true
        //我的股票
        }else if(marketType == StockMarketType.MyStocks){
            // console.log("我的股票")
     
     
            this.stockMarketNode.active = false
            this.myStockNode.active = true
    
            this.btn_buy.active = true
            this.setMyStockContent()
        //金融头条
        }else if(marketType == StockMarketType.TouTiao){
            this.stockMarketNode.active = false
            this.myStockNode.active = false
            
            this.btn_buy.active = false
        }
    }
    //低风险-高风险toggle
    onStockRiskTypeToggle(event,customData){
        //Common5.playEffect("sound/按键点击")
        if(this.curStockRiskType == customData){
            return
        }
        this.setStockMarketContent(customData)
    }
    //初始化我的股票
    setMyStockContent(){
        this.myStockContent.removeAllChildren()
        let stocksStorageConfig = User.getStocksData()
        let myStockHistoryData = User.getMyStockData()
        //console.log("myStockHistoryData==",myStockHistoryData)
        let userHetong = User.getUserHeTong()

        let taskIdArray = User.getCurTaskId()
        //let kuaidiGSKaiye = taskIdArray[0]>=MainTaskIdEnum.MainTask_548
    
        for(var key in myStockHistoryData){
            let singleStockData = stocksStorageConfig[key]
            let nowPrice = singleStockData["curPrice"]
            let buyPrice = myStockHistoryData[key].buyPrice
            let riskAttributes = singleStockData["riskAttributes"]
            let childItem = cc.instantiate(this.myStockItem)
            if(riskAttributes == "高"){
                childItem.getChildByName("icon_red").active = true
            }else{
                childItem.getChildByName("icon_green").active = true
            }

            if(key == '巨富集团'){
                childItem.getChildByName('btn_buy').active = false
                childItem.getChildByName('btn_sell').active = false
                childItem.getChildByName('无法卖出').active = true
            }
            let singConfig = StockManager.getSingleCompanyConfig(key)


            childItem.getChildByName("stockName").getComponent(cc.Label).string = key
            childItem.getChildByName("newPrice").getComponent(cc.Label).string = Common5.getNumberChangeHanzi(nowPrice,'1',1)+""
            childItem.getChildByName("rateOfRise").getComponent(cc.Label).string = ((nowPrice/buyPrice - 1)*100).toFixed(1) + "%"
            childItem.getChildByName("buyPrice").getComponent(cc.Label).string = Common5.getNumberChangeHanzi(myStockHistoryData[key].buyPrice,'1',1)+""


            let numindex = (myStockHistoryData[key].prossess/singConfig.stockSum)*100
     
            let baoliuNum = null//numindex.toFixed(1).slice(0, -1)

            if(numindex<=1){
                baoliuNum = 1
            }else if(numindex>1 && numindex<10){
                baoliuNum = numindex.toFixed(2).slice(0, -1)
            }else  if(numindex>10 && numindex<100){
                baoliuNum = Math.floor(numindex)
            }else{
                baoliuNum = 100
            }
            //console.log('(myStockHistoryData[key].prossess/singConfig.stockSum)*100',baoliuNum)
            childItem.getChildByName("possess").getComponent(cc.Label).string = baoliuNum+'%'//myStockHistoryData[key].prossess//(myStockHistoryData[key].prossess/singConfig.stockSum)*100 + '%'

            childItem.getChildByName("btn_buy").attr({stockConfig:stocksStorageConfig[key]})
            childItem.getChildByName("btn_sell").attr({stockConfig:stocksStorageConfig[key]})
            childItem.active = true
            if(nowPrice >= buyPrice){
                childItem.getChildByName("stockName").color = new cc.Color().fromHEX("#D20D00")
                childItem.getChildByName("newPrice").color = new cc.Color().fromHEX("#D20D00")
                childItem.getChildByName("rateOfRise").color = new cc.Color().fromHEX("#D20D00")
                childItem.getChildByName("buyPrice").color = new cc.Color().fromHEX("#D20D00")
                childItem.getChildByName("possess").color = new cc.Color().fromHEX("#D20D00")
            }else{
                childItem.getChildByName("stockName").color = new cc.Color().fromHEX("#03A239")
                childItem.getChildByName("newPrice").color = new cc.Color().fromHEX("#03A239")
                childItem.getChildByName("rateOfRise").color = new cc.Color().fromHEX("#03A239")
                childItem.getChildByName("buyPrice").color = new cc.Color().fromHEX("#03A239")
                childItem.getChildByName("possess").color = new cc.Color().fromHEX("#03A239")
            }
            this.myStockContent.addChild(childItem)
        }
    }
    //买入
    onBtnBuy(event){
        //Common5.playEffect("sound/按键点击")

    
        if(this.buyStockNode){
            this.buyStockNode.removeFromParent()
        }
        this.buyStockNode = cc.instantiate(this.buyStockPrefab)
        this.node.addChild(this.buyStockNode)
        this.buyStockNode.getComponent(BuyStockBox).initBoxContent(event.target.stockConfig)    
    }
    //卖出
    onBtnSell(event){
       
   



        //Common5.playEffect("sound/按键点击")
        if(this.saleStockNode){
            this.saleStockNode.removeFromParent()
        }
        this.saleStockNode = cc.instantiate(this.saleStockPrefab)
        this.node.addChild(this.saleStockNode)
        this.saleStockNode.getComponent(SaleStockBox).initBoxContent(event.target.stockConfig)   
    }



    //刷新
    onBtnRefresh(){
        //Common5.playEffect("sound/按键点击")

        let tab = {
            onClose: (finish)=>{
                if (finish) {
                    Common5.ReportDY("inLevel", '证券中心-AD-股票刷新');
          
                    StockManager.refreshAllStocksData(User.getDay()+1,true)
                }
                else{
                    
                    Common5.showTips_custom("广告未观看完");
                }
            },onFailed:()=>{

            }
        }
        AppPlatform.playVideo_custom(tab)
        
    }
    //查阅
    onBtnView(event){
        //Common5.playEffect("sound/按键点击")

        let tab = {
            onClose: (finish)=>{
                if (finish) {
                    Common5.ReportDY("inLevel", '证券中心-AD-查阅');
                   
                    if(this.jinRongTouTiaoBox){
                        this.jinRongTouTiaoBox.removeFromParent()
                    }
                    this.jinRongTouTiaoBox = cc.instantiate(this.jinRongTouTiaoPrefab)
                    this.node.addChild(this.jinRongTouTiaoBox)
                    // this.jinRongTouTiaoBox.getComponent(JinRongTouTiaoBox).initBoxContent()  
                }
                else{
                   
                    Common5.showTips_custom("广告未观看完");
                }
            },onFailed:()=>{

            }
        }
        AppPlatform.playVideo_custom(tab)

    }

    checkFinishTask(){
        let myStockHistoryData = User.getMyStockData()
        for(var key in myStockHistoryData){
            let singConfig = StockManager.getSingleCompanyConfig(key)
            let newProssess = myStockHistoryData[key].prossess
            if(key == '巨富集团' && newProssess >= singConfig.stockSum){
                //完成任务526
                let mainTaskInfo:any = TaskManager.getCurUnLockMainTaskInfo()
                let mainId = mainTaskInfo.Id
                if(mainId == MainTaskIdEnum.MainTask_530){
                    
                    //EventMgr.emitEvent_custom(ryw_Event.RefreshUnLockGame);
                    TaskManager.finishCurMainTask(MainTaskIdEnum.MainTask_530)
                    this.node.removeFromParent()
                    this.node.destroy()
                    
                }
                
            }


        }
       
    }
}