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

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 scoreBiz from "../mobileFuHuaQi/fuHuaQi/score";
import * as fuhuaqiData from "../../data/fuHuaQi/fuhuaqi";
import * as financingData from "../../data/fuHuaQi/monthTask/financing";
import { CHANGEMODE, CYCSRBJ, CYCXFX, ENTERPRISESIZE, FINANCINGROUNDS, FUHUAQICUSTOMTASKTYPE, FUHUASTATE, INDUSTRY, LISTINGSITUATION, MOVEOUTCAUSE, MOVEOUTCAUSENOTCLIENT, MOVEOUTTRACE, MOVEOUTTYPE, NASHUIRENZIZHI, RAS, SCOREWAYS, STATEENUM, TASKTYPEENUM, VIRTUALCAUSE } 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";
import { findFuHuaQiScoreInfo_repair, initFuHuaQiScore_repair } from "../../data/fuHuaQi/scoreRepair";
import { addMany_repair, getAllLog_repair } from "../../data/fuHuaQi/scoreLogRepair";
import { findI18nRegisterListByParam, findOneI18nRegister } from "../../data/fuHuaQi/instituQualify/i18nRegister";
import * as icrData from "../../data/fuHuaQi/instituQualify/icr";
import * as startupTeacherData from "../../data/fuHuaQi/instituQualify/startupTeacher";
import * as zjBeyondLayoutData from "../../data/fuHuaQi/instituQualify/zjBeyondLayout";
import { replenishMyEnterpriseInPutInfo, updateMoveOutInfo } from "../mobileFuHuaQi/enterprise/myEnterprise";
import { findEnterpriseInitialTeamsByParam } from "../../data/enterprise/initialTeam";
import { count } from "console";
import { onceSheetBecomeOfblockData } from "../../util/analysisExcel";
import { findEnterpriseList } from "../../data/enterprise/enterprise";
import { extractData } from "../../util/piecemeal";
import { EnterpriseListConfig } from "../../config/splitResultConfig";
import { changeAddToString } from "../../tools/system";
import { changeEnumValue } from "../../util/verificationEnum";
import { addTask } from "../../data/fuHuaQi/customTask";
import { addressIsInZJ, getAddressLatAndLng, latLngInZJ } from "../../tools/transCode";

const xlsx = require('node-xlsx');
const path = require('path');
const fs = require('fs');

/**
 * 发放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) {
        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 {}
    
}

export async function addFinancingIndustry() {
    let dataList = await financingData.findFinancingList({});
    for (let i = 0; i < dataList.length; i++) {
        let {uscc, fuHuaQiUscc, name, taskId} = dataList[i];
        let enterInfo = await enterpriseData.findEnterpriseByUscc(uscc);
        let finInfo = await financingData.findFinancingInfoByTaskIdAndSucc(taskId, uscc);
        finInfo.industry = JSON.parse( JSON.stringify(enterInfo.industry));
        finInfo.save();
    }
    console.log("补全融资领域成功",dataList.length);
    return {}
}

export async function addBussiness() {
    let {sheetMap} = getExcel(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", '企业经营数据底库数据.xlsx' ));
    let sheetDataList = sheetMap["Sheet1"];
   
    let dataList = [];
    let distinctMap = {};
    sheetDataList.forEach( (subList, index)=> {
        if (!index) return;
        let year = subList[1].split('/')[0] ? parseInt(subList[1].split('/')[0]) : 0;
        let quarter = subList[1].split('/')[1] ? parseInt(subList[1].split('/')[1]) : 0;
        let beOnTheMarket = [];//上市情况
        let isBeOnTheMarket = false;
        if (subList[9] == "是" || subList[10] == "是" || subList[11] == "是") {
            beOnTheMarket.push(LISTINGSITUATION.科创板);
            isBeOnTheMarket = true;
        }
        if (subList[12] == "是") {
            beOnTheMarket.push(LISTINGSITUATION.A股);
            isBeOnTheMarket = true;
        }
        if (subList[13] == "是") {
            beOnTheMarket.push(LISTINGSITUATION.海外);
            isBeOnTheMarket = true;
        }
        dataList.push({
            fuHuaQiName:subList[0],
            year, quarter,
            name:subList[2],
            addfirst:subList[3],
            uscc:subList[4],
            BI:subList[5],//营业收入
            RD:subList[6],//研发投入
            TXP:subList[7],//纳税
            beOnTheMarket,
            isBeOnTheMarket
        });
        if (!distinctMap[subList[4]]) distinctMap[subList[4]] = 0;
        distinctMap[subList[4]] += 1;
    });

    for (let uscc in distinctMap) {
        if (distinctMap[uscc] > 1) console.log(uscc);
    }


    let fuHuaQiNameMap = await fuhuaqiData.findAllFuHuaQiOperationUsccMap();

    let qxList = [];
    for (let i= 0; i < dataList.length; i++) {
        let {fuHuaQiName, uscc} = dataList[i];
       
        if (fuHuaQiName == "大得创同(上海)科技有限公司") {
            fuHuaQiName = `大得创同（上海）科技有限公司`
        }
        else if (fuHuaQiName.indexOf("上海京航创业孵化器管理有限公司") > -1) {
            fuHuaQiName = "上海京航创业孵化器管理有限公司"
        } 
        else if (fuHuaQiName.indexOf("上海创智空间创业孵化器管理有限公司") > -1) {
            fuHuaQiName = "上海创智空间创业孵化器管理有限公司"
        }
        else if (fuHuaQiName.indexOf("上海祖率创业孵化器管理有限公司") > -1) {
            fuHuaQiName = "上海祖率创业孵化器管理有限公司"
        }
        else if (fuHuaQiName == "上海纳贤创业孵化器经营管理有限公司") {
            fuHuaQiName = "上海纳贤创业孵化器管理有限公司";
        }

        let check = true;
        if (!fuHuaQiNameMap[fuHuaQiName]) check = false;

        let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);
        if (!enterpriseInfo || !enterpriseInfo.uscc) check = false;
        // else if (enterpriseInfo.qualification) {
        //     if (enterpriseInfo.qualification.isHighTech == true && isHighTech )
        // }
        // isHighTech:Boolean,
        // highTechMs:Number,//高新技术
        // isZjtx:Boolean,
        // zjtxMs:Number,//专精特新
        // isXjrpy:Boolean,
        // xjrpyMs:Number,//小巨人培育
        // isXjr:Boolean,
        // xjrMs:Number,//小巨人
        // beOnTheMarket:[Number],//上市情况
        // isBeOnTheMarket:{type:Boolean, default:false}//是否上市
        if (check) qxList.push(dataList[i]);
    }


    return {};
}

/**
 * 内网用 外网不能调用
 */
export async function repairScore() {
    let data = await findFuHuaQiList({});

    let createMonthMap = {};
    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//在获取列表的时候要同步数据
        // });
        let createMonth = !info.createTime ? 0 : new Date(info.createTime).getMonth();
        createMonthMap[info.uscc] = createMonth;
    });

    // await initFuHuaQiScore_repair(addList);

    let firstSelectList = await scoreLogData.getAllLog();
    let tagTimeOutList = await getAllLog_repair({timeMs:{"$gt":1691377409842}, ways:{"$ne":SCOREWAYS.任务得分} });

    let list = firstSelectList.concat(tagTimeOutList);
    list.sort((a,b) => {return a.timeMs - b.timeMs});

    /**获取除任务得分之外的初始分 */
    let initSortMap = {};//格式 {uscc:{type:info }}

    /**获取非任务得分 */
    let 我的信息 = {};
    let 我的数据 = {};
    let 我的企业数据 = {};
    list.forEach(info => {
        let {uscc, ways, addScore, timeMs} = info;
        if (ways == SCOREWAYS.任务得分) return;
        if (!我的信息[uscc]) 我的信息[uscc] = [];
        if (!我的数据[uscc]) 我的数据[uscc] = [];
        if (!我的企业数据[uscc]) 我的企业数据[uscc] = [];
        if (ways == SCOREWAYS.我的企业数据) 我的企业数据[uscc].push({ ways,addScore, timeMs });
        else if (ways == SCOREWAYS.我的信息) 我的信息[uscc].push({ ways,addScore, timeMs });
        else if (ways == SCOREWAYS.我的数据) 我的数据[uscc].push({ ways,addScore, timeMs });
        
        if (!initSortMap[uscc]) initSortMap[uscc] = {};
        if (!initSortMap[uscc][ways]) initSortMap[uscc][ways] = addScore;
    });

    let successMap = {};//修复好的数据 格式 {uscc:[] }
    /**延续性算分 */
    for (let uscc in 我的信息) {
        let subList = 我的信息[uscc].sort( (a, b) => {return a.timeMs - b.timeMs});
        if (!successMap[uscc]) successMap[uscc] = [];
        /**前一个分数减去后一个分数得到分值差 */
        let score = 0;
        subList.forEach( (info, index) => {
            let { addScore, timeMs } = info;
            if (!index) {
                score = addScore;//赋值初始分数
                successMap[uscc].push({
                    changeMode:CHANGEMODE.增加,
                    ways:SCOREWAYS.我的信息,
                    addScore:addScore,
                    timeMs,
                    month:moment(timeMs).format("YYYY-MM-DD"),
                });
            }
            else {
                let changeScore = addScore -score;
                score = addScore;
                successMap[uscc].push({
                    changeMode:changeScore > 0 ?CHANGEMODE.增加 : CHANGEMODE.减少,
                    ways:SCOREWAYS.我的信息,
                    addScore:changeScore,
                    timeMs,
                    month:moment(timeMs).format("YYYY-MM-DD"),
                });
            }
        });
    }

    for (let uscc in 我的数据) {
        let subList = 我的数据[uscc].sort( (a, b) => {return a.timeMs - b.timeMs});
        if (!successMap[uscc]) successMap[uscc] = [];
        /**前一个分数减去后一个分数得到分值差 */
        let score = 0;
        subList.forEach( (info, index) => {
            let { addScore, timeMs } = info;
            if (!index) {
                score = addScore;//赋值初始分数
                successMap[uscc].push({
                    changeMode:CHANGEMODE.增加,
                    ways:SCOREWAYS.我的数据,
                    addScore:addScore,
                    timeMs,
                    month:moment(timeMs).format("YYYY-MM-DD"),
                });
            }
            else {
                let changeScore = addScore - score;
                score = addScore;
                successMap[uscc].push({
                    changeMode:changeScore > 0 ?CHANGEMODE.增加 : CHANGEMODE.减少,
                    ways:SCOREWAYS.我的数据,
                    addScore:changeScore,
                    timeMs,
                    month:moment(timeMs).format("YYYY-MM-DD"),
                });
            }
        });
    }


    for (let uscc in 我的企业数据) {
        let subList = 我的企业数据[uscc].sort( (a, b) => {return a.timeMs - b.timeMs});
        if (!successMap[uscc]) successMap[uscc] = [];
        /**前一个分数减去后一个分数得到分值差 */
        let score = 0;
        subList.forEach( (info, index) => {
            let { addScore, timeMs } = info;
            if (!index) {
                score = addScore;//赋值初始分数
                successMap[uscc].push({
                    changeMode:CHANGEMODE.增加,
                    ways:SCOREWAYS.我的企业数据,
                    addScore:addScore,
                    timeMs,
                    month:moment(timeMs).format("YYYY-MM-DD"),
                });
            }
            else {
                let changeScore = addScore - score;
                score = addScore;
                successMap[uscc].push({
                    changeMode:changeScore > 0 ?CHANGEMODE.增加 : CHANGEMODE.减少,
                    ways:SCOREWAYS.我的企业数据,
                    addScore:changeScore,
                    timeMs,
                    month:moment(timeMs).format("YYYY-MM-DD"),
                });
            }
        });
    }

    /**算任务分数 */
    let taskMap = {};
    let taskList = await taskData.findTaskListByParam({});
    for (let i =0; i < taskList.length; i++) {
        let {fuHuaQiUscc, isSubmit, type, month, year, submitTime} = taskList[i];
        if (month == 8) continue;
        let addScore = 0;
        if (isSubmit) addScore = getOnceTaskScore(createMonthMap[fuHuaQiUscc]);
        else addScore = getOnceTaskDeductScore(createMonthMap[fuHuaQiUscc]);

        let timeMs = 0;
        if (isSubmit) timeMs = submitTime;
        else {
            timeMs = new Date(`${year}-${month+1}-1 00:00:0${type}`).valueOf();
        }
        if (!successMap[fuHuaQiUscc]) successMap[fuHuaQiUscc] = [];
        if (!taskMap[fuHuaQiUscc]) taskMap[fuHuaQiUscc] = [];
        taskMap[fuHuaQiUscc].push({
            taskType:type,
            timeMs,
            ways:SCOREWAYS.任务得分,
            addScore,
            changeMode:addScore>0 ? CHANGEMODE.增加 : CHANGEMODE.减少,
            month:moment(timeMs).format("YYYY-MM-DD"),
        });
        successMap[fuHuaQiUscc].push({
            taskType:type,
            timeMs,
            ways:SCOREWAYS.任务得分,
            addScore,
            changeMode:addScore>0 ? CHANGEMODE.增加 : CHANGEMODE.减少,
            month:moment(timeMs).format("YYYY-MM-DD"),
        });
    }

    // let secondMap = {};
    /**排序算总分 */
    let filesList = [];
    for (let uscc in successMap) {
        let subList = successMap[uscc].sort( (a, b) => {return a.timeMs - b.timeMs});

        let nodeScore = 400;
        let itemLogList = [];
        let taskLogList = [];
        let 任务得分 = 0;
        let 我的企业得分 = 0;
        let 我的数据得分 = 0;
        let 我的信息得分 = 0;

        subList.forEach(info => {
            let {taskType, timeMs, ways, addScore, changeMode, month} = info;
            nodeScore += addScore;
            filesList.push({taskType, timeMs, ways, addScore, changeMode, score:nodeScore, uscc});
            itemLogList.push({ways, addScore, score:nodeScore, month});
            if (ways == SCOREWAYS.任务得分){
                任务得分 +=  addScore;
                taskLogList.push({taskType, ways, addScore, score:nodeScore,month});//todo
            }
            if (ways == SCOREWAYS.我的企业数据) 我的企业得分 +=  addScore;
            if (ways == SCOREWAYS.我的数据) 我的数据得分 +=  addScore;
            if (ways == SCOREWAYS.我的信息) 我的信息得分 +=  addScore;
        });

        /**验算分数 */
        let dbScoreInfo = await scoreData.findFuHuaQiScoreInfo(uscc);
        let check = dbScoreInfo.myDataScore + dbScoreInfo.baseDataScore + dbScoreInfo.myEnterpriseScore + dbScoreInfo.taskScore + 400;
        if (Math.ceil(check) != Math.ceil(nodeScore)) console.log("验算不通过")
    }
    /** 将第二次清洗好的有ms的数据和 大于 1691377409842  时刻的数据进行组合*/

    // fs.writeFileSync(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", "scoreLog.json" ), JSON.stringify(filesList));
    
}


export async function changeScoreLogByJson() {
    let dataStr = fs.readFileSync(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", "scoreLog.json" ));
    let data = JSON.parse(dataStr);
    await scoreLogData.addMany(data);
    console.log("分数日志修复成功");
    // let dataStr2 = fs.readFileSync(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", "score.json" ));
    // let data2 = JSON.parse(dataStr2);
    // await initFuHuaQiScore(data2);

    // console.log("分数修复成功");
    return {};
}


export async function changeTaskScortTimeData() {
    let list = await scoreLogData.getLogByParam({ways:SCOREWAYS.任务得分, changeMode:CHANGEMODE.减少})
    for (let i = 0; i < list.length; i++) {
        let {uscc, ways, taskType, changeMode, timeMs} = list[i];
        let newTimeMs = moment(timeMs).subtract(1,'months').valueOf();
        await scoreLogData.updateLog(uscc, timeMs, ways,taskType, newTimeMs);
    }
    console.log("完成全部分数数据修复");
}


export async function instituQualifyNameChangeToOperationName() {
    let nameMap = await fuhuaqiData.findFuHuaQiOperationNameMapByParam({})

    let i18nList = await findI18nRegisterListByParam({});
    for (let i = 0; i < i18nList.length; i++) {
        let {id, uscc} = i18nList[i];
        let itemInfo = await findOneI18nRegister(id)
        itemInfo.name = nameMap[uscc];
        await itemInfo.save();
    }

    let icrList = await icrData.findListDataByParam({});
    for (let i = 0; i < icrList.length; i++) {
        let {id, uscc} = icrList[i];
        let itemInfo = await icrData.findOneData(id)
        itemInfo.name = nameMap[uscc];
        await itemInfo.save();
    }

    
    
    let startupTeacherList = await startupTeacherData.findListDataByParam({});
    for (let i = 0; i < startupTeacherList.length; i++) {
        let {id, uscc} = startupTeacherList[i];
        let itemInfo = await startupTeacherData.findOneData(id)
        itemInfo.name = nameMap[uscc];
        await itemInfo.save();
    }


    let zjBeyondLayoutList = await zjBeyondLayoutData.findListDataByParam({});
    for (let i = 0; i < zjBeyondLayoutList.length; i++) {
        let {id, uscc} = zjBeyondLayoutList[i];
        let itemInfo = await zjBeyondLayoutData.findOneData(id)
        itemInfo.name = nameMap[uscc];
        await itemInfo.save();
    }

    console.log("完成全部名称数据修复");

}


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

    let createMonthMap = {};
    data.forEach(info => {
        let createMonth = !info.createTime ? 0 : new Date(info.createTime).getMonth();
        createMonthMap[info.uscc] = createMonth;
    });

    let taskList = await taskData.findTaskListByParam({});
    let taskScoreMap = {};
    for (let i =0; i < taskList.length; i++) {
        let {fuHuaQiUscc, isSubmit, type, month, year, submitTime} = taskList[i];
        if (month == 8) continue;
        let addScore = 0;
        if (isSubmit) addScore = getOnceTaskScore(createMonthMap[fuHuaQiUscc]);
        else addScore = getOnceTaskDeductScore(createMonthMap[fuHuaQiUscc]);

        let timeMs = 0;
        if (isSubmit) timeMs = submitTime;
        else {
            timeMs = new Date(`${year}-${month+1}-1 00:00:0${type}`).valueOf();
        }
        if (!taskScoreMap[fuHuaQiUscc]) taskScoreMap[fuHuaQiUscc] = 0;
        taskScoreMap[fuHuaQiUscc] += addScore;
    }

    for (let uscc in taskScoreMap) {
        let item = await scoreData.findFuHuaQiScoreInfo(uscc);
        item.taskScore = taskScoreMap[uscc];
        await item.save();
    }

    console.log("任务分数修复成功");
}


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

    for (let i = 0; i < data.length; i++) {
        let info = data[i];
        await scoreBiz.updateScore(info.uscc, SCOREWAYS.我的企业数据, false);
    }
    

    console.log("我的企业分数修复成功");
}

export async function enterpriseOutAnIn() {
    let fuHuaQiUscc = "91310000080089147T";
    
    let oldEnterpriseList = await enterpriseData.findEnterpriseList({fuHuaQiUscc:fuHuaQiUscc});

    let oldFuHuaQiInfo = await fuhuaqiData.findFuHuaQiByUSCC(fuHuaQiUscc);
    oldFuHuaQiInfo.fuHuaEnterpriseTotal = oldEnterpriseList.length;
    await oldFuHuaQiInfo.save();

    let newFuHuaQiUscc = "91310115MA1K4CG620";
    for (let i = 0; i < oldEnterpriseList.length; i++ ) {
        let info = oldEnterpriseList[i];
        if (info.uscc == "91310115MA1H8W6M37" || info.uscc == "91310115MACRM01T7F" || info.uscc == "91310115MA1HBMUQ8M") {
            continue;
        }
        await updateMoveOutInfo(fuHuaQiUscc, info.uscc,  MOVEOUTTYPE.非毕业迁出, MOVEOUTTRACE.迁出孵化器_仍在张江, [MOVEOUTCAUSE.其他] );
        let itemData:any = {
            name:info.name,
            uscc:info.uscc,
            logonTime:info.logonTime,
            isNaturalPersonHolding:info.isNaturalPersonHolding,
            leasedArea:info.leasedArea,
            timeOfImmigration:new Date().valueOf()
        }
        if (info.industry && info.industry.length) {
            itemData.industry = [];
            info.industry.forEach(subItem => {
                itemData.industry.push(subItem)
            })
        } else {
            itemData.industry = [INDUSTRY.综合];
        }

        if (info.mainBusiness) {
            itemData.mainBusiness = info.mainBusiness;
        } else {
            itemData.mainBusiness = "-";
        }

        if (info.firstIncubationTime) {
            itemData.firstIncubationTime = info.firstIncubationTime;
        } else {
            itemData.firstIncubationTime = new Date().valueOf();
        }

        if (info.logonAddress[0] != "") {
            itemData.logonAddress = [info.logonAddress[0], info.logonAddress[1], info.logonAddress[2],info.logonAddress[3]];
            itemData.oldLogonAddress =  [info.logonAddress[0], info.logonAddress[1], info.logonAddress[2],info.logonAddress[3]];
        } else {
            itemData.logonAddress = ["上海市", "上海市", "浦东新区", "盛荣路88弄"]
            itemData.oldLogonAddress = ["上海市", "上海市", "浦东新区", "盛荣路88弄"]
        }

        if (info.operatingAddress[0] != "") {
            itemData.operatingAddress = [info.operatingAddress[0], info.operatingAddress[1], info.operatingAddress[2], info.operatingAddress[3]];
        } else {
            itemData.operatingAddress = ["上海市", "上海市", "浦东新区", "盛荣路88弄"]
        }


        await replenishMyEnterpriseInPutInfo(newFuHuaQiUscc, itemData);

        console.log(info.uscc, "更新成功");
    }

    return {isSuccess:true}
}


export async function enterpriseOutAndInMoverOut() {
   
    let changeList = [
        {uscc:"91310107MA1G03JC01", state:4, moveOutType:2, moveOutTrace:3, moveOutCause:[3], moveOutTime:1682581601081},
        {uscc:"91310115MA1K4DHM2C", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[3], moveOutTime:1682581635490},
        {uscc:"91310115MA1K4RB106", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[7], moveOutTime:1682489345033},
        {uscc:"91310115MA1K4KW74X", state:4, moveOutType:2, moveOutTrace:2, moveOutCause:[3], moveOutTime:1682581666692},
        {uscc:"91310114580594174C", state:4, moveOutType:1, moveOutTrace:0, moveOutCause:[], moveOutTime:1682493625633},
        {uscc:"91310115MA1K3UF6XJ", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[7], moveOutTime:1682490204904},
        {uscc:"91310115MA1K3TCU4J", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[7], moveOutTime:1682581717220},
        {uscc:"91310115332407042L", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[6], moveOutTime:1682581801827},
        {uscc:"91310115MA1K46M054", state:4, moveOutType:2, moveOutTrace:3, moveOutCause:[7], moveOutTime:1682581847519},
        {uscc:"91310115787835043H", state:4, moveOutType:2, moveOutTrace:3, moveOutCause:[6], moveOutTime:1682582011770},
        {uscc:"91310115MA1K464U6J", state:4, moveOutType:2, moveOutTrace:2, moveOutCause:[3], moveOutTime:1682581928164},
        {uscc:"91310115MA1K3KLW3B", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[3], moveOutTime:1682490897888},
        {uscc:"91310120MA1HP2CD93", state:4, moveOutType:2, moveOutTrace:3, moveOutCause:[7], moveOutTime:1682581883451},
        {uscc:"91310115324572718T", state:4, moveOutType:2, moveOutTrace:3, moveOutCause:[3], moveOutTime:1682581973779},
        {uscc:"91310115093486846M", state:4, moveOutType:2, moveOutTrace:2, moveOutCause:[3], moveOutTime:1682585240969},
        {uscc:"91310104MA1FR4XU6C", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[3], moveOutTime:1682585292604},
        {uscc:"91310115MA1HA97AX8", state:4, moveOutType:2, moveOutTrace:2, moveOutCause:[3], moveOutTime:1682585337416},
        {uscc:"91310115MA1K3M7X8G", state:4, moveOutType:3, moveOutTrace:1, moveOutCause:[11], moveOutTime:1682497119206},
        {uscc:"91310115MA1K3M0971", state:4, moveOutType:2, moveOutTrace:3, moveOutCause:[7], moveOutTime:1682585388144},
        {uscc:"91310110552932869C", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[7], moveOutTime:168258542922},
        {uscc:"91310117MA1J15099E", state:4, moveOutType:3, moveOutTrace:1, moveOutCause:[8], moveOutTime:1682485522736},
        {uscc:"91310115MA1K3W8E63", state:4, moveOutType:2, moveOutTrace:3, moveOutCause:[3], moveOutTime:1682585495658},
        {uscc:"91310115MA1K3RL6XG", state:4, moveOutType:3, moveOutTrace:3, moveOutCause:[8], moveOutTime:1682490173126},
        {uscc:"91310115MA1K4F0L16", state:4, moveOutType:2, moveOutTrace:2, moveOutCause:[3], moveOutTime:1682585529101},
        {uscc:"91310115MA1K3LJQ46", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[4], moveOutTime:1682585601768},
        {uscc:"91310230MA1K2RQFXL", state:4, moveOutType:2, moveOutTrace:3, moveOutCause:[3], moveOutTime:1682585647682},
        {uscc:"91310115MA1K4LKT09", state:4, moveOutType:3, moveOutTrace:1, moveOutCause:[10], moveOutTime:1682585682836},
        {uscc:"91310115MA1K4FDJ8K", state:4, moveOutType:3, moveOutTrace:3, moveOutCause:[8], moveOutTime:1682497079382},
        {uscc:"91310120MA1HR26EXF", state:4, moveOutType:2, moveOutTrace:3, moveOutCause:[7], moveOutTime:1682489670911},
        {uscc:"91310115MA1K4K5U0K", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[3], moveOutTime:1682585704050},
        {uscc:"91310115MA1H8EFK59", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[4], moveOutTime:1682585874838},
        {uscc:"91310115MA1K4GYW0W", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[4], moveOutTime:1682585926865},
        {uscc:"91310115MA1K4DWQ0P", state:4, moveOutType:3, moveOutTrace:1, moveOutCause:[8], moveOutTime:1682497148951},
        {uscc:"91310230MA1JT9A10G", state:4, moveOutType:2, moveOutTrace:3, moveOutCause:[7], moveOutTime:1690795581180},
        {uscc:"91310115MA1K3EP51A", state:4, moveOutType:3, moveOutTrace:1, moveOutCause:[11], moveOutTime:1682496860528},
        {uscc:"91310115MA7BUMWB7C", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[2], moveOutTime:1690795713974},
        {uscc:"91310112MA1GCDMK8E", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[1], moveOutTime:1690870871550},
        {uscc:"91310115MA1K4JDJ9C", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[3], moveOutTime:1682490257084},
        {uscc:"91310115MA1K4PEN4T", state:4, moveOutType:2, moveOutTrace:2, moveOutCause:[3], moveOutTime:1682586130235},
        {uscc:"91310115MA1K4NP00K", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[3], moveOutTime:1682586160618},
        {uscc:"91310115MA1K4LT43K", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[4], moveOutTime:1690870986478},
        {uscc:"91310115MA1K44L62W", state:4, moveOutType:3, moveOutTrace:1, moveOutCause:[8], moveOutTime:1682496967197},
        {uscc:"91310115MA1K4FQ649", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[2], moveOutTime:1690871109622},
        {uscc:"91310115MA1K4U7PXE", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[7], moveOutTime:1682586238748},
        {uscc:"91310115MA1K3XJE9C", state:4, moveOutType:3, moveOutTrace:1, moveOutCause:[10], moveOutTime:1682589237793},
        {uscc:"91310115MA1K3Y9R4C", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[3], moveOutTime:1682589152059},
        {uscc:"91310120MA1J0TKL4G", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[1], moveOutTime:1690871225076},
        {uscc:"91310000MA1H379QXG", state:4, moveOutType:2, moveOutTrace:3, moveOutCause:[7], moveOutTime:1682589550895},
        {uscc:"91310115MA1K4HEA69", state:4, moveOutType:3, moveOutTrace:3, moveOutCause:[11], moveOutTime:1682497591076},
        {uscc:"91310115MA1K4JG37P", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[3], moveOutTime:1682588966244},
        {uscc:"91310115MA1K3G7E6N", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[3], moveOutTime:1682589207448},
        {uscc:"91310110MA1G8R1G8L", state:4, moveOutType:2, moveOutTrace:3, moveOutCause:[3], moveOutTime:1682589400881},
        {uscc:"913101153245129428", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[4], moveOutTime:1682589344316},
        {uscc:"91310115MA1K4NJH1U", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[4], moveOutTime:1682589000664},
        {uscc:"91310115MA1K4CU53G", state:4, moveOutType:3, moveOutTrace:2, moveOutCause:[9], moveOutTime:1682497003624},
        {uscc:"91310115MA1K4LAP4F", state:4, moveOutType:1, moveOutTrace:0, moveOutCause:[], moveOutTime:1682496580775},
        {uscc:"91310115MA1HA2U13D", state:4, moveOutType:1, moveOutTrace:0, moveOutCause:[], moveOutTime:1690871378964},
        {uscc:"91310115MA1K4T9Y39", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[7], moveOutTime:1682589482853},
        {uscc:"91310115MA1K4T1B4B", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[5], moveOutTime:1690871457954},
        {uscc:"91310115MA1HAPWW2K", state:4, moveOutType:2, moveOutTrace:3, moveOutCause:[3], moveOutTime:1682589695091},
        {uscc:"91310115MA1K3UM56C", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[1], moveOutTime:1690871523129},
        {uscc:"91310115MA1K46216C", state:4, moveOutType:2, moveOutTrace:3, moveOutCause:[5], moveOutTime:1690871584270},
        {uscc:"91310115MABTG59019", state:4, moveOutType:2, moveOutTrace:1, moveOutCause:[7], moveOutTime:1682589274328}
    ];
    let fuHuaQiUscc = "91310000080089147T";
    for (let i = 0; i <changeList.length; i++) {
        let info = changeList[i];
        let item = await enterpriseData.findEnterpriseByUscc(info.uscc);
        item.state = info.state;
        item.moveOutType = info.moveOutType;
        item.moveOutTrace = info.moveOutTrace;
        item.moveOutCause = info.moveOutCause;
        item.moveOutTime = info.moveOutTime;
        item.fuHuaQiUscc = fuHuaQiUscc;
        await item.save();
        console.log(info.uscc, "更新成功");
    }
    
    return {isSuccess:true}
}


/**更新2024年的分数 */
export async function updteScortFor2024() {
    let scoreList = await scoreData.findScoreDataByParam({});

    for (let i = 0; i < scoreList.length; i++) {

        /**上一次评分 */
        // lastScore:{type:Number, default:0}//在获取列表的时候要同步数据
        let {startScore, uscc, myDataScore, baseDataScore, myEnterpriseScore, taskScore} = scoreList[i];
        // await scoreData.findFuHuaQiScoreInfo(uscc);
        /**计算分数 */
        let count = startScore+myDataScore+baseDataScore+myEnterpriseScore+taskScore;
        let change = 0;
        let lastYearStar = 0;
        if (count <= 100) {
            change = -2;
            lastYearStar = 1;
        } else if (count > 100 && count <= 300) {
            change = -1;
            lastYearStar = 2;
        } else if (count > 300 && count <= 500) {
            change = 0;
            lastYearStar = 3;
        }else if (count > 500 && count <= 600) {
            change = 1;
            lastYearStar = 4;
        }else if (count > 600) {
            change = 2;
            lastYearStar = 5;
        }

        let taskList = await taskData.findTaskListByParam({fuHuaQiUscc:uscc, key:{"$gt":20240, "$lt":20245}});
        let check = 0;
        let notCheck = 0;
        taskList.forEach(item => {
            let {isSubmit} = item;
            if (isSubmit) check += 5;
            else notCheck -= 10
        });
        //计算任务分
        let newTask = check + notCheck;
        let newStartScore = startScore - change;

        let newScore = newStartScore+myDataScore+baseDataScore+myEnterpriseScore+newTask;
        //添加日志
        await scoreLogData.addLog(uscc, SCOREWAYS.分值重置, CHANGEMODE.减少, newScore, newScore-count);
        let newInfo = await scoreData.findFuHuaQiScoreInfo(uscc);
        newInfo.updateTime = new Date().valueOf();
        newInfo.taskScore = newTask;
        newInfo.lastYearStar = newStartScore;
        await newInfo.save(); 
    }

    console.log("分数更新完毕");
    return {isSuccess:true}
}

/**
 * 第二次修改
 * @returns 
 */
export async function repairResettingScore() {
    let scoreList = await scoreData.findScoreDataByParam({});

    // for (let i = 0; i < scoreList.length; i++) { 
    //     let { uscc } = scoreList[i];
    //     let taskList = await taskData.findTaskListByParam(
    //         {
    //             fuHuaQiUscc:uscc,
    //             year:2024
    //         }
    //     );
    //     let check = 0;
    //     let notCheck = 0;
    //     taskList.forEach(item => {
    //         let {isSubmit, key} = item;
    //         if (key == 20245) {
    //             if (isSubmit) check += 5;
    //         } else {
    //             if (isSubmit) check += 5;
    //             else notCheck -= 10
    //         }
    //     });
    //     let task2023List = await taskData.findTaskListByParam({year:2023, fuHuaQiUscc:uscc});
    //     let check2023 = 0;
    //     let notCheck2023 = 0;
    //     task2023List.forEach(item => {
    //         let {isSubmit, task} = item;
    //         if (isSubmit) check2023 += 5;
    //         else notCheck2023 -= 10
    //     });
    //     let taskCount2023 = check2023 + notCheck2023;//2023年度任务总分
    //     console.log();
    // }
    // return

    for (let i = 0; i < scoreList.length; i++) {
        //延续分数 然后重置
        let { uscc, lastYearStar, myDataScore, baseDataScore, myEnterpriseScore, startScore } = scoreList[i];
        let task2023List = await taskData.findTaskListByParam({year:2023, fuHuaQiUscc:uscc});
        let check2023 = 0;
        let notCheck2023 = 0;
        task2023List.forEach(item => {
            let {isSubmit} = item;
            if (isSubmit) check2023 += 5;
            else notCheck2023 -= 10
        });
        let taskCount2023 = check2023 + notCheck2023;//2023年度任务总分
        let count2023 = 400 + myDataScore + baseDataScore + myEnterpriseScore + taskCount2023;

        let change = 0;
        let newLastYearStar = 0;
        if (count2023 <= 100) {
            change = -2;
            newLastYearStar = 1;
        } else if (count2023 > 100 && count2023 <= 300) {
            change = -1;
            newLastYearStar = 2;
        } else if (count2023 > 300 && count2023 <= 500) {
            change = 0;
            newLastYearStar = 3;
        }else if (count2023 > 500 && count2023 <= 600) {
            change = 1;
            newLastYearStar = 4;
        }else if (count2023 > 600) {
            change = 2;
            newLastYearStar = 5;
        }

        let newStartScore = change + 400;//新的初始分

        let newLogInfo = await scoreLogData.getNewLog(uscc);
        let logList = await scoreLogData.getLogByParam({uscc, timeMs:{"$gt":1713923224940} });
        let socreT = newLogInfo.score;//归档前的本年度分数
        for (let j = 0; j < logList.length; j++) {
            let {score, timeMs, addScore} = logList[j];
            socreT = socreT + addScore;
            await scoreLogData.updateInfo({uscc, timeMs}, {score:socreT});
        }
        /**重置分 */
        let taskList = await taskData.findTaskListByParam(
            {
                fuHuaQiUscc:uscc,
                year:2024
            }
        );
        let check = 0;
        let notCheck = 0;
        taskList.forEach(item => {
            let {isSubmit, key} = item;
            if (key == 20245) {
                if (isSubmit) check += 5;
            } else {
                if (isSubmit) check += 5;
                else notCheck -= 10
            }
        });
        let newTask = check + notCheck;//新的任务分数
        let newInfo = await scoreData.findFuHuaQiScoreInfo(uscc);
        newInfo.updateTime = new Date().valueOf();
        newInfo.taskScore = newTask;
        newInfo.startScore = newStartScore;
        newInfo.lastYearStar = newLastYearStar;

        await newInfo.save(); 
        
        let updateLogInfo = {
            score:(newStartScore+myDataScore+baseDataScore+myEnterpriseScore+newTask),
            timeMs:new Date().valueOf(),
            addScore:( (newStartScore+myDataScore+baseDataScore+myEnterpriseScore+newTask) - socreT ),
        };
        await scoreLogData.updateInfo({uscc, ways:SCOREWAYS.分值重置 }, updateLogInfo);
    }

    console.log("分数更新完毕");
    return {isSuccess:true}
}


export async function outPutOnceEnterprise91310115MA1K4TB91Q() {
    await updateMoveOutInfo("91310115MA1K3TAP0N", "91310115MA1K4TB91Q", MOVEOUTTYPE.非毕业迁出, MOVEOUTTRACE.迁出孵化器_仍在张江, [MOVEOUTCAUSENOTCLIENT.办公空间拓展_无合适办公空间_]);
    console.log("迁出成功");
}


/*第一次清洗企业数据 */
export async function ETL() {
    //比对名称和uscc 有一个相同认为是同一个公司
    let fhqNameMap = await fuhuaqiData.findFuHuaQiOperationNameMapByParam({});

    let data = onceSheetBecomeOfblockData('第一批企业数据校验结果.xlsx', 'Sheet1');
    let dataList = data[0].blockData;

    for (let i = 1; i < dataList.length; i++) {
        let itemList = dataList[i];

        let 原文件导入名称 = itemList[0];
        let 系统匹配企业名称 = itemList[1];
        let 登记状态 = itemList[2];
        let 法定代表人 = itemList[3];
        let 注册资本 = itemList[4];
        let 实缴资本 = itemList[5];
        let 成立日期 = itemList[6];
        let 统一社会信用代码 = itemList[7];
        let 企业地址 = itemList[8];
        let 所属省份 = itemList[9];
        let 所属城市 = itemList[10];
        let 所属区县 = itemList[11];
        let 电话 = itemList[12];
        let 更多电话 = itemList[13];
        let 邮箱 = itemList[14];
        let 更多邮箱 = itemList[15];
        let 企业机构类型 = itemList[16];
        let 纳税人识别号 = itemList[17];
        let 注册号 = itemList[18];
        let 组织机构代码 = itemList[19];
        let 参保人数 = itemList[20];
        let 参保人数所属年报 = itemList[21];
        let 核准日期 = itemList[22];
        let 营业期限 = itemList[23];
        let 国标行业门类 = itemList[24];
        let 国标行业大类 = itemList[25];
        let 国标行业中类 = itemList[26];
        let 国标行业小类 = itemList[27];
        let 企查查行业门类 = itemList[28];
        let 企查查行业大类 = itemList[29];
        let 企查查行业中类 = itemList[30];
        let 企查查行业小类 = itemList[31];
        let 企业规模 = itemList[32];
        let 曾用名 = itemList[33];
        let 英文名 = itemList[34];
        let 官网 = itemList[35];
        let 通信地址 = itemList[36];
        let 企业简介 = itemList[37];
        let 经营范围 = itemList[38];
        let 登记机关 = itemList[39];
        let 纳税人资质 = itemList[40];
        let 最新年报年份 = itemList[41];
        let 企业经营状态 = itemList[42];

        let enterpriseInfo = await enterpriseData.selectOneEnterpriseByParam({"$or":[{name:系统匹配企业名称}, {uscc:统一社会信用代码}]});
        if (!enterpriseInfo || !enterpriseInfo.uscc) {
            console.log(`跳过点1 ${i}  数据为  ${统一社会信用代码}  ${系统匹配企业名称}`);
            continue;
        }

        /**处理注销企业 */
        if (统一社会信用代码 == "-") {
            console.log(`跳过点2 ${i}  数据为  ${统一社会信用代码}  ${系统匹配企业名称}`);
            continue;
        }

        /**名字相同 uscc不同 */
        if (enterpriseInfo.uscc != 统一社会信用代码) {
            enterpriseInfo.uscc = 统一社会信用代码;
        }
        if (enterpriseInfo.name != 系统匹配企业名称) {
            enterpriseInfo.name = 系统匹配企业名称;
        }

        /**核对基础信息，注册时间，注册地址，经营地址等 */
        if (成立日期 != "-") {
            enterpriseInfo.logonTime = new Date(成立日期).valueOf();
        }
        enterpriseInfo.logonAddress = [所属省份, 所属城市, 所属区县, 企业地址 ];
        if (经营范围 != "-" && enterpriseInfo.mainBusiness) {
            enterpriseInfo.mainBusiness = 经营范围;
        }
        let ras = RAS.续存;
        if (登记状态.indexOf("注销") != -1) {
            //企业注销  注销将企业改成迁出
            let 等级状态数组 = 登记状态.split("(");
            if (等级状态数组[1]) {
                enterpriseInfo.logOffMS = new Date(等级状态数组[1].replace(")", "")).valueOf();
            }
            enterpriseInfo.state = FUHUASTATE.迁出;
            enterpriseInfo.moveOutType = MOVEOUTTYPE.企业注销;
            ras = RAS.注销;
        }

        /** 增补字段 */
        enterpriseInfo.RAS = ras;//登记状态
        enterpriseInfo.legalPerson = 法定代表人;//法人
        enterpriseInfo.zhuceziben = 注册资本;//注册资本
        enterpriseInfo.shijiaoziben = 实缴资本;//实缴资本
        enterpriseInfo.dianHua = 电话;//电话
        enterpriseInfo.gengDuoDianHua = 更多电话;//更多电话
        enterpriseInfo.mail = 邮箱;//邮箱
        enterpriseInfo.moreMail = 更多邮箱;//更多邮箱
        enterpriseInfo.enterpriseType = 企业机构类型;//企业（机构）类型
        enterpriseInfo.zhuCeHao = 注册号;//注册号
        enterpriseInfo.zuZhiJiGouDaiMa = 组织机构代码;//组织机构代码
        enterpriseInfo.canBaoRenShu = 参保人数 == "-" || !参保人数 ? 0: parseInt(参保人数);  //参保人数
        enterpriseInfo.canBaoRenShuNianBao = 参保人数所属年报 == "-" || !参保人数所属年报 ? 0: parseInt(参保人数所属年报);  //参保人数所属年报
        enterpriseInfo.yingYeQiXian = 营业期限;//营业期限
        switch (企业规模) {
            case 'XS(微型)':  enterpriseInfo.qiYeGuiMo = ENTERPRISESIZE.微型;break;
            case 'S(小型)':  enterpriseInfo.qiYeGuiMo = ENTERPRISESIZE.小型;break;
            case 'M(中型)':  enterpriseInfo.qiYeGuiMo = ENTERPRISESIZE.中型;break;
            case 'L(大型)':  enterpriseInfo.qiYeGuiMo = ENTERPRISESIZE.大型;break;
            default:  enterpriseInfo.qiYeGuiMo = ENTERPRISESIZE.未知;break;
        }
        enterpriseInfo.guanWang = 官网;//官网
        enterpriseInfo.tongXinDiZhi = 通信地址;//通信地址
        enterpriseInfo.jianJie = 企业简介;//企业简介
        enterpriseInfo.dengJiJiGuan = 登记机关;//登记机关
        switch (纳税人资质) {
            case 'XS(微型)':  enterpriseInfo.naShuiRenZiZhi = NASHUIRENZIZHI.一般纳税人;break;
            case '增值税一般纳税人':  enterpriseInfo.naShuiRenZiZhi = NASHUIRENZIZHI.增值税一般纳税人;break;
            case 'M(中型)':  enterpriseInfo.naShuiRenZiZhi = NASHUIRENZIZHI.小规模纳税人;break;
            default:   enterpriseInfo.naShuiRenZiZhi = NASHUIRENZIZHI.未知;break;
        }
        enterpriseInfo.zuiXinNianBaoNianFen = 最新年报年份 == "-" || !最新年报年份 ? 0: parseInt(最新年报年份);  //最新年报年份

        await enterpriseInfo.save();
    }
    
    console.log("数据清洗结束");
}

export async function jiaoyanshuju() {
    let list = await enterpriseData.findEnterpriseList({fuHuaQiUscc:"91310115MA1K42L91E", state:{"$ne":4} });
    let 缺失注册时间 = 0;
    let 缺失注册时间的企业 = '';
    let 缺失注册地址 = 0;
    let 缺失经营地址 = 0;
    let 缺失迁入前地址 = 0;
    let 非新建企业 = 0;
    let 实体孵化未填报孵化面积 = 0;
    let 名单  = [];
    let 主营业务缺失 = 0;
    list.forEach(info => {
        if (!info.logonAddress || !info.logonAddress[0]) 缺失注册地址 += 1;
        
        if (!info.operatingAddress || !info.operatingAddress[0]) 缺失经营地址 += 1;
        if (!info.isCreate) {
            非新建企业 += 1;
            if (!info.oldLogonAddress || !info.oldLogonAddress[0]) 缺失迁入前地址 += 1;
        }
        if (!info.logonTime) {
            缺失注册时间 += 1;
            缺失注册时间的企业 = info.name;
        }
        if (info.state == FUHUASTATE.实体孵化 && !info.leasedArea) {
            实体孵化未填报孵化面积 += 1;
            名单.push(info.name);
        }
        if (!info.mainBusiness) 主营业务缺失 += 1;

    });
    let count = list.length;
    console.log();
}

let list = [

{name:"上海岷麒半导体技术有限公司", add:"上海市上海市浦东新区中国(上海)自由贸易试验区申江路5709号、秋月路26号1幢3层J-1室", time:"2024-04-09"},
{name:"上海企无行科技有限公司", add:"上海市上海市浦东新区蔡伦路85弄95号1幢2层A区201-3室", time:"2024-06-26"},
{name:"上海立业乐信息科技有限公司", add:"上海市上海市浦东新区蔡伦路85弄95号1幢2层A区201-2室", time:"2024-06-25"},
{name:"巨服（上海）医疗科技有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区龙东大道3000号1幢A楼601-11、12室", time:"2024-06-27"},
{name:"上海钟贺生物科技有限公司", add:"上海市上海市浦东新区蔡伦路1690号2号楼104室", time:"2023-12-13"},
{name:"上海瑞衍墨信息科技有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区金科路2966号1幢201室", time:"2024-06-24"},
{name:"上海钮晨科技有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区中科路1358号、环科路999弄3号一层G009工位", time:"2024-06-14"},
{name:"上海莫涵堂科技有限公司", add:"上海市上海市浦东新区沈梅路123弄9-10号四层4A室", time:"2024-06-07"},
{name:"上海沃睿丰新能源有限公司", add:"上海市上海市浦东新区沈梅路123弄9-10号三层303室", time:"2024-06-03"},
{name:"耐科思特电子科技（上海）有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区郭守敬路498号8幢19号楼3层", time:"2014-06-12"},
{name:"上海署雀新材料有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区纳贤路800号1幢B座7层714室", time:"2020-08-14"},
{name:"上海罗领世新材料技术有限公司", add:"上海市上海市浦东新区盛荣路88弄8号201室", time:"2024-05-20"},
{name:"中太乐曼（上海）科技有限公司", add:"上海市上海市浦东新区张衡路666弄1号610室", time:"2024-05-07"},
{name:"海纳智联数字科技（上海）有限公司", add:"上海市上海市浦东新区上海市浦东新区秀浦路3999弄1号", time:"2024-06-07"},
{name:"上海且尧电力科技有限公司", add:"上海市上海市浦东新区秀浦路3188弄65号303室", time:"2023-02-23"},
{name:"上海玩悦网络科技有限公司", add:"上海市上海市浦东新区上海市浦东新区秀浦路68号1幢东区3层311室", time:"2021-06-01"},
{name:"上海都井智能科技有限公司", add:"上海市上海市浦东新区上海市浦东新区秀浦路68号1幢东区2层212室", time:"2023-11-02"},
{name:"琛迅（上海）科技有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区郭守敬路351号1幢619室", time:"2024-06-03"},
{name:"上海仪茂科技有限公司", add:"上海市上海市浦东新区上海市浦东新区青黛路800号1幢B座3层317室", time:"2024-06-27"},
{name:"上海心纪元创时代生命科学有限公司", add:"上海市上海市浦东新区上海市浦东新区周浦镇天雄路166弄3号205室", time:"2024-06-27"},
{name:"上海集煜予科技有限公司", add:"上海市上海市浦东新区中国(上海)自由贸易试验区郭守敬路498号12幢2层21204、21206室", time:"2022-11-10"},
{name:"上海翼马平川智能科技有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区郭守敬路498号8幢19号楼3层", time:"2023-03-14"},
{name:"上海叁台元科技科技有限公司", add:"上海市上海市浦东新区中国(上海)自由贸易试验区张衡路200号2幢3层", time:"2024-05-14"},
{name:"上海澜昆微电子科技有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区郭守敬路498号8幢19号楼3层", time:"2024-05-15"},
{name:"上海麦浦迪科技有限公司", add:"上海市上海市浦东新区中国(上海)自由贸易试验区郭守敬路498号8幢19号楼3层", time:"2024-06-06"},
{name:"智领未来信息科技（上海）有限公司", add:"上海市上海市浦东新区中国(上海)自由贸易试验区郭守敬路498号8幢19号楼3层", time:"2024-04-28"},
{name:"上海琨特网络科技有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区郭守敬路498号8幢19号楼3层", time:"2024-05-09"},
{name:"火数云（上海）计算机系统有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区张衡路200号2幢3层", time:"2024-06-13"},
{name:"上海阿欧一数字科技有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区张衡路200号2幢3层", time:"2024-06-11"},
{name:"智略云（上海）网络科技有限公司", add:"上海市上海市浦东新区康桥路666号2幢二层212室", time:"2024-06-03"},
{name:"智昱云（上海）网络科技有限公司", add:"上海市上海市浦东新区康桥路666号2幢二层201室", time:"2024-06-06"},
{name:"上海辉棵生物医药有限公司", add:"上海市上海市浦东新区中科路702号3幢13层A1324室", time:"2024-04-21"},
{name:"锐云威科技（上海）有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区盛荣路188弄5号701A室", time:"2023-09-11"},
{name:"上海利澎科技有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区盛荣路188弄5号603室", time:"2024-06-14"},
{name:"上海旷泓网络科技有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区盛荣路188弄5号606B室", time:"2024-06-20"},
{name:"上海升是科技有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区盛荣路188弄5号504室", time:"2024-06-19"},
{name:"上海仪名半导体有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区盛荣路188弄5号407C室", time:"2024-06-11"},
{name:"领羚科技（上海）有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区张江路505号18层03-2单元（实际楼层为15楼）", time:"2024-06-26"},
{name:"艾比欧义（上海）生物工程科技有限公司", add:"上海市上海市青浦区徐泾镇崧泽大道1728、1758号3幢9F12", time:"2023-10-13"},
{name:"上海创锌嘉电子科技有限公司", add:"上海市上海市浦东新区建韵路399号8幢3层342室", time:"2024-06-14"},
{name:"伊斐玛科技（上海）有公司", add:"上海市上海市浦东新区建韵路399号6幢4层414室", time:"2024-06-04"},
{name:"利元吉(上海)文化科技有限公司", add:"上海市上海市浦东新区上海市浦东新区秀浦路2555号2幢1207室B-6", time:"2024-06-13"},
{name:"上海斗才计量检测有限公司", add:"上海市上海市浦东新区上海市浦东新区建韵路500号4幢3层", time:"2023-02-13"},
{name:"张济堂健康科技（上海）有限公司", add:"上海市上海市浦东新区上海市浦东新区建韵路500号1幢110室", time:"2024-06-05"},
{name:"树伍科技（上海）有限公司", add:"上海市上海市浦东新区上海市浦东新区建韵路500号3幢336室", time:"2024-06-06"},
{name:"上海敖鼎智能科技有限公司", add:"上海市上海市浦东新区上海市浦东新区建韵路500号4幢3层", time:"2024-06-18"},
{name:"上海晶钺科技有限公司", add:"上海市上海市浦东新区上海市浦东新区建韵路500号4幢3层", time:"2024-06-19"},
{name:"上海果贞信息科技有限公司", add:"上海市上海市浦东新区上海市浦东新区建韵路500号4幢3层", time:"2024-06-24"},
{name:"上海君和创意数字科技有限公司", add:"上海市上海市浦东新区中国(上海)自由贸易试验区科苑路151号203室", time:"2024-06-07"},
{name:"东方三少（上海）咨询管理有限公司", add:"上海市上海市浦东新区上海市浦东新区建韵路500号4幢3层", time:"2024-06-24"},
{name:"上海汐鲁香科技有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区科苑路151号2楼222室", time:"2024-06-12"},
{name:"International Nexus Trade Co.,Limited", add:"香港特别行政区香港特别行政区屯门区屯门街6号行外中心185G/F", time:"2024-05-20"},
{name:"莱柏亿网络科技（上海）有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区金沪路1155号518室", time:"2024-04-09"},
{name:"安睿杰科技（上海）有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区盛夏路169号、张东路1658号1幢9层910室", time:"2024-04-29"},
{name:"优泽木科技（上海）有限公司", add:"上海市上海市浦东新区上海市浦东新区秀浦路2388号2幢305-60工位", time:"2024-06-11"},
{name:"上海沐阁科技有限公司", add:"上海市上海市浦东新区上海市浦东新区秀浦路2388号2幢305-3工位", time:"2024-01-11"},
{name:"上海申颐瑞信息科技有限公司", add:"上海市上海市浦东新区上海市浦东新区秀浦路2500弄6号612室", time:"2024-06-03"},
{name:"上海法润特汽车科技有限公司", add:"上海市上海市金山区上海市浦东新区秀浦路2500弄6号711室", time:"2024-06-13"},
{name:"上海昕之茂新能源科技有限公司", add:"上海市上海市浦东新区上海市浦东新区秀浦路2388号3幢305室", time:"2024-05-11"},
{name:"度芯(上海）科技有限公司", add:"上海市上海市浦东新区上海市浦东新区秀浦路2500弄6号303室", time:"2024-06-07"},
{name:"上海芯月湾半导体技术有限公司", add:"上海市上海市浦东新区上海市浦东新区秀浦路2500弄6号305室", time:"2024-06-07"},
{name:"上海智矽半导体有限公司", add:"上海市上海市浦东新区上海市浦东新区秀浦路2500弄6号106室", time:"2024-06-27"},
{name:"上海蜗翎教育科技有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区孙桥路999号1幢166-6室", time:"2024-06-27"},
];
let list2 = [
    {name:"耐科思特电子科技（上海）有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区郭守敬路498号8幢19号楼3层"},
    {name:"上海署雀新材料有限公司", add:"上海市上海市奉贤区上海市奉贤区金路1998弄3号"},
    {name:"上海且尧电力科技有限公司", add:"上海市上海市浦东新区新杨公路1588号4幢"},
    {name:"上海玩悦网络科技有限公司", add:"上海市上海市闵行区上海市闵行区中春路988号11幢2楼"},
    {name:"上海都井智能科技有限公司", add:"上海市上海市奉贤区上海市奉贤区平庄西路1599号"},
    {name:"上海集煜予科技有限公司", add:"上海市上海市浦东新区中国(上海)自由贸易试验区郭守敬路498号12幢2层21204、21206室"},
    {name:"上海叁台元科技科技有限公司", add:"上海市上海市浦东新区中国(上海)自由贸易试验区张衡路200号2幢3层"},
    {name:"锐云威科技（上海）有限公司", add:"上海市上海市奉贤区明城路1088弄7号1-2层"},
    {name:"艾比欧义（上海）生物工程科技有限公司", add:"上海市上海市青浦区徐泾镇崧泽大道1728、1758号3幢9F12"},
    {name:"上海斗才计量检测有限公司", add:"上海市上海市奉贤区上海市奉贤区南桥镇南桥路311号"},
    {name:"莱柏亿网络科技（上海）有限公司", add:"上海市上海市浦东新区中国（上海）自由贸易试验区金沪路1155号518室"}
]


let list3 = [
    {name:"上海岷麒半导体技术有限公司",time:"2024-04-09", uscc:"91310115MADGY7E84L",add:"中国（上海）自由贸易试验区申江路5709号、秋月路26号1幢3层J-1室"},
    {name:"上海立业乐信息科技有限公司",time:"2024-06-25", uscc:"91310115MADPDDA38Y",add:"中国（上海）自由贸易试验区蔡伦路85弄95号1幢2层A区201-2室"},
    {name:"巨服（上海）医疗科技有限公司",time:"2024-06-27", uscc:"91310115MADQGXYE2N",add:"中国（上海）自由贸易试验区龙东大道3000号1幢A楼601-11、12室"},
    {name:"上海钟贺生物科技有限公司",time:"2023-12-13", uscc:"91310120MAD61UXJ91",add:"上海市奉贤区兰博路1088弄56号2层204室"},
    {name:"上海瑞衍墨信息科技有限公司",time:"2024-06-24", uscc:"91310115MADNQ03C0C",add:"中国（上海）自由贸易试验区金科路2966号1幢201室"},
    {name:"上海钮晨科技有限公司",time:"2024-06-14", uscc:"91310115MADP5FWY32",add:"中国（上海）自由贸易试验区中科路1358号、环科路999弄3号一层G009工位"},
    {name:"上海莫涵堂科技有限公司",time:"2024-06-07", uscc:"91310115MADMN4N38J",add:"上海市浦东新区沈梅路123弄9-10号四层4A室"},
    {name:"上海沃睿丰新能源有限公司",time:"2024-06-03", uscc:"91310115MADMJ74U4F",add:"上海市浦东新区沈梅路123弄9-10号三层303室"},
    {name:"耐科思特电子科技（上海）有限公司",time:"2014-06-12", uscc:"913100000942192568",add:"中国（上海）自由贸易试验区郭守敬路498号8幢19号楼3层"},
    {name:"上海署雀新材料有限公司",time:"2020-08-14", uscc:"91310120MA1HXXXM4X",add:"中国（上海）自由贸易试验区纳贤路800号1幢B座7层714室"},
    {name:"上海罗领世新材料技术有限公司",time:"2024-05-20", uscc:"91310115MADM88R599",add:"中国（上海）自由贸易试验区盛荣路88弄8号201室"},
    {name:"中太乐曼（上海）科技有限公司",time:"2024-05-07", uscc:"91310115MADL0BBJ50",add:"中国（上海）自由贸易试验区张衡路666弄1号610室"},
    {name:"海纳智联数字科技（上海）有限公司",time:"2024-06-07", uscc:"91310115MADLQ4MX22",add:"上海市浦东新区秀浦路3999弄1号"},
    {name:"上海且尧电力科技有限公司",time:"2023-02-23", uscc:"91310000MAC9EN8X7W",add:"中国（上海）自由贸易试验区临港新片区新杨公路1588号4幢"},
    {name:"上海玩悦网络科技有限公司",time:"2021-06-01", uscc:"91310112MA1GEPC47G",add:"上海市浦东新区秀浦路68号1幢东区3层311室"},
    {name:"上海都井智能科技有限公司",time:"2023-11-02", uscc:"91310120MAD2EGMK66",add:"上海市浦东新区秀浦路68号1幢东区2层212室"},
    {name:"琛迅（上海）科技有限公司",time:"2024-06-03", uscc:"91310115MADM5AUG71",add:"中国（上海）自由贸易试验区郭守敬路351号1幢619室"},
    {name:"上海仪茂科技有限公司",time:"2024-06-27", uscc:"91310115MADQALLF2F",add:"上海市浦东新区青黛路800号1幢B座3层317室"},
    {name:"上海心纪元创时代生命科学有限公司",time:"2024-06-27", uscc:"91310115MADQGYCJ68",add:"上海市浦东新区周浦镇天雄路166弄3号205室"},
    {name:"上海集煜予科技有限公司",time:"2022-11-10", uscc:"91310115MAC3B8T832",add:"中国（上海）自由贸易试验区郭守敬路498号12幢2层21204、21206室"},
    {name:"上海翼马平川智能科技有限公司",time:"2023-03-14", uscc:"91310112MACA17G55E",add:"中国（上海）自由贸易试验区郭守敬路498号8幢19号楼3层"},
    {name:"上海澜昆微电子科技有限公司",time:"2024-05-15", uscc:"91310115MADJMJE17M",add:"中国（上海）自由贸易试验区郭守敬路498号8幢19号楼3层"},
    {name:"上海麦浦迪科技有限公司",time:"2024-06-06", uscc:"91310115MADNACYW76",add:"中国（上海）自由贸易试验区郭守敬路498号8幢19号楼3层"},
    {name:"智领未来信息科技（上海）有限公司",time:"2024-04-28", uscc:"91310115MADHBHBP74",add:"中国（上海）自由贸易试验区郭守敬路498号8幢19号楼3层"},
    {name:"上海琨特网络科技有限公司",time:"2024-05-09", uscc:"91310115MADJU5HG4D",add:"中国（上海）自由贸易试验区郭守敬路498号8幢19号楼3层"},
    {name:"火数云（上海）计算机系统有限公司",time:"2024-06-13", uscc:"91310115MADPHD2M4N",add:"中国（上海）自由贸易试验区张衡路200号2幢3层"},
    {name:"上海阿欧一数字科技有限公司",time:"2024-06-11", uscc:"91310115MADMTML106",add:"中国（上海）自由贸易试验区张衡路200号2幢3层"},
    {name:"智略云（上海）网络科技有限公司",time:"2024-06-03", uscc:"91310115MADM55PW23",add:"上海市浦东新区康桥路666号2幢二层212室"},
    {name:"智昱云（上海）网络科技有限公司",time:"2024-06-06", uscc:"91310115MADMHC7R1H",add:"上海市浦东新区康桥路666号2幢二层201室"},
    {name:"上海辉棵生物医药有限公司",time:"2024-04-21", uscc:"91310115MADJHT3Q17",add:"中国（上海）自由贸易试验区中科路702号3幢13层A1324室"},
    {name:"锐云威科技（上海）有限公司",time:"2023-09-11", uscc:"91310120MACX7THN2P",add:"中国（上海）自由贸易试验区盛荣路188弄5号701A室"},
    {name:"上海利澎科技有限公司",time:"2024-06-14", uscc:"91310115MADP651U1Y",add:"中国（上海）自由贸易试验区盛荣路188弄5号603室"},
    {name:"上海旷泓网络科技有限公司",time:"2024-06-20", uscc:"91310115MADMU8WMXU",add:"中国（上海）自由贸易试验区盛荣路188弄5号606B室"},
    {name:"上海升是科技有限公司",time:"2024-06-19", uscc:"91310115MADPR2Y45M",add:"中国（上海）自由贸易试验区盛荣路188弄5号504室"},
    {name:"上海仪名半导体有限公司",time:"2024-06-11", uscc:"91310115MADN85H158",add:"中国（上海）自由贸易试验区盛荣路188弄5号407C室"},
    {name:"领羚科技（上海）有限公司",time:"2024-06-26", uscc:"91310115MADP1XEP2E",add:"中国（上海）自由贸易试验区张江路505号18层03-2单元（实际楼层为15楼）"},
    {name:"艾比欧义（上海）生物工程科技有限公司",time:"2023-10-13", uscc:"91310118MAD11NG44C",add:"上海市青浦区徐泾镇崧泽大道1728、1758号3幢9F12"},
    {name:"上海创锌嘉电子科技有限公司",time:"2024-06-14", uscc:"91310115MADMDFFJ3L",add:"上海市浦东新区建韵路399号8幢3层342室"},
    {name:"利元吉（上海）文化科技有限公司",time:"2024-06-13", uscc:"91310115MADMYY2012",add:"上海市浦东新区秀浦路2555号2幢1207室B-6"},
    {name:"上海斗才计量检测有限公司",time:"2023-02-13", uscc:"91310120MAC6X8XD2F",add:"上海市浦东新区建韵路500号4幢3层"},
    {name:"张济堂健康科技（上海）有限公司",time:"2024-06-05", uscc:"91310115MADMFP5F58",add:"上海市浦东新区建韵路500号1幢110室"},
    {name:"树伍科技（上海）有限公司",time:"2024-06-06", uscc:"91310115MADNUGLN02",add:"上海市浦东新区建韵路500号3幢336室"},
    {name:"上海敖鼎智能科技有限公司",time:"2024-06-18", uscc:"91310115MADMGNF57D",add:"上海市浦东新区建韵路500号4幢3层"},
    {name:"上海晶钺科技有限公司",time:"2024-06-19", uscc:"91310115MADPR1X46U",add:"上海市浦东新区建韵路500号4幢3层"},
    {name:"上海果贞信息科技有限公司",time:"2024-06-24", uscc:"91310115MADN0Y4344",add:"上海市浦东新区建韵路500号4幢3层"},
    {name:"上海君和创意数字科技有限公司",time:"2024-06-07", uscc:"91310115MADMN00W8J",add:"中国（上海）自由贸易试验区科苑路151号203室"},
    {name:"东方三少（上海）咨询管理有限公司",time:"2024-06-24", uscc:"91310115MADP9B213J",add:"上海市浦东新区建韵路500号4幢3层"},
    {name:"上海汐鲁香科技有限公司",time:"2024-06-12", uscc:"91310115MADP704823",add:"中国（上海）自由贸易试验区科苑路151号2楼222室"},
    {name:"莱柏亿网络科技（上海）有限公司",time:"2024-04-09", uscc:"91310115MADGYPCU04",add:"中国（上海）自由贸易试验区金沪路1155号518室"},
    {name:"安睿杰科技（上海）有限公司",time:"2024-04-29", uscc:"91310115MADJ6Y2H5E",add:"中国（上海）自由贸易试验区盛夏路169号、张东路1658号1幢9层910室"},
    {name:"优泽木科技（上海）有限公司",time:"2024-06-11", uscc:"91310115MADN814A5T",add:"上海市浦东新区秀浦路2388号2幢305-60工位"},
    {name:"上海沐阁科技有限公司",time:"2024-01-11", uscc:"91310115MADAKJCP1A",add:"上海市浦东新区秀浦路2388号2幢305-3工位"},
    {name:"上海申颐瑞信息科技有限公司",time:"2024-06-03", uscc:"91310115MADMJ8WK3K",add:"上海市浦东新区秀浦路2500弄6号612室"},
    {name:"上海法润特汽车科技有限公司",time:"2024-06-13", uscc:"91310115MADPH8G93J",add:"上海市浦东新区秀浦路2500弄6号711室"},
    {name:"上海昕之茂新能源科技有限公司",time:"2024-05-11", uscc:"91310115MADKJBD13C",add:"上海市浦东新区秀浦路2388号3幢305室"},
    {name:"度芯（上海）科技有限公司",time:"2024-06-07", uscc:"91310115MADLQ81W19",add:"上海市浦东新区秀浦路2500弄6号303室"},
    {name:"上海芯月湾半导体技术有限公司",time:"2024-06-07", uscc:"91310115MADN3DYR0E",add:"上海市浦东新区秀浦路2500弄6号305室"},
    {name:"上海智矽半导体有限公司",time:"2024-06-27", uscc:"91310115MADQ9WK24L",add:"上海市浦东新区秀浦路2500弄6号106室"},
    {name:"上海蜗翎教育科技有限公司",time:"2024-06-27", uscc:"91310115MADPN0A10U",add:"中国（上海）自由贸易试验区孙桥路999号1幢166-6室"}
]

export async function t() {
    // let notList = [];
    // for (let i = 0; i < list3.length; i++) {
    //     let info = list3[i];
    //     let res:any = await changeAddresCode(info.add, info.add.substring(0, 3));
    //     if (!res || res.error ) console.log("报错", res.error)
    //     else {
    //         let iszj = isPointInPolygon(res);
    //         if (iszj) notList.push(info.name)
    //     }
       
    // }

    let map = {};
    list3.forEach(info => {
        map[info.name] = info;
    })

    list.forEach(info => {
        let check = map[info.name];
        if (check) {
            if (check.add != info.add) console.log(info.name, "原来:", info.add, "  企查查: ", check.add);
            if (check.time != info.time) console.log(info.name, "原来:", info.time, "  企查查: ", check.time);
        }
        else {
            // console.log("特化:", info.name);
        }
    });
    console.log();
}


/**
 * 导出在孵企业列表
 */
export async function test111() {
    /**查询内容 */
    let usccMap = await fuhuaqiData.findFuHuaQiOperationNameMapByParam({});//用于将孵化器uscc变成孵化器名称
    let dataBaseList = await findEnterpriseList({labels:{"$elemMatch": {  "labelId":"zfqy", "state":true  }} } );

    /**组合二维数组  titleList 与 keyList 要一一对应 */ 
    const TitleList = [
        "企业名称", "入库时间", "所属孵化器", "新注册/新迁入", "孵化状态", "虚拟孵化服务模式", "统一信用代码", "行业领域","主营业务",
        "注册时间", "首次入孵时间", "迁入时间", "是否自然人控股", "迁入前注册地址",
        "注册地址", "经营地址", "租赁面积（平方米）","创业创新方向","创业创始人背景",
        "海外专利", "一类专利","二类专利", 
        "是否上市" , "高新技术" , "专精特新" , "小巨人培育" , "小巨人"
    ];//表头顺序  如果这里修改了 下面的keyList也要修改
    const KeyList = [
        "name", "createTime", "fuhuaqiUscc", "isCreate",  "state", "virtualCause", "uscc", "industry", "mainBusiness", 
        "logonTime","firstIncubationTime", "timeOfImmigration", "isNaturalPersonHolding", "oldLogonAddress",
        "logonAddress", "operatingAddress", "leasedArea","cycxfx","cycsrbj",
        "alienPatent", "classIPatent", "secondClassPatent",
        "beOnTheMarket", "highTechMs", "zjtxMs", "xjrpyMs", "xjrMs"
    ];//表头对应的字段顺序
    let dataList = [TitleList];
    
    dataBaseList.forEach( info => {
        /**截取返回结果 */
        let changeData:any = extractData(EnterpriseListConfig, info, true);

        /**匹配所属孵化器名称  匹配不上时这里显示空字符串 */
        changeData.fuhuaqiUscc = usccMap[info.fuHuaQiUscc] || "";
        if (!info.taskId || info.enterpriseIsInPut) {
            if (info.enterpriseIsInPut) changeData.isCreate = "底库数据";
            else {
                changeData.isCreate =  (changeData.isCreate)? "补录新注册":"补录新迁入";
            }
        }else changeData.isCreate = (changeData.isCreate) ? "新注册" : "新迁入";

        if (!changeAddToString(info.oldLogonAddress)) {
            changeData.oldLogonAddress = "-";
        }
        if (!changeAddToString(info.logonAddress)) {
            changeData.logonAddress = "-";
        }
        if (!changeAddToString(info.operatingAddress)) {
            changeData.operatingAddress = "-";
        }

        changeData.cycxfx = changeEnumValue(CYCXFX, changeData.cycxfx) || "未选择";
        changeData.cycsrbj = changeEnumValue(CYCSRBJ, changeData.cycsrbj) || "未选择";

        changeData.isNaturalPersonHolding = changeData.isNaturalPersonHolding ? "是" : "否";

        /**修改枚举值 */
        changeData.industry = changeEnumValue(INDUSTRY, changeData.industry);
        changeData.state = changeEnumValue(FUHUASTATE, changeData.state);
        changeData.virtualCause = changeEnumValue(VIRTUALCAUSE, changeData.virtualCause);
        
        /**-         let intellectualProperty = changeData.intellectualProperty || {}
        changeData.alienPatent =  intellectualProperty.alienPatent || 0;
        changeData.classIPatent =  intellectualProperty.classIPatent || 0;
        changeData.secondClassPatent =  intellectualProperty.secondClassPatent || 0;

        if (changeData.qualification) {
            let onceData = changeData.qualification;
            let beOnTheMarket = "无上市";
            if (onceData.beOnTheMarket){
                beOnTheMarket = verificationEnumTools.changeEnumValue( configEnum.FINANCINGROUNDS, onceData.beOnTheMarket) || "无上市"
            }

            changeData.beOnTheMarket = beOnTheMarket;
            changeData.highTechMs = onceData.highTechMs ? new Date(onceData.highTechMs).getFullYear() : '未认证';//高新技术
            changeData.zjtxMs = onceData.zjtxMs ? new Date(onceData.zjtxMs).getFullYear() : '未认证';//专精特新
            changeData.xjrpyMs = onceData.xjrpyMs ? new Date(onceData.xjrpyMs).getFullYear() : '未认证';//小巨人培育
            changeData.xjrMs = onceData.xjrMs ? new Date(onceData.xjrMs).getFullYear() : '未认证';//小巨人

        } else {
            changeData.beOnTheMarket = "无上市";//是否上市
            changeData.highTechMs =  '未认证';//高新技术
            changeData.zjtxMs =  '未认证';//专精特新
            changeData.xjrpyMs =  '未认证';//小巨人培育
            changeData.xjrMs =  '未认证';//小巨人
        }
        
        /**根据表头与key的顺序 生成小数组 */
        let subList = [];
        KeyList.forEach( keyStr => {
            let value = changeData[keyStr];
            if (value == null || value == undefined) value = "-"
            subList.push( value );
        });
        dataList.push(subList);
    });

   
    
    
    let data = [
        {
            name:"sheet1",
            data:dataList
        }
    ];
    let buff = xlsx.build(data);
    fs.writeFileSync(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", '在孵企业excel.xlsx' ), buff);
    

    console.log();
    // return dataList;
}



/** 孵化器诊断报告依赖的数据 */
export async function zhenDuanBaoGao() {
    
    let fhqList = [
        "上海衍禧堂企业管理有限公司",
        "上海谦岩企业管理有限公司",
        "上海瀜澈企业管理有限公司",
        "上海点金树创业孵化器有限公司",
        "上海翔港创业投资有限公司",
        "上海晟唐创业孵化器管理有限公司"
    ];


    async function t(name) {
        let fuHuaQiInfo = await fuhuaqiData.findOnceByParam({"operationName":{"$regex":`${name}`}});
        let 我的数据字段 = [
            {cName:"在孵面积", key:"incubatedAcreage"}, 
            {cName:"孵化器总面积", key:"acreageTotal"}, 
            {cName:"孵化器自用面积", key:"acreagePersonalUse"}, 
            {cName:"经备案孵化场地", key:"hatchingGround"}, 
            {cName:"注册地址", key:"fuHuazhuCeDiZhi"}, 
            {cName:"联系地址", key:"fuHuaLianXiDiZhi"}
        ];
        let 我的数据缺失 = "";
        let 我的数据缺失数量 = 0;
        for (let i in 我的数据字段) {
            let {cName, key} = 我的数据字段[i];
            if (!fuHuaQiInfo[key]) {
                我的数据缺失 += `${cName}信息、`;
                我的数据缺失数量 += 1;
            }
            if (key == "fuHuazhuCeDiZhi" || key == "fuHuaLianXiDiZhi") {
                if (!fuHuaQiInfo[key][0]) {
                    我的数据缺失 += `${cName}信息、`;
                    我的数据缺失数量 += 1;
                }
            }
        }
        let 我的数据诊断 = `我的数据：完善度：${Math.round(((我的数据字段.length - 我的数据缺失数量)/我的数据字段.length)*100)}%，`;
        if (我的数据缺失数量) {
            我的数据诊断 += `缺失${我的数据缺失}，请尽快完善。`;
        } else {
            我的数据诊断 += "无信息缺失。"
        }
        let 我的信息字段 = [
            {cName:"注册时间", key:"logonTime"},
            {cName:"孵化器级别", key:"lv"},
            {cName:"认定时间", key:"identificationTime"},
            {cName:"孵化领域", key:"industry"},
            {cName:"机构性质", key:"institutionalNature"},
            {cName:"运营模式", key:"operationModel"},
            {cName:"创业团队", key:"foundingTeam"},
            {cName:"联系人", key:"liaison"},
            {cName:"联系电话", key:"liaisonPhone"},
            {cName:"孵化器简介", key:"introduction"},
        ];
        let 我的信息缺失 = "";
        let 我的信息缺失数量 = 0;
        for (let i in 我的信息字段) {
            let {cName, key} = 我的信息字段[i];
            if (!fuHuaQiInfo[key]) {
                我的信息缺失 += `${cName}信息、`;
                我的信息缺失数量 += 1;
            }
            if (key == "foundingTeam") {
                if (!fuHuaQiInfo[key][0]) {
                    我的信息缺失 += `${cName}信息、`;
                    我的信息缺失数量 += 1;
                }
            }
        }
        let 我的信息诊断 = `我的信息：完善度：${Math.round(((我的信息字段.length - 我的信息缺失数量)/我的信息字段.length)*100)}%，`;
        if (我的信息缺失数量) {
            我的信息诊断 += `缺失${我的信息缺失}，请尽快完善。`;
        } else {
            我的信息诊断 += "无信息缺失。"
        }
        
        /**任务填报 */
        let taskKeyList = [20246, 20245, 20244, 20243, 20242, 20241];
        let taskList = await taskData.findTaskListByParam({fuHuaQiUscc:fuHuaQiInfo.uscc, key:{"$in":taskKeyList} });
        let 任务填报 = "近六个月任务填报中，";
        let 最新一次出租率Id = '';
        taskList.forEach(element => {
            let { isSubmit, type, key, taskId} = element;
            if (!isSubmit) {
                if (type == TASKTYPEENUM.新注册或迁入企业登记) 任务填报 += `${key}缺失新入孵企业登记，`;
                else if (type == TASKTYPEENUM.孵化器月度填报)  任务填报 += `${key}缺失出租率登记，`;
                else  任务填报 += `${key}缺失企业融资登记，`;
            }
            if (isSubmit && type == TASKTYPEENUM.孵化器月度填报 && key == 20246) {
                最新一次出租率Id = taskId;
            }
        });
        if (任务填报 == "近六个月任务填报中，") {
            任务填报 += `出租率填报状况正常，企业融资情况填报正常，新增企业填报正常。均按时填报。`;
        }
        
    
        /**企业信息填报情况 */
        let 企业信息诊断 = `我的数据中孵化器总面积为${fuHuaQiInfo.acreageTotal}㎡，自用面积为${fuHuaQiInfo.acreagePersonalUse}㎡，在孵面积为${fuHuaQiInfo.incubatedAcreage}㎡，`;
        if ((fuHuaQiInfo.acreageTotal - fuHuaQiInfo.acreagePersonalUse) != fuHuaQiInfo.incubatedAcreage) {
            企业信息诊断 += '自用面积与在孵面积的和不等于总面积，请核对信息正确性。';
        }
        let thisFuHuaInfo = await enterpriseData.statsFuHuaQiEnterpriseArea(fuHuaQiInfo.uscc);
        企业信息诊断 += `在孵企业${thisFuHuaInfo.count}家，企业信息中占孵面积共计${thisFuHuaInfo.areaCount}㎡。`;
        if (thisFuHuaInfo.areaCount > fuHuaQiInfo.incubatedAcreage) {
            企业信息诊断 += '企业占孵面积高于在孵面积，明显不合理，需要考虑是否存在未迁出企业影响信息的正确性。'
        } else {
            if (最新一次出租率Id) {
                let newTaskInfo = await monthTableData.findMonthTableByTaskId(最新一次出租率Id);
                企业信息诊断 += `最新一次填报的出租率为${newTaskInfo.occupancyRate}%，`;
                let 高或低 = '';
                let 企业面积计算 = Math.round(thisFuHuaInfo.areaCount/fuHuaQiInfo.incubatedAcreage * 10000)/100
                if (newTaskInfo.occupancyRate > 企业面积计算 ) {
                    高或低 = '高';
                } else 高或低 = '低';
                let 程度 = '';
                if ( Math.abs(newTaskInfo.occupancyRate - 企业面积计算) >= 10) {
                    程度 = '远';
                }else {
                    程度 = '略';
                }
                企业信息诊断 += `${程度}${高或低}于企业出租面积计算出来的出租率（${企业面积计算}%）。可能原因为企业信息未及时更新，还需着重校验每个企业占孵面积。`
        
            } else {
                企业信息诊断 += `最近一月没有任务提交。`;
            }
        }
        
        
    
        let list = await enterpriseData.findEnterpriseList({fuHuaQiUscc:fuHuaQiInfo.uscc, state:{"$ne":4} });
        let 缺失注册时间 = 0;
        let 缺失注册时间的企业 = '';
        let 缺失注册地址 = 0;
        let 缺失经营地址 = 0;
        let 缺失迁入前地址 = 0;
        let 非新建企业 = 0;
        let 实体孵化未填报孵化面积 = 0;
        let 名单  = [];
        let 主营业务缺失 = 0;
        list.forEach(info => {
            if (!info.logonAddress || !info.logonAddress[0]) 缺失注册地址 += 1;
            
            if (!info.operatingAddress || !info.operatingAddress[0]) 缺失经营地址 += 1;
            if (!info.isCreate) {
                非新建企业 += 1;
                if (!info.oldLogonAddress || !info.oldLogonAddress[0]) 缺失迁入前地址 += 1;
            }
            if (!info.logonTime) {
                缺失注册时间 += 1;
                缺失注册时间的企业 = info.name;
            }
            if (info.state == FUHUASTATE.实体孵化 && !info.leasedArea) {
                实体孵化未填报孵化面积 += 1;
                名单.push(info.name);
            }
            if (!info.mainBusiness) 主营业务缺失 += 1;
    
        });
        let count = list.length;
        let 企业信息对比 = `非迁出企业共计${count}家，`;
        if (缺失注册时间) 企业信息对比 += `${缺失注册时间}家企业缺失注册时间，`;
        if (缺失注册地址) 企业信息对比 += `${缺失注册地址}家企业缺失注册地址，`;
        if (缺失经营地址) 企业信息对比 += `${缺失经营地址}家企业缺失经营地址，`;
        if (主营业务缺失) 企业信息对比 += `${主营业务缺失}家企业缺失主营业务，`;
        if (缺失迁入前地址) {
            企业信息对比 += `${非新建企业}家非新建企业中${缺失迁入前地址}家企业缺失迁入前地址。`
        }
        if (实体孵化未填报孵化面积) {
            if (实体孵化未填报孵化面积 <= 2) {
                企业信息对比+=`存在${实体孵化未填报孵化面积}家实体孵化企业未填报占孵面积，名单如下：`;
                名单.forEach(subItem => {
                    企业信息对比 += `“${subItem}”、`;
                })
            } else {
                企业信息对比 += `${count}家企业中有${实体孵化未填报孵化面积}家企业未填报占孵面积，信息缺失比较严重，请及时补充。`
            }
        }
    
        console.log("=================================");
        console.log(name);
        console.log(我的数据诊断);
        console.log(我的信息诊断);
        console.log(任务填报);
        console.log(企业信息诊断);
        console.log(企业信息对比);
        console.log("=================================");
        console.log("=================================");
        console.log("=================================");
        console.log();
    }
    
    for (let i in fhqList) {
        await t(fhqList[i]);
        console.log();
    }

}

/**
 * 修复自定义任务
 */
export async function xiuFuCustomTask() {
    //找到任务表中出现过的数据月份
    let keyList = await taskData.statsTaskYearAndMonth();
    let list = [];
    keyList.forEach(info => {
        let {_id} = info;
        let {year, month} = _id;
        let monthStr = month <=9 ? `0${month}` : `${month}`;
        list.push({year:_id.year, month:_id.month, key:parseInt(`${year}${monthStr}`)});
    });
    list.sort((a, b) => {return a.key - b.key});

    for (let i in list) {
        let {year, month} = list[i];
        let monthStr = month <=9 ? `0${month}` : `${month}`;
        let dataCycle = parseInt(`${year}${monthStr}`);
        let customTaskType = FUHUAQICUSTOMTASKTYPE.月度任务;
        let customTaskId = `${customTaskType}_${dataCycle}`;
        
        let startMs = moment(new Date(`${year}-${monthStr}-01 00:00:00`)).add(1, 'months').valueOf();
        let endMs =  moment(new Date(`${year}-${monthStr}-01 00:00:00`)).add(2, 'months').valueOf() - 1000;
        await addTask(customTaskId, customTaskType, dataCycle, startMs, endMs);

        //关联对应的任务
        await taskData.updateTaskCustomTaskId(year, month, customTaskId);

    }
    console.log("数据更新完成");
    //添加信息到自定义任务表中
}

export async function test11111() {
    let list = await enterpriseData.findEnterpriseList({fuHuaQiUscc:"91310115069312504K"});
    let keyList = [{key:"name", desc:"企业名称"},
    {key:"taskId", desc:"绑定的任务id"},
    {key:"uscc", desc:"统一信用代码"},
    {key:"fuHuaQiUscc", desc:"孵化器统一信用代码"},
    {key:"industry", desc:"领域"},
    {key:"logonTime", desc:"注册时间"},
    {key:"firstIncubationTime", desc:"首次入孵时间"},
    {key:"timeOfImmigration", desc:"迁入时间"},
    {key:"isNaturalPersonHolding", desc:"是否自然人控股企业"},
    {key:"oldLogonAdd", desc:"弃用"},
    {key:"logonAdd", desc:"弃用"},
    {key:"operatingAdd", desc:"弃用"},
    {key:"isCreate", desc:"是否新建"},
    {key:"leasedArea", desc:"租赁面积（平方米）"},
    {key:"mainBusiness", desc:"主营业务"},
    {key:"createTime", desc:"录入时间"},
    {key:"draftLock", desc:"草稿锁，true为提交之后，false为草稿"},
    {key:"enterpriseIsInPut", desc:"兼容原始数据无法判断是否是迁入企业这个问题加的字段"},
    {key:"draftId", desc:"保存之后就不认这个id了"},
    {key:"firstLoginIsChangePwd", desc:"首次登录是否修改密码"},
    {key:"state", desc:"状态"},
    {key:"virtualCause", desc:"虚拟孵化原因"},
    {key:"virtualCauseDes", desc:"虚拟孵化描述"},
    {key:"moveOutType", desc:"迁出类型"},
    {key:"moveOutTrace", desc:"迁出去向"},
    {key:"moveOutCause", desc:"迁出原因"},
    {key:"moveOutTime", desc:"迁出时间"},
    {key:"logonAddress", desc:"注册地址"},
    {key:"operatingAddress", desc:"经营地址"},
    {key:"oldLogonAddress", desc:"迁入前注册地址"},
    {key:"initialTeam", desc:"弃用"},
    {key:"qualification", desc:"企业资质"},
    {key:"intellectualProperty", desc:"知识产权"},
    {key:"firstClassTalent", desc:"舍弃"},
    {key:"haveFirstClassTalent", desc:"是否拥有国际一流人才"},
    {key:"tipsQualification", desc:"企业资质"},
    {key:"tipsIntellectualProperty", desc:"知识产权"},
    {key:"tipsFinancingInfo", desc:"企业融资"},
    {key:"graduation", desc:"拟毕业情况"},
    {key:"cycxfx", desc:"创业创新方向"},
    {key:"cycsrbj", desc:"创业创始人背景"},
    {key:"securePhon", desc:"安全手机号，用于做修改密码用"},
    {key:"RAS", desc:"登记状态"},
    {key:"logOffMS", desc:"注销时间"},
    {key:"legalPerson", desc:"法人"},
    {key:"zhuceziben", desc:"注册资本"},
    {key:"shijiaoziben", desc:"实缴资本"},
    {key:"dianHua", desc:"电话"},
    {key:"gengDuoDianHua", desc:"更多电话"},
    {key:"mail", desc:"邮箱"},
    {key:"moreMail", desc:"更多邮箱"},
    {key:"enterpriseType", desc:"企业（机构）类型"},
    {key:"zhuCeHao", desc:"注册号"},
    {key:"zuZhiJiGouDaiMa", desc:"组织机构代码"},
    {key:"canBaoRenShu", desc:"参保人数"},
    {key:"canBaoRenShuNianBao", desc:"参保人数所属年报"},
    {key:"yingYeQiXian", desc:"营业期限"},
    {key:"qiYeGuiMo", desc:"企业规模"},
    {key:"guanWang", desc:"官网"},
    {key:"tongXinDiZhi", desc:"通信地址"},
    {key:"jianJie", desc:"企业简介"},
    {key:"dengJiJiGuan", desc:"登记机关"},
    {key:"naShuiRenZiZhi", desc:"纳税人资质"},
    {key:"zuiXinNianBaoNianFen", desc:"最新年报年份"}];
    

    let resList = [];
    let titleList = [];
    keyList.forEach(keyInfo =>{
        let {key, desc} = keyInfo;
        titleList.push(desc);
    });
    resList.push(titleList);
    list.forEach(info => {
        let subList = [];
        keyList.forEach(keyInfo =>{
            let {key} = keyInfo;
            let value = info[key];
            if (key == "industry") value = changeEnumValue(INDUSTRY, value)
            if (key == "logonTime" || key == "firstIncubationTime" || key == "timeOfImmigration") {
                if (!isNaN(value)) value = moment(value).format("YYYY-MM-DD");
            }
            if (key == "state") {
                value = changeEnumValue(FUHUASTATE, value);
            }
            if (key == "logonAddress" || key == "operatingAddress" || key == "oldLogonAddress") {
                value = changeAddToString(value);
            }
            if (key == "RAS") {
                value = changeEnumValue(RAS, value);
            }
            if (key == "qiYeGuiMo") {
                value = changeEnumValue( ENTERPRISESIZE,value)
            }
            if (key == "naShuiRenZiZhi") {
                value = changeEnumValue(NASHUIRENZIZHI, value);
            }
            subList.push(value);
        });
        resList.push(subList);
    });

    let data = [
        {
            name:"sheet1",
            data:resList
        }
    ];
    let buff = xlsx.build(data);
    fs.writeFileSync(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", '雨艺在孵企业excel.xlsx' ), buff);

    console.log();
}

export async function test() {
    // let enterpriseList = await enterpriseData.findEnterpriseList({});
    
    let list = await enterpriseData.findEnterpriseList({state:FUHUASTATE.实体孵化});
    let enterpriseList = [];
    for (let i = 0; i < list.length; i++) {
        let {logonTime, industry, logonAddress, state, lng, lat} = list[i];
        // continue;
        let zaiFuQiYeSuccess = false;
        let logonAddressSuccess = false;
        if (logonTime) {
            let yearLong = moment().diff(logonTime, 'years');
            if (industry.indexOf(INDUSTRY.人工智能及智能制造) != -1 || industry.indexOf(INDUSTRY.生物医药) != -1 || industry.indexOf(INDUSTRY.集成电路) != -1) {
                if (yearLong < 5) zaiFuQiYeSuccess = true;
            } else {//其他领域
                if (yearLong < 4) zaiFuQiYeSuccess = true;
            }
        }
        if (logonAddress && logonAddress.length && logonAddress[1] && state == FUHUASTATE.实体孵化) {
            if (lat && lng) {
                let isInZJ = await latLngInZJ(parseFloat(lat), parseFloat(lng));
                if (isInZJ) {
                    logonAddressSuccess = true;
                }
            }
           
        }
        if (logonAddressSuccess && zaiFuQiYeSuccess) {
            enterpriseList.push(list[i]);
            console.log(i);
        }
    }
    let usccMap = await fuhuaqiData.findFuHuaQiOperationNameMapByParam({});//用于将孵化器uscc变成孵化器名称

    /**组合二维数组  titleList 与 keyList 要一一对应 */ 
    const TitleList = [
        "企业名称", "入库时间", "所属孵化器", "新注册/新迁入", "孵化状态", "虚拟孵化服务模式", "统一信用代码", "行业领域","主营业务",
        "注册时间", "首次入孵时间", "迁入时间", "是否自然人控股", "迁入前注册地址",
        "注册地址", "经营地址", "租赁面积（平方米）","创业创新方向","创业创始人背景",
        "海外专利", "一类专利","二类专利", 
        "是否上市" , "高新技术" , "专精特新" , "小巨人培育" , "小巨人"
    ];//表头顺序  如果这里修改了 下面的keyList也要修改
    const KeyList = [
        "name", "createTime", "fuhuaqiUscc", "isCreate",  "state", "virtualCause", "uscc", "industry", "mainBusiness", 
        "logonTime","firstIncubationTime", "timeOfImmigration", "isNaturalPersonHolding", "oldLogonAddress",
        "logonAddress", "operatingAddress", "leasedArea","cycxfx","cycsrbj",
        "alienPatent", "classIPatent", "secondClassPatent",
        "beOnTheMarket", "highTechMs", "zjtxMs", "xjrpyMs", "xjrMs"
    ];//表头对应的字段顺序
    let dataList = [TitleList];
    for (let i =0; i < enterpriseList.length; i++) {
        let info = enterpriseList[i];

        /**截取返回结果 */
        let changeData:any = extractData(EnterpriseListConfig, info, true);

        /**匹配所属孵化器名称  匹配不上时这里显示空字符串 */
        changeData.fuhuaqiUscc = usccMap[info.fuHuaQiUscc] || "";
        if (!info.taskId || info.enterpriseIsInPut) {
            if (info.enterpriseIsInPut) changeData.isCreate = "底库数据";
            else {
                changeData.isCreate =  (changeData.isCreate)? "补录新注册":"补录新迁入";
            }
        }else changeData.isCreate = (changeData.isCreate) ? "新注册" : "新迁入";

        if (!changeAddToString(info.oldLogonAddress)) {
            changeData.oldLogonAddress = "-";
        }
        if (!changeAddToString(info.logonAddress)) {
            changeData.logonAddress = "-";
        }
        if (!changeAddToString(info.operatingAddress)) {
            changeData.operatingAddress = "-";
        }

        changeData.cycxfx = changeEnumValue(CYCXFX, changeData.cycxfx) || "未选择";
        changeData.cycsrbj = changeEnumValue(CYCSRBJ, changeData.cycsrbj) || "未选择";

        changeData.isNaturalPersonHolding = changeData.isNaturalPersonHolding ? "是" : "否";

        /**修改枚举值 */
        changeData.industry = changeEnumValue(INDUSTRY, changeData.industry);
        changeData.state = changeEnumValue(FUHUASTATE, changeData.state);
        changeData.virtualCause = changeEnumValue(VIRTUALCAUSE, changeData.virtualCause);
        
        /**- */
        let intellectualProperty = changeData.intellectualProperty || {}
        changeData.alienPatent =  intellectualProperty.alienPatent || 0;
        changeData.classIPatent =  intellectualProperty.classIPatent || 0;
        changeData.secondClassPatent =  intellectualProperty.secondClassPatent || 0;

        if (changeData.qualification) {
            let onceData = changeData.qualification;
            let beOnTheMarket = "无上市";
            if (onceData.beOnTheMarket){
                beOnTheMarket = changeEnumValue( FINANCINGROUNDS, onceData.beOnTheMarket) || "无上市"
            }

            changeData.beOnTheMarket = beOnTheMarket;
            changeData.highTechMs = onceData.highTechMs ? new Date(onceData.highTechMs).getFullYear() : '未认证';//高新技术
            changeData.zjtxMs = onceData.zjtxMs ? new Date(onceData.zjtxMs).getFullYear() : '未认证';//专精特新
            changeData.xjrpyMs = onceData.xjrpyMs ? new Date(onceData.xjrpyMs).getFullYear() : '未认证';//小巨人培育
            changeData.xjrMs = onceData.xjrMs ? new Date(onceData.xjrMs).getFullYear() : '未认证';//小巨人

        } else {
            changeData.beOnTheMarket = "无上市";//是否上市
            changeData.highTechMs =  '未认证';//高新技术
            changeData.zjtxMs =  '未认证';//专精特新
            changeData.xjrpyMs =  '未认证';//小巨人培育
            changeData.xjrMs =  '未认证';//小巨人
        }
        
        /**根据表头与key的顺序 生成小数组 */
        let subList = [];
        KeyList.forEach( keyStr => {
            let value = changeData[keyStr];
            if (value == null || value == undefined) value = "-"
            subList.push( value );
        });

        dataList.push(subList);
    }


    let data = [
        {
            name:"sheet1",
            data:dataList
        }
    ];
    let buff = xlsx.build(data);
    fs.writeFileSync(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", `截至${new Date().getMonth()+1}全部企业.xlsx` ), buff);
    console.log("数据更新完成");

}

export async function 修复重复() {
    let usccList = await enterpriseData.repeatEnterprise();


    for (let i= 0; i < usccList.length; i++) {
        let uscc = usccList[i];
        let thisUsccEnterpriseList = await findEnterpriseList({uscc});
        thisUsccEnterpriseList.forEach(item => {
            let { _id, uscc, fuHuaQiUscc, name, state, createTime, taskId, draftLock, firstLoginIsChangePwd, zuZhiJiGouDaiMa } = item;
            console.log(_id, uscc, fuHuaQiUscc, name, state, moment(createTime).format("YYYY-MM-DD"), taskId, draftLock, firstLoginIsChangePwd, zuZhiJiGouDaiMa);
        });
        console.log("--");
        console.log();
    }

    let removeList = [];
    removeList.push({uscc:"91310115MAD600EEXK", zuZhiJiGouDaiMa:null});
    removeList.push({uscc:"91310115MABRJG092Y", firstLoginIsChangePwd:false});//上海岩测科技有限公司
    removeList.push({uscc:"91310115MABQABT77B", firstLoginIsChangePwd:false});//上海欢引科技有限公司
    removeList.push({uscc:"91310115MAC7AQU44W", firstLoginIsChangePwd:false});//广天映泰（上海）生物科技有限公司
    removeList.push({uscc:"91310115MA1K4T7Y0L", zuZhiJiGouDaiMa:null});
    removeList.push({uscc:"91310115MA1HBEHJ6X", firstLoginIsChangePwd:false});//上海伴芯科技有限公司
    removeList.push({uscc:"91310115MACCLEPJ70", state:4 });//上海池瀚生物科技有限公司
    removeList.push({uscc:"91310115MA1HB8TL2B", firstLoginIsChangePwd:false});//上海锶唯弗实业有限公司
    removeList.push({uscc:"91310115MA1K4UBL2E", firstLoginIsChangePwd:false});//九奕半导体设备（上海）有限公司
    removeList.push({uscc:"91310115MA1K3NHN2N", state:4 });//上海巍啊数字科技有限公司
    removeList.push({uscc:"91310120MA1HRWDU7C", zuZhiJiGouDaiMa:null});
    removeList.push({uscc:"91310114398613914X", zuZhiJiGouDaiMa:null});
    removeList.push({uscc:"91310000342209349R", zuZhiJiGouDaiMa:null });
    removeList.push({uscc:"91310115MA1H9BY42P", fuHuaQiUscc:null});
    removeList.push({uscc:"91310115MA1HB1146N", zuZhiJiGouDaiMa:null});
    removeList.push({uscc:"91310115MA1HAQKR87", zuZhiJiGouDaiMa:null});
    removeList.push({uscc:"91310115MA1HB1BX7C", zuZhiJiGouDaiMa:null});
    
    

    console.log();
}

export async function 补充经纬度() {
    let enterpriseList = await findEnterpriseList({});
    // for (let i = 0; i < enterpriseList.length; i++) {
    //     let {uscc} = enterpriseList[i];
    //     let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    //     if (enterpriseInfo.logonAddress && enterpriseInfo.logonAddress.length && enterpriseInfo.logonAddress[0]) {
    //         let pointInfo = await getAddressLatAndLng(changeAddToString(enterpriseInfo.logonAddress), enterpriseInfo.logonAddress[0], uscc);
    //         if (!pointInfo.error) {
    //             enterpriseInfo.lng = pointInfo.lng;
    //             enterpriseInfo.lat = pointInfo.lat;
    //             console.log(i);
    //         }
    //     }
    //     await enterpriseInfo.save();
        
    // }
    for (let i = 0; i < enterpriseList.length; i++) {
        let {uscc} = enterpriseList[i];
        let enterpriseInfo = await enterpriseData.findEnterpriseByUscc(uscc);
        if (enterpriseInfo.oldLogonAddress && enterpriseInfo.oldLogonAddress.length && enterpriseInfo.oldLogonAddress[0]) {
            let pointInfo = await getAddressLatAndLng(changeAddToString(enterpriseInfo.oldLogonAddress), enterpriseInfo.oldLogonAddress[0], uscc);
            if (!pointInfo.error) {
                enterpriseInfo.oldLng = pointInfo.lng;
                enterpriseInfo.oldLat = pointInfo.lat;
                console.log(i);
            }
        }
        await enterpriseInfo.save();
        
    }
    console.log("经纬度更新成功");
}