import { gameRequestApi } from "@/api/common.js";
const {
    // getPlayCount,
    validGame,
    getGameRule,
    gamePlay,
    getGameNumberPolling
} = gameRequestApi;

const MemberCenterPath = "/pages/member-center/member-center/member-center-index";
const GameHomePath = "/pages/game/game-h5";
const OpenCardPath = "/pages/open-card/open-card/open-card";
const ShareWxaPath = "/pages/access-2-h5/h5-share/h5-share";
const IntegralDetailPath = "/pages/points-mall/points-detail/points-detail";
const CouponListPath = "/pages/member-center/coupon/coupon-list/coupon-list";

export function Manager(component) {

    let _component;
    if (component) {
        _component = component;
    }

    this.init = (component) => {
        _component = component;
    }

    const showAlert = (options) => {
        _component.alertOptions = options;
    }

    const hiddenAlert = () => {
        _component.alertOptions = {};
    }

    this.showTips = (message)=>{
        showAlert({
            show: true,
            content: message,
            cancel: () => {
                hiddenAlert();
            },
        });
    }


    const checkAttest = () => {
        return new Promise((resolve, reject) => {
            let query = _component.$route.query;
            if (+query.isAttest) {
                resolve();
                return;
            } else {
                reject();
                showAlert({
                    show: true,
                    content: "成为会员才可参与游戏哦~\n快认证成为会员赢好礼吧！",
                    buttonList: [
                        {
                            text: "立即认证",
                            click: () => {
                                hiddenAlert();
                                // TODO
                                openCard();
                            },
                        },
                    ],
                    cancel: () => {
                        hiddenAlert();
                    },
                });
            }
        });
    }

    const checkTime = () => {
        return new Promise((resolve, reject) => {
            let game = _component.game;
            let content = "无法参与游戏";
            switch (+game.status) {
                case 0:
                    content = "游戏还没开始，请耐心等待,\n去其他地方先逛逛吧~";
                    break;
                case 1:
                    resolve();
                    return;
                case 2:
                    content = "来晚一步，游戏已结束，\n去其他地方看看吧~";
                    break;
                case 3:
                    content = "来晚一步，游戏已结束，\n去其它地方看看吧~";
                    break;
                default:
                    break;
            }

            reject();
            showAlert({
                show: true,
                content: content,
                buttonList: [
                    {
                        text: "前往会员中心",
                        click: () => {
                            hiddenAlert();
                            // window.wx.miniProgram
                            // TODO
                            toMemberCenter();
                        },
                    },
                ],
                cancel: () => {
                    hiddenAlert();
                },
            });

        });
    }

    // const checkCount = () => {
    //     return new Promise((resolve, reject) => {

    //         let query = _component.$route.query;
    //         getPlayCount(query).then((res) => {
    //             let rule = _component.rule;
    //             if (rule.playTimes > res) {
    //                 resolve();
    //             } else {
    //                 reject();
    //                 showAlert({
    //                     show: true,
    //                     content: rule.giveawayType == '21' ? "今日免费次数已用完，明早继续" : '免费游戏次数已用完，去其他地方看看吧~',
    //                     buttonList: [
    //                         {
    //                             text: "前往会员中心",
    //                             click: () => {
    //                                 hiddenAlert();
    //                                 // TODO
    //                                 toMemberCenter();
    //                             },
    //                         },
    //                     ],
    //                     cancel: () => {
    //                         hiddenAlert();
    //                     },
    //                 });
    //             }
    //         }).catch(() => {
    //             resolve();
    //         })

    //     });
    // }

    const checkLimit = () => {
        return new Promise((resolve) => {
            validGame(_component.$route.query).then(resolve).catch((error) => {
                error = error || {};
                showAlert({
                    show: true,
                    title: "",
                    content: error.message || '网络异常',
                    cancel: () => {
                        hiddenAlert();
                    },
                })
            })
        })
    }

    
    const play = () => {
        let openTimePromise = new Promise((resolve)=>{
            setTimeout(()=>{
                resolve(1);
            },1500)
        })

        return new Promise((resolve,reject)=>{
            if (_component.isOpening) {
                reject();
                return;
            }
            _component.isOpening = true;
            Promise.all([gamePlay(_component.$route.query),openTimePromise]).then((values)=>{
                let res = values[0];
                setTimeout(() => {
                    _component.isOpening = false;
                }, 300)
                resolve(res)
            }).catch((res) => {
                console.log("res---->",res);
                _component.isOpening = false;
                reject(res);
                let content = "";
                let title = "";
                let buttonList = [
                    {
                        text: "前往会员中心",
                        click: () => {
                            hiddenAlert();
                            // TODO
                            toMemberCenter();
                        },
                    },
                ];
                switch (+res.code) {
                    case 2001:
                        // 游戏已结束
                        content = "来晚一步，游戏已结束，\n去其他地方看看吧~";
                        break;
                    case 2002:
                        // 游戏未开始
                        content = "游戏还没开始，请耐心等待，\n去其他地方看看吧~";
                        break;
                    case 2003:
                        // 游戏无权限
                        title = "很遗憾";
                        content = "您暂无权限参加本次游戏，\n详情请查看游戏规则";
                        buttonList = [{
                            text: "查看规则",
                            click: () => {
                                hiddenAlert();
                                _component.toGameRule();
                            },
                        }];
                        break;
                    case 2004:
                        // 抽奖次数已达上限
                        content = "游戏次数已达上限，\n去其他地方看看吧~";
                        break;
                    case 2005:
                        // 用户游戏抽奖次数小于0
                        title = "游戏剩余次数已用完";
                        content = `每邀请${_component.shareConditionObj.inviteNum}位好友助力即可获得${_component.shareConditionObj.value}次游戏机会哦~`;
                        buttonList = [{
                            text: "分享好友",
                            click: () => {
                                _component.shareWx();
                                hiddenAlert();
                            },
                        }, {
                            text: "分享朋友圈",
                            click: () => {
                                _component.sharePyq();
                                hiddenAlert();
                            },
                        }];
                        break;
                    case 2006:
                        // 用户积分不足
                        content = "积分不足，\n先去获取些积分吧~";
                        buttonList = [{
                            text: "立即获取积分",
                            click: () => {
                                hiddenAlert();
                                window.wx.miniProgram.navigateTo({
                                    url: '/' + _component.rule.dumpPath,
                                })
                            },
                        }];
                        break;
                    case 2007:
                        // 用户游戏抽奖今日免费次数小于0
                        content = "今日免费次数已用完，\n明早继续";
                        break;
                    case 2008:
                        // 用户游戏抽奖总免费次数小于0
                        content = "免费游戏次数已达上限，\n去其他地方看看吧~";
                        break;
                    default:
                        content = res.message || "系统异常";
                        buttonList = [];
                        break;
                }
                if (title || content) {
                    showAlert({
                        show: true,
                        title: title,
                        content: content,
                        buttonList: buttonList,
                        cancel: () => {
                            hiddenAlert();
                        },
                    })
                }
            })
        })
    }


    this.checkMyReward = () => {
        return new Promise((resolve, reject) => {
            let game = _component.game;
            let content = "无法参与游戏";
            switch (+game.status) {
                case 0:
                    content = "游戏还没开始，请耐心等待,\n去其他地方先逛逛吧~";
                    break;
                default:
                    resolve();
                    return;
            }
            reject();
            showAlert({
                show: true,
                content: content,
                buttonList: [
                    {
                        text: "前往会员中心",
                        click: () => {
                            hiddenAlert();
                            // window.wx.miniProgram
                            // TODO
                            toMemberCenter();
                        },
                    },
                ],
                cancel: () => {
                    hiddenAlert();
                },
            });

        })
            .then(checkAttest)
    }

    this.checkPlay = () => {
        return checkTime()
            .then(checkAttest)
            .then(checkLimit)
    }

    this.play = () => {
        // .then(checkCount)
        return this.checkPlay()
            .then(() => {
                return play();
            })
    }


    const openCard = () => {
        let query = _component.$route.query;
        let path = OpenCardPath;//小程序开卡页面，固定，不可更改
        let options = {
            type: 2,//  开卡之后要做的事件类型 1，开卡完成打开网页  2,开卡完成打开小程序页面
            data: {
                path: `${GameHomePath}?gameId=${query.gameId}&enterpriseId=${query.enterpriseId}&shareMemberId=${query.shareMemberId || ''}&isFrom=openCard`
            }
        }
        path += "?intent=" + encodeURIComponent(JSON.stringify(options));
        window.wx.miniProgram.navigateTo({
            url: path,
        });
    }

    const toMemberCenter = () => {
        window.wx.miniProgram.reLaunch({
            url: MemberCenterPath,
        });
    }

    this.shareWx = (shareOptions) => {
        // let shareOptions = {
        //     title: '',
        //     path: '',
        //     imageUrl: '',
        // };
        let url = `${ShareWxaPath}?shareOptions=${encodeURIComponent(JSON.stringify(shareOptions))}&content=邀好友助力加参与游戏次数，赢好礼&confirmText=立即分享`;
        window.wx.miniProgram.navigateTo({
            url,
        });
    }

    this.getConditionObj = function () {
        return new Promise((resolve, reject) => {
            let conditionObj = _component.conditionObj;
            if (conditionObj && conditionObj.gameId) {
                resolve(conditionObj)
                return;
            }
            let query = _component.$route.query;
            getGameRule({
                gameId: query.gameId,
                enterpriseId: query.enterpriseId,
            }).then((rule) => {
                let gameRuleConditionList = rule.gameRuleConditionList || [];
                gameRuleConditionList.map((item) => {
                    let obj = JSON.parse(item.conditionJson);
                    if (+obj.type == 11 || +obj.type == 12) {
                        conditionObj = obj;
                    }
                })
                _component.conditionObj = conditionObj;
                resolve(conditionObj)
            }).catch(reject)
        })
    }

    this.support = async () => {
        let query = _component.$route.query;
        
        if (query.memberId == query.shareMemberId) {
            showAlert({
                show: true,
                content: "无法为自己助力，赶快邀请好友助力",
                buttonList: [
                    {
                        text: "邀请好友助力",
                        click: () => {
                            hiddenAlert();
                            // window.wx.miniProgram
                            // TODO
                            _component.clickShareBtn();
                        },
                    },
                ],
                cancel: () => {
                    hiddenAlert();
                },
            });
            return;
        }

        let conditionObj = await this.getConditionObj();

        if (_component.helpDetail.helpStatus == 3) {
            showAlert({
                show: true,
                title: '',
                content: `很遗憾你已${conditionObj.type == 12 ? '关注服务号' : '认证'}，无法助力好友  可立即参与游戏，赢取好礼`,
                buttonList: [
                    {
                        text: "参与游戏赢好礼",
                        click: () => {
                            hiddenAlert();
                            _component.toPlayGame();
                        },
                    },
                ],
                cancel: () => {
                    hiddenAlert();
                },
            });
            return;
        }

        if (conditionObj.type == 11) {
            // 认证
            if (+query.isAttest) {
                // 已认证
                showAlert({
                    show: true,
                    content: "很遗憾，您已成为会员，无法助力好友，可立即参与游戏，赢取好礼",
                    buttonList: [
                        {
                            text: "参与游戏赢好礼",
                            click: () => {
                                hiddenAlert();
                                // window.wx.miniProgram
                                // TODO
                                _component.toPlayGame();
                            },
                        },
                    ],
                    cancel: () => {
                        hiddenAlert();
                    },
                });
            } else {
                showAlert({
                    show: true,
                    content: "仅差一步，您当前还不是会员，无法助力，立即认证成为会员，助力赢取好礼",
                    buttonList: [
                        {
                            text: "立即认证会员",
                            click: () => {
                                hiddenAlert();
                                // window.wx.miniProgram
                                // TODO
                                // 未认证
                                openCard();
                            },
                        },
                    ],
                    cancel: () => {
                        hiddenAlert();
                    },
                });

            }
        } else if (conditionObj.type == 12) {
            // 关注服务号
            _component.shareFwh(conditionObj);
        }
    }


    let pollingTimer;
    let playNumberPolling = async () => {
        let query = _component.$route.query;
        let res = await getGameNumberPolling({
            gameId: query.gameId,
            enterpriseId: query.enterpriseId,
            memberId: query.memberId
        })
        _component.playNumberObj.playNumber = res;
    }

    this.startPolling = () => {
        pollingTimer = setInterval(function () {
            playNumberPolling();
        }, 10000);
    }
    this.stopPolling = () => {
        clearInterval(pollingTimer);
    }



    this.toIntegralDetail = function () {
        window.wx.miniProgram.navigateTo({
            url: IntegralDetailPath,
        })
    }

    this.toCouponList = function () {
        window.wx.miniProgram.navigateTo({
            url: CouponListPath,
        })
    }

    return this;
}
