import { _decorator, Color, Component, instantiate, misc, Node, Prefab, Size, Sprite, tween, Tween, UIOpacity, UITransform, Vec3, Widget } from 'cc';
import { ani_frame, att_ani_data, attributes_data, event_item, event_item_delete_drag_other, guo_ju_qing_dai_dao_ju, scene_item_data, widget_item_data, zhao_xi_jie_data, zhao_xi_jie_item_data } from '../../data/data';
import { config } from '../config';
import { tools } from '../tools';
import { gameManager } from './gameManager';
import { widget_base } from './widget/widget_base';
import { ClientEvent } from '../clientEvent';
import { widget_drag } from './widget/widget_drag';
const { ccclass, property } = _decorator;
class BindTarget{
    color : Color;
    opacity:number;
    size:Size;
    pos:Vec3;
    rotation:number;
    anchorPointX:number;
    anchorPointY:number;
}
@ccclass('scene_page')
export class scene_page extends Component {
    @property(Node) content:Node = null;
    @property(Node) maskView:Node  = null;
    @property(Prefab) widget_click_prefab:Prefab = null;
    @property(Prefab) widget_drag_prefab:Prefab = null;
    @property(Prefab) widget_slide_prefab:Prefab = null;
    @property(Prefab) widget_img_prefab:Prefab = null;
    @property(Prefab) widget_animation_prefab:Prefab = null;
    private mData:scene_item_data = null;
    private mIsMask:boolean = false;
    private mSceneAtt:attributes_data = null;
    private mWidgetList:Map<number,Node> = new Map;
    private bindTarget:BindTarget = null;

    protected mAnimationList:att_ani_data[] = []; //动画组
    protected mCurRunAnimation:ani_frame[] = [];
    protected mCurAnimation:att_ani_data = null;
    protected mPlayStatus:boolean = false;
    public initView(page_data:scene_item_data){
        this.mData = page_data;
        this.mIsMask = this.mData.is_check_mask;
        this.mSceneAtt = this.mData.att;
        if(this.mData.is_full_screen){
            this.content.getComponent(Widget).enabled = true;
        }else{
            this.content.getComponent(Widget).enabled = false;
        }
        this.content.position = Vec3.ZERO;
        this.mAnimationList = this.mSceneAtt.animation_list;
        console.log("scene_page this.mAnimationList", this.mAnimationList)
        if(this.mIsMask){
            this.maskView.active = true;
        }else{
            this.maskView.active = false;
        }
        this.initViewAtt()
        ClientEvent.on(config.EventRun.NOTICE_EVENT,this.widgetBeActive.bind(this),this)
        ClientEvent.on(config.EventRun.SHOW_ZHAO_BU_TONG_FINISH_STATUS,this.on_zhao_bu_tong_finish.bind(this),this)
        ClientEvent.on(config.EventRun.ON_ZHAO_BU_TONG_ALL_FINISH,this.on_zhao_bu_tong_all_finish.bind(this),this)
    }

    public checkFinish(widget_id:number):boolean{
        let widget = this.mWidgetList.get(widget_id)
        if(!widget){
            tools.showToast("配置监听其他控件错误")
            return true
        }
        return widget.getComponent(widget_base).getIsFinish();
    }

    public checkShow(widget_id:number):boolean{
        let widget = this.mWidgetList.get(widget_id)
        if(!widget){
            return true
        }
        return widget.getComponent(widget_base).getIsShow();
    }
    protected onDestroy(): void {
        this.mWidgetList.clear()
        ClientEvent.off(config.EventRun.SHOW_ZHAO_BU_TONG_FINISH_STATUS,this.on_zhao_bu_tong_finish.bind(this),this)
        ClientEvent.off(config.EventRun.ON_ZHAO_BU_TONG_ALL_FINISH,this.on_zhao_bu_tong_all_finish.bind(this),this)
        ClientEvent.off(config.EventRun.NOTICE_EVENT,this.widgetBeActive.bind(this),this)
    }

    widgetBeActive(widgetId:number,event:event_item){
        let item = this.mWidgetList.get(widgetId)
        if(item){
            item.getComponent(widget_base).beActive(widgetId,event)
        }
        console.log("scene_page =",event.type)
        if(event.type===config.event_type.scene_ani){

            let ani_id = event.event_item_scene_ani.ani_id;
            this.mCurAnimation = this.getAniById(ani_id)
            if(this.mCurAnimation){
                this.mCurRunAnimation = this.mCurAnimation.ani_frame_list;
                if(this.mCurRunAnimation.length<2){
                    
                }else{
                    this.runAnimation()
                }
            }else{
                return tools.showToast(`错误的动画配置！id:${this.mData.att.id}-请检查`)
            }
        }else if(event.type===config.event_type.delete_drag_other_data){
            let wd = event.event_item_delete_drag_other_data.widget_id
            let index = event.event_item_delete_drag_other_data.delete_drag_other_index
            let other_widget_list = event.event_item_delete_drag_other_data.widget_list
            if(other_widget_list.length==0) {
                item = this.mWidgetList.get(wd)
                if(item){
                    item.getComponent(widget_drag).deleteOtherDrag(index)
                }else{
                    // tools.showToast("删除拖拽目标配置错误！")
                }
            } else {
                let data_list:event_item_delete_drag_other[] = JSON.parse(JSON.stringify(other_widget_list))
                let first_data = new event_item_delete_drag_other
                first_data.widget_id = wd
                first_data.delete_drag_other_index = index
                data_list.unshift(first_data)
                var data_map:Map<number,number> = new Map;
                for(let i=0;i<data_list.length;i++) {
                    const element = data_list[i]
                    let wd = element.widget_id
                    let index = element.delete_drag_other_index
                    if(index!=-1) {
                        let e_item = this.mWidgetList.get(wd)
                        if(e_item){
                            let minus_index = 0
                            if(data_map.get(wd)==null) {
                                data_map.set(wd,0)
                            } else {
                                let v = data_map.get(wd)
                                minus_index = v+1
                                data_map.set(wd,minus_index)
                            }
                            // console.log('minus_index=',minus_index)
                            let c_index = index - minus_index
                            e_item.getComponent(widget_drag).deleteOtherDrag(c_index)
                        }
                    }
                }
            }
        }else if(event.type===config.event_type.active_event) {
            let data = event.event_item_active_event_data
            this.eventMoreBindingWidgetList(data, event) 
        }else if(event.type===config.event_type.stop_active_event) {
            let data = event.event_item_stop_active_event_data
            this.eventMoreBindingWidgetList(data, event) 
        }else if(event.type===config.event_type.hide) {
            let data = event.event_item_hide_data
            this.eventMoreBindingWidgetList(data, event)
        }
    }
    eventMoreBindingWidgetList(data, event:event_item) {
        if(data!=null) {
            if(data.binding_widget_list==null||data.binding_widget_list.length==0) {
                return
            }
            for(let i=0;i<data.binding_widget_list.length;i++) {
                const element = data.binding_widget_list[i]
                let e_widget_id = element.binding_widget_id
                let e_item = this.mWidgetList.get(e_widget_id)
                if(e_widget_id!=-1){
                    if(e_item){
                        e_item.getComponent(widget_base).beActive(e_widget_id,event)
                    }
                }
            }
        }  
    }
    on_zhao_bu_tong_finish(widget:zhao_xi_jie_item_data){
       let item =   this.mWidgetList.get(widget.widget_id)
       if(item===null){
           return tools.showToast("配置找茬错误！")
       }
       item.getComponent(widget_base).showZhaoButongFinishStatus()
    }
    on_zhao_bu_tong_all_finish(data: zhao_xi_jie_data) {
        let delay_time = zhao_xi_jie_data.finish_widget_hidden_delay_time * 1000
        setTimeout(()=> {
            let widget_list = gameManager.getWidgetList(this.mData)
            for (let index = 0; index < widget_list.length; index++) {
                const widget_data = widget_list[index];
                if(widget_data.type == config.Widget_Type_List.CLICK_TYPE || 
                    widget_data.type == config.Widget_Type_List.SLIDE_TYPE ||
                    widget_data.type == config.Widget_Type_List.DRAG_TYPE) {
                    let item =  this.mWidgetList.get(widget_data.att.id)
                    item.getComponent(widget_base).hideZhaoButongFinishStatus()
                }
            }
        }, delay_time)
    }
    public initViewAtt(){
        if(this.mData.is_full_screen){

        }else{
            this.initPos()
            this.initSize()
        }
        this.initBG()
        this.initWidgetList()
    }

    public initWidgetList(){
        let widget_list =  gameManager.getWidgetList(this.mData).sort((a,b)=>{
            return a.att.z - b.att.z;
        })
        let is_dai_dao_ju_drag = (id:number)=>{
            let task:guo_ju_qing_dai_dao_ju =gameManager.Singleton.mSceneManager.getSceneTask()._guo_ju_qing_dai_dao_ju;
            if(task==null){
                return false;
            }

            for (let index = 0; index < task.widget_list.length; index++) {
                const element = task.widget_list[index];
                if(id==element.widget_id){
                    return true
                }
            }
            return false;
        } 
        for (let index = 0; index < widget_list.length; index++) {
            const widget_data = widget_list[index];
            let item:Node = null;
            switch (widget_data.type) {
                case config.Widget_Type_List.CLICK_TYPE:
                    item = instantiate(this.widget_click_prefab)
                break;
                case config.Widget_Type_List.SLIDE_TYPE:
                    item = instantiate(this.widget_slide_prefab)
                break;
                case config.Widget_Type_List.DRAG_TYPE:
                    if(is_dai_dao_ju_drag(widget_data.att.id)){

                    }else{
                        item = instantiate(this.widget_drag_prefab)
                    }
                break;
                case config.Widget_Type_List.IMG_TYPE:
                    item = instantiate(this.widget_img_prefab)
                break;
                case config.Widget_Type_List.ACTION_TYPE:
                    item = instantiate(this.widget_animation_prefab)
                break;
            }
            if(item){
                let com = item.getComponent(widget_base);
                if(com===null){
                    console.log("error--widget_data.type:",widget_data.type)
                }else{
                    item.name =`type${widget_data.type}-id${ widget_data.att.id}`
                    com.initView(widget_data)
                    item.parent = this.content;
                    this.mWidgetList.set(widget_data.att.id,item)
                }
            }
    
    
        }
    }

    public getBG(){
        return this.content;
    }

    public initBG(){
        if(this.mSceneAtt.src.length>0){
            tools.loadUrl(this.mSceneAtt.src,this.content.getComponent(Sprite))
        }
    }

    public initSize(){
        this.content.getComponent(UITransform).contentSize = new Size(this.mSceneAtt.width,this.mSceneAtt.height)
    }

    public initPos(){
        this.content.position = new Vec3(this.mSceneAtt.x,this.mSceneAtt.y)
    }

    runAnimation(){
        if(this.bindTarget!=null){
            Tween.stopAllByTarget(this.bindTarget)
            this.bindTarget = null;
        }
        // Tween.stopAll()
        let getFrameData = (index)=>{
            let cur_frame:ani_frame =this.mCurRunAnimation[index];
            let up_frame:ani_frame = index>0?this.mCurRunAnimation[index-1]:this.mCurRunAnimation[0];
            return {"cur_frame":cur_frame,"up_frame":up_frame}
        }
        let cur_index = 0;
        let data = getFrameData(cur_index);
        let call_back = ()=>{
            cur_index++;
            if(cur_index>=this.mCurRunAnimation.length){
                if(this.mCurAnimation.isLoop){
                    cur_index = 0;
                }else{
                    this.mPlayStatus = false;
                    return;
                }
            }
            let data = getFrameData(cur_index);
            this.runFrame(data.cur_frame,data.up_frame,call_back)
        }
        this.runFrame(data.cur_frame,data.up_frame,call_back)
    }

    runFrame(frame:ani_frame,up_frame:ani_frame,call){
        let self = this;
        let tweenDuration: number = frame.next_time;
        // this.content.getComponent(Sprite).spriteFrame = gameManager.getCacheSpriteFrameByName(frame.url)
        let n_pos:Vec3 = new Vec3(frame.pos_x,frame.pos_y)
        let _color = new Color()
        _color = _color.fromHEX(frame.color)
        
        this.bindTarget = new BindTarget();
        let rotation = up_frame.rotation == undefined?0:up_frame.rotation
        this.bindTarget.rotation = rotation
        this.bindTarget.color = new Color().fromHEX(up_frame.color)
        this.bindTarget.opacity = up_frame.transparent;
        this.bindTarget.size = new Size(up_frame.size_width,up_frame.size_height)
        this.bindTarget.pos = new Vec3(up_frame.pos_x,up_frame.pos_y)
        this.bindTarget.anchorPointX = up_frame.anchor_point_x==undefined?0.5:up_frame.anchor_point_x
        this.bindTarget.anchorPointY = up_frame.anchor_point_y==undefined?0.5:up_frame.anchor_point_y
   
        let color_opactiy_tw_size = tween(this.bindTarget)
        .to( tweenDuration, { pos:n_pos,color: _color,opacity:frame.transparent,size:new Size(frame.size_width,frame.size_height),rotation:frame.rotation, anchorPointX:frame.anchor_point_x, anchorPointY:frame.anchor_point_y }, {
            onUpdate(tar:BindTarget){
                self.content.getComponent(Sprite).color = tar.color; 
                self.content.getComponent(UIOpacity).opacity = tar.opacity;
                // self.content.getComponent(UITransform).setContentSize(tar.size)
                self.content.position = tar.pos
                self.content.angle = tar.rotation;
                self.content.getComponent(UITransform).setAnchorPoint(tar.anchorPointX, tar.anchorPointY)
            }
        }).call(()=>{
            call()
        });
        color_opactiy_tw_size.start();

    }

    private getAniById(id:number){
        if(this.mAnimationList.length>0){
            for (let index = 0; index < this.mAnimationList.length; index++) {
                const element = this.mAnimationList[index];
                if(id==element.ani_id){
                    return element;
                }
            }
        }
        return null;
    }
}


