import i18n from "../../../i18n/i18n";
import { AudioMgr } from "../../../main/ViewManage";
import ViewObject from "../../../main/ViewObject";
import { HttpStateType, ReveData } from "../../../util/CHttp";
import GoodItem from "../../common/GoodItem";
import PetIcon from "../../common/PetIcon";
import FFCalAttr from "../../data/FFCalAttr";
import { __EquipQHData } from "../../data/sdata/SManage";
import { EquipAttr } from "../../data/udata/Player";
import Equip from "./Equip";
import EquipQHAttrItem from "./EquipQHAttrItem";
import EquipQHMax from "./EquipQHMax";
import EquipStar from "./EquipStar";
/**
 * 装备强化
 */
const { ccclass, property } = cc._decorator;

@ccclass
export default class EquipQH extends ViewObject {

    @property(GoodItem)
    mEquipItem: GoodItem = null;

    @property(cc.Label)
    mEquipName: cc.Label = null;//名字

    @property(cc.Node)
    mContent: cc.Node = null;//背包容器

    @property(cc.Prefab)
    mGoodItem: cc.Prefab = null;//道具节点

    @property(cc.Label)
    mQHLevel: cc.Label = null;//强化等级

    @property(cc.Label)
    mQHBfbLabel: cc.Label = null;//强化百分比

    @property(cc.ProgressBar)
    mQHBfbBar: cc.ProgressBar = null;//强化百分比

    @property(cc.Label)
    mQHMoney: cc.Label = null;//强化消耗的货币

    @property(cc.Node)
    mXhContent: cc.Node = null;//消耗容器

    @property(cc.Node)
    mBtSort: cc.Node = null;//排序按钮面板

    @property(cc.Node)
    mQHFull: cc.Node = null;//强化满级后显示
    @property(cc.Node)
    mFullWord: cc.Node = null;//满级后文字提示


    @property([EquipQHAttrItem])
    mQHAttrs: Array<EquipQHAttrItem> = [];//强化前后属性

    @property(cc.Node)
    mOneKeyBt: cc.Node = null;//一键放入按钮

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

    @property(sp.Skeleton)      // 强化动画
    spine1: sp.Skeleton = null;

    @property(sp.Skeleton)
    spine2: sp.Skeleton = null;

    /**
     * 装备界面
     */
    private equip: Equip = null;
    /**
     * 当前选中的伙伴
     */
    private petIcon: PetIcon = null;
    /**
     * 当前强化的装备
     */
    // private goodItem: GoodItem = null;
    /**
     * 当前选中的道具
     */
    private curGoodItem: Array<GoodItem> = []
    /**
     * 一键快捷回调
     */
    private oneKeyCallback: () => void;
    /**
     * 排序按钮回调
     */
    private sortCallback: (type: number) => void;

    public inGuide = false;//是否引导中
    public guideStep: number = 0;    //指引步骤
    public qhType: number = 0;  // 0 强化装备上的装备  1 强化背包的装备
    public equipAttr: EquipAttr = null;

    onLoad() {
        this.mBtSort.active = false
    }

    public init(equipAttr: EquipAttr, petIcon: PetIcon, equip: Equip) {
        this.qhType = 0;
        this.equip = equip
        this.petIcon = petIcon
        this.equipAttr = equipAttr
        this.mEquipItem.initEquip(this.main, equipAttr)
        this.mEquipName.string = i18n.t(this.main.sManage.getEquipById(equipAttr.id).name)
        for (let i = 0; i < 20; i++) {
            let node = cc.instantiate(this.mGoodItem);
            node.parent = this.mContent;
        }
        for (let i = 0; i < 10; i++) {
            let node = cc.instantiate(this.mGoodItem);
            node.parent = this.mXhContent;
        }

        this.checkToggle()


        this.node.getComponent(EquipQHMax).init(this.equip, petIcon, equipAttr)
        this.node.getComponent(EquipStar).init(this.equip, petIcon, equipAttr)
        this.scheduleOnce(() => {
            if (this.inGuide) {
                if (this.guideStep == 1) {
                    this.onGuide_1();
                }
            }
        }, 0.1);
    }
    /**
     * 选择当前页卡
     */
    public checkToggle() {
        let scrollView = this.mContent.parent.parent.getComponent(cc.ScrollView)
        scrollView.stopAutoScroll()
        scrollView.scrollToTop()
        this.mEquipItem.flushEquip(this.main)
        this.curGoodItem = []
        this.flushEquipPag();
        this.flushXH()
        this.setOneKeyCallback(() => {
            this.oneKeyPush()
        })
        this.setSortCallback((type: number) => {
            if (type == 0) {//品质排序
                EquipQH.sortPag(0, this.mContent)
            } else {//战力排序
                EquipQH.sortPag(1, this.mContent)
            }
        })
    }

    /**
     * 刷新属性
     */
    private flushAttr(PI) {
        let equipData = this.main.sManage.getEquipById(this.equipAttr.id);
        let __qhList = this.main.sManage.getEquipQHByType(equipData)
        //当前等级
        let curQHLevel = FFCalAttr.getEquipQHLevel(this.main, this.equipAttr.PI, equipData)
        //目标等级
        let qhLevel = FFCalAttr.getEquipQHLevel(this.main, PI, equipData)

        let maxQH = equipData.level + this.equipAttr.qhMax * 5;
        if (qhLevel >= maxQH) {//满级
            this.mQHFull.active = true
            qhLevel = maxQH
        } else {
            this.mQHFull.active = false
        }
        if (curQHLevel >= maxQH) {
            this.mOneKeyBt.active = false
        } else {
            this.mOneKeyBt.active = true
        }
        if (this.curGoodItem.length >= 10) {
            this.mQHFull.active = true
            this.mOneKeyBt.children[0].getComponent(cc.Label).string = '一键卸下'
        } else {
            this.mOneKeyBt.children[0].getComponent(cc.Label).string = '一键放入'
        }
        let tempAttrExp = 0

        let _qhAttr1: __EquipQHData = null //当前属性
        let _qhAttr2: __EquipQHData = null //目标属性
        let _qhAttr3: __EquipQHData = null //升级属性
        if (curQHLevel > 0) {
            _qhAttr1 = __qhList[curQHLevel - 1]
            tempAttrExp = _qhAttr1.exp
        }
        if (qhLevel > 0) {
            _qhAttr2 = __qhList[qhLevel - 1]
            tempAttrExp = _qhAttr2.exp
        }

        if (qhLevel >= __qhList.length) {
            _qhAttr3 = __qhList[qhLevel - 1]
        } else {
            _qhAttr3 = __qhList[qhLevel]
        }

        let tmpAdd = qhLevel - curQHLevel
        if (tmpAdd > 0) {
            this.mQHLevel.string = 'Lv.' + qhLevel + '/' + maxQH + '(+' + (tmpAdd) + ')';
        } else {
            this.mQHLevel.string = 'Lv.' + qhLevel + '/' + maxQH;
        }

        let curExp = PI - tempAttrExp
        let uplevelExp = _qhAttr3.exp - tempAttrExp

        let bfb = curExp / uplevelExp;
        if (bfb > 1) {
            bfb = 1
        }
        this.mQHBfbBar.progress = bfb
        this.mQHBfbLabel.string = Math.floor(bfb * 100) + '%'

        if (curQHLevel >= maxQH) {
            this.mFullWord.active = true
        } else {
            this.mFullWord.active = false
        }

        let tempEquipAttr = FFCalAttr.getEquipAttr(this.main, this.equipAttr, equipData)
        let equipAttr1 = cc.instantiate(this.equipAttr)
        equipAttr1.PI = PI
        let tempEquipAttr1 = FFCalAttr.getEquipAttr(this.main, equipAttr1, equipData)

        let atk1 = tempEquipAttr.atk
        let def1 = tempEquipAttr.def
        let hp1 = tempEquipAttr.hp
        let sd1 = tempEquipAttr.sp

        let atk2 = tempEquipAttr1.atk
        let def2 = tempEquipAttr1.def
        let hp2 = tempEquipAttr1.hp
        let sd2 = tempEquipAttr1.sp

        let arr1 = [atk1, def1, hp1, sd1]
        let arr2 = [atk2, def2, hp2, sd2]
        let index = 0
        for (let i = 0; i < 4; i++) {
            let v1 = arr1[i]
            let v2 = arr2[i]
            if (v1 > 0) {
                const element = this.mQHAttrs[index];
                element.setAttr(i, v1, v2)
                index++
            }
        }
        for (let i = index; i < this.mQHAttrs.length; i++) {
            const element = this.mQHAttrs[i];
            element.node.active = false
        }
    }
    /**
      * 刷新装备背包
      */
    public flushEquipPag() {
        let equip = this.main.player.equip;
        let index = 0;
        let content = this.mContent;
        for (let i = 0; i < equip.length; i++) {
            const element = equip[i];
            let equipData = this.main.sManage.getEquipById(element.id);
            if (equipData.type != 5 && equipData.type != 6 && equipData.type != 11) {
                if (this.mEquipItem.equip.__index != element.__index) {
                    if (index >= content.children.length) {
                        this.addGoodItem(content);
                    }
                    let node = content.children[index];
                    node.opacity = 255
                    let equipItem = node.getComponent(GoodItem);
                    equipItem.initEquip(this.main, element);
                    if (element.id >= 10000 && element.id < 20000) {
                        node.zIndex = 0
                    } else {
                        let zdl = FFCalAttr.getZdl(equipItem.equipData)
                        if (zdl > cc.macro.MAX_ZINDEX - 2) {
                            zdl = cc.macro.MAX_ZINDEX - 2
                        }
                        node.zIndex = zdl
                    }

                    equipItem.setCallback((gi) => {
                        this.main.playerEffectByPath(AudioMgr.qh2);
                        this.addEquip(gi);
                        this.guideCallback && this.guideCallback();
                    });
                    index++;
                } else {
                    this.qhType = 1;
                }
            }
        }

        for (let i = index; i < content.children.length; i++) {
            let node = content.children[i];
            node.opacity = 255
            let equipItem = node.getComponent(GoodItem);
            equipItem.setNull();
            node.zIndex = cc.macro.MAX_ZINDEX - 1
        }
    }


    private addGoodItem(content: cc.Node) {
        for (let i = 0; i < 4; i++) {
            let node = cc.instantiate(this.mGoodItem);
            node.parent = content;
        }
    }
    public setOneKeyCallback(oneKeyCallback: () => void) {
        this.oneKeyCallback = oneKeyCallback
    }
    /**
     * 一键放入
     */
    private oneKeyPush() {
        if (this.curGoodItem.length >= 10) {
            for (let i = 0; i < this.curGoodItem.length; i++) {
                const element = this.curGoodItem[i]
                element.node.opacity = 255
            }
            this.curGoodItem = []
        } else {
            for (let i = 0; i < this.curGoodItem.length; i++) {
                const element = this.curGoodItem[i]
                element.node.opacity = 255
            }
            this.curGoodItem = []
            let exp = 0
            for (let i = 0; i < 10; i++) {
                if (i >= this.mContent.children.length) {
                    break
                }
                const node = this.mContent.children[i];
                let equipItem = node.getComponent(GoodItem);
                if (equipItem.equip) {
                    equipItem.node.opacity = 100
                    exp += equipItem.equipData.qh_exp
                    exp += equipItem.equip.PI
                    let PI = this.equipAttr.PI + exp
                    this.curGoodItem.push(equipItem)
                    let qhLevel = FFCalAttr.getEquipQHLevel(this.main, PI, this.main.sManage.getEquipById(this.equipAttr.id))

                    let maxQH = this.main.sManage.getEquipById(this.equipAttr.id).level + this.equipAttr.qhMax * 5
                    if (qhLevel >= maxQH) {
                        break
                    }
                }
            }
        }
        this.flushXH()
    }
    private onclickOneKey() {
        if (this.oneKeyCallback) {
            this.oneKeyCallback()
        }
    }

    /**
     * 背包中的装备添加到消耗材料
     * @param goodItem 
     */
    private addEquip(goodItem: GoodItem) {
        if (goodItem.node.opacity == 100) {
            return
        }
        if (this.curGoodItem.length >= 10) {
            this.main.showTips(i18n.t('消耗材料以满'))
        } else {
            goodItem.node.opacity = 100
            this.curGoodItem.push(goodItem)
            this.flushXH()
        }
    }

    private removeEquip(goodItem: GoodItem) {
        for (let i = 0; i < this.curGoodItem.length; i++) {
            const element = this.curGoodItem[i];
            if (element.equip.__index == goodItem.equip.__index) {
                element.node.opacity = 255
                this.curGoodItem.splice(i, 1)
                break
            }
        }
        this.flushXH()
    }

    private flushXH() {
        let exp = 0
        for (let i = 0; i < this.mXhContent.children.length; i++) {
            const node = this.mXhContent.children[i];
            let tmpItem = node.getComponent(GoodItem)
            if (i < this.curGoodItem.length) {
                let goodItem = this.curGoodItem[i]
                tmpItem.initEquip(this.main, goodItem.equip)
                tmpItem.setCallback((gItem: GoodItem) => {
                    this.removeEquip(gItem)
                })
                exp += goodItem.equipData.qh_exp
                exp += goodItem.equip.PI
            } else {
                tmpItem.setNull()
            }
        }

        this.mQHMoney.string = '' + exp * 5

        let PI = this.equipAttr.PI + exp
        this.flushAttr(PI)
    }
    /**
     * 排序按钮
     */
    private onclickSort() {
        this.mBtSort.active = !this.mBtSort.active
    }

    public setSortCallback(sortCallback: (type: number) => void) {
        this.sortCallback = sortCallback
    }

    public static sortPag(type, content: cc.Node) {
        for (let i = 0; i < content.children.length; i++) {
            let node = content.children[i];
            let equipItem = node.getComponent(GoodItem);
            if (equipItem.equip) {
                if (equipItem.equipData.id == 20001) {
                    node.zIndex = 0
                } else if (equipItem.equipData.id >= 10000 && equipItem.equipData.id < 20000) {
                    node.zIndex = 0
                } else {
                    if (type == 0) {
                        node.zIndex = equipItem.equipData.pz
                    } else {
                        let zdl = FFCalAttr.getZdl(equipItem.equipData)
                        if (zdl > cc.macro.MAX_ZINDEX - 2) {
                            zdl = cc.macro.MAX_ZINDEX - 2
                        }
                        node.zIndex = zdl
                    }
                }
            } else {
                node.zIndex = cc.macro.MAX_ZINDEX - 1
            }
        }
    }


    private onclickStarSort() {
        this.mBtSort.active = false
        this.sortCallback(0)
    }
    private onclickZdlSort() {
        this.mBtSort.active = false
        this.sortCallback(1)
    }
    /**
     * 强化按钮
     */
    private onclickQHSend() {
        if (this.qhType == 0) {
            this.QHFcun();
        } else if (this.qhType == 1) {
            this.QHFcun1();
        }
    }

    QHFcun() {
        let removeEquips = []
        for (let i = 0; i < this.curGoodItem.length; i++) {
            const element = this.curGoodItem[i];
            removeEquips.push(element.equip.__index)
        }
        if (removeEquips.length == 0) {
            this.main.showTips("没有添加任何材料");
            return
        }
        let msg = {
            petId: this.petIcon.id,
            equipId: this.equipAttr.id,
            equips: removeEquips
        }
        this.main.gameHttp.sendJson('equip/v1/qh', msg, (state, reve: ReveData) => {
            this.main.stopLoad();
            if (state == HttpStateType.SUCCESS) {
                if (reve.retCode == 0) {
                    this.playQHSpine();
                    this.main.playerEffectByPath(AudioMgr.qh);
                    this.equipAttr.PI = reve.data.PI
                    this.curGoodItem = []
                    this.mEquipItem.flushEquip(this.main);
                    this.flushEquipPag()
                    this.equip.flushEquip(this.petIcon)
                    this.equip.flushPagSize()
                    this.flushXH()
                    if (this.inGuide) {
                        if (this.guideStep == 1) {
                            this.onGuideExit();
                        }
                    }
                    this.main.showTips('强化成功');
                } else {
                    this.main.showTips(reve.message);
                    if (this.inGuide) {
                        if (this.guideStep == 1) {
                            this.onGuideExit();
                        }
                    }
                }
            } else {
                this.main.showTips('网络异常');
            }
        });
    }

    QHFcun1() {
        let removeEquips = []
        for (let i = 0; i < this.curGoodItem.length; i++) {
            const element = this.curGoodItem[i];
            removeEquips.push(element.equip.__index)
        }
        if (removeEquips.length == 0) {
            this.main.showTips("没有添加任何材料");
            return
        }
        let msg = {
            equipIndex: this.mEquipItem.equip.__index,
            equips: removeEquips
        }
        this.main.gameHttp.sendJson('equip/v1/qh1', msg, (state, reve: ReveData) => {
            this.main.stopLoad();
            if (state == HttpStateType.SUCCESS) {
                if (reve.retCode == 0) {
                    this.playQHSpine();
                    this.main.playerEffectByPath(AudioMgr.qh);
                    this.equipAttr.PI = reve.data.PI
                    this.curGoodItem = []
                    this.mEquipItem.flushEquip(this.main);
                    this.equip.mEquipPack.setEquipType(this.equip.curPage);
                    this.flushEquipPag()
                    this.equip.flushEquip(this.petIcon)
                    this.equip.flushPagSize()
                    this.flushXH()
                    this.main.showTips('强化成功');
                } else {
                    this.main.showTips(reve.message);
                }
            } else {
                this.main.showTips('网络异常');
            }
        });
    }


    playQHSpine() {
        this.spine1.setAnimation(0, "atk", false);
        this.spine1.setCompleteListener(() => {
            this.spine1.setAnimation(0, "idle", false);
            this.spine2.node.active = true;
            this.spine2.setAnimation(0, "animation", false);
            this.spine2.setCompleteListener(() => {
                this.spine2.node.active = false;
                this.spine1.clearTrack(0);
            })
        })
    }


    /**
     * 引导中的点击回调
     */
    private guideCallback: () => void

    public setGuideCallback(guideCallback: () => void) {
        this.guideCallback = guideCallback
    }

    /**
    * 开始引导强化装备
    */
    private onGuide_1() {
        let guideMask = this.main.mGuideMask
        let targetNode = this.mContent.children[0];
        guideMask.setTargetNode(targetNode);
        guideMask.show();
        this.setGuideCallback(() => {
            targetNode = this.QHBtnNode;
            guideMask.setTargetNode(targetNode);
        })
    }

    public onGuideExit() {
        let guideMask = this.main.mGuideMask
        let targetNode = this.node.getChildByName("top_left").getChildByName("fh");
        guideMask.setTargetNode(targetNode)
        guideMask.show()

        let closeCallback = this.closeCallback

        this.setCloseCallback(() => {
            guideMask.close();
            if (closeCallback) {
                closeCallback()
            }
        })

    }

}
