import moment = require("moment");
import { ARTICLEPOSITION, MAILTYPE, MEMBERSTATE, MEMBERTYPE, PARTYBUILDSUBTYPEENUM, PARTYBUILDTYPEENUM, PAYMENTSTATUS, STATE, USERREGISTERSTATE } from "../config/enum";
import { TABLEENUM } from "../data/models/model";
import { find, findCount, findOnce, findOnceToSort } from "../data/select";
import { createOrder } from "./member/order";
import { updateOneData } from "../data/update";
import { addOneData } from "../data/add";
import { updateRegisterStartQueue } from "./register";
import { systemSendMail } from "./mail";

/**
 * 初始化任务
 */
export async function initSystemTask() {
    /**初始文字管理名称 */
    await initWenZangQueue();

    await createUserOrder();
    setInterval(async function () {
        await createUserOrder();
    }, 24 * 3600 * 1000);


    //注册状态
    let registerStart = await findOnce(TABLEENUM.系统表, {key:"注册开放时间"});

    if (!registerStart || !registerStart.key) {
        addOneData(TABLEENUM.系统表, {key:"注册开放时间", value:"true"});
    } else {
        //现有的
        if (registerStart.value == "true") {
            updateRegisterStartQueue(true);
        }
        else if (registerStart.value == "false") {
            updateRegisterStartQueue(false);
        }
    }


    console.log(`systemTask init success`);
}

export async function createUserOrder() {
    const NowMs = new Date().valueOf();
    /**到期时间距离今天小于90天 */
    let selectParam:any = {
        "$and":[
            {lifespanEndTime:{"$lt":NowMs + (30 * 24 * 3600 * 1000)}}
        ],
        isAdmin:STATE.否,
        userRegisterState:USERREGISTERSTATE.通过
    }
    let files = ["userId", "lifespanEndTime", "loginId", "phone", "unitName", "memberLevel", "memberType", "unitMemberType", "individualMemberType"];
    let count = await findCount(TABLEENUM.用户表, selectParam);
    if (count) {
        let userList = await find(TABLEENUM.用户表, selectParam, files );
        let addCount = 0;
        for (let i= 0; i < userList.length; i++) {
            let { userId, loginId, phone, unitName, memberLevel, memberType, unitMemberType, individualMemberType} = userList[i];
            let itemInfo = await findOnceToSort(TABLEENUM.订单表, {userId}, {orderCycleStart:-1}, ["id", "orderCycleStart", "orderCycleEnd"]);
            if (itemInfo && itemInfo.id) {//第一条订单应该由审核员创建 不应该由系统创建
                if (itemInfo.orderCycleEnd < NowMs ) {
                    /**创建一条新的订单 */
                    let subType = memberType == MEMBERTYPE.个人会员 ? individualMemberType : unitMemberType;
                    let newOrderStartTime = itemInfo.orderCycleEnd;//新订单的开始时间是上一条订单的结束时间
                    await createOrder(userId, loginId, phone, unitName, newOrderStartTime, memberLevel, memberType, subType, false);
                    await updateOneData(TABLEENUM.用户表, {userId}, {paymentStatus:PAYMENTSTATUS.未支付, memberState:MEMBERSTATE.异常, });
                    addCount += 1;

                     //发送邮件
                    await systemSendMail(userId, MAILTYPE.会员进入宽限期 );
                }
            }
        }
        console.log(`已创建${addCount}条订单`);
    }
}


export let wenZhangQueue = {};
async function initWenZangQueue() {
    wenZhangQueue = {};
    for (let key in ARTICLEPOSITION) {
        let anyKey:any = key;
        if (isNaN(anyKey)) {
            let keyStr = key;
            let value = ARTICLEPOSITION[key];
            if(/_dou/.test(keyStr)) keyStr = keyStr.replace(/_dou/, "，");
            if(/_zyh/.test(keyStr)) keyStr = keyStr.replace(/_zyh/, "“");
            if(/_yyh/.test(keyStr)) keyStr = keyStr.replace(/_yyh/, "”");
            if(/_dun/.test(keyStr)) keyStr = keyStr.replace(/_dun/, "、");
            if(/_ju/.test(keyStr)) keyStr = keyStr.replace(/_ju/, "。");
            if(/_hgh/.test(keyStr)) keyStr = keyStr.replace(/_hgh/, "-");
            if(/_kbh/.test(keyStr)) keyStr = keyStr.replace(/_kbh/, "");
            wenZhangQueue[value] = keyStr;
        }
    }
    let wenZiDBList = await find(TABLEENUM.党建, {type:PARTYBUILDTYPEENUM.学习园地, subType:PARTYBUILDSUBTYPEENUM.文字资料});
    wenZiDBList.forEach(info => {
        let {id, name} = info;
        wenZhangQueue[id] = `学习园地-${name}`;
    });
    let zhuTiDBList = await find(TABLEENUM.党建, {type:PARTYBUILDTYPEENUM.主题教育});
    zhuTiDBList.forEach(info => {
        let {id, name} = info;
        wenZhangQueue[id] = `主题教育-${name}`;
    });
}