/**
 * 系统任务逻辑
 * 作者:李欣鸣
 * 目前下发任务有 
 * 1: 每月1日0时0分，下发孵化器任务
 * 2：每月倒数第7天，发送短信提示
 * 
 */

import moment = require("moment");
import { findTaskCountByKey, findTaskListByParam } from "../data/fuHuaQi/task";
import { getTimeKey } from "../tools/system";
import { provideTask, retrieveTask } from "./mobileFuHuaQi/fuHuaQi/task";
import { findFuHuaQiList } from "../data/fuHuaQi/fuhuaqi";
import { sendTaskPointOut } from "./sms";
import { logHandle } from "../util/log";
import { createSmsPointOutData, findSmsPointOutData } from "../data/fuHuaQi/smsPointOut";
import { SMSTYPE } from "../config/enum";

export function initSystemTask() {
    fuHuaQiTask();
    setInterval(async function () {
        await fuHuaQiTask();
    }, 3600 * 1000);
    console.log(`systemTask init success`);
}


/**
 * 发放/回收 任务
 * @returns 
 */
async function fuHuaQiTask() {
    const Key = getTimeKey();
    let count = await findTaskCountByKey(Key);
    if (count != 0) return;

    /**生成新的任务 */
    await provideTask();
    /**回收旧任务计算分数 */
    await retrieveTask();
}


/**
 * 短信任务  每月倒数第七天发送
 */
export async function smsTask() {
    let nowMs = new Date().valueOf();
    let lastDate = moment(nowMs).endOf("month").format("YYYY-MM-DD");
    let checkMs = moment(lastDate+' 00:00:00').subtract(7,'days').valueOf();

    let dataMonth = moment(nowMs).subtract(1,'month').month() + 1;
    let dataYear = new Date(nowMs).getFullYear();

    

    if (nowMs > checkMs) {
        /**本月已经更新过了就不再更新 */
        let dbData = await findSmsPointOutData(dataMonth, dataYear);
        if (dbData && dbData.year) return;

        //发送短信验证
        let fuHuaQiList = await findFuHuaQiList({userState:false});

        let allPhoneMap = {};
        for (let i = 0; i < fuHuaQiList.length; i++) {
            let {personInChargePhone, uscc} = fuHuaQiList[i];

            allPhoneMap[uscc] = personInChargePhone;
        }

        let notCheckTaskList = await findTaskListByParam({month:dataMonth, year:dataYear, isSubmit:false});

        let phoneMap = {};
        notCheckTaskList.forEach(info => {
            let phone = allPhoneMap[info.fuHuaQiUscc];
            if (!phone) return;
            phoneMap[phone] = 1;
        });

        let phoneList = Object.keys(phoneMap);
        let sendRes = await sendTaskPointOut(phoneList, dataMonth);
        if (!sendRes )logHandle(`提示短信发送成功 共计${phoneList.length}条`);

        await createSmsPointOutData(dataMonth, dataYear, SMSTYPE.信息填报提醒);

    }

}
