import moment = require("moment");
import { ERRORENUM } from "../config/errorEnum";
import { BizError } from "../util/bizError";
import { FILETYPE } from "../config/enum";

const md5 = require("md5");

/**
 * 生成系统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);
}

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

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

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


export function getUserToken(loginId:string) {
    return md5(`${loginId}_${Math.ceil(Math.random()*1000)}${new Date().valueOf()}`);
}

export function getMySqlMs(time?) {
    time = time || new Date().valueOf();
    // time += (8*3600*1000);
    return moment(time).format("YYYY-MM-DD HH:mm:ss");
}

export function getClientMs(time) {
    if (!time) return new Date().valueOf();
    return new Date(time).valueOf();
}

export function getPartyMemberId(param) {
    return md5(`${param}-${new Date().valueOf()}-${Math.ceil(Math.random() * 10000)}`);
}


export function getDefPwd(phone:string) {
    return md5(`${phone.slice(5, 11)}`);
}

export function getFileType(fileName) {
    let fileType = 0;
    fileName.forEach(info => {
        let repList = info.split(".");
        let type = repList[repList.length-1];
        if (!type) throw new BizError(ERRORENUM.文件不存在, `文件名 ${info}`);
        let typeNum = 0;
        switch(type) {
            case 'pdf': typeNum = FILETYPE.pdf; break;
            case 'doc': 
            case 'docx': typeNum = FILETYPE.word; break;
            case 'jpg': 
            case 'png': typeNum = FILETYPE.图片; break;
        };
        if (typeNum) {
            if (!fileType) fileType = typeNum;
            else if (fileType != typeNum) fileType = FILETYPE.多类型;
        }
    });
    return fileType;
}
