/**
 * 企业相关逻辑
 * 作者: 李欣鸣
 * 包括新注册企业，迁入企业
 * 
 */
import { MoveInEnterpriseParamConfig, RegisterEnterpriseParamConfig } from "../../config/checkParamConfig";
import { ERRORENUM } from "../../config/errorEnum";
import { EnterpriseInfoConfig } from "../../config/ojbectResultKeyConfig";
import { BizError } from "../../util/bizError";
import { checkChange, checkParamater, extractData, getTaskId } from "../../util/tools"
import moment = require("moment");
import { createEnterprise, deleteEnterprise,findEnterpriseCount, findEnterpriseByUscc, findEnterpriseList, findEnterpriseListByFuHuaQiUsccName, 查询所有已绑定过的孵化器id } from "../../data/enterprise/enterprise";
import { EnterpriseListConfig } from "../../config/ojbectResultKeyConfig";
import { findAllFuHuaQi, findFuHuaQiByUSCC } from "../../data/fuHuaQi/fuhuaqi";


/**
 * 新注册企业
 * 小程序端
 * @param uscc 孵化器统一信用代码
 * @param param 表单参数
 * @returns {isSuccess:true/false}
 */
export async function registerEnterprise(uscc:string, param) {
    const TaskId = getTaskId(uscc);

    checkParamater("新注册企业", RegisterEnterpriseParamConfig, param);//校验表单参数

    let dataBaseInfo = await findEnterpriseByUscc(param.uscc);
    if ( dataBaseInfo&& dataBaseInfo.uscc)  throw new BizError(ERRORENUM.该企业已存在, `${param.uscc}已经在库中存在`);

    param.isCreate = true;//标识此次操作是否是新注册企业并不是迁入企业
    await createEnterprise(uscc, TaskId, param);

    return {isSuccess:true};
}


/**
 * 修改新注册企业的表单
 * 小程序端
 * @param uscc 孵化器统一信用代码
 * @param param 表单参数
 * @returns {isSuccess:true/false}
 */
export async function updateRegisterEnterprise(uscc:string, param) {

    checkParamater("新注册企业表单修改", RegisterEnterpriseParamConfig, param);//校验表单参数

    let dataBaseInfo = await findEnterpriseByUscc(param.uscc);
    if (!dataBaseInfo || !dataBaseInfo.uscc) throw new BizError(ERRORENUM.未找到数据, `库中不存在${param.uscc}这个企业`);

    let changeList = checkChange(param, dataBaseInfo);//比对修改字段
    if ( !changeList.length ) throw new BizError(ERRORENUM.数据无更新, `${param.uscc}数据无更新`);

    changeList.forEach(key => {
        dataBaseInfo[key] = param[key];
    });

    await dataBaseInfo.save();

    return {isSuccess:true};
}


/**
 * 迁入企业登记
 * 小程序端
 * @param uscc 孵化器统一信用代码
 * @param param 表单参数
 * @returns {isSuccess:true/false}
 */
export async function moveInEnterprise(uscc:string, param) {
    const TaskId = getTaskId(uscc);

    checkParamater("迁入企业登记", MoveInEnterpriseParamConfig, param);//校验表单参数

    let dataBaseInfo = await findEnterpriseByUscc(param.uscc);
    if ( dataBaseInfo&& dataBaseInfo.uscc)  throw new BizError(ERRORENUM.该企业已存在, `${param.uscc}已经在库中存在`);

    await createEnterprise(uscc, TaskId, param);

    return {isSuccess:true};
}


/**
 * 修改迁入企业登记信息
 * 小程序端
 * @param uscc 孵化器统一信用代码
 * @param param 表单参数
 * @returns {isSuccess:true/false}
 */
export async function updateMoveInEnterprise(uscc:string, param) {

    checkParamater("修改迁入企业登记信息", MoveInEnterpriseParamConfig, param);//校验表单参数

    let dataBaseInfo = await findEnterpriseByUscc(param.uscc);
    if (!dataBaseInfo || !dataBaseInfo.uscc) throw new BizError(ERRORENUM.未找到数据, `库中不存在${param.uscc}这个企业`);

    let changeList = checkChange(param, dataBaseInfo);
    if ( !changeList.length ) throw new BizError(ERRORENUM.数据无更新, `${param.uscc}数据无更新`);

    changeList.forEach(key => {
        dataBaseInfo[key] = param[key];
    });

    await dataBaseInfo.save();

    return {isSuccess:true};
}


/**
 * 根据企业id查询企业信息
 * 小程序端  回显
 * @param uscc 企业统一信用代码
 */
export async function getEnterpriseByUscc(uscc:string) {
    let dataBaseInfo = await findEnterpriseByUscc(uscc);
    if (!dataBaseInfo || !dataBaseInfo.uscc) throw new BizError(ERRORENUM.未找到数据, `库中不存在${uscc}这个企业`);

    let data = extractData(EnterpriseInfoConfig, dataBaseInfo);

    return {data};
}


/**
 * 根据企业id删除草稿企业
 * 小程序端
 * @param uscc 企业统一信用代码
 */
export async function deleteEnterpriseByUscc(uscc:string) {
    let dataBaseInfo = await findEnterpriseByUscc(uscc);
    if (!dataBaseInfo || !dataBaseInfo.uscc) throw new BizError(ERRORENUM.未找到数据, `库中不存在${uscc}这个企业`);

    if (dataBaseInfo.draftLock) throw new BizError(ERRORENUM.已入库的数据不能删除, uscc);

    await deleteEnterprise(uscc);

    return {isSuccess:true};
}


/**
 * 获取在孵企业信息列表
 * 管理后台端
 * @param time 新注册时间/迁入时间
 * @param fuHuaQiUscc 所属孵化器 
 * @param industry 行业领域
 * @param isNaturalPersonHolding 自然人控股
 * @param page 页数
 * @returns {dataList:[], count:0}  dataList=数据列表  count:条件筛选下的数据总数
 */
export async function enterpriseList(time:string, fuHuaQiUscc:string, industry, isNaturalPersonHolding:number, page:number) {
    let selectParam:any = {};
    if ( time.length > 0 ) {
        let startT = moment(time).startOf('month').valueOf();
        let endT = moment(time).endOf('month').valueOf();
        selectParam['$or'] = [
            {"firstIncubationTime":{'$gt':startT, '$lt':endT}},
            {"timeOfImmigration":{'$gt':startT, '$lt':endT}},
        ];
    }

    if (time) selectParam.logonTime = time; selectParam.timeOfImmigration = time;
    if (fuHuaQiUscc) selectParam.fuHuaQiUscc = fuHuaQiUscc;
    if (industry.length > 0) selectParam.industry = industry;
    if (isNaturalPersonHolding == 2 || isNaturalPersonHolding == 3) {
        selectParam.isNaturalPersonHolding = isNaturalPersonHolding == 2 ? true : false;
    }
    
    let dataBaseList = await findEnterpriseList(selectParam, (page-1)*10 );
    let count = await findEnterpriseCount(selectParam);
    let dataList = [];
    dataBaseList.forEach( info => {
        let changeData = extractData(EnterpriseListConfig, info);

        dataList.push(changeData);
    });

    return {count, dataList};
}


export async function getAffiliationFuHuaQi() {
    let  dataList = [];
    let list = await 查询所有已绑定过的孵化器id();

    let allList = await findAllFuHuaQi();
    let distinctMap = {}; // {uscc:name}
    allList.forEach(info => {
        distinctMap[info.uscc] = info.name;
    });

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

    
    return {dataList}
}
