/**
 * 小程序端  企业入口  用户基础功能路由
 */

import * as asyncHandler from 'express-async-handler';
import { checkEnterpriseUser, checkInterior, checkUser } from '../middleware/user';
import { getMySqlMs, getPinyinInitials, randomId } from '../tools/system';
import { OPERATIONALDATATYPE, TABLEID, TABLENAME } from '../config/enum/dbEnum';
import { changeEnumValue } from '../util/verificationEnum';
import { CHANGESTATE, DEGREE, FUHUASTATE, IPRALLTYPE, ZZMM } from '../config/enum/enum';
import { operationalData } from '../data/operationalData';
import { onceSheetBecomeOfblockData } from '../util/analysisExcel';
import { qccData } from '../biz/dataInit';
const xlsx = require('node-xlsx');
const path = require('path');
const fs = require('fs');

export function setRouter(httpServer) {
    //管理员登录登出
    httpServer.post('/admin/data/maintenance/datainit/1210', checkInterior, asyncHandler(data1210));
    httpServer.post('/admin/data/maintenance/datainit/qcc', checkInterior, asyncHandler(qccDatat0519));
}

export async function data1210(req, res) {
    let 入驻信息add = [
        {
            info_enterId:randomId(TABLEID.入驻信息表),
            building:'1',
            occupancyRate:"0%",
            enteredEnterprises:"0"
        },
        {
            info_enterId:randomId(TABLEID.入驻信息表),
            building:'3',
            occupancyRate:"0%",
            enteredEnterprises:"0"
        },
        {
            info_enterId:randomId(TABLEID.入驻信息表),
            building:'4',
            occupancyRate:"0%",
            enteredEnterprises:"0"
        },
    ]
    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.入驻信息表, 入驻信息add, {});

    //读取文件
    let {sheetMap} = getExcel(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", '在孵企业导入1210.xlsx' ));
    let dataList = sheetMap['Sheet1'];

    let fuhuaqiExcelData = getExcel(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", '在孵企业导入_孵化器提供1210.xlsx' ));
    let data2List = fuhuaqiExcelData.sheetMap['雨艺孵化器孵化企业明细'];

    let dataMap = {};
    
    for (let i= 1; i < dataList.length; i++) {
        let subList = dataList[i];
        let enterpriseName = subList[0];
        let RAS = subList[1];
        let zhuceziben = subList[3];
        let shijiaoziben = subList[4];
        let logonTime = subList[5];
        let uscc = subList[6];
        let logonAddress = [subList[8], subList[9], subList[10], subList[7].replace("上海市浦东新区", "")];
        let gengDuoDianHua = subList[12];
        let mail = subList[13];
        let moreMail = subList[14];
        let enterpriseType = subList[15];
        let zhuCeHao = subList[17];
        let zuZhiJiGouDaiMa = subList[18];
        let yingYeQiXian = subList[21];
        let qiYeGuiMo = subList[30];
        let tongXinDiZhi = JSON.stringify([subList[8], subList[9], subList[10],subList[34].replace("上海市浦东新区", "")]);
        let jianJie = subList[35];
        let jingYingFanWei = subList[36];
        let dengJiJiGuan = subList[37];
        let naShuiRenZiZhi = subList[38];
        //法人
        let faRenName = subList[2];
        //参保人数
        let canbaoNumber = subList[19] && subList[19] != '-' ? subList[19] : '';
        let canbaoYear = subList[20] && subList[20] != '-' ? subList[20] : '';

        dataMap[enterpriseName] = {
            enterpriseName,
            RAS,
            zhuceziben,
            shijiaoziben,
            uscc,
            logonAddress,
            gengDuoDianHua,
            mail,
            moreMail,
            enterpriseType,
            zhuCeHao,
            zuZhiJiGouDaiMa,
            yingYeQiXian,
            qiYeGuiMo,
            tongXinDiZhi,
            jianJie,
            dengJiJiGuan,
            naShuiRenZiZhi,
            faRenName,
            canbaoNumber,
            canbaoYear,
            jingYingFanWei,
            logonTime
        }


    }

    let 去重={};
    for (let i = 1; i < data2List.length; i++) {
        let subList = data2List[i];
        let phone = subList[14];
        if (!去重[phone]) 去重[phone] = 1;
        else console.log(phone, "重复了");

    }

    for (let i = 1; i < data2List.length; i++) {
        let subList = data2List[i];
        let enterpriseName = subList[1];
        let qccInfo = dataMap[enterpriseName];

        let eId = randomId(TABLEID.企业基础信息表);
        let pinyinName = getPinyinInitials(qccInfo.enterpriseName)
        let enterpriseInfo = {//基础信息表
            eId,
            enterpriseName:qccInfo.enterpriseName,
            pinyinName,
            RAS:qccInfo.RAS,
            zhuceziben:qccInfo.zhuceziben,
            shijiaoziben:qccInfo.shijiaoziben,
            uscc:qccInfo.uscc,
            logonAddress:JSON.stringify(qccInfo.logonAddress),
            gengDuoDianHua:qccInfo.gengDuoDianHua,
            mail:qccInfo.mail,
            moreMail:qccInfo.moreMail,
            enterpriseType:qccInfo.enterpriseType,
            zhuCeHao:qccInfo.zhuCeHao,
            zuZhiJiGouDaiMa:qccInfo.zuZhiJiGouDaiMa,
            yingYeQiXian:qccInfo.yingYeQiXian,
            qiYeGuiMo:qccInfo.qiYeGuiMo,
            tongXinDiZhi:qccInfo.tongXinDiZhi,
            jianJie:qccInfo.jianJie,
            dengJiJiGuan:qccInfo.dengJiJiGuan,
            naShuiRenZiZhi:qccInfo.naShuiRenZiZhi,
            jingYingFanWei:qccInfo.jingYingFanWei,
            logonTime:qccInfo.logonTime,
            shuiHao:subList[2],
            liaison:subList[13],
            liaisonPhone:subList[14]+'',
            shuiWuJu:subList[17] || '',
            state:CHANGESTATE.已通过,
            register:CHANGESTATE.已通过,
            
        };
        
        let enterprise_leaseInfo:any = {//租赁信息表
            leaseId:randomId(TABLEID.租赁信息),
            eId,
            area:subList[4] ? subList[4] : 0,
            building:subList[45] || '',
            // roomNumber:subList[4] || '',
            roomNumber:subList[3] || '',
            bankName:subList[18] || '',
        };

        let enterprise_fuhua:any = {//孵化表
            fId:randomId(TABLEID.企业孵化信息),
            eId,
            jiShuHeTongJiaoYi:subList[30] || 0,
            state:FUHUASTATE.实体孵化
        };

        let enterprise_legal_personInfo:any = {//法人信息
            legalId:randomId(TABLEID.法人信息表),
            eId,
            name:subList[5],
            phone:subList[8],
            idCard:subList[9],
            domicile:subList[10] || '',
        };
        if (subList[7] && DEGREE[subList[7]]) enterprise_legal_personInfo.degree = DEGREE[subList[7]];
        if (subList[11] && ZZMM[subList[11]]) {
            enterprise_legal_personInfo.politicalStatus =ZZMM[subList[11]];
        }
        if (subList[10]) {
            enterprise_legal_personInfo.domicile = subList[10];
        }

      

        if (subList[40]) {
            let zlsjList = subList[40].split("-");
            enterprise_leaseInfo.startTime = getMySqlMs(new Date(zlsjList[0]).valueOf());
            enterprise_leaseInfo.endTime = getMySqlMs(new Date(zlsjList[1]).valueOf());
        }
        

        if (subList[41] && subList[41] != '/') {
            let mzqList = subList[41].split('-');
            enterprise_leaseInfo.rentFreeStart = getMySqlMs(new Date(mzqList[0]).valueOf());
            enterprise_leaseInfo.rentFreeEnd = getMySqlMs(new Date(mzqList[1]).valueOf());
        }

        let rfrqList = subList[42].split('-');

        enterprise_fuhua.startTime = getMySqlMs(new Date(rfrqList[0]).valueOf());
        enterprise_fuhua.endTime = getMySqlMs(new Date(rfrqList[1]).valueOf());


        let enterprise_userInfo = {//登录账户表
            uId:randomId(TABLEID.企业用户表),
            userName:subList[13],
            phone:subList[14]+'',
            pwd:'111111',
            eId
        };

        await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业基础信息表, enterpriseInfo, {});
        await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.租赁信息, enterprise_leaseInfo, {});
        await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业孵化信息, enterprise_fuhua, {});
        await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.法人信息表, enterprise_legal_personInfo, {});
        await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业用户表, enterprise_userInfo, {});

        if(qccInfo.canbaoYear && qccInfo.canbaoNumber) {
            let enterprise_canbaoInfo = {
                cId:randomId(TABLEID.参保记录),
                eId,
                annual:getMySqlMs(`${ qccInfo.canbaoYear.match(/\d+/g)[0]}-01-01 00:00:00`),
                zhuanKe:0,
                benKe:0,
                shuoshi:0,
                boShi:0,
                boshiyishang:0,
                qiTa:qccInfo.canbaoNumber
            }
            await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.参保记录, enterprise_canbaoInfo, {});
        }
       

        if (subList[31]) {
            for(let i = 0; i < parseInt(subList[31]); i++) {
                let enterprise_2022iprInfo = {
                    iprId:randomId(TABLEID.知识产权),
                    eId,
                    year:getMySqlMs("2022-01-01 00:00:00"),
                    number:1,
                    iprType:IPRALLTYPE.软件著作权,
                    selectedValue:null,
                    iprName:null,
                    iprUrl:null,
                    // softwareCopyrightCount:null,
                    // inventionPatentCount:null,
                    // overseasPatentCount:null,
                    // plantVarietyCount:null,
                    // icLayoutCount:null,
    
                }
                await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.知识产权, enterprise_2022iprInfo, {});
            }
        }
        if (subList[32]) {
            for(let i = 0; i < parseInt(subList[32]); i++) {
                let enterprise_2023iprInfo = {
                    iprId:randomId(TABLEID.知识产权),
                    eId,
                    year:getMySqlMs("2023-01-01 00:00:00"),
                    number:1,
                    iprType:IPRALLTYPE.软件著作权,
                    selectedValue:null,
                    iprName:null,
                    iprUrl:null,
                    // softwareCopyrightCount:null,
                    // inventionPatentCount:null,
                    // overseasPatentCount:null,
                    // plantVarietyCount:null,
                    // icLayoutCount:null,
                }
                await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.知识产权, enterprise_2023iprInfo, {});
            }
            
        }
        if (subList[33]) {
            for(let i = 0; i < parseInt(subList[33]); i++) {
                let enterprise_2022patent = {
                    iprId:randomId(TABLEID.知识产权),
                    eId,
                    year:getMySqlMs("2022-01-01 00:00:00"),
                    number:1,
                    iprType:IPRALLTYPE.发明专利,
                    selectedValue:null,
                    iprName:null,
                    iprUrl:null,
                }
                await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.知识产权, enterprise_2022patent, {});
            }
        }
        if (subList[34]) {
            for(let i = 0; i < parseInt(subList[34]); i++) {
                let enterprise_2022patent = {
                    iprId:randomId(TABLEID.知识产权),
                    eId,
                    year:getMySqlMs("2023-01-01 00:00:00"),
                    number:1,
                    iprType:IPRALLTYPE.发明专利,
                    selectedValue:null,
                    iprName:null,
                    iprUrl:null,
                }
                await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.知识产权, enterprise_2022patent, {});
            }
        }

        if (subList[35] || subList[36] || subList[37] || subList[38]) {
            let enterprise_qualification:any = {
                qId:randomId(TABLEID.企业资质),
                eId,
            }
            if (subList[35]) enterprise_qualification.kxTime =  getMySqlMs(`${ subList[35].match(/\d+/g)[0]}-01-01 00:00:00`);
            if (subList[36]) enterprise_qualification.zjtxTime =  getMySqlMs(`${ subList[36].match(/\d+/g)[0]}-01-01 00:00:00`);
            if (subList[37]) enterprise_qualification.xjrTime =  getMySqlMs(`${ subList[37].match(/\d+/g)[0]}-01-01 00:00:00`);
            if (subList[38]) enterprise_qualification.gaoXinJiShuTime =  getMySqlMs(`${ subList[38].match(/\d+/g)[0]}-01-01 00:00:00`);
            await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业资质, enterprise_qualification, {});
        }

    }
   
    console.log("数据导入成功");
    res.success({isSuccess:true});
}


export async function qccDatat0519(req, res) {
    console.log("开始清洗企查查数据");
    qccData();

    res.success({isSuccess:true})
}


/**
 * 获取当个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 asyncqccdata(req, res) {
    
}