/**
 * 会员首页展板逻辑
 * 【二期内容：申请理事、申请常务理事、申请专家会员、会员积分、活动列表[立即参加]、消息中心暂时展示缴费提醒】
 */

import moment = require("moment");
import { INDIVIDUALMEMBERTYPE, MEMBERSTATE, MEMBERTYPE, PAYMENTSTATUS, STATE, UNITMEMBERTYPE, USERREGISTERSTATE } from "../../config/enum";
import { ERRORENUM } from "../../config/errorEnum";
import { addManyData } from "../../data/add";
import { deleteManyData } from "../../data/delete";
import { TABLEENUM } from "../../data/models/model";
import { find, findOnce } from "../../data/select";
import { updateOneData } from "../../data/update";
import { generateSystemId, getEdition, successResult } from "../../tools/system";
import { BizError } from "../../util/bizError";
import { extractData } from "../../util/piecemeal";
import { eccEnumValue } from "../../util/verificationEnum";
import { eccFormParam } from "../../util/verificationParam";
import { getCityNameByCode } from "../../config/cityConfig";


/**
 * 会员信息展示
 * @param userId 登录的用户id
 * @returns 个人会员：{头部数据， 基本信息， 专业信息， 其他附件}
 * @returns 单位会员：{头部数据， 基本信息， 单位信息， 单位所获得科研成果}
 */
export async function getMemberData({userId}) {
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId});
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);

    let topSelectFiles = ["loginId", "memberType", "userRegisterState", "integral", "joinTime", "lifespanStartTime", "lifespanEndTime", "memberLevel", "isFirstPay", "paymentStatus", "memberState"];
    let baseSelectFiles = [];
    let majorSelectFiles = [];
    let otherAttachment:any= {};
    /**判断会员类型，个人会员与单位会员返回不同字段 */
    if (oldInfo.memberType == MEMBERTYPE.单位会员) {
        baseSelectFiles = ["userId", "unitName", "uscc", "legalPerson", "legalPersonPhone", "legalPersonMail", "unitMail", "contactPerson", 
        "contactPersonDuties", "contactPersonPhone", "uusinessLicenseUrl", "addres", "sheng", "shi", "qu", "kaishezhuanYe", "danWeiJianJie"];
        majorSelectFiles = ["unitMemberType", "yuanXiaoBanXueLeiXing", "yuanXiaoZhuGuanBuMen", "yuanXiaoFuZeRen", "yuanXiaoFuZeRenZhiWu", 
        "yuanXiaoFuZeRenDianHua", "yuanXiaoBanGongFuZeRen", "yuanXiaoBanGongFuZeRenDianHua", "ZhuYaoFuZeRenYouXiang", "yuanXiaoKeYanFuZeRen", 
        "yuanXiaoKeYanFuZeRenDianHua", "jiaoXueFuZeRenXinMing", "jiaoXueFuZeRenDianHua"];
        /**获取单位科研成果数据 */
        let oldKeYanList = await find(TABLEENUM.单位所获得科研成果表, {userId}, ["id", "startTime", "endTime", "describe"]);
        if (!otherAttachment.dataList) otherAttachment.dataList = [];
        oldKeYanList.forEach(info => {
            otherAttachment.dataList.push({
                id:info.id,
                startTime: info.startTime,
                endTime: info.endTime,
                describe:info.describe
            });
        })

    } else {
        baseSelectFiles = ["userId", "name", "sex", "nation", "birth", "documentType", "documentId", "sheng", "shi", "qu", "phone", "mail", 
        "addres", "photoUrl", "education", "uscc", "unitName"];
        majorSelectFiles = ["unitName", "duties", "workTitle", "profCategory", "studyResume", "workResume", "profAchievement", "otherEMP", "otherPROF"]; 
        let otherAttachmentFiles = ["cardUrlJust", "cardUrlBack", "academicCERTUrl", "professionalCERTUrl", "auxiliaryMaterial"];
        otherAttachment = extractData(oldInfo, otherAttachmentFiles);
    }

    /**返回指定配置字段 */
    let topInfo:any = extractData(oldInfo, topSelectFiles);
    let baseInfo:any = extractData(oldInfo, baseSelectFiles);
    let majorInfo:any = extractData(oldInfo, majorSelectFiles);
    
    /**处理枚举值 */
    topInfo.integral = 0;
    if(topInfo.joinTime) topInfo.joinTime = moment(topInfo.joinTime).format("YYYY-MM-DD");
    if(topInfo.lifespanEndTime) {
        if(topInfo.memberState == MEMBERSTATE.异常) topInfo.lifespanEndTime = "欠费中"; 
        else topInfo.lifespanEndTime = moment(topInfo.lifespanEndTime).format("YYYY-MM-DD");
    }

    if(topInfo.userRegisterState == USERREGISTERSTATE.通过) topInfo.userRegisterState = "已入会";
    else topInfo.userRegisterState = "未入会";
    // if(topInfo.memberLevel) topInfo.memberLevel = changeEnumValue(MEMBERLEVEL, topInfo.memberLevel);
    // if(baseInfo.sex) baseInfo.sex = changeEnumValue(SEX, baseInfo.sex);
    // if(baseInfo.documentType) baseInfo.documentType = changeEnumValue(DOCUMENTTYPE, baseInfo.documentType);
    // if(baseInfo.nation) baseInfo.nation = changeEnumValue(NATION, baseInfo.nation);
    // if(majorInfo.profCategory) majorInfo.profCategory = changeEnumValue(PROFCATEGORY, majorInfo.profCategory);
    // if(majorInfo.unitMemberType) majorInfo.unitMemberType = changeEnumValue(UNITMEMBERTYPE, majorInfo.unitMemberType);
    // if(majorInfo.yuanXiaoBanXueLeiXing) majorInfo.yuanXiaoBanXueLeiXing = changeEnumValue(BANXUELEIXING, majorInfo.yuanXiaoBanXueLeiXing);

    return {topInfo, baseInfo, majorInfo, otherAttachment};
}


/**
 * 单位会员 修改
 * @param form 修改信息表单
 * @param keyanForm 修改科研信息表单
 * @param userId 登录的用户id
 * @returns 
 */
export async function unitMemberUpdate({form, keyanForm, userId}) {
    const keyanFormItemConfig = {
        startTime: 'Number',
        endTime: 'Number',
        describe: 'String'
    };
    keyanForm.forEach(item => {
        eccFormParam("单位会员修改", keyanFormItemConfig, item );
    });
    
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId});
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);

    /**校验枚举 */
    const EccFuncName = '单位会员修改';
    eccEnumValue(EccFuncName, '单位信息类型', UNITMEMBERTYPE, form.unitMemberType);

    /**确保邮箱的唯一性 */
    let distinctMailInfo = await findOnce(TABLEENUM.用户表, {mail:form.unitMail}, ["userId"]);
    if (distinctMailInfo && distinctMailInfo.userId && distinctMailInfo.userId != oldInfo.userId) throw new BizError(ERRORENUM.邮箱重复, oldInfo.loginId, oldInfo.mail );
    form.mail = form.unitMail;
    /**修改会员用户信息 */
    await updateOneData(TABLEENUM.用户表, {userId}, form);

    /**删除对应userId科研成果 */
    let oldKeYanList= await find(TABLEENUM.单位所获得科研成果表, {userId});
    if (oldKeYanList && oldKeYanList.length) {
        await deleteManyData(TABLEENUM.单位所获得科研成果表, {userId});
    }
    

    /**添加新的科研信息 */
    let addList = [];
    for (let i = 0; i < keyanForm.length; i++) {
        let { startTime, endTime, describe } = keyanForm[i];
        addList.push({
            id:generateSystemId(TABLEENUM.单位所获得科研成果表, userId),
            userId,
            startTime, endTime, describe
        });
    }
    await addManyData(TABLEENUM.单位所获得科研成果表, addList);

    return successResult();
}


/**
 * 个人会员 修改
 * @param userId 登录的用户id
 * @param form 修改信息表单
 * @returns 
 */
 export async function individualMemberUpdate({form, userId}) {
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId});
    if (!oldInfo || !oldInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);
    await updateOneData(TABLEENUM.用户表, {userId}, form);

    return successResult();
}


/**
 * 消息中心列表
 * 缴费消息提醒
 * @param userId 登录的用户id
 */
export async function getXiaoXiZhongXin({userId}) {
    const SelectFiles = ["userId", "lifespanEndTime", "isGracePeriod", "gracePeriodEndTime", "lifespanStartTime"];
    let oldInfo = await findOnce(TABLEENUM.用户表, {userId, isAdmin:STATE.否}, SelectFiles);

    let dataInfo:any = extractData(oldInfo, ["lifespanStartTime", "lifespanEndTime"]);

    const NowMs = new Date().valueOf();

    /**判断是否宽限期 */
    let str = '';
    if (oldInfo.isGracePeriod == STATE.是 && oldInfo.gracePeriodEndTime > NowMs) str = "宽限期中";
    else {
        if (NowMs > oldInfo.lifespanEndTime) {
            str = '过期';
            if (NowMs > oldInfo.lifespanEndTime + (90*24*3600*1000)){
                str += '1年外';
            } else if ( NowMs > oldInfo.lifespanEndTime + (90*24*3600*1000) ) {
                str += '1年内';
            } else if (NowMs > oldInfo.lifespanEndTime + (30*24*3600*1000)) {
                str += '90天内';
            } else {
                str += '30天内'; 
            }
        } else {
            if (NowMs > oldInfo.lifespanEndTime - (90*24*3600*1000) ) {
                str = "不足90天";
            } else {
                str = "大于90天";
            }
        }
    }
    dataInfo.membershipFees = str;

    return {dataInfo};
}


/**
 * 地图省数量统计
 * @param userId 登录的用户id 
 * @returns 
 */
export async function getSheng ({userId}) {
    let myOldInfo = await findOnce(TABLEENUM.用户表, {userId}, ["sheng"]);
    if (!myOldInfo || !myOldInfo.sheng) throw new BizError(ERRORENUM.目标数据不存在);
    let myDataInfo = extractData(myOldInfo, ["sheng"]);

    let allOldList = await find(TABLEENUM.用户表, {}, ["sheng"]);
    if (!allOldList || !allOldList.length) throw new BizError(ERRORENUM.目标数据不存在);
    
    let allDataList = {};
    allOldList.forEach( info => {
        //初始数据包含没有填省份的，过滤省份为undefined的数据，统计省份个数
        if (info.sheng) {
            if (!allDataList[info.sheng]) allDataList[info.sheng] = 0;
            allDataList[info.sheng] += 1;
        }
    })

    return {myDataInfo, allDataList};
}


/**
 * 活动列表
 */
 export async function getHuoDongTongZhi () {
    let oldList = await find(TABLEENUM.活动通知, {}, ["id", "name"]);
    if (!oldList || oldList.length<1) throw new BizError(ERRORENUM.目标数据不存在);
    
    let dataList = [];
    oldList.forEach( info => {
        let item = extractData(info, ["id", "name"]);
        dataList.push(item);
    })

    return {dataList};
}


/**
 * 根据会员类别返回对应可下载的证书类型
 * @param param0 
 * @returns 
 */
 export async function getCertificate({userId}) {
    const Files = ["userId", "memberType", "userRegisterState", "paymentStatus", "individualMemberType", "unitMemberType", 
    "sheng", "documentId", "memberNum", "lifespanStartTime", "lifespanEndTime", "shi","qu","addres", "unitName", "session"];
    let userInfo = await findOnce(TABLEENUM.用户表, {userId}, Files);
    if (!userInfo || !userInfo.userId) throw new BizError(ERRORENUM.目标数据不存在);

    let certificate = false;//是否可以下载
    let cefaInfo:any = {};
    let msg = '会员注册尚未审核通过，无法下载证书';
    //判断是否审批通过
    if (userInfo.userRegisterState == USERREGISTERSTATE.通过) {
        if(userInfo.memberType == MEMBERTYPE.个人会员) {
            //个人会员已支付可下载
            if (userInfo.individualMemberType == INDIVIDUALMEMBERTYPE.普通会员 && userInfo.paymentStatus != PAYMENTSTATUS.未支付) certificate = true;
            //个人会员专家无需支付可下载
            if (userInfo.individualMemberType == INDIVIDUALMEMBERTYPE.专家会员) certificate = true;
            if (certificate) {
                cefaInfo = {
                    area:getCityNameByCode(userInfo.sheng),
                    documentId:userInfo.documentId,
                    memberNum:userInfo.memberNum,
                    session:getEdition(Math.floor(userInfo.session/100), userInfo.session%100 ),
                    lifespanTime:`${moment(userInfo.lifespanStartTime).format("YYYY年MM月DD日")}至${moment(userInfo.lifespanEndTime).format("YYYY年MM月DD日")}`
                }
                msg = ``;
            } else {
                msg = `会员注册尚未缴费，无法下载证书`;
            }
        } else if(userInfo.memberType == MEMBERTYPE.单位会员) {
            //院校无需支付可下载
            if (userInfo.unitMemberType == UNITMEMBERTYPE.院校) certificate = true;
            //机构和其他已支付可下载
            else if (userInfo.paymentStatus != PAYMENTSTATUS.未支付) {
                certificate = true;
            }
            if (certificate) {
                let addresStr = "";
                if (getCityNameByCode(userInfo.sheng) == getCityNameByCode(userInfo.shi)) {
                    addresStr = `${getCityNameByCode(userInfo.shi)}${getCityNameByCode(userInfo.qu)}${userInfo.addres}`;
                } else {
                    addresStr = `${getCityNameByCode(userInfo.sheng)}${getCityNameByCode(userInfo.shi)}${getCityNameByCode(userInfo.qu)}${userInfo.addres}`;
                }
                cefaInfo = {
                    unitName:userInfo.unitName,
                    addres:addresStr,
                    memberNum:userInfo.memberNum,
                    session:getEdition(Math.floor(userInfo.session/100), userInfo.session%100 ),
                    lifespanTime:`${moment(userInfo.lifespanStartTime).format("YYYY年MM月DD日")}至${moment(userInfo.lifespanEndTime).format("YYYY年MM月DD日")}`
                }
                if (userInfo.unitMemberType == UNITMEMBERTYPE.院校) {
                    let diffYearNum = moment().diff(moment(userInfo.lifespanStartTime), 'years');
                    let startTimeStr = moment(userInfo.lifespanStartTime).add(diffYearNum, 'years').format("YYYY年MM月DD日");
                    let endTimeStr = moment(userInfo.lifespanStartTime).add(diffYearNum+1, 'years').format("YYYY年MM月DD日");
                    cefaInfo.lifespanTime = `${startTimeStr}至${endTimeStr}`;
                }
                msg = ``;
            } else {
                msg = `会员注册尚未缴费，无法下载证书`;
            }
        }
    }
    
    return {certificate, cefaInfo, msg};
}





