/**
 * 数据初始化
 * 
 */
import { FUHUAQILNVESTMENTSTYLE, FUHUAQILV, INDUSTRY, INSTITUTIONALNATURE } from "../config/enum";
import { createEnterpriseToList, findEnterpriseCount } from "../data/enterprise/enterprise";
import { findFinancingCount } from "../data/fuHuaQi/monthTask/financing";
import { createFuHuaQiToList, findAllFuHuaQiOperationUsccMap, findAllNotDisabledFuHuaQi, findFuHuaQiUserCount } from "../data/fuHuaQi/fuhuaqi";
import { createMonthTableToList, findMonthCount } 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}  
}


/**
 * 初始化原始数据
 */
export async function initBasicData() {
    await initFuHuaQiData();
    await initEnterprise();
    await initMonth();
}

async function initFuHuaQiData() {
    let count =  await findFuHuaQiUserCount({});
    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("---> 孵化器数据 初始化成功");
}

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("---> 企业数据 初始化成功");
}

async function initMonth() {
    let count =  await findMonthCount({});
    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月月度数据 初始化成功");
}

// async function initFinancing() {
//     :{type:String, index:true},//融资企业统一信用代码 冗余字段
//     :{type:String, index:true},//孵化器统一信用代码 冗余字段
//     :String,//企业名称
//     :{type:String, index:true},//任务id
//     :String,//注册地址
//     :String,//经营地址
//     :Number,//融资金额(万元)
//     :String,//投资机构名称
//     :Number,//获得投资时间
//     :{type:Boolean, default:false},//孵化器是否投资
//     :Number,//孵化器投资金额(万元)
//     :Number,//孵化器投资方式
//     :{type:Boolean, default:false},//草稿锁，true为提交之后，false为草稿
//     :Number,//录入时间
//     industry:[Number],//领域
//     logonTime:Number,//注册时间
//     financingRounds:Number,//融资轮次
    

//     let count =  await findFinancingCount({});
//     if (count > 10) {
//         console.log("*** 融资数据 无需初始化");
//         return;
//     }

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

//     let {sheetMap} = getExcel(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", '12月融资企业数据.xlsx' ));
//     let dataList = sheetMap['在孵企业月度数据'];
    
    
//     let addList = [];
//     dataList.forEach((subList, index) => {
//         let uscc = subList[4];
//         let fuhuaqi = subList[3];
//         let fuHuaQiUscc = distinctMap[fuhuaqi];
//         if ( !fuHuaQiUscc || !uscc) {
//             return;
//         }
//         let name = subList[2];
//         let taskId = `${fuHuaQiUscc}20231`;
//         let logonAdd = subList[6];
//         let operatingAdd = subList[7];
//         let financingAmount = subList[11] || 0;
//         let investmentInstitutionsName = subList[12];
//         let timeToObtainInvestment = new Date(subList[13]).valueOf();
//         let fuHuaQiInvestment = subList[13] == "是" ? true : false;
//         let fuHuaQiInvestmentAmount = subList[14] ||0;
//         let fuHuaQiInvestmentStyle = subList[15] ? FUHUAQILNVESTMENTSTYLE.自有基金
//         let draftLock = true;
//         let createTime = new Date().valueOf();
//         addList.push({

//         });
//     });

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