/**
 * 数据初始化
 * 
 */
import { FUHUAQILV, INDUSTRY, INSTITUTIONALNATURE } from "../config/enum";
import { createEnterpriseToList, findEnterpriseCount } from "../data/enterprise/enterprise";
import { createFuHuaQiToList, findAllFuHuaQiOperationUsccMap, findAllNotDisabledFuHuaQi, findFuHuaQiCount } from "../data/fuHuaQi/fuhuaqi";
import { createMonthTableToList, findMonthTableListCount } from "../data/fuHuaQi/monthTask/monthTable";
import { getPwdMd5 } from "./system";
import * as taskTool from "./taskTool";
const xlsx = require('node-xlsx');
const path = require('path');
const md5 = require("md5");

const OldTypeChangeConfig = {
    "文化创意":INDUSTRY.文化创意,
    "TMT":INDUSTRY.文化创意,
    "集成电路":INDUSTRY.集成电路,
    "微电子":INDUSTRY.集成电路,
    "先进制造":INDUSTRY.集成电路,
    "自动化":INDUSTRY.集成电路,
    "芯片半导体":INDUSTRY.集成电路,
    "电子商务":INDUSTRY.综合,
    "物联网":INDUSTRY.综合,
    "农业":INDUSTRY.综合,
    "综合型":INDUSTRY.综合,
    "区块链":INDUSTRY.软件和信息服务业,
    "电子信息":INDUSTRY.软件和信息服务业,
    "信息安全":INDUSTRY.软件和信息服务业,
    "新一代信息技术":INDUSTRY.软件和信息服务业,
    "互联网":INDUSTRY.软件和信息服务业,
    "高技术服务":INDUSTRY.软件和信息服务业,
    "大数据信息技术":INDUSTRY.软件和信息服务业,
    "技术研发":INDUSTRY.软件和信息服务业,
    "信息科技":INDUSTRY.软件和信息服务业,
    "软件":INDUSTRY.软件和信息服务业,
    "信息服务业":INDUSTRY.软件和信息服务业,
    "元宇宙":INDUSTRY.软件和信息服务业,
    "网络科技领域":INDUSTRY.软件和信息服务业,
    "IT计算机":INDUSTRY.软件和信息服务业,
    "工业4.0":INDUSTRY.人工智能及智能制造,
    "人工智能大数据":INDUSTRY.人工智能及智能制造,
    "智能制造":INDUSTRY.人工智能及智能制造,
    "人工智能":INDUSTRY.人工智能及智能制造,
    "生物医药":INDUSTRY.生物医药,
    "医疗器械":INDUSTRY.生物医药,
    "生物科技":INDUSTRY.生物医药,
    "大健康":INDUSTRY.生物医药

}

/**
 * 获取当个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}  
}


/**
 * 初始化原始数据  
 * 6.0版本后弃用 不再检查原始数据是否存在，当需要从零部署的时候，需要把这里的return放开
 */
export async function initBasicData() {
    return;
    await initFuHuaQiData();
    await initEnterprise();
    await initMonth();
}


/**
 * 初始化孵化器数据
 * @returns 
 */
async function initFuHuaQiData() {
    let count =  await findFuHuaQiCount({});
    if (count > 1) {
        console.log("*** 孵化器数据 无需初始化");
        return;
    }
    let {sheetMap} = getExcel(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", '孵化器原始数据.xlsx' ));
    let dataList = sheetMap['孵化器'];
    let titleMap = {
        "0":"operationName",//运营机构名称
        "1":"name",//名称
        "2":"uscc",
        "3":"lv",
        "4":"industry",//领域
        "5":"institutionalNature",//机构性质
        "6":"liaison",//联系人
        "7":"liaisonPhone",//联系电话
        "8":"personInCharge",//负责人
        "9":"personInChargePhone",//负责人联系电话
        "11":"acreageTotal",//孵化器总面积
        "12":"incubatedAcreage",//在孵面积
        "13":"acreagePersonalUse",//孵化器自用面积
    };
    
    let addList = [];
    dataList.forEach((subList, index) => {
        if (!index) return;//跳过表头
        let addDataInfo:any = {
            firstLoginIsChangePwd:false,
            userState:false,
            virtualEnterpriseNum:0
        };
        for (let i = 0; i < 12; i++) {
            if (i == 10) continue;
            let item =subList[i];
            let key = titleMap[i];
            let value = item;
            if (i ==2) {
                let itemStr = `${item}`;
                addDataInfo.pwd = getPwdMd5(itemStr, md5(itemStr.slice(itemStr.length-6)));
            }
            if (i == 3) {
                value = FUHUAQILV[item] || 0;
            }
            if (i == 4) {
                value = [];
                if (item) {
                    let oldList = item.split(',');
                    oldList.forEach(oldStr => {
                        value.push(OldTypeChangeConfig[oldStr.trim()]);
                    });
                }
                
            }
            if (i == 5) {
                value = INSTITUTIONALNATURE[item] || 0;
            }
            addDataInfo[key] = value;
        }
        addList.push(addDataInfo);
    });

    await createFuHuaQiToList(addList);
    console.log("---> 孵化器数据 初始化成功");
}


/**
 * 初始化企业数据
 * @returns 
 */
async function initEnterprise() {
    let count =  await findEnterpriseCount({});
    if (count > 10) {
        console.log("*** 企业数据 无需初始化");
        return;
    }
    let {sheetMap} = getExcel(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", '企业原始数据.xlsx' ));
    let dataList = sheetMap['在孵企业'];

    let fuHuaQiUsccMap = await findAllFuHuaQiOperationUsccMap();

    let titleMap = {
        "0":"name",//名称
        "3":"fuHuaQiUscc",//所属孵化器
        "4":"uscc",
        "5":"industry",//领域
        "8":"logonTime",//注册时间
        "9":"timeOfImmigration",//迁入时间 导入的时候不用管这个字段
        "10":"oldLogonAdd",//迁入前地址
        "13":"logonAdd",//注册地址
        "14":"operatingAdd",//经营地址
        "15":"firstIncubationTime",//首次入孵时间
        "16":"isNaturalPersonHolding",//是否自然人控股企业
        "18":"leasedArea",//租赁面积（平方米）
    };
    let titleIndexList = Object.keys(titleMap);
    let utc = new Date();
    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 ==3) {
                if (!item || !fuHuaQiUsccMap[item]) {
                    isJump = true;
                    break;
                }
                value = fuHuaQiUsccMap[item];
                addDataInfo.taskId = taskTool.generateMonthTaskId(value);//生成id
            }
            if (i == 4) {
                if (!item) {
                    isJump = true;
                    break;
                }
            }

            if (i == 5) {
                value = [];
                if (item) {
                    let oldList = item.split(',');
                    oldList.forEach(oldStr => {
                        let valueNum = OldTypeChangeConfig[oldStr.trim()];

                        if (valueNum) value.push(valueNum);
                    });
                };
                
            }

            if (i == 16) {
                value = !item ? false : true;
            }
            if (i == 8 && item) {
                value = new Date((item - 25569 ) * 86400 * 1000 + utc.getTimezoneOffset()*1000*60);
            }
            if (i == 9 && item) {
                value = new Date((item - 25569 ) * 86400 * 1000 + utc.getTimezoneOffset()*1000*60);
            }
            if (i == 15 && item) {
                value = new Date((item - 25569 ) * 86400 * 1000 + utc.getTimezoneOffset()*1000*60);
            }
            if ([18].indexOf(i) > -1 ) {
                if(!item) value = 0;
                else value = new Date(value).valueOf()
            } 
            if ([10,13,14].indexOf(i) > -1 && !item) {
                value = "";
            }

            addDataInfo[key] = value;
        }
        if (!isJump) addList.push(addDataInfo);
    });

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


/**
 * 初始化2022年12月孵化器出租率
 * @returns 
 */
async function initMonth() {
    let count =  await findMonthTableListCount({});
    if (count > 10) {
        console.log("*** 12月月度数据 无需初始化");
        return;
    }
    let {sheetMap} = getExcel(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", '12月孵化器出租率.xlsx' ));
    let dataList = sheetMap['孵化器月度数据'];

    let addList= [];

    let fhqList = await findAllNotDisabledFuHuaQi();
    let distinctMap = {};
    fhqList.forEach(info => {
        let {uscc, operationName} = info;
        distinctMap[operationName] = uscc;
    });

    dataList.forEach((subList, index) => {
        let name = subList[2];
        let occupancyRate = subList[6];
        let uscc = distinctMap[name];

        if (!uscc || !name || !occupancyRate ) {
            return;
        }

        let addInfo = {
            taskId:`${uscc}20231`,
            name: `12月孵化器月度填报`,
            fuHuaQiUscc:uscc,
            occupancyRate : parseInt(`${occupancyRate *10000}`)/100,
            draftLock:true,
            month:12,
            year:2022,
            isUpdate:true,
            submitTime:new Date().valueOf()
        };

        addList.push(addInfo);
    });

    await createMonthTableToList(addList);
    console.log("---> 12月月度数据 初始化成功");
}