/**
 * 导入相关方法
 */

import { UpExcelNameType } from "../config/enum";
import { TABLEID } from "../config/enum/dbEnum";
import { systemConfig } from "../config/serverConfig";
import { randomId } from "../tools/system";
import { onceSheetBecomeOfblockData } from "../util/analysisExcel";
import * as verificationEnumTools from "../util/verificationEnum";
import * as labelEnum from "../config/enum/labelEnum";
import * as configEnum from "../config/enum";
import * as industryEnum from "../config/enum/industryEnum";
import * as sysTools from "../tools/system";

import * as negotiationData from "../data/negotiation";
import * as enterpriseData from "../data/enterprise";
import * as manageData from "../data/manage";
import moment from "moment";
import { BizError } from "../util/bizError";
import { ERRORENUM } from "../config/errorEnum";
import { getEnterpriseMap, getManageData } from "../util/piecemeal";

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


/**
 * 导出excel模板地址
 * @param excelType excel对应文件类型
 * @returns 
 */
export async function excelUrl(excelType) {
    let excelName = verificationEnumTools.changeEnumValue(UpExcelNameType, excelType);
    let excelUrl = `${systemConfig.excelModelUrl}${excelName}.xlsx`
    return excelUrl;
}


/**
 * 将文件数据写入对应文件
 * @param list 文件数据
 * @param excelName 需要写入的文件
 * @returns 
 */
export async function upShowExcel(list, excelType) {
    let data = [];

    list.forEach(info => {
        data.push({
            name:"Sheet1",
            data:info.data
        });
    })

    let buff = xlsx.build(data);

    if (excelType == UpExcelNameType.在谈在跟) {
        await 在谈在跟(buff);
    } else if (excelType == UpExcelNameType.全部企业) {
        await 全部企业(buff);
    } else if (excelType == UpExcelNameType.经营数据) {
        await 经营数据(buff);
    }
    
    return {isSuccess:true}
}


export async function 在谈在跟(buff) {
    fs.writeFileSync(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", "在谈在跟.xlsx" ), buff);

    let excelData = onceSheetBecomeOfblockData("在谈在跟.xlsx", "Sheet1");

    let negotiationList = []; 
    excelData.forEach( info => {
        let {blockData} = info;
        for (let i = 2; i < blockData.length; i++) {
            let rowData = blockData[i];
            /**枚举转换 */
            let industry = [industryEnum.ALLINDUSTRY[rowData[1]]];
            // let registrationStatus = configEnum.REGISTRATIONSTATUS[rowData[2]];
            let progressStatus = configEnum.PROGRESSSTATUS[rowData[2]];
            //准备在谈在跟数据
            let negotiationInfo = {
                id: randomId(TABLEID.在跟在谈),
                name: rowData[0],
                industry: industry,
                // registrationStatus: registrationStatus,
                progressStatus: progressStatus,
                primaryContact: rowData[3],
                contactDepartment: rowData[4],
                progressDetails: rowData[5],
                createTime:new Date().valueOf(),
            }

            negotiationList.push(negotiationInfo);
        }
    });
        
    await negotiationData.createDataByParam(negotiationList);
    console.log("在谈在跟数据导入成功");
}


export async function 全部企业(buff) {
    fs.writeFileSync(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", "全部企业.xlsx" ), buff);

    let excelData = onceSheetBecomeOfblockData("全部企业.xlsx", "Sheet1");

    /**获取所有企业 */
    let enterpriseMap = await getEnterpriseMap();

    let enterpriseList = [];
    excelData.forEach( info => {
        let {blockData} = info;
        for (let i = 2; i < blockData.length; i++) {
            let rowData = blockData[i];

            if (!sysTools.eccUscc(rowData[1])) throw new BizError(ERRORENUM.统一社会信用代码不合法);
            let now = new Date().valueOf();
            if (new Date(rowData[6]).valueOf() > now) throw new BizError(ERRORENUM.不可选择未来时间);
            if (new Date(rowData[7]).valueOf() > now) throw new BizError(ERRORENUM.不可选择未来时间);
        
            /**不能出现重复的统一社会信用代码 */
            let thisEnterprise = enterpriseMap[rowData[1]];
            if (thisEnterprise) throw new BizError(ERRORENUM.该企业已存在, `${rowData[1]}已经在库中存在`);

            /**枚举转换 */
            let subDivide = [industryEnum.SUBDIVIDE[rowData[12]]]; //细分行业领域-小台账用
            let industry = [industryEnum.ALLINDUSTRY[rowData[13]]]; //行业领域
            let labelList = parseLabels(rowData); //解析标签
            let enterpriseNature = labelEnum.ENTERPRISENATURE[rowData[9]]; //企业性质
            let property = labelEnum.PROPERTY[rowData[10]]; //所属物业
            let RAS = configEnum.RAS[rowData[15]];
            let logonAddress = [rowData[2], rowData[3], rowData[4], rowData[5]];

            //准备企业数据
            let enterpriseInfo = {
                // id: randomId(TABLEID.企业基础信息表),
                name: rowData[0],
                uscc: rowData[1],
                logonAddress: logonAddress,
                logonTime: new Date(rowData[6]).valueOf(),
                parkEntryTime: new Date(rowData[7]).valueOf(),
                subDivide,
                industry,
                property,
                enterpriseNature,
                leasedArea: rowData[14],
                RAS,
                jingYingFanWei: rowData[16],
                legalPerson: rowData[17],
                zhuceziben: rowData[18],
                dianHua: rowData[19],
                createTime: new Date().valueOf(),
                labels: labelList,
                pwd: sysTools.getPwdMd5(rowData[1], md5(rowData[1].slice(rowData[1].length-6))),
                firstLoginIsChangePwd:false,
                isSettled: configEnum.STATE.是
            };

            enterpriseList.push(enterpriseInfo);
        }
    });
    await enterpriseData.createDataByParam(enterpriseList);
    console.log("全部企业数据导入成功");
}


export async function 经营数据(buff) {
    fs.writeFileSync(path.join(__dirname.substring(0,__dirname.indexOf("out")), "res", "经营数据.xlsx" ), buff);

    let excelData = onceSheetBecomeOfblockData("经营数据.xlsx", "Sheet1");

    /**获取所有企业 */
    let enterpriseMap = await getEnterpriseMap();

    let manageList = [];

    for (let thisexcel = 0; thisexcel < excelData.length; thisexcel++) {
        let info = excelData[thisexcel];
        let {blockData} = info;
        for (let i = 2; i < blockData.length; i++) {
            let rowData = blockData[i];

            /**不能出现重复的统一社会信用代码 */
            let thisEnterprise = enterpriseMap[rowData[1]];
            if (!thisEnterprise) throw new BizError(ERRORENUM.该企业不存在, `${rowData[1]}在库中不存在`);

            if (!sysTools.eccUscc(rowData[1])) throw new BizError(ERRORENUM.统一社会信用代码不合法);

            /**枚举转换 */
            let period = configEnum.PERIOD[rowData[3]];

            /**校验经营数据是否重复 */
            let isAdd = await getManageData(rowData[1], rowData[2], period);
            if (!isAdd) throw new BizError(ERRORENUM.请勿重复提交填报数据, `${rowData[1]}已有${rowData[2]}年${period}时间经营数据`);

            //准备经营数据
            let manageInfo = {
                id: randomId(TABLEID.企业经营数据),
                uscc: rowData[1],
                name: rowData[0],
                year: rowData[2],
                period: period,
                BI: rowData[4],
                VAT: rowData[5],
                CIT: rowData[6],
                PIT: rowData[7],
                RD: rowData[8],
                isSubmit:true,
                createTime:new Date().valueOf(),
            }


            manageList.push(manageInfo);
        }
    }
        
    await manageData.createDataByParam(manageList);
    console.log("经营数据数据导入成功");
}


/**
 * 处理企业标签
 * @param {Object} rowData Excel行数据
 * @returns {Array} 标签数组
 */
function parseLabels(rowData) {
    let labels = [];
    let currentTime = new Date().valueOf();
    
    // 1. 基础标签 (BASELABEL)
    if (rowData[8]) {
        labels.push({
            labelId: labelEnum.ENTERPRISESYSTEMLABEL[rowData[8]],
            labelType: labelEnum.LABELTYPE.基础标签,
            state: true
        });
    }
    
    if (rowData[9]) {
        labels.push({
            labelId: labelEnum.ENTERPRISESYSTEMLABEL[rowData[9]],
            labelType: labelEnum.LABELTYPE.企业性质,
            state: true
        });
    }
    
    if (rowData[10]) {
        labels.push({
            labelId: labelEnum.ENTERPRISESYSTEMLABEL[rowData[10]],
            labelType: labelEnum.LABELTYPE.所属物业,
            state: true
        });
    }
    
    if (rowData[11]) {
        labels.push({
            labelId: labelEnum.ENTERPRISESYSTEMLABEL[rowData[11]],
            labelType: labelEnum.LABELTYPE.入驻年份,
            state: true
        });
    }
    
    // // 2. 入驻年份标签 (ENTERPRISESYSTEMLABEL)
    // let entryYear = rowData['parkEntryTime'];
    // if (entryYear && entryYear != "-") {
    //     let yearValue;
    //     switch (entryYear.toString()) {
    //         case '2023年':
    //             yearValue = labelEnum.ENTERPRISESYSTEMLABEL["2023年"];
    //             break;
    //         case '2024年':
    //             yearValue = labelEnum.ENTERPRISESYSTEMLABEL["2024年"];
    //             break;
    //         case '2025年':
    //             yearValue = labelEnum.ENTERPRISESYSTEMLABEL["2025年"];
    //             break;
    //         case '2026年':
    //             yearValue = labelEnum.ENTERPRISESYSTEMLABEL["2026年"];
    //             break;
    //         case '2027年':
    //             yearValue = labelEnum.ENTERPRISESYSTEMLABEL["2027年"];
    //             break;
    //         case '2028年':
    //             yearValue = labelEnum.ENTERPRISESYSTEMLABEL["2028年"];
    //             break;
    //         // default:
    //         //     yearValue = labelEnum.ENTERPRISESYSTEMLABEL["其他年份"];
    //     }
        
    //     labels.push({
    //         labelId: yearValue,
    //         labelType: labelEnum.LABELTYPE.入驻年份,
    //         state: true
    //     });
    // }

    // // 3. 所属物业（PROPERTY）
    // let property = rowData['property'];
    // if (property && property != "-") {
    //     let propertyValue;
    //     switch (property) {
    //         case "于田大厦":
    //             propertyValue = labelEnum.PROPERTY.于田大厦;
    //         break;
    //         case "同济科技园":
    //             propertyValue = labelEnum.PROPERTY.同济科技园;
    //         break;
    //         case "嘉亭荟":
    //             propertyValue = labelEnum.PROPERTY.嘉亭荟;
    //         break;
    //         case "上海智慧出行设计谷":
    //             propertyValue = labelEnum.PROPERTY.上海智慧出行设计谷;
    //         break;
    //         case "汽车创新港":
    //             propertyValue = labelEnum.PROPERTY.汽车创新港;
    //         break;
    //         case "汽车城大厦":
    //             propertyValue = labelEnum.PROPERTY.汽车城大厦;
    //         break;
    //         case "国际汽车城软件园":
    //             propertyValue = labelEnum.PROPERTY.国际汽车城软件园;
    //         break;
    //     }

    //     labels.push({
    //         labelId: propertyValue,
    //         labelType: labelEnum.LABELTYPE.所属物业,
    //         state: true
    //     });
    // }

    // // 4. 企业性质 enterpriseNature: EnterpriseNatureMap[rowData.enterpriseNature] || labelEnum.ENTERPRISENATURE.实体型
    // let enterpriseNature = rowData['enterpriseNature'];
    // if (enterpriseNature && enterpriseNature != "-") {
    //     let enterpriseNatureValue;
    //     switch (enterpriseNature) {
    //         case "实体型":
    //             enterpriseNatureValue = labelEnum.ENTERPRISENATURE.实体型;
    //         break;
    //         case "注册型":
    //             enterpriseNatureValue = labelEnum.ENTERPRISENATURE.注册型;
    //         break;
    //         case "虚拟型":
    //             enterpriseNatureValue = labelEnum.ENTERPRISENATURE.虚拟型;
    //         break;
    //     }

    //     labels.push({
    //         labelId: enterpriseNatureValue,
    //         labelType: labelEnum.LABELTYPE.企业性质,
    //         state: true
    //     });
    // }
    
    return labels;
}



