import User from "../../FrameWork/User/User";
import AppPlatform from "../../FrameWork/Util/AppPlatform";
import Common5 from "../../Platform/th/Common5";
import UserManager from "../Manager/UserManager";
import GetAward from "../SCommon/GetAward";
import PrefabManage, { GameType } from "../PrefabManager/PrefabManage";
import ChatManager from "./ChatManager";
import ChatSoundPlay from "./ChatSoundPlay";
import JuQingManager from "./JuQingManager";
import GameReport, { ENTERTYPE } from "../../FrameWork/Report/ZyZyReport";
import TaskManager from "./TaskManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class ChatDialog extends cc.Component {
    //聊天内容
    @property(cc.Node)
    chatInfoNode: cc.Node = null
    @property(cc.Node)
    chatInfoContent: cc.Node = null
    @property(cc.Node)
    contentItemLeft: cc.Node = null
    @property(cc.Node)
    contentItemRight: cc.Node = null

    //选择回复选项
    @property(cc.Node)
    selectBottomNode: cc.Node = null
    @property(cc.Node)
    answerItem: cc.Node = null
    @property(cc.Node)
    answerZhuanZhangItem: cc.Node = null
    @property(cc.Node)
    zhuanzhangNode: cc.Node = null

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


    // @property(cc.Node)
    // successNode:cc.Node = null
    // @property(cc.Node)
    // failNode:cc.Node = null

    curJsonName = null//当前json文件名
    curIndexStr = null
    curPersonConversationJson = null//当前用户的聊天记录json
    historyRecordArray = []//保存每一句对话的id
    curDay = 0//当天
    backBtn: cc.Node = null
    curTimer = null

    chatBaseConfig = null;
    finishDialogCallFunc = null
    onLoad() {

    }
    //点击进入聊天
    enterDialog(jsonName, indexStr, finishDialogCallFunc?) {
        this.finishDialogCallFunc = finishDialogCallFunc
        //Common5.playEffect("sound/按键点击")
        this.curDay = User.getDay()

        // //这里打个补丁,需要用到场景的返回按钮,返回到聊天列表
        // let canvas = cc.director.getScene().getChildByName('Canvas')
        // let back = canvas.getChildByName("topNodeShow2").getChildByName("back")
        // if(back){
        //     this.backBtn = cc.instantiate(back)
        //     this.backBtn.parent = canvas
        //     this.backBtn.active = true
        //     Common5.setNodeToTargetPos(this.backBtn,back)

        //     var clickEventHandler = new cc.Component.EventHandler();
        //     clickEventHandler.target = this.node; //这个node节点是你的事件处理代码组件所属的节点
        //     clickEventHandler.component = "Chat";//这个是代码文件名
        //     clickEventHandler.handler = "onBtnCloseClick";
        //     clickEventHandler.customEventData = "xxx";

        //     var button = this.backBtn.addComponent(cc.Button);
        //     button.clickEvents = []
        //     button.clickEvents.push(clickEventHandler);
        // }

        //console.log("获取聊天数据==",User.getAllChatRecordData()) 
        this.chatInfoContent.removeAllChildren()
        //聊天的对象人名
        this.curJsonName = jsonName
        this.curIndexStr = indexStr



        //获取json配置
        this.curPersonConversationJson = ChatManager.getPersonConfig(this.curJsonName)


        //console.log(this.curPersonConversationJson, 'this.curPersonConversationJson+++++++++++++==')
        let chatPerson = ChatManager.getConfigByJsonName(this.curJsonName)
        this.chatBaseConfig = chatPerson;                                     //add by sxb20230306 保存当前聊天的基本配置信息
        let personName = ChatManager.getNameByJson(this.curJsonName)
        this.historyRecordArray = []

        // this.chatListNode.active = false
        this.chatInfoNode.active = true
        this.chatInfoNode.getChildByName("tittleStr").getComponent(cc.Label).string = personName
        // let allRecord = ChatManager.getAllChatRecordData()//User.getChatData()
        // let personJson = ChatManager.getPersonConfig(this.curJsonName)
        let recordData = ChatManager.getChatRecordDataByJson(this.curJsonName)

        let firstChatId = 0


        let callFunc = () => {
            let isFinish = false//该条聊天记录是否结束
            for (let i = 0; i < recordData.length; i++) {
                if (recordData[i].indexStr == this.curIndexStr) {
                    isFinish = recordData[i].isFinish
                    break
                }
            }

            console.log(isFinish, '该条聊天记录结束')
            if (isFinish) {
                this.exitNode.active = true
                this.node.getChildByName('EndGame').active = true
                this.showChatHistory(recordData)
            } else {
                for (var j = 0; j < this.curPersonConversationJson.length; j++) {
                    if (this.curPersonConversationJson[j].indexStr == this.curIndexStr) {
                        firstChatId = this.curPersonConversationJson[j].id
                        break
                    }
                }
                this.showCurDayChatContent(firstChatId, true)
            }
        }
        if (this.curIndexStr) {
            callFunc()
        } else {
            //优先显示未完成对话的第一条
            for (let i = 0; i < recordData.length; i++) {
                if (!recordData[i].isFinish) {
                    this.curIndexStr = recordData[i].indexStr
                    callFunc()
                    return
                }
            }
            //显示已聊天的最后一条
            this.curIndexStr = recordData[recordData.length - 1].indexStr
            callFunc()
            return
        }

    }

    //显示特定天的聊天信息
    showDayChatInfo(isShowRecord, dayArr) {
        let config = this.curPersonConversationJson
        //不需要对话,只显示记录
        if (isShowRecord) {

            //只显示对话,不显示记录
        } else {
            for (var i = 0; i < config.length; i++) {
                if (config[i].dayIndex == dayArr) {
                    this.showCurDayChatContent(config[i].id, true)
                    return
                }
            }
        }

    }
    //显示聊天记录
    showChatHistory(recordData) {
        for (let i = 0; i < recordData.length; i++) {
            if (recordData[i].isFinish) {
                for (var j = 0; j < this.curPersonConversationJson.length; j++) {
                    if (this.curPersonConversationJson[j].indexStr == recordData[i].indexStr) {
                        this.showCurDayChatContent(this.curPersonConversationJson[j].id, false)
                    }
                }
            }
        }
        // let allRecord = User.getChatData()
        // //console.log('allRecord',allRecord);
        // let curPersonRecord = allRecord[this.curJsonName]
        // //console.log('curPersonRecord',curPersonRecord)
        // if(curPersonRecord && curPersonRecord["finishIndex"]){
        //     for(var i=0;i<curPersonRecord["finishIndex"].length;i++){
        //         //console.log('curPersonRecord["finishIndex"][i]',curPersonRecord["finishIndex"][i],curPersonRecord["finishIndex"])
        //         this.showCurDayChatContent(curPersonRecord["finishIndex"][i],false)
        //     }
        // }    
    }
    getIndexById(id) {
        let idIndex = 0
        let config = this.curPersonConversationJson
        for (var i = 0; i < config.length; i++) {
            if (config[i].id == id) {
                idIndex = i
                break
            }
        }
        return idIndex
    }
    //显示对话聊天信息
    showCurDayChatContent(id, isNeedShowAnswer) {
        let idIndex = id;//this.getIndexById(id)

        let curItem = null
        console.log('showCurDayChatContent inIndex', idIndex);
        let chatMsg = this.getChatMsg(idIndex);
        if (chatMsg.speaker == "me") {
            curItem = this.contentItemRight
        } else if (chatMsg.speaker == "other") {
            curItem = this.contentItemLeft
            Common5.playEffect('微信来消息')
        }
        /*
        * add by sxb 2023-3-6
        * 新增一个群聊的逻辑
        */
        else if (this.chatBaseConfig.qunLiaoType == 'group' && chatMsg.speaker != "me") {
            curItem = this.contentItemLeft
        }
        //end 


        let childItem = cc.instantiate(curItem)
        childItem.active = true
        let chatPerson = ChatManager.getConfigByJsonName(this.curJsonName)

        // 2023-3-6 sxb新增群聊的逻辑补丁
        if (this.chatBaseConfig.qunLiaoType == 'group' && chatMsg.speaker != "me") {
            chatPerson = ChatManager.getConfigByJsonName(chatMsg.speaker)
        }
        //end

        //console.log('chatPerson',chatPerson);
        if (chatMsg.speaker == "me") {
            Common5.addUrlSprite_custom("head/男主", childItem.getChildByName("avatar").getComponent(cc.Sprite));

        } else {
            if (chatPerson) {

                Common5.addUrlSprite_custom("head/" + chatPerson.imgPath, childItem.getChildByName("avatar").getComponent(cc.Sprite));
            } else {

                Common5.addUrlSprite_custom("head/" + chatMsg.speaker, childItem.getChildByName("avatar").getComponent(cc.Sprite));
            }

        }

        if (chatMsg.contentType == "word") {
            childItem.getChildByName("chatBg").active = true
            let contentStr = childItem.getChildByName("chatBg").getChildByName("contentStr")
            contentStr.getComponent(cc.Label).string = chatMsg.contentDesc
            contentStr.getComponent(cc.Label)["_forceUpdateRenderData"](true);
            //换行
            if (contentStr.width > cc.winSize.width * 0.7) {
                contentStr.width = cc.winSize.width * 0.7
                contentStr.getComponent(cc.Label).overflow = cc.Label.Overflow.RESIZE_HEIGHT;
                contentStr.getComponent(cc.Label)["_forceUpdateRenderData"](true);
            }
        } else if (chatMsg.contentType == "img") {
            let chatSprite = childItem.getChildByName("chatSprite")
            console.log('chatMsg.imgPath', chatMsg.contentPath);
            // Common5.getSpriteFrameFromBundle("allRes",chatMsg.contentPath,chatSprite.getComponent(cc.Sprite));
            Common5.addUrlSprite_custom(chatMsg.contentPath, chatSprite.getComponent(cc.Sprite));

            chatSprite.active = true
        } else if (chatMsg.contentType.toUpperCase() == "ZHUANZHANG") {
            //新增转账类型

            let chatSprite = childItem.getChildByName("chatSprite")
            let zhuanzhuangImg = 'JuQingChat/texture/微信聊天/wxzz/';
            let money = parseFloat(chatMsg.contentDesc)
            if (chatMsg.speaker == 'me') {
                zhuanzhuangImg = zhuanzhuangImg + 'wxzhuanzhang3';
            } else {
                let isShouKuan = cc.sys.localStorage.getItem(`${chatMsg.indexStr}_${chatMsg.id}_zhuanzhang`) ?? '未收款';
                if (isNeedShowAnswer || isShouKuan == "未收款") {
                    zhuanzhuangImg = zhuanzhuangImg + 'wxzhuanzhang4';
                    chatSprite.attr({ id: id, money: money, type: 'zhuanzhang', status: '未收款' })
                    cc.sys.localStorage.setItem(`${chatMsg.indexStr}_${chatMsg.id}_zhuanzhang`, "未收款");
                } else {
                    zhuanzhuangImg = zhuanzhuangImg + 'wxzhuanzhang1';
                }
            }
            Common5.getSpriteFrameFromBundle("GameRes", zhuanzhuangImg, chatSprite.getComponent(cc.Sprite));
            chatSprite.active = true
        } else if (chatMsg.contentType == "TeShuWuPin") {
            //新增转账类型

            let chatProp = childItem.getChildByName("chatProp")
            let id = parseFloat(chatMsg.contentDesc)
            let img = 'CommonRes/image/icon/' + id;

            if (chatMsg.speaker == 'me') {

            } else {
                if (isNeedShowAnswer) {
                    chatProp.attr({ iconId: id, type: 'TeShuWuPin', status: '未接收' })
                    chatProp.getChildByName("ADIcon").active = true
                } else {
                    chatProp.getChildByName("ADIcon").active = false
                }
            }
            Common5.getSpriteFrameFromBundle("allRes", img, chatProp.getComponent(cc.Sprite));
            chatProp.active = true
        } else if (chatMsg.contentType.toUpperCase() == "SOUND") {
            let chatSound = childItem.getChildByName("chatSound")
            chatSound.attr({
                sound: chatMsg.contentPath.split('|')[0]
            })
        }

        this.historyRecordArray.push(id)
        this.chatInfoContent.addChild(childItem)
        //this.chatInfoNode.getChildByName("chatContentScrollview").getComponent(cc.ScrollView).scrollToBottom(0.1)

        this.scheduleOnce(() => {
            this.chatInfoNode.getChildByName("chatContentScrollview").getComponent(cc.ScrollView).scrollToBottom(0.1)
        })
        //console.log('isNeedShowAnswer',isNeedShowAnswer)
        if (isNeedShowAnswer) {
            this.showNextAnswer(idIndex)
        }

    }
    //显示我的回复选项
    showNextAnswer(curId) {
        let callFunc = () => {
            this.selectBottomNode.getChildByName("myAnswerSelectNode").removeAllChildren()
            console.log('curId', curId)
            let chatMsg = this.getChatMsg(curId);
            let selectArr = chatMsg.next
            if (selectArr) {
                for (var i = 0; i < selectArr.length; i++) {
                    let selectId = selectArr[i]
                    let idIndex = selectId;//this.getIndexById(selectId)
                    chatMsg = this.getChatMsg(idIndex);
                    if (chatMsg.speaker == "me") {
                        let childItem = null;
                        let contentStr = chatMsg.contentDesc
                        if (chatMsg.contentType.toUpperCase() == "ZHUANZHANG") {
                            childItem = cc.instantiate(this.answerZhuanZhangItem)
                            contentStr = '转账 ' + chatMsg.contentDesc
                        } else if (chatMsg.contentType == "TeShuWuPin") {
                            //这里未处理?
                            childItem = cc.instantiate(this.answerItem)
                        } else {
                            childItem = cc.instantiate(this.answerItem)
                        }
                        if (contentStr.length > 11) {
                            contentStr = contentStr.substr(0, 11) + "..."
                        }

                        childItem.getChildByName("contentStr").getComponent(cc.Label).string = contentStr
                        childItem.attr({ selectIndex: selectArr[i], curId: curId })
                        childItem.active = true
                        this.selectBottomNode.active = true
                        this.selectBottomNode.getChildByName("myAnswerSelectNode").addChild(childItem)
                    } else if (chatMsg.speaker == "other") {
                        Common5.playEffect('手机收到消息')
                        this.showCurDayChatContent(selectArr[i], true)

                    }
                    //20230306 add by sxb for 群聊
                    else if (this.chatBaseConfig.qunLiaoType == 'group' && chatMsg.speaker != 'me') {
                        Common5.playEffect('手机收到消息')
                        this.showCurDayChatContent(selectArr[i], true)
                    }
                }
            } else {
                this.checkIsFinishConversation(curId)
            }

        }
        this.curTimer = setTimeout(() => {
            callFunc()
        }, 1000);
    }
    //点击选择回复
    onMySelectItemClick(event) {
        let selectIndex1 = event.target.selectIndex
        let curId = event.target.curId;
        this.selectBottomNode.active = false
        this.selectBottomNode.getChildByName("myAnswerSelectNode").removeAllChildren()

        let chatMsg = this.getChatMsg(selectIndex1);
        if (chatMsg.contentType.toUpperCase() == "ZHUANZHANG") {
            if (User.getMoney() < Number(chatMsg.contentDesc)) {
                PrefabManage.showTextTips("金钱不够,不能转账")
                return
            }
            this.zhuanzhangNode.getChildByName('money').getChildByName('w').getComponent(cc.Label).string = chatMsg.contentDesc;
            this.zhuanzhangNode.attr({ selectIndex: selectIndex1, curId: curId });
            this.zhuanzhangNode.active = true;
        } else if (chatMsg.contentType == "TeShuWuPin") {
            //这里未处理?
            this.showCurDayChatContent(selectIndex1, true)
        } else {
            Common5.playEffect('sound/微信发消息')
            this.showCurDayChatContent(selectIndex1, true)
        }
    }
    getChatMsg(selectIndex1) {
        let chatMsg = ChatManager.getChatMsgByIndex(this.curPersonConversationJson, selectIndex1);
        if (chatMsg == null) {
            Common5.showTips_custom('index配置出错')
            return;
        }
        return chatMsg;
    }
    //检测对话是否结束
    checkIsFinishConversation(curId) {
        let chatMsg = this.getChatMsg(curId);
        if (chatMsg.isFinish) {
            // let chatPeriodTab = User.getChatPeriodTab()
            // User.setChatData(this.curJsonName,this.historyRecordArray,chatMsg.dayIndex+chatPeriodTab.curDay);
            ChatManager.setChatRecordData(this.curJsonName, this.curIndexStr, true)
            this.finishDialogCallFunc && this.finishDialogCallFunc()
            if (this.curJsonName == 'WX_ShenMiRen') {

            } else {
                JuQingManager.finishCurJuQing(this.curIndexStr, chatMsg.unLockJuQingIndex)
            }

            if (chatMsg.isSuccess) {
                console.log("对话结束==,成功!")
                this.exitNode.active = true
                this.node.getChildByName('EndGame').active = true

                cc.tween(this.node)
                    .delay(1.0)
                    .call(() => {
                        //this.onBtnCloseClick()
                    })
                    .start()
            } else {
                console.log("对话结束==,失败!")
                this.exitNode.active = true
                this.node.getChildByName('EndGame').active = true
                cc.tween(this.node)
                    .delay(1.0)
                    .call(() => {
                        //this.successNode.active = false
                        //this.failNode.active = true
                    })
                    .start()
            }
        }
    }
    onBtnShareClick() {
        //Common5.playEffect("sound/按键点击")
        console.log('=================聊天分享函数')


    }
    protected onDestroy(): void {
        clearTimeout(this.curTimer);
    }
    onBtnCloseClick() {
        //Common5.playEffect("sound/按键点击")
        clearTimeout(this.curTimer);
        this.selectBottomNode.active = false
        this.backBtn.active = false
        // this.successNode.active = false
        // this.failNode.active = false

        this.chatInfoNode.active = false

        this.zhuanzhangNode.active = false;

    }
    onZhuanzhangClick(event) {
        let zhuanzhang = event.target;
        console.log(zhuanzhang.status, zhuanzhang.type, 'zhuanzhang+++111')
        if (zhuanzhang.type &&
            zhuanzhang.type == 'zhuanzhang' &&
            zhuanzhang.money &&
            zhuanzhang.status &&
            zhuanzhang.status == '未收款') {


            let tab = {
                onClose: (finish) => {
                    if (finish) {
                        User.setShowAdNum(User.getShowAdNum() + 1)
                        Common5.ReportDY("inLevel", `任务${TaskManager.getCurUnLockMainTaskId()}-AD-手机领取红包`)
                        // Common5.ReportDY("inLevel", "手机-AD-领取红包");
                        let money = parseFloat(zhuanzhang.money);
                        UserManager.addMoney(money, zhuanzhang);
                        // Common5.showMoneyFlyParticle(zhuanzhang);
                        zhuanzhang.attr({ status: '已收款' })

                        let chatMsg = this.getChatMsg(zhuanzhang.id);
                        cc.sys.localStorage.setItem(`${chatMsg.indexStr}_${chatMsg.id}_zhuanzhang`, "已收款");

                        let zhuanzhuangImg = 'JuQingChat/texture/微信聊天/wxzz/wxzhuanzhang1';
                        Common5.getSpriteFrameFromBundle("GameRes", zhuanzhuangImg, event.target.getComponent(cc.Sprite));

                    } else {
                        Common5.showTips_custom("广告未观看完");
                    }
                }, onFailed: () => {

                }
            }
            AppPlatform.playVideo_custom(tab)


        }



    }
    onPropClick(event) {
        // chatProp.attr({iconId: id, type: 'TeShuWuPin', status:'未接收'})
        //             chatProp.getChildByName("ADIcon").active = true

        let propNode = event.target;
        // console.log(zhuanzhang.status, zhuanzhang.type, 'zhuanzhang+++111')
        if (propNode.type &&
            propNode.type == 'TeShuWuPin' &&
            propNode.iconId &&
            propNode.status &&
            propNode.status == '未接收') {


            let tab = {
                onClose: (finish) => {
                    if (finish) {
                        User.setShowAdNum(User.getShowAdNum() + 1)
                        Common5.ReportDY("inLevel", `任务${TaskManager.getCurUnLockMainTaskId()}-AD-手机领取道具`)
                        // Common5.ReportDY("inLevel", "手机-AD-领取道具");
                        propNode.attr({ status: '已接收' })

                        event.target.getChildByName("ADIcon").active = false
                        // let zhuanzhuangImg = 'GameRes/ui/chat/wxzz/wxzhuanzhang1';
                        // Common5.getSpriteFrameFromBundle("allRes",zhuanzhuangImg,event.target.getComponent(cc.Sprite));
                        let goodArray = [{ goodId: propNode.iconId, goodNum: 1 }]
                        PrefabManage.loadPrefabByType(GameType.GetAward, null, (prefabNode) => {
                            prefabNode.getComponent(GetAward).initView(goodArray, () => {

                            });
                        }, true)

                    } else {
                        Common5.showTips_custom("广告未观看完");
                    }
                }, onFailed: () => {

                }
            }
            AppPlatform.playVideo_custom(tab)


        }
    }

    onZhuanzhangCloseClick(event) {
        let curId = this.zhuanzhangNode["curId"];
        this.zhuanzhangNode.active = false;
        this.zhuanzhangNode.getChildByName('money').getChildByName('w').getComponent(cc.Label).string = '0.00';

        this.showNextAnswer(curId);
    }
    onZhuanzhangOkCloseClick(event) {
        let selectIndex = this.zhuanzhangNode["selectIndex"]
        let money = parseFloat(this.zhuanzhangNode.getChildByName('money').getChildByName('w').getComponent(cc.Label).string);
        if (money > UserManager.getCurMoney()) {
            console.log('钱不够啊');
            // Common5.showCommonTips();
            PrefabManage.showTextTips("金额不够,无法转账")
            this.exitNode.active = true
            //this.node.getChildByName('EndGame').active = true
        } else {
            UserManager.subMoney(money);
            //Common5.playEffect('手机信息回复')
            this.showCurDayChatContent(selectIndex, true)
            this.zhuanzhangNode.active = false;

            GameReport.EnterReport(ENTERTYPE.XUANGUAN, '转账' + money)
        }

    }
    onChatSoundClick(event) {
        let node_: cc.Node = event.target;
        let sound = event.target.sound;
        Common5.playEffect(sound);
        node_.getChildByName('soundrecv').getComponent(ChatSoundPlay).isPlay = true;
        cc.tween(this.node)
            .delay(2.0)
            .call(() => {
                node_.getChildByName('soundrecv').getComponent(ChatSoundPlay).isPlay = false;
            })
            .start();
    }
    // onBtnRestartClick(){

    // }

    itemLeftClickEvent(event) {
        let target = event.target
        console.log('itemLeftClickEvent')
    }



}