import { ChannelUser } from './../domain/ChannelUser';
import { Channel, pinus } from 'pinus';
import { getRandValueByMinMax, getRandEelm, decodeIdCntArrayStr } from '../pubUtils/util';
import { DEFAULT_HEROES, TERAPH_RANDOM } from "../consts";
import { DicTeraph } from '../pubUtils/dictionary/DicTeraph';
import { Teraph, RoleModel, RoleType, RoleUpdate } from '../db/Role';
import { ROLE_SELECT } from '../consts';
import { SCHOOL } from '../pubUtils/dicParam';
import { gameData } from '../pubUtils/data';
import { SchoolModel } from '../db/School';
import { SclResultInter, SclPosInter } from '../pubUtils/interface';
import { CheckMeterial } from './rewardService';
import { HeroUpdate } from '../db/Hero';
import { SkinUpdate } from '../db/Skin';
import { Figure } from '../domain/dbGeneral';

export async function getTeraphStrengthenResult(role: RoleType, count: number, dicTeraph: DicTeraph, teraph: Teraph) {
    let criAttr: number[] = [], times = 0;
    let check = new CheckMeterial(role.roleId, role);
    for(let i = 0; i < count; i++) {
        let attrs: number[] = []; // 可以强化的属性
        dicTeraph.mainAttrMax.forEach((max, id) => {
            if (teraph.attr.get(id) < max) {
                attrs.push(id);
            }
        });
        if(attrs.length <= 0) break; // 如果所有属性都到最高
        let isEnough = await check.decrease(dicTeraph.upMaterial);

        if(!isEnough) break; // 消耗不足

        let num = getRandValueByMinMax(TERAPH_RANDOM.MIN, TERAPH_RANDOM.MAX); // 强化时随机增加 2-4 属性
        let arr = getRandEelm(attrs, num); // 随机出的属性id
        let critical = getRandValueByMinMax(0, 100);//属性暴击率
        if(teraph.criCount == undefined || teraph.count == undefined) {
            teraph.criCount = 0;
            teraph.count = 0;
        }
        let isCritical = critical <= dicTeraph.criRate; // 每10次需要2次保底暴击
        if(!isCritical && Math.floor((teraph.count + 2)/10) * 2 > teraph.criCount) {
            isCritical = true;
        } else if (isCritical && Math.ceil(teraph.count/10) * 2 <= teraph.criCount) {
            isCritical = false;
        }
        teraph.count ++;
        if(isCritical) teraph.criCount ++;        

        let criEffect = isCritical?dicTeraph.criEffect: 1; // 暴击效果
        for (let attrId of arr) {
            let val = teraph.attr.get(attrId); // 已有的强化值
            val += dicTeraph.mainAttrUp.get(attrId) * criEffect;
            let max = dicTeraph.mainAttrMax.get(attrId);
            if(val > max) {
                val = max;
                let attrIndex = attrs.indexOf(attrId);
                attrs.splice(attrIndex, 1);
            }
            teraph.attr.set(attrId, val);
            if(isCritical) criAttr.push(attrId);
        }
        times++;

    }
    return { times, consumes: check.getConsume(), criAttr }
}

/**
 * 
 * @param channel 
 * @param user 
 */
export function addUserToChannel(channel: Channel, user: ChannelUser) {
    const users = channel.getMembers();
    const { uid, sid } = user;
    if (users.indexOf(uid) === -1) {
        channel.add(uid, sid);
    }
}

export async function getSimpleRoleInfo(roleId: string) {
    if (!roleId) return null;
    let role = await RoleModel.findByRoleId(roleId, ROLE_SELECT.SHOW_SIMPLE, true);
    return role;
}

export async function getSimpleRoleInfos(roleIds: string[]) {
    if (!roleIds || !roleIds.length) return null;
    let roles = await RoleModel.findRoleByField('roleId', roleIds, ROLE_SELECT.SHOW_SIMPLE, true);
    return roles;
}

/**
 * 百家学宫
 * @param roleId 
 */
export async function getSchoolList(roleId: string) {

    const dicPosition = decodeIdCntArrayStr(SCHOOL.SCHOOL_POSITION, 1); // id=>isOpen

    const userSchoolList = await SchoolModel.findByRoleId(roleId);

    let school = new Array<SclResultInter>();
    gameData.school.forEach((dicSchool) => {
        let position = new Array<SclPosInter>();
        dicPosition.forEach((isOpen, dicId) => {
            let id = parseInt(dicId);

            let userSchool = userSchoolList.find(cur => cur.schoolId == dicSchool.id && cur.positionId == id);
            if (userSchool) {
                position.push({
                    id,
                    hid: userSchool.hid,
                    isOpen: userSchool.isOpen
                });
            } else {
                position.push({
                    id,
                    hid: 0,
                    isOpen: !!isOpen
                });
            }
        });

        school.push({
            id: dicSchool.id,
            position
        });
    });
    return school;
}

function getDefaultHeroInfos(heroes: Map<number, HeroUpdate>, skins: Map<number, SkinUpdate>) {
    const initInfos: { heroInfo: HeroUpdate, skinInfo: SkinUpdate}[] = [];
    for(let hid of DEFAULT_HEROES) {
        initInfos.push({
            heroInfo: heroes.get(hid),
            skinInfo: skins.get(hid)
        });
    }
    return initInfos;
}

export function getDefaultRoleInfo(heroes: Map<number, HeroUpdate>, skins: Map<number, SkinUpdate>, role:RoleUpdate, figureInfo: { heads: Figure[], frames: Figure[], spines: Figure[] }) {
    const initInfos = getDefaultHeroInfos(heroes, skins);
    return { initInfos, role, figureInfo };
}

export function getInitHeroById(hid: number) {
    return {
        heroInfo: pinus.app.get('initHeroes').get(hid),
        skinInfo: pinus.app.get('initSkins').get(hid)
    }
}