import moment = require("moment");
import { ARTICLEPOSITION, 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";

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

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

    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;
                }
            }
        }
        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}`;
    });
}