/**
 * 系统中使用的工具
 * 包括 草稿箱id生成规则
 * 包括 密码加密规则
 */

import moment = require("moment");
import { wenZhangQueue } from "../biz/task";
import { MEMBERTYPE } from "../config/enum";
const md5 = require("md5");

/**
 * 返回编辑正确的结果
 * @returns 
 */
export function successResult() {
    return {success:true}
}


/**
 * 抛出错误信息
 * @returns 
 */
 export function successErrorResult(msg) {
    return {code:500, success:false, msg};
}


/**
 * 生成系统id
 * @param tableName 
 * @param userId 
 * @returns 
 */
export function generateSystemId(tableName:string, userId:string) {
    return md5(`${tableName}${Math.floor(Math.random() * 10000)}${userId}${new Date().valueOf()}${Math.floor(Math.random() * 100)}`);
}

/**
 * 生成token
 * @param userId 
 * @returns 
 */
export function generateToken(userId:string) {
    return md5(`${userId}${Math.floor(Math.random() * 10000)}${new Date().valueOf()}${Math.floor(Math.random() * 100)}`);
}

/**
 * 生成userid
 */
export function generateUserId(phone?) {
    let str = `${Math.random() * 100}${new Date().valueOf()}${Math.floor(Math.random() * 10000)}`;
    if (phone) str += phone;
    return md5(str);
}

/**
 * 获取code的id
 * @param loginId 用户Id
 * @param todaySendCount 今日发送次数
 * @returns ''
 */
 export function getSMSCodeId(loginId:string, todaySendCount:number) {
    return md5(`${loginId}${todaySendCount}${new Date().valueOf()}`);
}


/**
 * 获取一个随机6位数的验证码
 * @returns 
 */
export function generateSMSCode() {
    let code = ``;
    for (let i =0; i < 6; i++) {
        code += Math.floor(Math.random() * 10);
    }
    return code;
}


/**
 * 生成唯一订单id
 */
export function generateOrderId(userId:string) {
    return md5(`${userId}${Math.random() * 100}${new Date().valueOf()}${Math.floor(Math.random() * 1000)}`);
}


/*
 * 获取今天开始时刻的时间戳  0时0分
 * @returns 
 */
export function getTodayMs() {
    return new Date(`${ moment().format("YYYY-MM-DD")} 00:00:00`).valueOf();
}



export function generateWXOrderId(memberType, userId) {
    let thisDate = new Date();
    return `${md5(`${memberType}${userId}${Math.random() * 100}${thisDate.valueOf()}${Math.floor(Math.random() * 1000)}`)}`;
}

/**
 * 倒推 届次
 */
export function getSessionByEdition(jie, ci) {

}


/**
 * 获取届次
 * @param year 入会年份 
 * @param month 入会月份
 * 下拉选择起始届次：2008年第四届第一次
 * @returns 
 */
export function getEdition(year, month) {
    //起始年份和月份 第一届第一次
    const startYear = 1993;
    const Num = ((year-startYear)+1)/5;
    let jie = Math.ceil(Num);
    let ci = Math.ceil(((Num*100) - ((jie - 1)*100))/10);
    if (month <= 6)  ci = ci - 1;
    
    return `第${chuangeStr(jie)}届,第${chuangeStr(ci)}次`;
    // const startYear = 1993;
    // let jie = Math.ceil(((year-startYear)+1)/5);
    // let ci = ((((year-startYear)+1)/5) - (jie - 1)) * 10;
    // if (month < 6)  ci = ci -1;


    // let currentYear = new Date().getFullYear();
    // if (year > currentYear) throw new BizError(ERRORENUM.无法获取未来届次);

    // //计算从起始时间给定时间的总月份数
    // let totalMonth = (year - startYear) * 12 + month;
    // //每次是6个月
    // let sessions = Math.ceil(totalMonth / 6);
    // //每10次一届，从第四届开始计算
    // let times = Math.ceil(sessions / 10);
    // let sessionNumber = sessions - (times - 1) * 10 //届次是从第四届第一次开始，所以需要减一

    // return `第${times}届,第${sessionNumber}次`;
}
function chuangeStr(count) {
    let map = {
        "0":"十",
        "1":"一",
        "2":"二",
        "3":"三",
        "4":"四",
        "5":"五",
        "6":"六",
        "7":"七",
        "8":"八",
        "9":"九"
    };
    let jieStr = "";

    let shiWei = Math.floor(count/10);
    let geWei = count%10;
    if ( !shiWei ) {
        jieStr = map[geWei];
    } else if (shiWei == 1) {
        jieStr = `十`;
        if (geWei)  jieStr += map[geWei];
    }else {
        jieStr = `${ map[shiWei] }十${map[geWei]}`;
    }
    
    return jieStr;
}


export function changeArticleName(idList) {
    let str = '';
    idList.forEach((id, index) => {
        if (index) str += ',';
        str += `${wenZhangQueue[id]}`;
    });
    return str;
}


/**
 * 获取会员编号
 * @param db 
 * @param memberTypeStr 
 * @param joinTime 
 * @param sheng 
 * @returns CEFA+入会时间+行政区域代码+5位流水号+DW（单位）/GR（个人）
 * 个人会员：以审核时间算正式入会时间
 * 单位会员：以审核时间算正式入会时间
 * 例 CEFA-20230620-11-00001GR
 */
export function getMenberNum( joinTime, sheng, userCount, memberType) {
    //定义编号前缀
    const JoinTimeStr = moment(joinTime).format("YYYYMMDD");
    const Province = parseInt(`${parseInt(sheng)/10000}`);

    let numStr = '';
    for (let i = `${userCount}`.length; i < 5;i++) {
        numStr+='0';
    }
    numStr += (userCount+1);

    let memberTypeStr = "";
    if(memberType == MEMBERTYPE.个人会员) memberTypeStr = "GR";
    if(memberType == MEMBERTYPE.单位会员) memberTypeStr = "DW";
    return `CEFA-${JoinTimeStr}-${Province}-${numStr}-${memberTypeStr}`;
}


/**
 * 生成密码
 * @param userId 
 * @returns 
 */
export function generatePwd(userId:string, pwd:string) {
    return md5(`${userId}${pwd}`);
}