/**
 * 管委会移动端-企业管理
 * 6.0新加功能
 */

import moment = require("moment");
import { FUHUASTATE, INDUSTRY, MOVEOUTTYPE } from "../../../config/enum";
import { findEnterpriseByUscc, findEnterpriseCount, findEnterpriseListToPage } from "../../../data/enterprise/enterprise";
import { findLabelLogByParam } from "../../../data/enterprise/enterpriseLabelLog";
import { getLabelNamMap } from "../../../data/label";
import { changeAddToString } from "../../../tools/system";
import { extractData } from "../../../util/piecemeal";
import { changeEnumManyValue, changeEnumValue, eccEnumValue } from "../../../util/verificationEnum";
import { BizError } from "../../../util/bizError";
import { ERRORENUM } from "../../../config/errorEnum";
import { findFuHuaQiByUSCC, findFuHuaQiOperationNameMapByParam } from "../../../data/fuHuaQi/fuhuaqi";
import { ENTERPRISESYSTEMLABEL, GUANWEIHUIMANANGENTERPRISELABEL, LABELGOAL } from "../../../config/enum/labelEnum";


/**
 * 企业详情
 * @param uscc 
 * @returns 
 */
export async function enterpriseInfomation(uscc:string) {
    let dbData = await findEnterpriseByUscc(uscc);
    if (!dbData || !dbData.uscc) throw new BizError(ERRORENUM.该企业不存在, uscc);
    let config = {
        name:{key:"名称"},
        uscc:{key:"统一信用代码"},
        mainBusiness:{key:"主营业务"},
        industry:{key:"领域"},
        leasedArea:{key:"租赁面积（平方米）"},
        isNaturalPersonHolding:{key:"是否自然人控股企业"},
        firstIncubationTime:{key:"首次入孵时间"},
        timeOfImmigration:{key:"迁入时间"},
        logonTime:{key:"注册时间"},
        logonAddress:{key:"注册地址"},
        operatingAddress:{key:"经营地址"},
        oldLogonAddress:{key:"迁入前地址"},
    };
  
    let enterpriseInfo:any = await extractData(config, dbData, false);
   
    /**枚举转换 */
    //孵化领域
    enterpriseInfo.industry = changeEnumManyValue(INDUSTRY, enterpriseInfo.industry);
    if (enterpriseInfo.industry.length > 1) enterpriseInfo.industryStr = "多领域";
    else enterpriseInfo.industryStr = enterpriseInfo.industry[0];
    //注册地址
    enterpriseInfo.logonAddressStr = changeAddToString(enterpriseInfo.logonAddress);
    //经营地址
    enterpriseInfo.operatingAddressStr = changeAddToString(enterpriseInfo.operatingAddress);
    //迁入地址
    enterpriseInfo.oldLogonAddressStr = changeAddToString(enterpriseInfo.oldLogonAddress);

    enterpriseInfo.firstIncubationTime = moment(enterpriseInfo.firstIncubationTime).format("YYYY-MM-DD");
    enterpriseInfo.timeOfImmigration = moment(enterpriseInfo.timeOfImmigration).format("YYYY-MM-DD");
    enterpriseInfo.logonTime = moment(enterpriseInfo.logonTime).format("YYYY-MM-DD");
    
    //知识产权
    enterpriseInfo.alienPatent = 0;//海外专利
    enterpriseInfo.classIPatent = 0;//一类专利
    enterpriseInfo.secondClassPatent = 0;//二类专利
    if (dbData.intellectualProperty) {
        enterpriseInfo.alienPatent = dbData.intellectualProperty.alienPatent;//海外专利
        enterpriseInfo.classIPatent = dbData.intellectualProperty.classIPatent;//一类专利
        enterpriseInfo.secondClassPatent = dbData.intellectualProperty.secondClassPatent;//二类专利
    }
    let fuHuaQiInfo = await findFuHuaQiByUSCC(dbData.fuHuaQiUscc);
    enterpriseInfo.fuHuaQiName = fuHuaQiInfo.operationName;//孵化器名称

    //标签动态
    let dbLogList = await findLabelLogByParam({uscc:uscc});

    let labelLogList = [];
    let labelNameMap = await getLabelNamMap(LABELGOAL.企业);
    dbLogList.forEach(info => {
        let { labelName } = labelNameMap[info.labelId];
        labelLogList.push({
            time:moment(info.ct).format("YYYY-MM-DD"),
            name:labelName,
            desc:info.desc,
            road:info.road > 2 ? "失效" : "生效"
        });
    });

    //标签
    enterpriseInfo.labels = [];
    if (dbData.labels && dbData.labels.length) {
        dbData.labels.forEach(info => {
        if (labelNameMap[info.labelId] && labelNameMap[info.labelId].state) {
            enterpriseInfo.labels.push({
                key:labelNameMap[info.labelId].labelName,
                state:!info.state
            });
        }
        
        });
    }

    return {enterpriseInfo, labelLogList};
}



/**
 * 企业库列表
 * @param name 
 * @param pageNumber 
 * @param labelId 
 * @param year 
 * @param month 
 * @returns 
 */
export async function enterpriseList(name:string, pageNumber:number, labelId:string, year:number, month:number) {
    if ( labelId ) eccEnumValue("企业库列表", "标签id", GUANWEIHUIMANANGENTERPRISELABEL, labelId);
    let startMs = 0;
    let endMs = 0;
    if (year && month) {
        endMs = moment(new Date(`${year}-${month}-1 00:00:00`).valueOf()).add(1, 'months').valueOf();
        startMs = moment(new Date(`${year}-${month}-1 00:00:00`).valueOf()).valueOf();
    } else if (year && !month) {
        throw new BizError(ERRORENUM.缺少月份参数);
    }

    let param:any = {};
    if (name) param.name = name;
    if (labelId == GUANWEIHUIMANANGENTERPRISELABEL.新注册企业 || labelId == GUANWEIHUIMANANGENTERPRISELABEL.新迁入企业) {
        param.taskId = {"$ne":null};
        param.draftLock = true;
        if (!year || !month) throw new BizError(ERRORENUM.参数错误);
        param.createTime = {"$gt":startMs, "$lt":endMs};
        param.isCreate = labelId == GUANWEIHUIMANANGENTERPRISELABEL.新注册企业;
    } else if (labelId == ENTERPRISESYSTEMLABEL.融资企业 || labelId == ENTERPRISESYSTEMLABEL.迁出企业 || labelId == ENTERPRISESYSTEMLABEL.毕业企业 || labelId == ENTERPRISESYSTEMLABEL.企业注销) {
        if (labelId != ENTERPRISESYSTEMLABEL.融资企业) {
            param.state = FUHUASTATE.迁出;
            if (labelId == ENTERPRISESYSTEMLABEL.毕业企业) param.moveOutType = MOVEOUTTYPE.毕业迁出;
            if (labelId == ENTERPRISESYSTEMLABEL.企业注销) param.moveOutType = MOVEOUTTYPE.企业注销;
        }
        //todo 融资企业
    } else if (labelId) {
        if (year || month) throw new BizError(ERRORENUM.多余年份与月份参数);
        param.labels =  {"$elemMatch": {  "labelId":labelId, "state":true  }};
    }

    let fuHuaQiNameMap = await findFuHuaQiOperationNameMapByParam({});
    let dbList = await findEnterpriseListToPage(param, (pageNumber-1)*10);
    let dataCount = await findEnterpriseCount(param);
    let labelNameMap = await getLabelNamMap(LABELGOAL.企业);
    const config = {
        uscc:{key:"统一信用代码"},
        name:{key:"企业名称"},
        industry:{key:"领域"},
        logonTime:{key:"注册时间"},
        leasedArea:{key:"租赁面积（平方米）"},
        logonAddress:{key:"注册地址"},
        operatingAddress:{key:"经营地址"}
    };
    let dataList = [];
    dbList.forEach(info => {
        let itemData:any = extractData(config, info, false);
        //注册地址
        itemData.logonAddressStr = changeAddToString(info.logonAddress);
        //经营地址
        itemData.operatingAddressStr = changeAddToString(info.operatingAddress);
        itemData.labels = [];
        if (info.labels && info.labels.length) {
            info.labels.forEach(info => {
                if (labelNameMap[info.labelId] && !labelNameMap[info.labelId].state) {
                    itemData.labels.push({
                        key:labelNameMap[info.labelId].labelName,
                        state:info.state
                    });
                }
            });
        }
        itemData.industry = changeEnumValue(INDUSTRY, info.industry);
        itemData.logonTime = moment(info.logonTime).format("YYYY/MM/DD");
        itemData.fuHuaQiName = fuHuaQiNameMap[info.fuHuaQiUscc] || "-";
        dataList.push(itemData);
    });

    return {dataList, dataCount};
}

