/**
 * 小程序端 孵化器入口 企业相关逻辑
 * 作者: lxm
 * 包括新注册企业，迁入企业
 * 
 */

import * as eccFormParamConfig from "../../../config/eccParam/fuHuaQi";
import { ERRORENUM } from "../../../config/errorEnum";
import { BizError } from "../../../util/bizError";
import * as sysTools from "../../../tools/system";
import * as taskTool from "../../../tools/taskTool";
import * as enterpriseData from "../../../data/enterprise/enterprise";
import * as splitResultConfig from "../../../config/splitResultConfig";
import * as configEnum from "../../../config/enum";
import { eccFormParam } from "../../../util/verificationParam";
import * as verificationEnumTools from "../../../util/verificationEnum";
import { checkChange, extractData } from "../../../util/piecemeal";
import { enterpriseLabelEvent } from "../../label";
import { findFuHuaQiByUSCC } from "../../../data/fuHuaQi/fuhuaqi";
import { LABELEVENT } from "../../../config/enum/labelEnum";
import * as leaseData from "../../../data/lease";

/**
 * 添加新注册企业
 * 小程序端
 * @param uscc 孵化器统一信用代码
 * @param param 表单参数
 * @returns {isSuccess:true/false}
 */
export async function registerEnterprise(uscc:string, param) {
    /**校验表单参数 */
    eccFormParam("新注册企业", eccFormParamConfig.RegisterEnterpriseParamConfig, param);
    verificationEnumTools.eccEnumValue('添加新注册企业', 'industry', configEnum.INDUSTRY, param.industry);
    if ( !sysTools.eccUscc(param.uscc) ) throw new BizError(ERRORENUM.统一社会信用代码不合法);
    let now = new Date().valueOf();
    if ( param.logonTime > now || param.firstIncubationTime > now) throw new BizError(ERRORENUM.不可选择未来时间);

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


    if (param.jiaSu == 1 || param.jiaSu == 2) {
        //判断
        if (param.jiaSu == 1 && !param.jiaSuZiZhi) {
            throw new BizError(ERRORENUM.参数错误, "加速企业缺失加速资质");
        } else if (param.jiaSu == 1 && param.jiaSuZiZhi.indexOf(configEnum.JIASUZIZHI.其他) >-1 && !param.jiaSuZiZhiDesc) {
            throw new BizError(ERRORENUM.参数错误, "加速企业的加速资质选了其他但是没填写内容");
        }
    } else throw new BizError(ERRORENUM.参数错误, "加速企业不符合1或2", param.jiaSu);

    param.jiaSu = param.jiaSu == 1;
    /**添加新注册企业标识 */
    param.draftId = sysTools.getDraftId(uscc);//草稿箱id
    param.isCreate = true;//标识此次操作是否是新注册企业并不是迁入企业
    const TaskId = taskTool.getTaskId(uscc);
    param.state = configEnum.FUHUASTATE.实体孵化;
    await enterpriseData.createEnterprise(uscc, TaskId, param);

    //2025新加内容
    let leaseInfo = await leaseData.findOnceData({uscc:param.uscc});
    if (leaseInfo && leaseInfo.uscc) { //
        leaseInfo.enterpriseName = param.name;
        leaseInfo.contractStartTime = param.contractStartTime;
        leaseInfo.contractEndTime = param.contractEndTime;
        leaseInfo.price = param.price;//单价
        leaseInfo.area = param.leasedArea;//租赁面积
        leaseInfo.areaUnit = param.areaUnit;
        leaseInfo.address = param.leaseAddress;
        leaseInfo.rentPayment = [
            {
               payStartTime:param.payStartTime,
               payLong:param.payLong
            }
        ];
        await leaseInfo.save();
    } else {
        let addLease = {
            uscc:param.uscc,
            enterpriseName:param.name,
            contractStartTime:param.contractStartTime,
            contractEndTime:param.contractEndTime,
            price:param.price,//单价
            area:param.leasedArea,//租赁面积
            rentPayment : [
                {
                payStartTime:param.payStartTime,
                payLong:param.payLong
                }
            ],
            address:param.leaseAddress,//地址
            areaUnit : param.areaUnit

        };
        await leaseData.createData(addLease);
    }

    return {isSuccess:true};
}


/**
 * 修改新注册企业的表单
 * 小程序端
 * @param uscc 孵化器统一信用代码
 * @param param 表单参数
 * @returns {isSuccess:true/false}
 */
export async function updateRegisterEnterprise(uscc:string, param) {
    /**校验表单参数 */
    eccFormParam("新注册企业表单修改", eccFormParamConfig.EnterpriseParamFormConfig, param );
    
    verificationEnumTools.eccEnumValue('修改新注册企业', 'industry', configEnum.INDUSTRY, param.industry);
    if ( !sysTools.eccUscc(param.uscc) ) throw new BizError(ERRORENUM.统一社会信用代码不合法);
    let now = new Date().valueOf();
    if ( param.logonTime > now || param.firstIncubationTime > now) throw new BizError(ERRORENUM.不可选择未来时间);

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

    /**修改时校验uscc是否重复 */
    let selectInfo = await enterpriseData.selectOneEnterpriseByParam({uscc:param.uscc, draftId:{"$ne":param.draftId} });
    if (selectInfo && selectInfo.uscc) throw new BizError(ERRORENUM.统一社会信用代码重复, `${param.uscc}已经在库中存在 不可以修改为这个统一信用代码`);

    /**如果是本月提交的，可以修改，如果不是，则不可以修改 */
    if ( sysTools.getThisMonthMs() > dataBaseInfo.createTime) {
        throw new BizError(ERRORENUM.不能修改过期任务数据, `修改新注册企业的表单 ${uscc} 违法操作`);
    }

    if (param.jiaSu == 1 || param.jiaSu == 2) {
        //判断
        if (param.jiaSu == 1 && !param.jiaSuZiZhi) {
            throw new BizError(ERRORENUM.参数错误, "加速企业缺失加速资质");
          } else if (param.jiaSu == 1 && param.jiaSuZiZhi.indexOf(configEnum.JIASUZIZHI.其他) > -1  && !param.jiaSuZiZhiDesc) {
            throw new BizError(ERRORENUM.参数错误, "加速企业的加速资质选了其他但是没填写内容");
        }
    } else throw new BizError(ERRORENUM.参数错误, "加速企业不符合1或2", param.jiaSu);

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

    await dataBaseInfo.save();

    let leaseInfo = await leaseData.findOnceData({uscc:param.uscc});
    if (leaseInfo && leaseInfo.uscc) { //
        leaseInfo.enterpriseName = param.name;
        leaseInfo.contractStartTime = param.contractStartTime;
        leaseInfo.contractEndTime = param.contractEndTime;
        leaseInfo.price = param.price;//单价
        leaseInfo.area = param.leasedArea;//租赁面积
        leaseInfo.address = param.leaseAddress;
        leaseInfo.areaUnit = param.areaUnit;
        leaseInfo.rentPayment = [
            {
               payStartTime:param.payStartTime,
               payLong:param.payLong
            }
        ];
        await leaseInfo.save();
    }

    return {isSuccess:true};
}


/**
 * 添加迁入企业登记
 * 小程序端
 * @param uscc 孵化器统一信用代码
 * @param param 表单参数
 * @returns {isSuccess:true/false}
 */
export async function moveInEnterprise(uscc:string, param) {
    /**校验表单参数 */
    eccFormParam("迁入企业登记", eccFormParamConfig.MoveInEnterpriseParamConfig, param );
    let now = new Date().valueOf();
    if ( param.logonTime > now || param.firstIncubationTime > now || param.timeOfImmigration > now) throw new BizError(ERRORENUM.不可选择未来时间);
    
    verificationEnumTools.eccEnumValue('添加迁入企业', 'industry', configEnum.INDUSTRY, param.industry);
    if ( !sysTools.eccUscc(param.uscc) ) throw new BizError(ERRORENUM.统一社会信用代码不合法);

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

    if (param.jiaSu == 1 || param.jiaSu == 2) {
        //判断
        if (param.jiaSu == 1 && !param.jiaSuZiZhi) {
            throw new BizError(ERRORENUM.参数错误, "加速企业缺失加速资质");
          } else if (param.jiaSu == 1 && param.jiaSuZiZhi.indexOf(configEnum.JIASUZIZHI.其他) > -1  && !param.jiaSuZiZhiDesc) {
            throw new BizError(ERRORENUM.参数错误, "加速企业的加速资质选了其他但是没填写内容");
        }
    } else throw new BizError(ERRORENUM.参数错误, "加速企业不符合1或2", param.jiaSu);

    param.jiaSu = param.jiaSu == 1;

    const TaskId =  taskTool.getTaskId(uscc);

    if ( dataBaseInfo && dataBaseInfo.state && dataBaseInfo.state == configEnum.FUHUASTATE.迁出) {
        dataBaseInfo.fuHuaQiUscc = uscc;
        dataBaseInfo.state = configEnum.FUHUASTATE.实体孵化;
        dataBaseInfo.isCreate = false;
        dataBaseInfo.virtualCause = 0;
        dataBaseInfo.virtualCauseDes = '';
        dataBaseInfo.moveOutType = 0;
        dataBaseInfo.moveOutTrace = 0;
        dataBaseInfo.moveOutCause = [];
        dataBaseInfo.taskId = TaskId;
        dataBaseInfo.moveOutTime = 0;
        dataBaseInfo.draftLock = false;
        for (let key in eccFormParamConfig.MoveInEnterpriseParamConfig) {
            dataBaseInfo[key] = param[key];
        }

        /**标签  迁入的是别人迁出的企业*/
        let fuHuaQiInfo = await findFuHuaQiByUSCC(uscc);
        await enterpriseLabelEvent(dataBaseInfo, LABELEVENT.迁出, fuHuaQiInfo.operationName);

        await dataBaseInfo.save();
    } else {
        /**添加新注册企业标识 */
        param.draftId = sysTools.getDraftId(uscc);//草稿箱id
        param.isCreate = false;//标识此次操作是否是迁入企业并不是新注册企业
        
        param.state = configEnum.FUHUASTATE.实体孵化;//默认就是实体孵化

        await enterpriseData.createEnterprise(uscc, TaskId, param);
    }

    //2025新加内容
    let leaseInfo = await leaseData.findOnceData({uscc:param.uscc});
    if (leaseInfo && leaseInfo.uscc) { //
        leaseInfo.enterpriseName = param.name;
        leaseInfo.contractStartTime = param.contractStartTime;
        leaseInfo.contractEndTime = param.contractEndTime;
        leaseInfo.price = param.price;//单价
        leaseInfo.area = param.leasedArea;//租赁面积
        leaseInfo.address = param.leaseAddress;
         leaseInfo.areaUnit = param.areaUnit;
        leaseInfo.rentPayment = [
            {
               payStartTime:param.payStartTime,
               payLong:param.payLong
            }
        ];
        await leaseInfo.save();
    } else {
        let addLease = {
            uscc:param.uscc,
            enterpriseName:param.name,
            contractStartTime:param.contractStartTime,
            contractEndTime:param.contractEndTime,
            price:param.price,//单价
            area:param.leasedArea,//租赁面积
            areaUnit : param.areaUnit,
            rentPayment : [
                {
                payStartTime:param.payStartTime,
                payLong:param.payLong
                }
            ],
            address:param.leaseAddress,//地址

        };
        await leaseData.createData(addLease);
    }
    
    return {isSuccess:true};
}


/**
 * 修改迁入企业登记信息
 * 小程序端
 * @param uscc 孵化器统一信用代码
 * @param param 表单参数
 * @returns {isSuccess:true/false}
 */
export async function updateMoveInEnterprise(uscc:string, param) {
    /**校验表单参数 */
    eccFormParam("修改迁入企业登记信息", eccFormParamConfig.EnterpriseInPutParamFormConfig, param);
    let now = new Date().valueOf();
    if ( param.logonTime > now || param.firstIncubationTime > now || param.timeOfImmigration > now) throw new BizError(ERRORENUM.不可选择未来时间);
    verificationEnumTools.eccEnumValue('修改迁入企业', 'industry', configEnum.INDUSTRY, param.industry);
    if ( !sysTools.eccUscc(param.uscc) ) throw new BizError(ERRORENUM.统一社会信用代码不合法);

    /**企业库中是否存在记录 */
    let dataBaseInfo = await enterpriseData.findEnterpriseByDraftId(param.draftId);
    if (!dataBaseInfo || !dataBaseInfo.uscc) throw new BizError(ERRORENUM.未找到数据, `库中不存在${param.uscc}这个企业`);

    /**修改时校验uscc是否重复 */
    let selectInfo = await enterpriseData.selectOneEnterpriseByParam({uscc:param.uscc, draftId:{"$ne":param.draftId} });
    if (selectInfo && selectInfo.uscc) throw new BizError(ERRORENUM.统一社会信用代码重复, `${param.uscc}已经在库中存在 不可以修改为这个统一信用代码`);

    /**如果是本月提交的，可以修改，如果不是，则不可以修改 */
    if ( sysTools.getThisMonthMs() > dataBaseInfo.createTime) {
        throw new BizError(ERRORENUM.不能修改过期任务数据, `修改新注册企业的表单 ${uscc} 违法操作`);
    }

    
    if (param.jiaSu == 1 || param.jiaSu == 2) {
        //判断
        if (param.jiaSu == 1 && !param.jiaSuZiZhi) {
            throw new BizError(ERRORENUM.参数错误, "加速企业缺失加速资质");
         } else if (param.jiaSu == 1 && param.jiaSuZiZhi.indexOf(configEnum.JIASUZIZHI.其他) > -1  && !param.jiaSuZiZhiDesc) {
            throw new BizError(ERRORENUM.参数错误, "加速企业的加速资质选了其他但是没填写内容");
        }
    } else throw new BizError(ERRORENUM.参数错误, "加速企业不符合1或2", param.jiaSu);
    
    /**修改数据 */
    let changeList = checkChange(param, dataBaseInfo);
    if ( !changeList.length ) throw new BizError(ERRORENUM.数据无更新, `${param.uscc}数据无更新`);
    changeList.forEach(key => {
        dataBaseInfo[key] = param[key];
    });
    dataBaseInfo.jiaSu = param.jiaSu == 1;

    await dataBaseInfo.save();

    let leaseInfo = await leaseData.findOnceData({uscc:param.uscc});
    if (leaseInfo && leaseInfo.uscc) { //
        leaseInfo.enterpriseName = param.name;
        leaseInfo.contractStartTime = param.contractStartTime;
        leaseInfo.contractEndTime = param.contractEndTime;
        leaseInfo.price = param.price;//单价
        leaseInfo.area = param.leasedArea;//租赁面积
        leaseInfo.address = param.leaseAddress;
        leaseInfo.areaUnit = param.areaUnit;
        leaseInfo.rentPayment = [
            {
               payStartTime:param.payStartTime,
               payLong:param.payLong
            }
        ];
        await leaseInfo.save();
    }

    return {isSuccess:true};
}


/**
 * 根据企业id查询企业信息
 * 包括新迁入企业和新注册企业的回显
 * 小程序端  回显
 * @param uscc 企业统一信用代码
 * @param draftId 草稿id
 * @returns {data} data 返回表单
 */
export async function getEnterpriseByDraftId(draftId:string) {
    let dataBaseInfo = await enterpriseData.findEnterpriseByDraftId(draftId);
    if (!dataBaseInfo || !dataBaseInfo.uscc) throw new BizError(ERRORENUM.未找到数据, `库中不存在draftId=${draftId}这个企业`);

    /**新注册企业和迁入企业回显信息不一样 */
    let data:any = {};
    if (dataBaseInfo.isCreate) data = extractData(splitResultConfig.EnterpriseInfoConfig, dataBaseInfo, false);
    else data = extractData(splitResultConfig.EnterpriseMoveInInfoConfig, dataBaseInfo, false);

    let leaseInfo = await leaseData.findOnceData({uscc:dataBaseInfo.uscc});

    if (!leaseInfo || !leaseInfo.uscc) {
        leaseInfo = {price:null, contractStartTime:null, contractEndTime:null, rentPayment:[ {payStartTime:null, payLong:null}] };
    }
    data.price = leaseInfo.price;
    data.contractStartTime = leaseInfo.contractStartTime;
    data.contractEndTime = leaseInfo.contractEndTime;
    let rentPaymentInfo = leaseInfo.rentPayment[0];
    data.payStartTime = rentPaymentInfo.payStartTime;
    data.payLong = rentPaymentInfo.payLong;
    data.areaUnit = leaseInfo.areaUnit || configEnum.AREAUNIT.面积;

    return {data};
}


/**
 * 根据企业id删除草稿企业
 * 小程序端
 * @param uscc 企业统一信用代码
 * @param draftId 草稿id
 * @returns {isSuccess:true/false}
 */
export async function deleteEnterpriseByDraftId(draftId:string) {
    let dataBaseInfo = await enterpriseData.findEnterpriseByDraftId(draftId);
    /**删除限制 */
    if (!dataBaseInfo || !dataBaseInfo.uscc) throw new BizError(ERRORENUM.未找到数据, `库中不存在draftId=${draftId}这个企业`);
    if (dataBaseInfo.draftLock) throw new BizError(ERRORENUM.已入库的数据不能删除, draftId);

    await enterpriseData.deleteEnterprise(draftId);

    return {isSuccess:true};
}

