import { _decorator, Component, EventTouch, Node, Rect, Sprite, UITransform, v2, Vec2, Vec3 } from 'cc';
import { widget_base } from './widget_base';
import { att_drag_data, other_widget_finish_listen_item, widget_item_data } from '../../../data/data';
import { gameManager } from '../gameManager';
import { ClientEvent } from '../../clientEvent';
import { config } from '../../config';
const { ccclass, property } = _decorator;

@ccclass('widget_drag')
export class widget_drag extends widget_base {
    @property(Node) img_zhaobutong:Node = null;
    private mDragData:att_drag_data = null;
    private mIsStartMove:boolean = false;
    private offset_x:number = 0;
    private offset_y:number = 0;
    private mDragRect:Rect = null;
    private other_drag_list:att_drag_data[] = [];
    protected init(){
        if(this.mData.att.drag_data!=null){
            this.mDragData = this.mData.att.drag_data
        }
        if(this.mData.att.drag_data.other_drag_list!=undefined){
            for (let index = 0; index <  this.mData.att.drag_data.other_drag_list.length; index++) {
                const element =  this.mData.att.drag_data.other_drag_list[index];
                let item = new att_drag_data;
                item.index = index;
                item.drag_pos_x = element.drag_pos_x;
                item.drag_pos_y = element.drag_pos_y;
                item.other_event_id = element.other_event_id;
                item.drag_size_width = element.drag_size_width;
                item.drag_size_height = element.drag_size_height;
                item.score = element.score;
                this.other_drag_list.push(item)
            }
        }

    }
    protected start(): void {
        if(this.mIsActive&&this.isInit){
            this.registeredEvent()
        }
    }
    protected registeredEvent(): void {
        this.node.off(Node.EventType.TOUCH_START)
        this.node.on(Node.EventType.TOUCH_START,(et:EventTouch)=>{
            if(!this.mIsActive) return
            this.mIsStartMove = true;
            let p = new Vec3(et.getUILocation().x,et.getUILocation().y)
            let n_p = this.node.parent.getComponent(UITransform).convertToNodeSpaceAR(p)
            this.node.position = new Vec3(n_p.x,n_p.y);

            this.setScenePageScroll(false)
        })
        this.node.off(Node.EventType.TOUCH_MOVE)
        this.node.on(Node.EventType.TOUCH_MOVE,(et:EventTouch)=>{
            if(!this.mIsActive) return
                let p = new Vec3(et.getUILocation().x,et.getUILocation().y)
                let n_p = this.node.parent.getComponent(UITransform).convertToNodeSpaceAR(p)
                this.node.position = new Vec3(n_p.x,n_p.y);
        })
        this.node.off(Node.EventType.TOUCH_END)
        this.node.on(Node.EventType.TOUCH_END,()=>{
            this.onEndEvent()
            this.setScenePageScroll(true)
        })
    }

    private setScenePageScroll(is_scroll:boolean) {
        let scene_page = this.getScenePage()
        if(scene_page==null) return
        if(is_scroll) {
            scene_page.startScrollTouch()
        } else {
            scene_page.stopScrollTouch()
        }
    }

    private onEndEvent(){
        if(!this.mIsActive) return
        this.mIsStartMove = false;
        this.checkOnecFinish()
    }

    private checkOther(){
        if(this.mDragData.other_drag_list==undefined){
            return false;
        }
        let isCheck = false;
        if(this.other_drag_list.length>0){
            for (let index = 0; index < this.other_drag_list.length; index++) {
                const item_data = this.other_drag_list[index];
                let w = item_data.drag_size_width;
                let h = item_data.drag_size_height;
                let pos =  new Vec3(this.mData.att.x+item_data.drag_pos_x,this.mData.att.y+item_data.drag_pos_y)
                let rect = new Rect(pos.x-w*0.5,pos.y-h*0.5,w,h)
                let p = this.node.position;
                let is = rect.contains(new Vec2(p.x,p.y))
                if(is){
                    if(item_data.other_event_id!=-1){
                        this.offEvent()
                        console.log("执行其他拖拽的完成事件id ",item_data.other_event_id,`,${index}`,rect,p)
                        ClientEvent.dispatchEvent(config.EventRun.WIDGET_DRAG_OTHER_FINISH,this.mData.att.id,item_data.score)
                        gameManager.Singleton.exeEvent(item_data.other_event_id)
                        isCheck = true;
                        break;
                    }
                    
                }
            }
        }
        return isCheck;
    }

    public deleteOtherDrag(index:number){
        // this.other_drag_list.splice(index,1)
        for (let i = 0; i < this.other_drag_list.length; i++) {
            const element = this.other_drag_list[i];
            if(element.index==index) {
                this.other_drag_list.splice(i,1)
                break
            }
        }
    }

    private checkOnecFinish(){
        if(this.checkMoveToDragRect()){
            this.mIsStartMove = false;
            this.checkAddOtherWidgetFinishListenOperation()
        } else {
            if(this.checkOther()){
                this.mIsStartMove = false;
            }else{
                if(this.mDragData.is_err_drag_back){
                    this.resetOriginPostion()
                }
            }
        }
    }

    public getDragRect():Rect{
        if(this.mDragData==null){
            this.mDragData = this.mData.att.drag_data
        }
        let w = this.mDragData.drag_size_width;
        let h = this.mDragData.drag_size_height;
        let pos =  new Vec3(this.mData.att.x+this.mDragData.drag_pos_x,this.mData.att.y+this.mDragData.drag_pos_y)
        this.mDragRect = new Rect(pos.x-w*0.5,pos.y-h*0.5,w,h)
        return this.mDragRect;
    }

    private checkMoveToDragRect():boolean{
        let p = this.node.position;
        let is = this.getDragRect().contains(new Vec2(p.x,p.y))
        return is
    }

    protected onFinishAnimation(): void {
        this.icon.position = new Vec3(this.mData.att.x,this.mData.att.y)
        // node.setSiblingIndex(node.parent.childrenCount - 1); 
        // this.icon.setSiblingIndex(999)
    }

    public showZhaoButongFinishStatus(): void {
        gameManager.Singleton.sys_click_correct_detail_music()
        this.img_zhaobutong.active = true;
        this.icon.position = new Vec3(this.mData.att.x,this.mData.att.y)
    }

    public hideZhaoButongFinishStatus(): void {
        if(this.img_zhaobutong != null) {
            this.img_zhaobutong.active = false;
        }
    }

    public toFinishEvent(){
        this.onFinishEvent()
    }

    // 复位
    private resetOriginPostion() {
        this.node.position = new Vec3(this.mData.att.x,this.mData.att.y)
    }

    // 检查添加其他控件
    private checkAddOtherWidgetFinishListenOperation() {
        let onFinishEvent_cb = (()=>{
            this.checkOtherListenWidgetFinish(false)
            this.onFinishEvent()
        })

        if(this.checkOtherWidgetFinishListenListData()==false) {
            onFinishEvent_cb()
            return
        }

        // 是-直接执行自身
        if(this.mDragData.is_direct_execute_myself) { 
            // console.log('直接-执行自身')
            onFinishEvent_cb()
        } 
        // 否-直接执行自身
        else { 
            // 是-选择其一执行自身
            let finish_list = this.checkOtherListenWidgetFinish(true)
            // console.log('完成的控件列表=',finish_list)
            if(this.mDragData.is_select_anyone_execute_myself) {
                let is_execute_myself = false
                for (let index = 0; index < finish_list.length; index++) {
                    const element = finish_list[index];
                    if(element.is_execute_myself) {
                        is_execute_myself = true
                        break
                    }
                }
                if(is_execute_myself) {
                    // console.log('满足其中一个条件-执行自身')
                    onFinishEvent_cb()
                } else {
                    // 归位
                    setTimeout(()=>{
                        this.resetOriginPostion()
                    },50)
                }
            } 
            // 否-选择其一执行自身
            else {
                // 控件全部完成
                if(finish_list.length==this.mDragData.other_widget_finish_listen_list.length) {
                    // console.log('控件全部完成-执行自身')
                    onFinishEvent_cb()
                    return
                }

                // 同时满足
                let execute_count = 0
                let have_count = 0
                for (let i = 0; i < this.mDragData.other_widget_finish_listen_list.length; i++) {
                    const i_element = this.mDragData.other_widget_finish_listen_list[i]
                    if(i_element.is_execute_myself) {
                        execute_count+=1
                        for (let j = 0; j < finish_list.length; j++) {
                            const j_element = finish_list[j];
                            if(i_element.widget_id==j_element.widget_id) {
                                have_count+=1
                            }
                        }
                    }
                }

                if(execute_count>0) {
                    if(execute_count==have_count) {
                        // console.log('同时满足条件-执行自身')
                        onFinishEvent_cb()
                        return
                    }
                }

                // 归位
                setTimeout(()=>{
                    this.resetOriginPostion()
                },50)
            }
        }
        
        // 未完成控件,执行监控事件
        this.checkOtherListenWidgetFinish(false)
    }

    private checkOtherWidgetFinishListenListData():boolean {
        if(this.mDragData.other_widget_finish_listen_list==undefined){
            return false
        }
        if(this.mDragData.other_widget_finish_listen_list.length<=0){
            return false
        }
        return true
    }

    private checkOtherListenWidgetFinish(is_finish_status:boolean):other_widget_finish_listen_item[]{
        if(this.checkOtherWidgetFinishListenListData()==false) {
            return []
        }
        let list = gameManager.Singleton.checkWidgetList(this.mDragData.other_widget_finish_listen_list,is_finish_status)
        if(is_finish_status==false&&list.length>0) {
            // for (let index = 0; index < list.length; index++) {
            //     const event = list[index];
            //     gameManager.Singleton.exeEvent(event.event_id)
            // }
            // console.log('list=',list)
            // 未完成:其中有2,只执行2; 没有2,所有1执行; 没有2&&没有1,所有0执行;
            let hight_list:other_widget_finish_listen_item[] = []
            let middle_list:other_widget_finish_listen_item[] = []
            let normal_list:other_widget_finish_listen_item[] = []
            for (let index = 0; index < list.length; index++) {
                const event = list[index];
                if(event.grade>=2) {
                    hight_list.push(event)
                    break
                } else if(event.grade==1) {
                    middle_list.push(event)
                } else {
                    normal_list.push(event)
                }
            }

            let exeEvent_cb = ((item_list:other_widget_finish_listen_item[])=>{
                for (let index = 0; index < item_list.length; index++) {
                    const event = item_list[index];
                    gameManager.Singleton.exeEvent(event.event_id)
                }
            })

            if(hight_list.length>0) {
                middle_list = []
                normal_list = []
                exeEvent_cb(hight_list)
            } else {
                if(middle_list.length>0) {
                    normal_list = []
                    exeEvent_cb(middle_list)
                } else {
                    exeEvent_cb(normal_list)
                }
            }

        }
        return list;
    }

}


