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

import moment = require("moment");
import { findTaskCountByParamCount, 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";
import { initSystemLabelData, systemLabel } from "./label";
const os = require('os');



/**
 * 初始化系统定时任务
 * 
 */
export async function initSystemTask() {
    const platform = os.platform();
    if (platform == "win32") return;
    /**
     * 6.0版本后舍弃系统自动发放任务
     */
    /**孵化器月度任务 */ 
    // fuHuaQiMonthTask();
    // setInterval(async function () {
    //     await fuHuaQiMonthTask();
    // }, 3600 * 1000);

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

    /**
     * 5.0版本舍弃企业季度任务
     */
    // /**企业季度任务 */
    // // enterpriseQuarterTask();
    // // setInterval(async function () {
    // //     await enterpriseQuarterTask();
    // // }, 3600 * 1000 * 2);
    
    /**
     * 6.0版本后，不在发送任务提醒
     */
    // /**初始化短信任务 */
    // smsTask();
    // setInterval(async function () {
    //     await smsTask();
    // }, 3600 * 1000);
    // console.log(`systemTask init success`);


    /**
    * 定时校验数据
    * 6.0新加  用于标签系统
    */
    await initSystemLabelData();
    // await systemLabel();
    let lastUpdateDay = moment().format("YYYY-MM-DD");
    setInterval(async function () {
        let hours = moment().hours();
        if ( moment().format("YYYY-MM-DD") == lastUpdateDay && hours>2 && hours <= 4) {
            await systemLabel();
            lastUpdateDay = moment().format("YYYY-MM-DD");
        }
    }, 3600 * 1000 * 1);
}


/**
 * 发放/回收 孵化器月度任务
 * @returns 
 */
async function fuHuaQiMonthTask() {
    const Key = taskTool.getTimeKey();
    let count = await findTaskCountByParamCount({key: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();
}


/**
 * 短信任务  每月倒数第七天发送
 * 6.0后不在发送任务提醒 舍弃
 */
async function smsTask() {
    return;
    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.信息填报提醒);

    }

}
