import {cache} from "$utils/request/cache";
import $request, {InstructionsCacheType, InstructionsMessageType} from "$utils/request";
import popup from "$utils/tool/popup";
import {PopupExportComponent} from "$popup/popup-export/const";
import user from "$config/user";
import params from '$utils/tool/params';
import globalConfig from '$config/config';


enum OpenType {
    room,
    play,
    user
}

export default {

    openUnique:'',

    updateCache(data:Record<string, any>,ids:Array<string>=[]){

        if (!data) return;

        ids.push('get_base_user_info-'+data.uid);

        ids.map((item)=> this.triggerUpdateCache(data,item));

        // let cacheSign =cache.getSign('get_base_user_info-'+data.uid);
        //
        // let cacheData = cache.getCache(cacheSign);
        // // 更新缓存
        // if (cacheData && cacheData.data.data) {
        //     let cacheItem = cacheData.data.data.data;
        //     let is_follow = data.status ? 1 : 0;
        //     let use_follow = is_follow ? 2 : 1;
        //     if (cacheItem.is_follow !== use_follow) {
        //         cacheItem.fans_num = cacheItem.fans_num + (is_follow ? 1 : -1);
        //         cacheItem.fans_num = cacheItem.fans_num < 0 ? 0 :cacheItem.fans_num;
        //         cacheItem.is_follow = use_follow;
        //         console.log(cacheItem);
        //         cache.updateCache(cacheSign,cacheData.data);
        //     }
        // }
    },

    triggerUpdateCache(data,id){
        let cacheSign =cache.getSign(id);

        let cacheData = cache.getCache(cacheSign);
        // 更新缓存
        if (cacheData && cacheData.data.data) {
            let cacheItem = cacheData.data.data.data;
            let is_follow = data.status ? 1 : 0;
            let use_follow = is_follow ? 2 : 1;
            if (cacheItem.is_follow !== use_follow) {
                if (cacheItem.fans_num !== undefined) {
                    cacheItem.fans_num = cacheItem.fans_num + (is_follow ? 1 : -1);
                    cacheItem.fans_num = cacheItem.fans_num < 0 ? 0 :cacheItem.fans_num;
                }
                cacheItem.is_follow = use_follow;
                cache.updateCache(cacheSign,cacheData.data);
            }
        }
    },

    openStatus: false,

    openDetail(resultItem:Record<string, any>,type:OpenType = OpenType.play){
        if (!user.isLogin()) return  popup.$open(PopupExportComponent.login);
        if (type === OpenType.play) {
            return this.openDetailTarget(resultItem);
        } else if (type === OpenType.user) {
            return this.openUserContent(resultItem);
        } else if (type === OpenType.room) {
            if (resultItem.is_need_password === 2){
                return  this.verifyPassword(resultItem);
            } else {
                return  this.routerRoom(resultItem);
            }
        }

    },

    openUserContent(resultItem) {
        return popup.$open(PopupExportComponent.chat,{
            user:resultItem
        });
    },

    verifyPassword(resultItem){

        return popup.$popup.open(PopupExportComponent.password,{
            placeholder:'请输入房间密码',
            confirm:(value)=>{
                return new Promise(  (resolve, reject)=> {

                    $request({
                        url:'room/enter_room_info',
                        data:{
                            rid: resultItem.rid,
                            password:value
                        },
                        cache:{
                            type: InstructionsCacheType.memory
                        },
                        token:true,
                        failMessage:true,
                        message:InstructionsMessageType.other
                    }).then((data)=>{

                        if (data.isSuccess) {
                            resolve(false);
                            return this.routerRoom(resultItem,value,{
                                infoData:JSON.stringify(data.data)
                            });
                        } else {
                            reject();
                        }

                    }).catch(reject);

                });
            }
        });

    },

    routerRoom(resultItem,password='',temporaryParams:Record<string, any>={}){

        return  globalConfig.app && globalConfig.app.$router.push(params.createParams({
            name:'talking',
            params:{
                rid:resultItem.rid,
                tid:resultItem.tid,
                room_number:resultItem.room_number,
                room_name: resultItem.room_name,
                room_cover: resultItem.room_cover,
                password,
                back:1
            },
            temporaryParams:temporaryParams
        }));
    },

    openDetailTarget(resultItem:Record<string, any>){

        // 如果不登录触发!user.verificationLogin() ||
        // if ( this.openStatus) return;

        this.clearTargetDetail();

        // this.openStatus = true;

        // popup.$loading({
        //     title:'获取中',
        //     delay:1000
        // });

        popup.$popup.open(PopupExportComponent.detail);

        this.openUnique = +new Date() +'_' + Math.ceil(Math.random() * 10000);

        let openUnique = this.openUnique;

        if (resultItem.pid) {
            return this.getUserInfo(resultItem,openUnique);
        } else if (resultItem.uid){

            return  $request({
                url:'player/get_player_list',
                data:{
                    uid: resultItem.uid,
                },
                token:true,
                page:{
                    page:1,
                    pageSize:1
                },
                cache:{
                    type: InstructionsCacheType.memory
                }
            }).then((data)=>{

                if (data.data.length > 0) {

                    resultItem.pid = data.data[0].pid;

                    return this.getUserInfo(resultItem,openUnique);

                } else {
                    return this.clearTargetDetail('获取失败');
                }


            }).catch(()=> this.clearTargetDetail('服务繁忙'));

        }

    },

    // 获取信息
    getUserInfo(useResultItem:Record<string, any>,openUnique){
        return Promise.all([this.getPlayInfo(useResultItem),this.getPlayList(useResultItem),this.getDetail(useResultItem)]).then(([info,playData,detail])=>{
            this.clearTargetDetail();

            playData = playData.data.palyer_game_list || [];

            let unshiftData;

            let resultData = [];

            playData.map((item,index)=>{

                let resultItem = {
                    label: item.game_name,
                    slot: 'tab-'+index,
                    pid: item.pid,
                    price: item.price
                }

                if (item.pid === useResultItem.pid) {
                    unshiftData = resultItem;
                } else {
                    resultData.push(resultItem);
                }

            });

            unshiftData && resultData.unshift(unshiftData);

            info = info.data || {};

            info.gameList = resultData;

            if (detail) {
                info.gameInfo = {
                    [useResultItem.pid]:detail
                }
            }

            // info
            if (!info.images) {
                info.images = [info.head_pic];
            } else {
                info.images = info.images.split(',');
            }

            if (this.openUnique === openUnique) {
                popup.$popup.open(PopupExportComponent.detail,{
                    option: info
                });
            }

        }).catch(()=> this.clearTargetDetail('服务繁忙'))
    },

    // 下单
    placeOrder(number,gameList=[],userInfo){

        let currentItem = {};
        let options = {
            number: number,
            gameList: gameList.map((item)=>{

                let price = parseFloat(item.price);
                let intPrice = parseInt(item.price);

                if (intPrice === price) {
                    price = intPrice;
                }

                let target = {
                    label: item.label || item.game_name,
                    value: item.pid,
                    price: price,
                    number: 1
                };
                if (item.pid === userInfo.pid) {
                    currentItem = target;
                    target.number = number;
                }
                return target
            }),
            item:currentItem,
            value: userInfo.pid,
            user: {
                header_pic: userInfo.head_pic,
                nick_name: userInfo.nick_name,
                uid: userInfo.uid
            }
        };

        return popup.$popup && popup.$popup.open(PopupExportComponent.order,{
            option:options
        });

    },


    clearTargetDetail(fail?:string){
        popup.hideLoading();
        this.openStatus = false;
        if (fail) {
            popup.$toast(fail);
        }

    },

    // 获取陪玩基本信息
    getPlayInfo(item:Record<string, any>) {
        return $request({
            url:'hxuser/get_base_user_info',
            data:{
                uid: item.uid
            },
            cache:{
                type: InstructionsCacheType.memory,
                id: 'get_base_user_info-'+item.uid
            },
            token:true
        });
    },

    // 获取陪玩下的游戏列表
    getPlayList(item:Record<string, any>){
        return $request({
            url:'player/get_player_game_lists',
            data:{
                pid: item.pid
            },
            cache:{
                type: InstructionsCacheType.memory
            },
            token:true
        })
    },

    // 获取陪玩当前游戏的详情
    getDetail(item:Record<string, any>){

        return new Promise((resolve)=>{
            $request({
                url:'player/get_player_info',
                data:{
                    pid: item.pid
                },
                cache:{
                    type: InstructionsCacheType.memory
                },
                token:true
            }).then((data)=>{
                data = data.data || {};

                data.game_info.skill_level_list.map((item)=>{
                    if (item.lid === data.lid) {
                        data.game_level_name = item.game_level_name;
                    }
                });

                resolve(data);

            }).catch(()=> resolve(undefined));
        });
    }

}

export {
    OpenType
}
