import { FUHUAINDUSTRY, FUHUAQILV, INDUSTRY, INSTITUTIONALNATURE } from "../config/enum";
import { createEnterpriseToList, findEnterpriseCount } from "../data/enterprise/enterprise";
import { createFuHuaQiToList, findAllFuHuaQiOperationUsccMap, findFuHuaQiUserCount } from "../data/fuHuaQi/fuhuaqi";
import { getPwdMd5, getTaskId } from "./tools";
const fs = require('fs');
const xlsx = require('node-xlsx');
const path = require('path');

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

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

async function initFuHuaQiData() {
    let count =  await findFuHuaQiUserCount({});
    if (count > 10) {
        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) {
                addDataInfo.pwd = getPwdMd5(item, item.slice(item.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 addList = [];
    dataList.forEach((subList, index) => {
        if (!index) return;//跳过表头
        let addDataInfo:any = {
            draftLock:true,
            createTime:new Date().valueOf(),
            isCreate: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 = getTaskId(value);
            }
            if (i == 4) {
                if (!item) {
                    isJump = true;
                    break;
                }
            }

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

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

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

            if (i == 9 && value !=0) addDataInfo.isCreate =false;
            if (i == 10 && value != "") addDataInfo.isCreate =false;

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

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