/**
 * 内部开放接口
 * 用于版本更新的数据维护
 */

import * as monthTableData from "../../data/fuHuaQi/monthTask/monthTable";
import * as taskData from "../../data/fuHuaQi/monthTask/task";
import * as enterpriseData from "../../data/enterprise/enterprise";
import * as fuhuaqiData from "../../data/fuHuaQi/fuhuaqi";
import * as financingData from "../../data/fuHuaQi/monthTask/financing";
import { CHANGEMODE, FUHUASTATE, INDUSTRY, SCOREWAYS, TASKTYPEENUM } from "../../config/enum";
import { ERRORENUM } from "../../config/errorEnum";
import { findAllNotDisabledFuHuaQi, findFuHuaQiList } from "../../data/fuHuaQi/fuhuaqi";
import { BizError } from "../../util/bizError";
import { logHandle } from "../../util/log";
import { initFuHuaQiScore } from "../../data/fuHuaQi/score";
import { updateScore } from "../mobileFuHuaQi/fuHuaQi/score";
import * as scoreData from "../../data/fuHuaQi/score";
import  * as scoreLogData from "../../data/fuHuaQi/scoreLog";
import { ScoreConfig } from "../../config/scoreConfig";
import moment = require("moment");
import * as sysTools from "../../tools/system";
const xlsx = require('node-xlsx');
const path = require('path');

/**
 * 发放1月数据
 */
export async function provideLastTask() {
    const TimeKey = '20232';

    let addList = [];//任务列表
    let monthList = [];//月度填报列表
    
    const MonthNumber = 1;//数据填报月份
    const YearNumber = 2023
    const MonthTableName = `${MonthNumber}月孵化器月度填报`;

    let fuHuaQiList = await findAllNotDisabledFuHuaQi();
    fuHuaQiList.forEach(info => {
        let { uscc } = info;
        let taskId = `${uscc}${TimeKey}`;
        addList.push( { key:TimeKey, type:TASKTYPEENUM.孵化器月度填报, month:1, taskId, fuHuaQiUscc:uscc, isSubmit:false},
            { key:TimeKey, type:TASKTYPEENUM.新注册或迁入企业登记, month:1, taskId, fuHuaQiUscc:uscc, isSubmit:false },
            { key:TimeKey, type:TASKTYPEENUM.融资企业填报, month:1, taskId, fuHuaQiUscc:uscc, isSubmit:false});
        /**任务报表的初始状态为 草稿(draftLock=fals) 未被编辑(isUpdate=false)  */
        monthList.push({ taskId, name:MonthTableName, fuHuaQiUscc:uscc, month:MonthNumber, year:YearNumber, draftLock:false, isUpdate:false });
    });

    try {
        /**初始化 任务 */
        await taskData.createTaskToList(addList);
        logHandle(`添加了${addList.length} 任务`);
         /**初始化 月度填报表 */
        await monthTableData.createMonthTableToList(monthList);
        logHandle(`添加了${monthList.length} 月度任务`);
    } catch (err) {
        new BizError(ERRORENUM.系统错误, '添加任务和月度报表的时候 出现了异常 请检查数据库  ', err);
    }
}


export async function updateEnterpriseFuHuaState() {
    await enterpriseData.updateEnterpriseState(FUHUASTATE.实体孵化);
    return {};
}

export async function updateFuHuaQiTaskYear() {
    await taskData.updateTaskYearData(2023);
    return {};
}

export async function initScoreData() {
    let data = await findFuHuaQiList({});

    let addList = [];
    data.forEach(info => {
        addList.push({
            uscc:info.uscc,//孵化器uscc
            startScore: 400,//初始分 400  创建孵化器的时候要在这里加上
            lastYearStar: 3,//去年星值  这里默认是3星  每年12月31日12时，需要根据分算星然后更新到这里
            myDataScore: 0,//我的数据获得的分数
            baseDataScore: 0,//基础数据获得的分数
            myEnterpriseScore: 0,//我的企业获得的分数
            taskScore: 0,//任务获得分数
            updateTime: new Date().valueOf(),//更新时间戳
            /**上一次评分 */
            lastScore:0//在获取列表的时候要同步数据
        });
    });
    await initFuHuaQiScore(addList);

    for (let i =0; i < data.length; i++) {
        let {uscc} = data[i];
        await updateScore(uscc, SCOREWAYS.我的企业数据, false);
        await updateScore(uscc, SCOREWAYS.我的信息, false);
        await updateScore(uscc, SCOREWAYS.我的数据, false);
    }
    
    /**初始化任务得分 */
    let taskList = await taskData.findTaskListByParam({});
    for (let i =0; i < taskList.length; i++) {
        let {fuHuaQiUscc, isSubmit, type, month, year} = taskList[i];
        let timeMs = moment([year, month, 1, 2]).add(1, 'M').valueOf();
        if ( isSubmit ) await initTaskScore(fuHuaQiUscc, SCOREWAYS.任务得分, true,timeMs, type);
        else await initTaskScore(fuHuaQiUscc, SCOREWAYS.任务得分, false,timeMs, type);
    }
    console.log("初始化评分成功");

}

async function initTaskScore(uscc:string, type:number, isSubmitTask:boolean, timeMs:number, subType?) {
    /**得分信息 */
    let scoreInfo = await scoreData.findFuHuaQiScoreInfo(uscc);
    if (!scoreInfo) return
    let fuHuaQiInfo = await fuhuaqiData.findFuHuaQiByUSCC(uscc);
    let newScore = 0;//新分数
    let oldScore = 0;//老分数
    let countScore = scoreInfo.startScore +scoreInfo.myDataScore +scoreInfo.baseDataScore +scoreInfo.myEnterpriseScore +scoreInfo.taskScore;

    /**单个任务得分 */
    let createMonth = !fuHuaQiInfo.createTime ? 0 : new Date(fuHuaQiInfo.createTime).getMonth();

    if (isSubmitTask) newScore = getOnceTaskScore(createMonth);
    else newScore = getOnceTaskDeductScore(createMonth);
    /**赋值新的分数 */
    scoreInfo.taskScore = scoreInfo.taskScore + newScore
    
    /**分数没有变化 */
    if (oldScore == newScore) return;

    let changeMode = oldScore > newScore ? CHANGEMODE.减少 : CHANGEMODE.增加;
    let newCountScore = countScore - oldScore + newScore;

    if (SCOREWAYS.任务得分 == type) {
        newScore = -1 * newScore;
        await scoreLogData.addLogTOInitData(uscc, type, changeMode, newCountScore, newScore, timeMs,subType);
    } else await scoreLogData.addLogTOInitData(uscc, type, changeMode, newCountScore, timeMs,newScore);
    
    scoreInfo.updateTime = new Date().valueOf();
    await scoreInfo.save();
}
/**
 * 算单个任务得分
 * @param month 入住月份  如果是去年 就是0   范围是0-11
 * @returns 
 */
function getOnceTaskScore(month:number) {
    let thisMonthTaskCount = 3; //后续接入任务可编辑要改这里
    return (ScoreConfig["任务常量_加分"]/(12-month)) * (1/thisMonthTaskCount);
}
/**
 * 算单个任务扣分
 * @param month 入住月份  如果是去年 就是0   范围是0-11
 * @returns 
 */
function getOnceTaskDeductScore(month:number) {
    let thisMonthTaskCount = 3; //后续接入任务可编辑要改这里
    return -((ScoreConfig["任务常量_扣分"]/(12-month)) * (1/thisMonthTaskCount));
}



export async function replenishTaskData() {
    let list = await enterpriseData.findStats();

    let taskMap = {};
    list.forEach(info => {
        if (info.taskId) {
            if (!taskMap[info.taskId]) taskMap[info.taskId] = 0;
            taskMap[info.taskId] += 1;
        }
    });


    for (let key in taskMap) {
        let value = taskMap[key];

        await taskData.updateSubmitCount(key, TASKTYPEENUM.新注册或迁入企业登记, value);

    }

    let fList = await financingData.findFinancingList({});

    let fTaskMap = {};
    fList.forEach(info => {
        if (info.taskId) {
            if (!fTaskMap[info.taskId]) fTaskMap[info.taskId] = 0;
            fTaskMap[info.taskId] += 1;
        }
    });

    for (let key in fTaskMap) {
        let value = fTaskMap[key];

        await taskData.updateSubmitCount(key, TASKTYPEENUM.融资企业填报, value);

    }

    console.log("初始化任务提交数成功");
}


/**
 * 2.1 同步地址
 */
export async function updateAdd() {
    /**查找所有孵化器 */
    let fhqList = await fuhuaqiData.findFuHuaQiList({});

    let updateList = [];//需要修改的地址
    fhqList.forEach(info => {
        if (info.hatchingGround && info.hatchingGround.length) {
            updateList.push({
                uscc:info.uscc,
                hatchingGround:info.hatchingGround
            });
        }
    });

    for (let i = 0; i < updateList.length; i++) {
        let {uscc, hatchingGround} = updateList[i];
        hatchingGround.forEach(info => {
            info.personInChargeAddress = getNewAdd(info.personInChargeAdd);
        });

        let fuhuaqiItem = await fuhuaqiData.findFuHuaQiByUSCC(uscc);
        fuhuaqiItem.hatchingGround = hatchingGround;

        await fuhuaqiItem.save();
    }

    console.log("孵化器 地址同步成功");

    /** 修改企业信息 */

    let enterpriseList = await enterpriseData.findEnterpriseList({});

    for (let i= 0; i < enterpriseList.length; i++) {
        let {uscc, oldLogonAdd, logonAdd, operatingAdd} = enterpriseList[i];
        let logonAddress = getNewAdd(logonAdd);
        let operatingAddress = getNewAdd(operatingAdd);
        let oldLogonAddress =  getNewAdd(oldLogonAdd);

        let item = await enterpriseData.findEnterpriseByUscc(uscc);
        
        item.logonAddress = logonAddress;
        item.operatingAddress = operatingAddress;
        item.oldLogonAddress = oldLogonAddress;

        await item.save();
    }

    /** 修改融资企业信息 */
    let financingList = await financingData.findFinancingList({});
    for (let i= 0; i < financingList.length; i++) {
        let {uscc, taskId, logonAdd, operatingAdd} = financingList[i];
        let logonAddress = getNewAdd(logonAdd);
        let operatingAddress = getNewAdd(operatingAdd);

        let item = await financingData.findFinancingInfoByTaskIdAndSucc(taskId, uscc);
        
        item.logonAddress = logonAddress;
        item.operatingAddress = operatingAddress;

        await item.save();
    }

    console.log("地址数据同步成功");

}

function getNewAdd(addStr:string) {
    if (!addStr) return ["", "", "", ""];
    let cityStr = "";//市
    let tackageStr = addStr;

    if (tackageStr.indexOf("中国(上海)") != -1 || tackageStr.indexOf("中国（上海）") != -1) {
        tackageStr = tackageStr.replace("中国(上海)", "");
        tackageStr = tackageStr.replace("中国（上海）", "");
        cityStr = "上海市";
    }

    let checkIndex = tackageStr.indexOf("上海市");
    if (checkIndex != -1) {
        cityStr = "上海市";
        tackageStr = tackageStr.replace("上海市","");
    } else {
        if ( tackageStr.indexOf("上海") != -1 ) {
            cityStr = "上海市";
            tackageStr = tackageStr.replace("上海","");
        }
    }

    let areaIndex = tackageStr.indexOf("区");
    let areaStr = "";//区
    if (areaIndex != -1) {
        areaStr = tackageStr.slice(0, areaIndex+1);
        tackageStr = tackageStr.replace(areaStr, "");
    }
    if (areaStr == "自由贸易试验区") areaStr = "浦东新区";
    let detailedStr = tackageStr;//详细

    return ["上海市", cityStr, areaStr, detailedStr];

}


export async function updateEnterpriseDataInfo() {
    let result = await enterpriseData.findEnterpriseList({});
    
    for (let i = 0; i < result.length; i++) {
        let dataItem = result[i];
        let info = await enterpriseData.findEnterpriseByUscc(dataItem.uscc);
        info.pwd = sysTools.getPwdMd5(info.uscc, sysTools.md5PwdStr(dataItem.uscc.slice(dataItem.uscc.length-6)));
        info.firstLoginIsChangePwd = false;

        await info.save();
    }
    console.log("补全企业密码成功");
    
}

/**
 * 获取当个excel文件数据
 * @param filePath 
 * @returns 
 */
function getExcel(filePath) {
    const workSheetsFromFile = xlsx.parse(filePath);
    let sheetMap = {};
    let sheetList = [];

    for (let i = 0; i < workSheetsFromFile.length; i++) {
        let sheetInfo = workSheetsFromFile[i];
        sheetMap[sheetInfo.name] = sheetInfo.data;
        sheetList.push(sheetInfo);
    }

    return {sheetMap, sheetList}  
}


export async function inputEnterpriseData() {
    let {sheetMap} = getExcel(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", '4月导入企业数据.xlsx' ));
    let dataList = sheetMap['在孵企业20233.xlsx'];

    let fuHuaQiUsccMap = await fuhuaqiData.findAllFuHuaQiOperationUsccMap();

    let titleMap = {
        "0":"name",//名称
        "1":"fuHuaQiUscc",//所属孵化器
        "2":"uscc",
        "4":"industry",//领域 
        "5":"logonTime",//注册时间
        "6":"firstIncubationTime",//首次入伏时间
        "7":"timeOfImmigration",//迁入时间 导入的时候不用管这个字段
        "8":"isNaturalPersonHolding",
        "9":"oldLogonAddress",//迁入前地址
        "10":"logonAddress",//注册地址
        "11":"operatingAddress",//经营地址
        "12":"leasedArea",//租赁面积（平方米）
    };
    let utc = new Date();
    let titleIndexList = Object.keys(titleMap);
    let addList = [];
    dataList.forEach((subList, index) => {
        if (!index) return;//跳过表头
        let addDataInfo:any = { draftLock:true, createTime:new Date().valueOf(), enterpriseIsInPut:true };

        let isJump = false;
        for (let subI = 0; subI < titleIndexList.length; subI++) {
            let i = parseInt(titleIndexList[subI]);

            let item = subList[i];
            let key = titleMap[i];
            let value = item;
            if (i ==1) {
                if (!item || !fuHuaQiUsccMap[item]) {
                    isJump = true;
                    continue;
                }
                value = fuHuaQiUsccMap[item];
            }
            if (i == 4) {
                value = INDUSTRY[value];
            }

            if (i == 8) {
                value = item == "是" ? true : false;
            }


            if (i == 11 || i==9 || i==10) {
                value = ["","","",item];  
            }

            if (i == 5 || i==6 || i==7) {
                if (typeof item == "string") {
                    value = new Date(item).valueOf();
                } 
                else {
                    value =  new Date((item - 25569 ) * 86400 * 1000 + utc.getTimezoneOffset()*1000*60).valueOf();
                }
            }

            addDataInfo[key] = value;
        }
        // if (!isJump) 
        addList.push(addDataInfo);
    });
    for (let i =0; i < addList.length; i++) {
        console.log(addList[i].logonTime);
    }

    await enterpriseData.createEnterpriseToList(addList);
    console.log("---> 企业数据 初始化成功", addList.length);
}


export async function replaceInitEnberpriseData() {
    let {sheetMap} = getExcel(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", '企业信息更新202304.xlsx' ));
    let dataList = sheetMap['表格'];
    let utc = new Date();
    for (let i = 1; i < dataList.length; i++) {
        let subList = dataList[i];

        let uscc = subList[4];

        let changeInfo:any = {
            isCreate : subList[3] == "新迁入" ? false : true,
            industry : INDUSTRY.生物医药,
            mainBusiness : subList[6] || "",
            logonTime : new Date((subList[7] - 25569 ) * 86400 * 1000 + utc.getTimezoneOffset()*1000*60).valueOf(),
            firstIncubationTime : new Date((subList[8] - 25569 ) * 86400 * 1000 + utc.getTimezoneOffset()*1000*60).valueOf(),
            timeOfImmigration : !subList[9] ? -1 : new Date((subList[9] - 25569 ) * 86400 * 1000 + utc.getTimezoneOffset()*1000*60).valueOf(),
            isNaturalPersonHolding : subList[10] == "是",
            oldLogonAddress : getNewAdd(subList[11]),
            logonAddress : getNewAdd(subList[12]),
            operatingAddress : getNewAdd(subList[13]),
            leasedArea : subList[14]
        };
        if (uscc == "91310120MA1HQ1TA5K") {
            changeInfo.uscc = "91310120MA1HQ1TA5K";
            uscc = "91310120ma1hq1ta5k";
        }

        let info = await enterpriseData.findEnterpriseByUscc(uscc);

        if (!info) continue;
       
        for (let key in changeInfo) {
            if (changeInfo[key] == -1) continue;
            info[key] = changeInfo[key];
        }

        await info.save();

    }

    console.log("完成");
}



export async function initEnterprisePwd() {
    let result = await enterpriseData.findEnterpriseList({pwd:null});

    for (let i = 0; i < result.length; i++) {
        let dataItem = result[i];
        let pwd = sysTools.getPwdMd5(dataItem.uscc, sysTools.md5PwdStr(dataItem.uscc.slice(dataItem.uscc.length-6)));
        await enterpriseData.updateEnterprisePwd(dataItem.uscc, pwd);
    }
    console.log("补全企业密码成功", result.length);
    return {}
    
}