/**
 * 基础企业库
 */

import * as verificationEnumTools from "../util/verificationEnum";
import * as configEnum from "../config/enum";
import * as industryEnum from "../config/enum/industryEnum";
import * as labelEnum from "../config/enum/labelEnum";
import * as enterpriseData from "../data/enterprise";
import { checkChange, extractData } from "../util/piecemeal";
import * as splitResultConfig from '../config/splitResultConfig';
import { eccFormParam } from "../util/verificationParam";
import { EnterpriseAddConfig, EnterpriseUpdateConfig, NegotiationAddConfig, NegotiationUpdateConfig } from "../config/eccParam/admin";
import { randomId } from "../tools/system";
import { TABLEID } from "../config/enum/dbEnum";
import { BizError } from "../util/bizError";
import { ERRORENUM } from "../config/errorEnum";
import * as sysTools from "../tools/system";
import * as labelData from "../data/label";
import * as negotiationData from "../data/negotiation";
import { convertLabelsToDbFormat, generateEnterpriseLabels, uniqueLabelList } from '../util/labelUtils';
import moment from "moment";
let md5 = require("md5");


/**
 * 企业库-获取所有企业uscc
 * @param uscc 
 */
export async function enterpriseUsccList() {
    let enterpriseDbList = await enterpriseData.findEnterpriseListByParam({isSettled: configEnum.STATE.是});

    /**组合返回结果 */
    let dataList = [];
    enterpriseDbList.forEach( info => {
        /**截取返回数据 */
        let changeData:any = extractData(splitResultConfig.enterpriseUsccListConfig, info, true);
        dataList.push(changeData);
    })

    return dataList;
}


/**
 * 企业库-获取所有企业库和在谈在跟企业的uscc
 * @param uscc 
 */
export async function enterpriseNegotiationUsccList() {
    /**企业库 */
    let enterpriseDbList = await enterpriseData.findEnterpriseListByParam({isSettled: configEnum.STATE.是});

    /**组合返回结果 */
    let dataList = [];
    enterpriseDbList.forEach( info => {
        /**截取返回数据 */
        let changeData:any = extractData(splitResultConfig.enterpriseUsccListConfig, info, true);
        dataList.push(changeData);
    })

    /**在谈在跟企业 */
    let negotiationDbList = await negotiationData.findNegotiationListByParam({});
    negotiationDbList.forEach( info => {
        /**截取返回数据 */
        let changeData:any = extractData(splitResultConfig.negotiationUsccListConfig, info, true);
        dataList.push({
            uscc:changeData.id,
            name:changeData.name
        });
    })

    return dataList;
}


/**
 * 企业建档-新增
 * @param param 
 */
export async function enterpriseCreate(param) {
    /**校验表单参数 */
    eccFormParam("管理后台新增企业建档", EnterpriseAddConfig, param);
    
    verificationEnumTools.eccEnumValue('管理后台新增企业建档', 'industry', industryEnum.ALLINDUSTRY, param.industry);
    verificationEnumTools.eccEnumValue('管理后台新增企业建档', 'enterpriseNature', labelEnum.ENTERPRISENATURE, param.enterpriseNature);
    verificationEnumTools.eccEnumValue('管理后台新增企业建档', 'property', labelEnum.PROPERTY, param.property);
    verificationEnumTools.eccEnumValue('管理后台新增企业建档', 'RAS', configEnum.RAS, param.RAS);
    if (param.subDivide) verificationEnumTools.eccEnumValue('管理后台新增企业建档', 'subDivide', industryEnum.SUBDIVIDE, param.subDivide);

    /**校验标签 */
    if (param.labels && param.labels.length > 0) {
        for (let i = 0; i < param.labels.length; i++) {
            let labelDbInfo = await labelData.findOnceLabel(param.labels[i]);
            if (!labelDbInfo && !labelDbInfo.id) throw new BizError(ERRORENUM.该标签不存在, `${param.labels[i]}在库中不存在`);
        }
    }

    if (!sysTools.eccUscc(param.uscc)) throw new BizError(ERRORENUM.统一社会信用代码不合法);
    let now = new Date().valueOf();
    if (param.logonTime > now) throw new BizError(ERRORENUM.不可选择未来时间);
    if (param.parkEntryTime > now) throw new BizError(ERRORENUM.不可选择未来时间);

    /**不能出现重复的统一社会信用代码 */
    let enterpriseDbInfo = await enterpriseData.findEnterpriseByUscc(param.uscc);
    if (enterpriseDbInfo && enterpriseDbInfo.uscc) throw new BizError(ERRORENUM.该企业已存在, `${param.uscc}已经在库中存在`);

    // 1. 获取所有可用的标签
    let activeLabels = await labelData.selectLabelList({ state: false });
    
    // 2. 生成企业标签数组
    let labels = await generateEnterpriseLabels(param, activeLabels);

    let zhuceziben = sysTools.formatRegisteredCapital(param.zhuceziben)

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

    // 4. 保存企业数据
    await enterpriseData.createDataByParam(enterpriseInfo);

    return { isSuccess: true };
}


/**
 * 企业库-列表
 * @param dataType 不传=所有企业、1=100平方公里、2=3.73平方公里、3=软件关联入驻企业、4=小台账企业、5=重点稳商企业
 * @param name 企业名称
 * @param industry 行业领域
 * @param subDivide 细分行业领域
 * @param parkEntryTime 入驻年份
 * @param logonTime 企业成立年份
 * @param labelIdList 企业标签 可多选
 * @param page 页
 */
export async function enterpriseList(dataType:number, name:string, industry, subDivide, parkEntryTime:number, logonTime:number, labelIdList, page:number) {
    let selectParam:any = {};
    if (name) {
        selectParam.name = {"$regex":`${name}`};
    }
    if (industry && industry.length > 0) {
        verificationEnumTools.eccEnumValue('管理后台获取企业库列表', 'industry', industryEnum.ALLINDUSTRY, industry);
        selectParam.industry = {"$in":industry};
    }
    if (subDivide && subDivide.length > 0) {
        verificationEnumTools.eccEnumValue('管理后台获取企业库列表', 'subDivide', industryEnum.SUBDIVIDE, subDivide);
        selectParam.subDivide = {"$in":subDivide};
    }
    if (parkEntryTime) {
        let parkEntryStartTime = moment(`${parkEntryTime}-01-01`).valueOf();
        let parkEntryEndTime = moment(`${parkEntryTime}-12-31`).valueOf();
        selectParam.parkEntryTime = {"$gte":parkEntryStartTime, "$lte":parkEntryEndTime};
    }
    if (logonTime) {
        let logonStartTime = moment(`${logonTime}-01-01`).valueOf();
        let logonEndTime = moment(`${logonTime}-12-31`).valueOf();
        selectParam.logonTime = {"$gte":logonStartTime, "$lte":logonEndTime};
    }

    //企业库列表分类
    let dataTypeLabelList = [];
    if (dataType) {
        if (dataType == labelEnum.BASELABEL["100平方公里"]) dataTypeLabelList.push(labelEnum.BASELABEL["100平方公里"].toString());
        else if (dataType == labelEnum.BASELABEL["3.73平方公里"]) dataTypeLabelList.push(labelEnum.BASELABEL["3.73平方公里"].toString());
        else if (dataType == labelEnum.BASELABEL.小台账企业) dataTypeLabelList.push(labelEnum.BASELABEL.小台账企业.toString());
        else if (dataType == labelEnum.BASELABEL.软件关联入驻企业) dataTypeLabelList.push(labelEnum.BASELABEL.软件关联入驻企业.toString());
        else if (dataType == labelEnum.BASELABEL.重点稳商企业) dataTypeLabelList.push(labelEnum.BASELABEL.重点稳商企业.toString());
    }

    // 处理标签筛选逻辑
    if (dataTypeLabelList.length > 0 || (labelIdList && labelIdList.length > 0)) {
        let labelConditions = [];
        
        // 如果传了dataType，必须包含该标签
        if (dataTypeLabelList.length > 0) {
            labelConditions.push({
                "labels": {
                    "$elemMatch": {
                        "labelId": { "$in": dataTypeLabelList }
                    }
                }
            });
        }
        
        // 如果传了labelIdList，必须包含其中任意一个标签
        if (labelIdList && labelIdList.length > 0) {
            let uniqueLabels = uniqueLabelList(labelIdList.map(id => id.toString()));
            
            if (uniqueLabels.length > 0) {
                labelConditions.push({
                    "labels": {
                        "$elemMatch": {
                            "labelId": { "$in": uniqueLabels }
                        }
                    }
                });
            }
        }
        
        // 构建查询条件
        if (labelConditions.length === 1) {
            Object.assign(selectParam, labelConditions[0]);
        } else if (labelConditions.length > 1) {
            // 使用 $and 连接多个条件，表示必须同时满足
            selectParam["$and"] = labelConditions;
        }
    }

    /**标签名称转换 */
    let labelDbList = await labelData.selectLabelList({});
    let labelDbMap = {};
    labelDbList.forEach( info => {
        labelDbMap[info.id] = info.labelName;
    })

    /**需要用到的查询数据 */
    // 使用更稳定的排序：首先按createTime，然后按id或uscc确保顺序稳定
    let enterpriseDbList = await enterpriseData.findEnterpriseListToPageSort(selectParam, (page - 1) * 10, {createTime: -1});
    let count = await enterpriseData.findEnterpriseCount(selectParam);//符合查询条件的数据总数

    /**组合返回结果 */
    let dataList = [];

    enterpriseDbList.forEach( info => {
        /**截取返回数据 */
        let changeData:any = extractData(splitResultConfig.enterpriseListConfig, info, true);

        /**将枚举值转为字符 */
        //行业领域
        let industry = [];
        if (changeData.industry && changeData.industry.length > 0) {
            // 数组处理
            let industryValue = verificationEnumTools.changeEnumValue(industryEnum.ALLINDUSTRY, changeData.industry);
            if (industryValue) {
                industry.push(industryValue);
            }
        }
        changeData.industry = industry;

        //细分行业领域
        let subDivide = [];
        if (changeData.subDivide && changeData.subDivide.length > 0) {
            // 数组处理
            let subDivideValue = verificationEnumTools.changeEnumValue(industryEnum.SUBDIVIDE, changeData.subDivide);
            if (subDivideValue) {
                subDivide.push(subDivideValue);
            }
        }
        changeData.subDivide = subDivide;

        //标签
        let labels = [];
        if (changeData.labels && changeData.labels.length > 0) {
            changeData.labels.forEach( info => {
                let {labelId, state} = info;
                // 只添加状态为true的标签
                if (state === true || state === undefined) {
                    labels.push(labelDbMap[labelId]);
                }
            })
        }
        changeData.labels = labels;
        changeData.property = verificationEnumTools.changeEnumValue(labelEnum.PROPERTY, changeData.property);
        changeData.enterpriseNature = verificationEnumTools.changeEnumValue(labelEnum.ENTERPRISENATURE, changeData.enterpriseNature)
        changeData.RAS = verificationEnumTools.changeEnumValue(configEnum.RAS, changeData.RAS);

        dataList.push(changeData);
    });
    
    return {count, dataList};
}


/**
 * 企业库-回显
 * @param uscc 
 */
export async function enterpriseInfo(uscc:string) {
    let enterpriseDbInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    if (!enterpriseDbInfo || !enterpriseDbInfo.uscc) throw new BizError(ERRORENUM.该企业不存在, `库中不存在uscc=${uscc}这个企业`);

    /**标签转换 */
    let labels = [];
    if (enterpriseDbInfo.labels && enterpriseDbInfo.labels.length > 0) {
        enterpriseDbInfo.labels.forEach( info => {
            let {labelId, state} = info;
            labels.push(labelId)
            // labels.push(verificationEnumTools.changeEnumValue(labelEnum.ENTERPRISESYSTEMLABEL, parseInt(labelId)))
        })
    }
    
    let dataInfo = {
        name: enterpriseDbInfo.name, //企业名称
        uscc: enterpriseDbInfo.uscc, //统一信用代码
        logonAddress: enterpriseDbInfo.logonAddress, //企业注册地址
        logonTime: enterpriseDbInfo.logonTime, //moment(enterpriseDbInfo.logonTime).format("YYYY-MM-DD"), //注册时间、成立时间
        parkEntryTime: enterpriseDbInfo.parkEntryTime, //moment(enterpriseDbInfo.parkEntryTime).format("YYYY-MM-DD"), //入驻园区时间
        labels: labels, //企业标签
        industry: enterpriseDbInfo.industry, //行业领域
        subDivide: enterpriseDbInfo.subDivide, //细分行业领域
        // property: enterpriseDbInfo.property.toString(), //所属物业
        // enterpriseNature: enterpriseDbInfo.enterpriseNature.toString(), //企业性质
        property: enterpriseDbInfo.property ? enterpriseDbInfo.property.toString() : "", //所属物业
        enterpriseNature: enterpriseDbInfo.enterpriseNature ? enterpriseDbInfo.enterpriseNature.toString() : "", //企业性质
        leasedArea: enterpriseDbInfo.leasedArea, //租赁面积（㎡）
        RAS: enterpriseDbInfo.RAS, //登记状态
        jingYingFanWei: enterpriseDbInfo.jingYingFanWei, //经营范围
        legalPerson: enterpriseDbInfo.legalPerson, //法人
        zhuceziben: enterpriseDbInfo.zhuceziben, //注册资本
        dianHua: enterpriseDbInfo.dianHua, //电话、联系方式
    };

    return {dataInfo};
}


/**
 * 企业库-修改
 * @param uscc 
 * @param param 
 */
export async function enterpriseUpdate(uscc:string, param) {
    /**校验参数 */
    eccFormParam("管理后台修改企业库", EnterpriseUpdateConfig, param);

    /**校验枚举 */
    verificationEnumTools.eccEnumValue('管理后台修改企业建档', 'industry', industryEnum.ALLINDUSTRY, param.industry);
    verificationEnumTools.eccEnumValue('管理后台修改企业建档', 'enterpriseNature', labelEnum.ENTERPRISENATURE, param.enterpriseNature);
    verificationEnumTools.eccEnumValue('管理后台修改企业建档', 'property', labelEnum.PROPERTY, param.property);
    verificationEnumTools.eccEnumValue('管理后台修改企业建档', 'RAS', configEnum.RAS, param.RAS);
    if (param.subDivide) verificationEnumTools.eccEnumValue('管理后台修改企业建档', 'subDivide', industryEnum.SUBDIVIDE, param.subDivide);

    /**校验标签 */
    if (param.labels && param.labels.length > 0) {
        // 检查标签中是否包含多个企业性质或所属物业
        let enterpriseNatureLabels = [];
        let propertyLabels = [];
        let yearLabels = [];
        
        for (let i = 0; i < param.labels.length; i++) {
            let labelId = param.labels[i];
            let labelDbInfo = await labelData.findOnceLabel(labelId);
            
            if (!labelDbInfo || !labelDbInfo.id) {
                throw new BizError(ERRORENUM.该标签不存在, `${labelId}在库中不存在`);
            }
            
            // 根据标签类型分类
            if (labelDbInfo.labelType === labelEnum.LABELTYPE.企业性质) {
                enterpriseNatureLabels.push(labelId);
            } else if (labelDbInfo.labelType === labelEnum.LABELTYPE.所属物业) {
                propertyLabels.push(labelId);
            } else if (labelDbInfo.labelType === labelEnum.LABELTYPE.入驻年份) {
                yearLabels.push(labelId);
            }
        }
        
        // 检查企业性质标签是否多选
        if (enterpriseNatureLabels.length > 1) {
            throw new BizError(ERRORENUM.企业性质不可多选, '企业性质不可多选');
        }
        
        // 检查所属物业标签是否多选
        if (propertyLabels.length > 1) {
            throw new BizError(ERRORENUM.所属物业不可多选, '所属物业不可多选');
        }
        
        // 检查入驻年份标签是否多选
        if (yearLabels.length > 1) {
            throw new BizError(ERRORENUM.入驻年份不可多选, '入驻年份不可多选');
        }
        
        param.labels = await convertLabelsToDbFormat(param.labels);
    }

    if (!sysTools.eccUscc(param.uscc)) throw new BizError(ERRORENUM.统一社会信用代码不合法);
    let now = new Date().valueOf();
    if (param.logonTime > now) throw new BizError(ERRORENUM.不可选择未来时间);
    if (param.parkEntryTime > now) throw new BizError(ERRORENUM.不可选择未来时间);

    /**校验企业 */
    let enterpriseDbInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    if (!enterpriseDbInfo || !enterpriseDbInfo.uscc) throw new BizError(ERRORENUM.该企业不存在, `库中不存在uscc=${uscc}这个企业`);

    /**修改字段 */
    let changeList = checkChange(param, enterpriseDbInfo);
    if (!changeList.length) throw new BizError(ERRORENUM.数据无更新, `${param.name}数据无更新`);
    changeList.forEach(key => {
        enterpriseDbInfo[key] = param[key];
    });

    /**处理入驻年份标签更新（新增的逻辑）*/
    if (param.parkEntryTime) {
        try {
            let year = moment(param.parkEntryTime).format("YYYY");
            
            if (year && year != "-") {
                let yearValue;
                switch (year.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 = year.toString();
                        break;
                }
                
                if (yearValue) {
                    // 查找现有的入驻年份标签
                    let existingYearLabelIndex = -1;
                    let existingYearLabel = null;
                    
                    for (let j = 0; j < enterpriseDbInfo.labels.length; j++) {
                        let label = enterpriseDbInfo.labels[j];
                        // 检查标签类型是否为入驻年份
                        if (label.labelType === labelEnum.LABELTYPE.入驻年份) {
                            existingYearLabelIndex = j;
                            existingYearLabel = label;
                            break;
                        }
                    }
                    
                    if (existingYearLabelIndex !== -1 && existingYearLabel) {
                        // 如果已存在入驻年份标签
                        if (existingYearLabel.labelId && existingYearLabel.labelId.toString() !== yearValue.toString()) {
                            // 标签年份与当前年份不一致，需要更新
                            enterpriseDbInfo.labels[existingYearLabelIndex]["labelId"] = yearValue.toString();
                            console.log(`已为企业 ${enterpriseDbInfo.name} (${enterpriseDbInfo.uscc}) 更新入驻年份标签：从 ${existingYearLabel.labelId} 更新为 ${yearValue}`);
                        } else {
                            // 标签年份一致，无需修改
                            console.log(`企业 ${enterpriseDbInfo.name} (${enterpriseDbInfo.uscc}) 入驻年份标签已是最新（${yearValue}），无需更新`);
                        }
                    } else {
                        // 不存在入驻年份标签，需要添加
                        enterpriseDbInfo.labels.push({
                            labelId: yearValue.toString(),
                            labelType: labelEnum.LABELTYPE.入驻年份,
                            state: true
                        });
                        console.log(`已为企业 ${enterpriseDbInfo.name} (${enterpriseDbInfo.uscc}) 添加 ${year}年 入驻年份标签`);
                    }
                }
            }
        } catch (error) {
            console.error(`为企业 ${enterpriseDbInfo.name} (${enterpriseDbInfo.uscc}) 处理入驻年份标签时出错:`, error);
            // 继续执行修改操作，标签更新失败不影响整体业务
        }
    }

    await enterpriseDbInfo.save();

    return {isSuccess:true};
}


/**
 * 企业库-删除
 * @param id 
 */
export async function enterpriseDelete(uscc:string) {
    let enterpriseDbInfo = await enterpriseData.findEnterpriseByUscc(uscc);
    if (!enterpriseDbInfo || !enterpriseDbInfo.name) throw new BizError(ERRORENUM.未找到数据, `库中不存在uscc=${uscc}这个企业`);

    await enterpriseData.removeOneData(uscc);

    return {isSuccess:true};
}


/**
 * 导出企业库信息列表
 * @param name 企业名称
 * @param industry 行业领域
 * @param parkEntryTime 入驻年份
 * @param logonTime 注册年份
 * @param labelIdList 标签ID列表
 * @param dataType 企业分类（1=100平方公里、2=3.73平方公里、3=软件关联入驻企业、4=小台账企业、5=重点稳商企业）
 * @returns 二维数组，第一行为表头，后续行为数据
 */
export async function outPutEnterpriseData(name:string, industry:string[], subDivide:string[], parkEntryTime:number, logonTime:number, labelIdList:string[], dataType:number, uscc:string[]) {
    /** 拼接查询条件 */
    let selectParam: any = {};
    if (name) {
        selectParam.name = { "$regex": `${name}` };
    }
    if (industry && industry.length > 0) {
        selectParam.industry = { "$in": industry };
    }
    if (subDivide && subDivide.length > 0) {
        selectParam.subDivide = { "$in": subDivide };
    }
    if (parkEntryTime) {
        let parkEntryStartTime = moment(`${parkEntryTime}-01-01`).valueOf();
        let parkEntryEndTime = moment(`${parkEntryTime}-12-31`).valueOf();
        selectParam.parkEntryTime = { "$gte": parkEntryStartTime, "$lte": parkEntryEndTime };
    }
    if (logonTime) {
        let logonStartTime = moment(`${logonTime}-01-01`).valueOf();
        let logonEndTime = moment(`${logonTime}-12-31`).valueOf();
        selectParam.logonTime = { "$gte": logonStartTime, "$lte": logonEndTime };
    }
    if (uscc) {
        selectParam.uscc = {"$in": uscc};
    }

    // 标签筛选
    let allLabelList = [];
    if (dataType) {
        if (dataType == 1) allLabelList.push(labelEnum.BASELABEL["100平方公里"].toString());
        else if (dataType == 2) allLabelList.push(labelEnum.BASELABEL["3.73平方公里"].toString());
        else if (dataType == 3) allLabelList.push(labelEnum.BASELABEL.软件关联入驻企业.toString());
        else if (dataType == 4) allLabelList.push(labelEnum.BASELABEL.小台账企业.toString());
        else if (dataType == 5) allLabelList.push(labelEnum.BASELABEL.重点稳商企业.toString());
    }
    if (labelIdList && labelIdList.length > 0) {
        labelIdList.forEach(info => {
            allLabelList.push(info.toString());
        });
    }

    if (allLabelList.length > 0) {
        let uniqueLabels = uniqueLabelList(allLabelList);
        selectParam.labels = { "$elemMatch": { labelId: { "$in": uniqueLabels } } };
    }

    /** 查询企业数据 */
    let enterpriseDbList = await enterpriseData.findEnterpriseListByParamSort(selectParam, {createTime: -1});

    /** 表头定义 */
    let titleList = [
        "企业名称",
        "统一社会信用代码",
        "所属省份",
        "所属城市",
        "所属区县",
        "详细地址",
        // "注册地址",
        "注册时间",
        "入驻时间",
        "细分行业领域",
        "行业领域",
        "所属物业",
        "企业性质",
        "租赁面积（㎡）",
        "登记状态",
        "经营范围",
        "法人",
        "注册资本",
        "联系电话",
        "企业标签"
    ];

    /** 字段映射 */
    let keyList = [
        "name",
        "uscc",
        "province",               // 所属省份
        "city",                  // 所属城市
        "district",              // 所属区县
        "logonAdd",               // 详细地址
        // "logonAddress",
        "logonTime",
        "parkEntryTime",
        "subDivide",
        "industry",
        "property",
        "enterpriseNature",
        "leasedArea",
        "RAS",
        "jingYingFanWei",
        "legalPerson",
        "zhuceziben",
        "dianHua",
        "labels"
    ];

    let dataList = [titleList]; // 第一行为表头

    enterpriseDbList.forEach(info => {
        /** 提取数据 */
        let changeData: any = extractData(splitResultConfig.enterpriseListConfig, info, true);

        /** 枚举值转文本 */
        changeData.industry = verificationEnumTools.changeEnumValue(industryEnum.ALLINDUSTRY, changeData.industry) || "未选择";
        changeData.subDivide = verificationEnumTools.changeEnumValue(industryEnum.SUBDIVIDE, changeData.subDivide) || "未选择";
        changeData.property = verificationEnumTools.changeEnumValue(labelEnum.PROPERTY, changeData.property) || "未选择";
        changeData.enterpriseNature = verificationEnumTools.changeEnumValue(labelEnum.ENTERPRISENATURE, changeData.enterpriseNature) || "未选择";
        changeData.RAS = verificationEnumTools.changeEnumValue(configEnum.RAS, changeData.RAS) || "未选择";

        /**注册地址转文本 */
        if (changeData.logonAddress) {
            changeData.province = changeData.logonAddress[0];
            changeData.city = changeData.logonAddress[1];
            changeData.district = changeData.logonAddress[2];
            changeData.logonAdd = changeData.logonAddress[3];
        }

        /** 标签转文本 */
        let labelNames = [];
        if (changeData.labels && changeData.labels.length > 0) {
            changeData.labels.forEach(label => {
                labelNames.push(verificationEnumTools.changeEnumValue(labelEnum.ENTERPRISESYSTEMLABEL, parseInt(label.labelId)) || "未知标签");
            });
        }
        changeData.labels = labelNames.join("、") || "无标签";

        /** 时间格式化 */
        if (changeData.logonTime && changeData.logonTime != "-") {
            changeData.logonTime = moment(changeData.logonTime).format("YYYY-MM-DD");
        } else {
            changeData.logonTime = "-";
        }
        if (changeData.parkEntryTime && changeData.parkEntryTime != "-") {
            changeData.parkEntryTime = moment(changeData.parkEntryTime).format("YYYY-MM-DD");
        } else {
            changeData.parkEntryTime = "-";
        }

        /** 生成一行数据 */
        let row = [];
        keyList.forEach(key => {
            let value = changeData[key];
            if (value === null || value === undefined || value === "") {
                value = "-";
            }
            row.push(value);
        });

        dataList.push(row);
    });

    return dataList;
}



