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

import User from "../../FrameWork/User/User";
import AppPlatform from "../../FrameWork/Util/AppPlatform";
import Common5 from "../../Platform/th/Common5";
import GuWanManager from "./GuWanManager";
import GameBase from "../SCommon/GameBase";
import PrefabManage, { GameType } from "../PrefabManager/PrefabManage";
import Fangbeibao from "./Fangbeibao";
import Jianding from "./Jianding";
import UserManager from "../Manager/UserManager";
import GameReport from "../../FrameWork/Report/ZyZyReport";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Wancheng extends GameBase {

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

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

    // LIFE-CYCLE CALLBACKS:
    viewArray:{isBuy:boolean, goodId:number,jiandingChishu:number}[] = []
    // onLoad () {}
    sprArray:string[]= []
    parentNode:cc.Node = null

    // setParentData(node){
    //     this.parentNode = node
    // }
    onLoad () {
        super.onLoad()
    }

    onDestroy(){
        super.onDestroy()
    }

    start(){
        let callFunc = ()=>{
            this.initView()
        }
        if(!Common5.guwanConfigs){
            cc.loader.loadRes('Json/guwanConfig/guwanConfigs.json', function (err, gameconfig) {
                if (err) {
                    return;
                }
                Common5.guwanConfigs = gameconfig.json;
                //console.log("古玩配置加载成功", Common5.guwanConfigs);
                callFunc()
            });
        }else{
            callFunc()
        }


           
    }
    
    initView () {
        let qipao = this.node.getChildByName('qipao')
        let lab = qipao.getChildByName('lab').getComponent(cc.Label)
        lab.string = '老王出品必属精品,这些古董可都是好货不要错过了'
        qipao.scale = 0.1
        qipao.active = true
        cc.tween(qipao)
        .to(1.0, {scale:1},{easing:'backOut'})
        .delay(5.0)
        .to(0.1, {scale:0.1})
        .union()
        .repeatForever()
        .start()


        
        this.sprArray = ['真品','赝品','鉴定第二次','鉴定第一次','鉴定前']
        let todayAntiqueIdList = User.getTodayAntiqueIdList()
        if(todayAntiqueIdList.length == 0){
            //console.log('刷新数据1111111')
            this.refreshData()
        }else{
            //console.log(todayAntiqueIdList,'刷新数据1111111')
            this.viewArray = todayAntiqueIdList
            this.refreshView()
        }

        for(let i =0; i<this.layoutView.childrenCount;i++){
            let node = this.layoutView.children[i]
            this.openTouchEvent2(node)
        }

        this.scheduleOnce(()=>{
            PrefabManage.preloadPrefabByType(GameType.HuXinJianDing)
        },0.1)

    }

    videoBtnClick(){
        //刷新数据
        //Common5.playEffect("ui")
        console.log('videoBtnClick+++++++++++++===')
        //Common5.playEffect("sound/按键点击")
        let tab = {
            onClose: (finish)=>{
                if(finish) {
                    this.reportKey(()=>{
                        GameReport.ADReport('古玩市场刷新古董',1)
                    })
                    Common5.ReportDY("inLevel", '古玩市场-AD-刷新古董');
                    //Common5.showTips_custom("开始抽奖");
                    Common5.guwanchengADNum++
                    this.refreshData()
                }
                else{
                    Common5.showTips_custom("广告未观看完");
                    this.reportKey(()=>{
                        GameReport.ADReport('古玩市场刷新古董',0)
                    })
                }
            },onFailed:()=>{

            }
        }
        AppPlatform.playVideo_custom(tab)


    }

    refreshData(){
        let tes1 = []
        for(let i=0;i<17;i++){
            tes1[i] = i
        }

        let xuqiuIndex = 5
        // let xuqiuIndex2 = 0
        let tes3 = []
        tes1.sort(function(){
            return 0.5 - Math.random()
        })

        for(let i= 0;i<xuqiuIndex;i++){
            let num = tes1[i]
            tes3.push(num)
        }
        //摆放的6个物品中必有一个食谱 // 食谱id是18
    
        tes3.push(18)

        tes3.sort(function(){
            return 0.5 - Math.random()
        })

        let todayAntiqueIdList:{isBuy:boolean, goodId:number, jiandingChishu:number}[] = []
        for(let i = 0; i<6; i++){
            let array_ = {isBuy:false, goodId:tes3[i],jiandingChishu:0}
            todayAntiqueIdList.push(array_)
        }
        User.setTodayAntiqueIdList(todayAntiqueIdList)
        
        this.refreshView()
        //console.log(tes3,'tes3++++++===')
        //console.log(todayAntiqueIdList,'tes3++++++===')
    }

    refreshView(){
        let todayAntiqueIdList = User.getTodayAntiqueIdList()
        let guwanConfigs = GuWanManager.getGuwanList()//Common5.guwanConfigs;
        // console.log(guwanConfigs,"guwanConfigs++++++++++++++++===")
        for(let i = 0; i<todayAntiqueIdList.length;i++){
            let isbuy = todayAntiqueIdList[i].isBuy
            let config = guwanConfigs[todayAntiqueIdList[i].goodId]
            //console.log(config)
            let node = this.layoutView.children[i]
            if(node && !isbuy){
                let price = config.buyPrice
                let icon = node.getChildByName('icon')
                let spr = config.spriteArray + '/鉴定前'
                node.active = true
                
                Common5.addUrlSprite_custom(spr, icon.getComponent(cc.Sprite))

                let jiageLab = node.getChildByName('jiageLab') 
                let aaa = Common5.getNumberChangeHanzi( price ,'1')
                aaa = aaa as string
                jiageLab.getComponent('cc.Label').string  = aaa
                node['GoodsConfig'] = config
                node['todayAntiqueIdIndex'] = i

            }else{
                node.active = false
            }
        }


    }

    openTouchEvent2(node){
        node.on(cc.Node.EventType.TOUCH_START,this.btnTouchStartNode,this)
        node.on(cc.Node.EventType.TOUCH_END,this.btnTouchEndNode,this)
    }
    closeTouchEvent2(node:cc.Node){
        node.off(cc.Node.EventType.TOUCH_START,this.btnTouchStartNode,this)
        node.off(cc.Node.EventType.TOUCH_END,this.btnTouchEndNode,this)
    }

    btnTouchStartNode(event){
        let target = event.target
        let icon = target.getChildByName('icon')
        icon.scale = 0.75
    }

    btnTouchEndNode(event){
        //Common5.playEffect("ui")
        //Common5.playEffect("sound/按键点击")
        let target = event.target
        let icon = target.getChildByName('icon')
        icon.scale = 0.7
        if(target['isRun']){
            return
        }
        if(!target['isRun']){
            target['isRun'] = true
        }
        let goodsConfig = target['GoodsConfig'] 
        let price = goodsConfig.buyPrice 
        let money = UserManager.getCurMoney()
        if(money-price>=0){
            // Common5.getPrefabFromBundle("subRes_Resources","Prefabs/UI/shangyejie/fangruBeibao",this.node.getChildByName("GameNode"),(fangruBeibao)=>{
            //     target['isRun'] = false
            //     let beibao:Fangbeibao = fangruBeibao.getComponent('Fangbeibao')
            //     beibao.setData(this.node, target)
            // });
            PrefabManage.loadPrefabByType(GameType.HuXinGouMai, null, (fangruBeibao)=>{
                target['isRun'] = false
                let beibao:Fangbeibao = fangruBeibao.getComponent('Fangbeibao')
                beibao.setData(this.node, target)
            })
            
        }else{
            PrefabManage.showTextTips('金币不足!',1)
            target['isRun'] = false
        }
    }

    jiandingLayerShow(targetNode){
     
        targetNode.active = false
        let bagGoods:{goodId:number,jiandingChishu:number, zhenjiawupin:number, fenlei:number, goodNum:number,priceNum:number}= {
            goodId:0, jiandingChishu:0, zhenjiawupin:0,fenlei:0,goodNum:0,priceNum:0
        }
  

        let todayAntiqueIdList = User.getTodayAntiqueIdList()
        let todayAntiqueIdIndex = targetNode['todayAntiqueIdIndex']
        for(let i = 0; i<todayAntiqueIdList.length;i++){
            if(todayAntiqueIdIndex == i){
                todayAntiqueIdList[i].isBuy = true
            }
        }
      
        let goodsConfig = targetNode['GoodsConfig'] 

        bagGoods.goodId = goodsConfig.id
        bagGoods.jiandingChishu = 0 //鉴定次数为0
        bagGoods.zhenjiawupin = 2 //没有鉴定
        bagGoods.fenlei = 0  //没有鉴定
        bagGoods.goodNum = 1 //没有鉴定
        bagGoods.priceNum = goodsConfig.buyPrice*0.9
        //User.setBagGoodsList(bagGoods)

  
        let price = goodsConfig.buyPrice 
        //UserManager.subMoney(price)
        //kouqian

        let jiandingChishu = 0
        User.setTodayAntiqueIdList(todayAntiqueIdList)
        // Common5.getPrefabFromBundleNew("subRes_Resources","Prefabs/UI/shangyejie/jiandingLayer",'GameNode',(jiandingLayer)=>{
        //     let jianding:Jianding = jiandingLayer.getComponent('Jianding')
        //     jianding.refreshData(jiandingChishu, goodsConfig, bagGoods)
            
        // });

        PrefabManage.loadPrefabByType(GameType.HuXinJianDing, null, (jiandingLayer)=>{
            let jianding:Jianding = jiandingLayer.getComponent('Jianding')
            jianding.refreshData(jiandingChishu, goodsConfig, bagGoods)
            UserManager.subMoney(price)
        })

    }

    fangruBeubao(targetNode){
        //背包数据更新 FIX ME
        //更新背包数据     // 0,1,2 0假,1真,2没有鉴定,3已经鉴定,fenlei0,1,2 
        //bagGoodsList:{goodId:number,jiandingChishu:number, zhenjiawupin:0, fenlei:0, goodNum:number}[] = [];
        let bagGoods:{goodId:number,jiandingChishu:number, zhenjiawupin:number, fenlei:number, goodNum:number,priceNum:number}= {
            goodId:0, jiandingChishu:0, zhenjiawupin:0,fenlei:0,goodNum:0,priceNum:0
        }


        targetNode.active = false
        let todayAntiqueIdList = User.getTodayAntiqueIdList()
        let todayAntiqueIdIndex = targetNode['todayAntiqueIdIndex']
        for(let i = 0; i<todayAntiqueIdList.length;i++){
            if(todayAntiqueIdIndex == i){
                todayAntiqueIdList[i].isBuy = true
            }
        }
        let goodsConfig = targetNode['GoodsConfig'] 
        let price = goodsConfig.buyPrice 
        UserManager.subMoney(price)
        User.setTodayAntiqueIdList(todayAntiqueIdList)

        bagGoods.goodId = goodsConfig.id
        bagGoods.jiandingChishu = 0 //鉴定次数为0
        bagGoods.zhenjiawupin = 2 //没有鉴定
        bagGoods.fenlei = 0  //没有鉴定
        bagGoods.goodNum = 1 //没有鉴定
        bagGoods.priceNum = goodsConfig.buyPrice*0.9
        //User.setBagGoodsList(bagGoods)
    }


    // update (dt) {}
}