import { extractData } from "../../../util/piecemeal";
import * as enterpriseData from "../../../data/enterprise/enterprise";
import * as splitResultConfig from "../../../config/splitResultConfig";
import * as fuHuaQiData from "../../../data/fuHuaQi/fuhuaqi";
import * as configEnum from "../../../config/enum";
import * as verificationEnumTools from "../../../util/verificationEnum";
import moment = require("moment");


/**
 * 获取在孵企业信息列表
 * 管理后台端
 * @param createType 新注册/迁入  1:全选 2:新注册 3:迁入   以前是时间  2/23日修改为类型
 * @param fuHuaQiUscc 所属孵化器 
 * @param industry 行业领域
 * @param isNaturalPersonHolding 自然人控股
 * @param state 孵化状态2.0
 * @param createTime 入库时间 
 * @param page 页数
 * @returns dataList:[], count:0  dataList=数据列表  count:条件筛选下的数据总数
 */
export async function enterpriseList(createType:number, fuHuaQiUscc:string, industry, isNaturalPersonHolding:number, state:number, createTime:number, name:string, page:number) {
    /**拼接查询条件 */
    let selectParam:any = {};
    if (createType == 2 || createType == 3) {
        selectParam.isCreate = createType == 2 ? true : false;
    }
    if (fuHuaQiUscc) selectParam.fuHuaQiUscc = fuHuaQiUscc;
    if (industry.length > 0) {
        verificationEnumTools.eccEnumValue('管理后台获取在孵企业信息列表', 'industry', configEnum.INDUSTRY, industry);
        selectParam.industry = industry;
    }
    if (isNaturalPersonHolding == 2 || isNaturalPersonHolding == 3) {
        selectParam.isNaturalPersonHolding = isNaturalPersonHolding == 2 ? true : false;
    }
    if (state != configEnum.INSIDESTATE.全部) {
        if (state == configEnum.INSIDESTATE.实体孵化) selectParam.state = configEnum.FUHUASTATE.实体孵化;
        if (state == configEnum.INSIDESTATE.虚拟孵化) selectParam.state = configEnum.FUHUASTATE.虚拟孵化;
    }
    if (createTime) {
        let startT = createTime;
        let endT = moment(createTime).endOf('month').valueOf();
        selectParam.createTime = {"$gt":startT, "$lt":endT};
    }
    if (name) {
        selectParam.name = {"$regex":`${name}`};
    }
    selectParam.draftLock = true; //未提交的企业不能查看

    /**需要用到的查询数据 */
    let usccMap = await fuHuaQiData.findAllFuHuaQiOperationNameMap();//用于将孵化器uscc变成孵化器名称
    let dataBaseList = await enterpriseData.findEnterpriseListToPage(selectParam, (page-1)*10 );
    let count = await enterpriseData.findEnterpriseCount(selectParam);//符合查询条件的数据总数

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

        /**匹配所属孵化器名称  匹配不上时这里显示空字符串 */
        changeData.fuhuaqiUscc = usccMap[info.fuHuaQiUscc] || "";

        /** 返回的isCreate字段为字符串 当为导入数据时这里显示为空字符  */
        if (info.enterpriseIsInPut) changeData.isCreate = "";
        else changeData.isCreate = (changeData.isCreate) ? "新注册" : "新迁入";

        changeData.state = verificationEnumTools.changeEnumValue(configEnum.FUHUASTATE, changeData.state);
        changeData.virtualCause = !changeData.virtualCause ? '-' : verificationEnumTools.changeEnumValue(configEnum.VIRTUALCAUSE, changeData.virtualCause);

        /**将枚举值转为字符 */
        changeData.industry = verificationEnumTools.changeEnumValue(configEnum.INDUSTRY, changeData.industry);
        
        dataList.push(changeData);
    });

    return {count, dataList};
}


/**
 * 导出在孵企业信息列表
 * 管理后台端
 * @param createType 新注册时间/迁入时间
 * @param fuHuaQiUscc 所属孵化器 
 * @param industry 行业领域 数组
 * @param isNaturalPersonHolding 自然人控股
 * @returns 二维数组
 */
export async function outPutEnterpriseData(createType:number, fuHuaQiUscc:string, industry, isNaturalPersonHolding:number, state:number, createTime:number, name:string, type:number) {
    /**拼接查询条件 */
    let selectParam:any = {};
    if (type == configEnum.OUTPUTTYPE.当前数据) {
        if (createType == 2 || createType == 3) {
            selectParam.isCreate = createType == 2 ? true : false;
        }
        if (fuHuaQiUscc) selectParam.fuHuaQiUscc = fuHuaQiUscc;
        if (industry.length > 0) selectParam.industry = industry;
        if (isNaturalPersonHolding == 2 || isNaturalPersonHolding == 3) {
            selectParam.isNaturalPersonHolding = isNaturalPersonHolding == 2 ? true : false;
        }
        if (state != configEnum.INSIDESTATE.全部) {
            if (state == configEnum.INSIDESTATE.实体孵化) selectParam.state = configEnum.FUHUASTATE.实体孵化;
            if (state == configEnum.INSIDESTATE.虚拟孵化) selectParam.state = configEnum.FUHUASTATE.虚拟孵化;
        }
        if (createTime) {
            let startT = createTime;
            let endT = moment(createTime).endOf('month').valueOf();
            selectParam.createTime = {"$gt":startT, "$lt":endT};
        }
        if (name) {
            selectParam.name = {"$regex":`${name}`};
        }
    }
    selectParam.draftLock = true;//匹配已经提交入库的企业

    /**查询内容 */
    let usccMap = await fuHuaQiData.findAllFuHuaQiOperationNameMap();//用于将孵化器uscc变成孵化器名称
    let dataBaseList = await enterpriseData.findEnterpriseList(selectParam );

    /**组合二维数组  titleList 与 keyList 要一一对应 */ 
    const TitleList = [
        "企业名称", "入库时间", "所属孵化器", "新注册/新迁入","统一信用代码", "行业领域","主营业务",
        "注册时间", "首次入孵时间", "迁入时间", "是否自然人控股", "迁入前注册地址",
        "注册地址", "经营地址", "租赁面积（平方米）"
    ];//表头顺序  如果这里修改了 下面的keyList也要修改
    const KeyList = [
        "name", "createTime", "fuhuaqiUscc", "isCreate", "uscc", "industry", "mainBusiness", "logonTime",
        "firstIncubationTime", "timeOfImmigration", "isNaturalPersonHolding", "oldLogonAdd",
        "logonAdd", "operatingAdd", "leasedArea"
    ];//表头对应的字段顺序
    let dataList = [TitleList];
    
    dataBaseList.forEach( info => {
        /**截取返回结果 */
        let changeData:any = extractData(splitResultConfig.EnterpriseListConfig, info, true);

        /**匹配所属孵化器名称  匹配不上时这里显示空字符串 */
        changeData.fuhuaqiUscc = usccMap[info.fuHuaQiUscc] || "";
        if (info.enterpriseIsInPut) changeData.isCreate = "";
        else changeData.isCreate = (changeData.isCreate) ? "新注册" : "新迁入";

        changeData.isNaturalPersonHolding = changeData.isNaturalPersonHolding ? "是" : "否";

        /**修改枚举值 */
        changeData.industry = verificationEnumTools.changeEnumValue(configEnum.INDUSTRY, changeData.industry);
        // dataList.push(changeData);
        /**根据表头与key的顺序 生成小数组 */
        let subList = [];
        KeyList.forEach( keyStr => {
            subList.push(changeData[keyStr] || '');
        });
        dataList.push(subList);
    });

    return dataList;
}


/**
 * 在孵企业页面的所属孵化器 下拉框
 * 管理后台端
 * 只返回有入孵企业的孵化器
 * @returns result result类型为数组对象 对象内容为{name, uscc}
 */
export async function getAffiliationFuHuaQi() {
    /**获取已有入孵企业的孵化器统一信用代码列表 */
    let bindList = await enterpriseData.findAllBindFuHuaQiUsccList();

    /**限制为 非禁用状态下的孵化器 */
    let notDisabledList = await fuHuaQiData.findAllNotDisabledFuHuaQi();

    let distinctMap = {}; //去重用的map对象 格式为:{uscc:name}
    notDisabledList.forEach(info => {
        distinctMap[info.uscc] = info.operationName;
    });

    let result = [];
    bindList.forEach(fuHuaQiUscc => {
        let fuHuaQiName = distinctMap[fuHuaQiUscc];
        if ( fuHuaQiName ) {
            result.push({
                name:fuHuaQiName,
                uscc:fuHuaQiUscc
            });
        }
    });

    return {result}
}


/**
 * 企业迁出列表
 * @param name 企业名称
 * @param fuHuaQiUscc 所属孵化器统一信用代码
 * @param industry 领域多选
 * @param isNaturalPersonHolding  是否自然人控股
 * @param page 页面
 * @returns 
 */
export async function enterpriseMoveOutList(name:string, fuHuaQiUscc:string, industry, isNaturalPersonHolding:number, page:number) {
    /**拼接查询条件 */
    let selectParam:any = {state:configEnum.FUHUASTATE.迁出};
    if (name) {
        selectParam.name = {"$regex":`${name}`};
    }
    if (fuHuaQiUscc) selectParam.fuHuaQiUscc = fuHuaQiUscc;
    if (industry.length > 0) {
        verificationEnumTools.eccEnumValue('管理后台获取在孵企业信息列表', 'industry', configEnum.INDUSTRY, industry);
        selectParam.industry = industry;
    }
    if (isNaturalPersonHolding == 2 || isNaturalPersonHolding == 3) {
        selectParam.isNaturalPersonHolding = isNaturalPersonHolding == 2 ? true : false;
    }
    selectParam.draftLock = true; //未提交的企业不能查看

    /**需要用到的查询数据 */
    let usccMap = await fuHuaQiData.findAllFuHuaQiOperationNameMap();//用于将孵化器uscc变成孵化器名称
    let dataBaseList = await enterpriseData.findEnterpriseListToPage(selectParam, (page-1)*10 );
    let count = await enterpriseData.findEnterpriseCount(selectParam);//符合查询条件的数据总数

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

        /**匹配所属孵化器名称  匹配不上时这里显示空字符串 */
        changeData.fuhuaqiUscc = usccMap[info.fuHuaQiUscc] || "";
        changeData.isNaturalPersonHolding = changeData.isNaturalPersonHolding ? "是" : "否";

        /**将枚举值转为字符 */
        changeData.industry = verificationEnumTools.changeEnumValue(configEnum.INDUSTRY, changeData.industry);
        
        dataList.push(changeData);
    });

    return {count, dataList};
}


/**
 * 导出 企业迁出列表
 * @param name 企业名称
 * @param fuHuaQiUscc 所属孵化器统一信用代码
 * @param industry 领域多选
 * @param isNaturalPersonHolding  是否自然人控股
 * @param type 页面
 * @returns 
 */
export async function outPutEnterpriseMoveOutList(name:string, fuHuaQiUscc:string, industry, isNaturalPersonHolding:number, type:number) {
    let fileName = "全部";
    /**拼接查询条件 */
    let selectParam:any = {state:configEnum.FUHUASTATE.迁出};
    if (type == configEnum.OUTPUTTYPE.当前数据) {
        if (name) {
            selectParam.name = {"$regex":`${name}`};
        }
        if (fuHuaQiUscc) selectParam.fuHuaQiUscc = fuHuaQiUscc;
        if (industry.length > 0) {
            verificationEnumTools.eccEnumValue('管理后台获取在孵企业信息列表', 'industry', configEnum.INDUSTRY, industry);
            selectParam.industry = industry;
        }
        if (isNaturalPersonHolding == 2 || isNaturalPersonHolding == 3) {
            selectParam.isNaturalPersonHolding = isNaturalPersonHolding == 2 ? true : false;
        }
        selectParam.draftLock = true; //未提交的企业不能查看
        fileName = "当前数据";
    }
    

    /**需要用到的查询数据 */
    let usccMap = await fuHuaQiData.findAllFuHuaQiOperationNameMap();//用于将孵化器uscc变成孵化器名称
    let dataBaseList = await enterpriseData.findEnterpriseList(selectParam);

    let keyList = [ "name", "moveOutTime", "moveOutType", "moveOutCause", "fuHuaQiUscc", "industry",
        "createTime","uscc","mainBusiness","logonTime","timeOfImmigration","oldLogonAdd","firstIncubationTime",
        "isNaturalPersonHolding","logonAdd","operatingAdd","leasedArea"];
    let titleList = ["企业名称"," 迁出时间"," 迁出类型"," 迁出原因"," 前所属孵化器"," 行业领域",
        "入库时间", "统一信用代码", "主营业务", "注册时间", "迁入时间", "迁入前注册地址",
        "首次入孵时间","是否自然人控股","注册地址","经营地址","租赁面积（平方米）"];
    /**组合返回结果 */
    let dataList = [titleList];
    dataBaseList.forEach( info => {
        /**截取返回数据 */
        let changeData:any = extractData(splitResultConfig.EnterpriseMoveOutListConfig, info, true);

        /**匹配所属孵化器名称  匹配不上时这里显示空字符串 */
        changeData.fuhuaqiUscc = usccMap[info.fuHuaQiUscc] || "";
        changeData.isNaturalPersonHolding = changeData.isNaturalPersonHolding ? "是" : "否";

        /**将枚举值转为字符 */
        changeData.industry = verificationEnumTools.changeEnumValue(configEnum.INDUSTRY, changeData.industry);
        
        let subList = [];
        
        for (let i = 0; i < keyList.length; i++) {
            let value = changeData[keyList[i]]
            subList.push(value);
        }
        dataList.push(subList);
    });

    return { fileName, dataList };
}