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

import moment = require("moment");
import { findTaskCountByKey, findTaskListByParam } from "../data/fuHuaQi/monthTask/task";
import * as taskTool from "../tools/taskTool";
import { provideMonthTask, retrieveMonthTask } from "./mobileFuHuaQi/fuHuaQi/task/monthTask";
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";
import { dataDeclarationTask } from "./mobileEnterprise/quarterTask/dataDeclaration";
import { findQuarterTaskCountByParam } from "../data/fuHuaQi/quarterTask/quarterTask";
import { provideFuHuaQiQuarterTask } from "./mobileFuHuaQi/fuHuaQi/task/quarterTask";


/**
 * 初始化任务
 */
export function initSystemTask() {
    /**孵化器月度任务 */
    fuHuaQiMonthTask();
    setInterval(async function () {
        await fuHuaQiMonthTask();
    }, 3600 * 1000);

     /**孵化器季度任务 */
     fuHuaQiQuarterTask();
     setInterval(async function () {
         await fuHuaQiQuarterTask();
     }, 3600 * 1000 * 2);

    /**企业季度任务 */
    enterpriseQuarterTask();
    setInterval(async function () {
        await enterpriseQuarterTask();
    }, 3600 * 1000 * 2);
    

    /**初始化短信任务 */
    smsTask();
    setInterval(async function () {
        await smsTask();
    }, 3600 * 1000);
    console.log(`systemTask init success`);

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


/**
 * 发放/回收 孵化器月度任务
 * @returns 
 */
async function fuHuaQiMonthTask() {
    const Key = taskTool.getTimeKey();
    let count = await findTaskCountByKey(Key);
    if (count != 0) return;

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


/**
 * 发放/回收 孵化器季度任务
 * @returns 
 */
async function fuHuaQiQuarterTask() {
    const Key = taskTool.getQuarterTimeKey();
    let count = await findQuarterTaskCountByParam({key:Key});
    if (count != 0) return;
    await provideFuHuaQiQuarterTask();
}


/**
 * 发放/回收  企业季度任务
 */
async function enterpriseQuarterTask() {
    /**不在填报月份不下发数据 */
    let thisMonth = new Date().getMonth() + 1;
    let tipsMonth = [1, 4, 7, 10];
    if ( tipsMonth.indexOf(thisMonth) == -1 ) return; 

    await dataDeclarationTask();
}


/**
 * 短信任务  每月倒数第七天发送
 */
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.信息填报提醒);

    }

}
