/**
 * 新入孵
 */

import { AdminRegisterAddConfig, AdminRegisterUpdateConfig, RegisterUpdateConfig, SettleInForUpdateConfig } from "../config/eccParam/enterprise";
import { OPERATIONALDATATYPE, TABLEID, TABLENAME } from "../config/enum/dbEnum";
import * as enumConfig from "../config/enum/enum";
import { operationalData, selectData, selectManyTableData } from "../data/operationalData";
import { BizError } from "../util/bizError";
import { eccFormParam } from "../util/verificationParam";
import { ERRORENUM } from "../config/enum/errorEnum";
import { getMySqlMs, getPinyinInitials, getToken, md5PwdStr, randomCode, randomId } from "../tools/system";
import moment = require("moment");
import { changeAdd, extractData } from "../util/piecemeal";
import { EnterpriseApplyForConfig } from "../config/splitResult/enterprise";
import { changeEnumValue } from "../util/verificationEnum";
import { systemConfig } from "../config/serverConfig";
import { systemSendMail } from "./mail";


//=======================================================新入孵企业
/**
 * 添加入孵企业
 */
 export async function createRuFu(param) {
    const FuncName = "管理员添加入孵企业"
    eccFormParam(FuncName, AdminRegisterAddConfig, param );

    let userInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业用户表, {phone:param.phone}, ["uId"]);
    if (userInfo && userInfo.uId) throw new BizError(ERRORENUM.手机号码重复);

    let filesList = ["eId", "uscc"];
    let enterpriseUserInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc:param.uscc, register:{"%ne%":enumConfig.CHANGESTATE.已驳回}}, filesList);
    if (enterpriseUserInfo && enterpriseUserInfo.eId) {
        throw new BizError(ERRORENUM.企业已存在);
    }

    let pinyinName = getPinyinInitials(param.enterpriseName);
    
    let addEInfo = {
        eId:randomId(TABLEID.企业基础信息表),
        enterpriseName:param.enterpriseName,
        pinyinName,
        uscc:param.uscc,
        logonTime:getMySqlMs(param.logonTime),
        logonAddress:JSON.stringify(["", "", "", param.logonAddress]),
        mail:param.mail,//邮箱地址
        state:enumConfig.CHANGESTATE.未审核,
        register:enumConfig.CHANGESTATE.未审核
    };
    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业基础信息表, addEInfo, {});

    let addUInfo = {
        eId:addEInfo.eId,
        uId:randomId(TABLEID.企业用户表),
        phone:param.phone,
        pwd:param.pwd,
        userName:param.userName
    };
    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业用户表, addUInfo, {});


    let fuHuaInfo = {
        eId:addEInfo.eId,
        fId:randomId(TABLEID.企业孵化信息),
        startTime:getMySqlMs(param.fuHuaTimeStart),
        endTime:getMySqlMs(param.fuHuaTimeEndTime),
        state:0,
    };
    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业孵化信息, fuHuaInfo, {});

    let leaseInfo = {
        eId:addEInfo.eId,
        leaseId:randomId(TABLEID.租赁信息),
        area:param.area,
        unitPrice:param.unitPrice,
        building: param.building|| null, // 楼号
        roomNumber:param.roomNumber,
        // startTime:getMySqlMs(param.fuHuaTimeStart), //小程序和管理后台没有填写租赁时间的位置，直接使用孵化开始时间
        // endTime:getMySqlMs(param.fuHuaTimeEndTime), //小程序和管理后台没有填写租赁时间的位置，直接使用孵化结束时间
        startTime: getMySqlMs(param.leaseStartTime),  // 租赁开始时间
        endTime: getMySqlMs(param.leaseEndTime),      // 租赁结束时间
        rent:param.rent,
    }
    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.租赁信息, leaseInfo, {});

    let addInfo = {
        approvalId: randomId(TABLEID.入孵申请审批表),
        eId:addEInfo.eId,
        changeType: enumConfig.CHANGETYPE.入孵申请,
        changeState: enumConfig.CHANGESTATE.未审核,
        createTimeMs: getMySqlMs()
    }
    await operationalData( OPERATIONALDATATYPE.增加, TABLENAME.入孵申请审批表, addInfo, {} );

    return {isSuccess:true};
}


/**
 * 入孵申请列表
 * @param page 
 * @param enterpriseName 
 * @returns 
 */
export async function settleInEnterpriseList(page:number, enterpriseName:string) {
    let selectParam:any = {state:enumConfig.CHANGESTATE.未审核, "%or%":[{register:enumConfig.CHANGESTATE.未审核}, {register:enumConfig.CHANGESTATE.已驳回}]};
    if (enterpriseName) selectParam.enterpriseName = {"%like%":enterpriseName};

    let filesList = ["eId", "enterpriseName", "uscc", "logonTime", "logonAddress", "mail", "register"];

    let manyTableInfo:any = {}
    manyTableInfo[TABLENAME.租赁信息] = {column:["area", "building", "roomNumber", "rent", "startTime", "endTime"], where:{} };
    manyTableInfo[TABLENAME.企业孵化信息] = {column:["state", "startTime", "endTime"], where:{} };
    manyTableInfo[TABLENAME.企业用户表] = {column:["userName", "pwd", "phone", "uId"], where:{} };
    // manyTableInfo[TABLENAME.入孵申请审批表] = {column:["approvalId", "changeState", "createTimeMs"], where:{"%literal%":`approval_histories.changeType = ${enumConfig.CHANGETYPE.入孵申请}`, "%limit%":1} };
    let resList = await selectManyTableData(OPERATIONALDATATYPE.多表分页, TABLENAME.企业基础信息表, selectParam, filesList, manyTableInfo, page );
    let allResList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, selectParam, ["eId"], manyTableInfo );
    
    let dataList = [];
    resList.forEach(info => {
        let builder = "";
        if (info.enterprise_leases[0].building) builder = changeEnumValue(enumConfig.BUILDING, parseInt(info.enterprise_leases[0].building)); 

        dataList.push({
            eId:info.eId,
            enterpriseName:info.enterpriseName,//企业名称
            uscc:info.uscc,//统一信用代码
            logonTime:moment(info.logonTime).format("YYYY-MM-DD"),//注册时间
            leaseTime:`${moment(info.enterprise_leases[0].startTime).format("YYYY-MM-DD")}至${moment(info.enterprise_leases[0].endTime).format("YYYY-MM-DD")}`,
            fuHuaTime:`${moment(info.enterprise_fuhuas[0].startTime).format("YYYY-MM-DD")}至${moment(info.enterprise_fuhuas[0].endTime).format("YYYY-MM-DD")}`,
            // leaseTimeStart:info.enterprise_leases[0].startTime || 0,
            // leaseTimeEnd:info.enterprise_leases[0].endTime || 0,
            leaseStartTime:info.enterprise_leases[0].startTime || 0,
            leaseEndTime:info.enterprise_leases[0].endTime || 0,
            fuHuaTimeStart:info.enterprise_fuhuas[0].startTime||0,
            fuHuaTimeEnd:info.enterprise_fuhuas[0].endTime||0,
            area:info.enterprise_leases[0].area,//租赁面积
            // unitPrice:info.enterprise_leases[0].unitPrice,//——暂时没用
            // roomNumber:info.enterprise_leases[0].roomNumber,
            building: builder,// 园区楼号
            roomNumber: info.enterprise_leases[0].roomNumber || "",// 室号
            rent:info.enterprise_leases[0].rent,//月租金
            logonAddress:changeAdd(JSON.parse(info.logonAddress)),//注册地址
            userName:info.enterprise_users[0].userName,//联系人
            pwd:info.enterprise_users[0].pwd,//登录密码
            phone:info.enterprise_users[0].phone,//登录手机号
            mail:info.mail,//邮箱地址
            uId:info.enterprise_users[0].uId,
            // totalPrice: info.enterprise_leases[0].totalPrice, // 添加年总价字段——暂时没用
            status: info.register == enumConfig.CHANGESTATE.已驳回 ? "已驳回" : "未审核" // 状态映射
        });
        
    });
    
    return {dataList, dataCount:allResList.length};
}


/**
 * 入孵申请通过
 * @param eId 
 * @returns 
 */
export async function settleInEnterprisePass(eId:string) {
    let filesList = ["eId", "enterpriseName", "uscc", "logonTime", "state"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, filesList);

    if (!resInfo || !resInfo.eId) {
        throw new BizError(ERRORENUM.数据不存在);
    }
    
    let updateInfo = {
        register:enumConfig.CHANGESTATE.已通过,
        randomCode:randomCode()
    }
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业基础信息表, updateInfo, {eId});

    let addInfo = {
        approvalId: randomId(TABLEID.入孵申请审批表),
        eId,
        changeType: enumConfig.CHANGETYPE.入孵申请,
        changeState: enumConfig.CHANGESTATE.已通过,
        createTimeMs: getMySqlMs()
    }
    await operationalData( OPERATIONALDATATYPE.增加, TABLENAME.入孵申请审批表, addInfo, {} );

    return {isSuccess:true};
}


/**
 * 入孵申请回显
 * @param eId 
 * @returns 
 */
export async function settleInEnterpriseById(eId:string) {
    let enterpriseUserInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, []);
    if (!enterpriseUserInfo || !enterpriseUserInfo.eId) {
        throw new BizError(ERRORENUM.请先申请入孵);
    }
   
    let filesList = ["eId", "enterpriseName", "uscc", "logonTime", "logonAddress", "mail"];
    let manyTableInfo:any = {}
    manyTableInfo[TABLENAME.租赁信息] = {column:["area", "building", "roomNumber", "rent", "startTime", "endTime"], where:{} };
    manyTableInfo[TABLENAME.企业孵化信息] = {column:["state", "startTime", "endTime"], where:{} };
    manyTableInfo[TABLENAME.企业用户表] = {column:["userName", "pwd", "phone", "uId"], where:{} };
    let resList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, {eId}, filesList, manyTableInfo );
    
    let dataInfo = {};
    resList.forEach(info => {
        dataInfo = {
            eId:info.eId,
            enterpriseName:info.enterpriseName,//企业名称
            uscc:info.uscc,//统一信用代码
            logonTime:moment(info.logonTime).format("YYYY-MM-DD"),//注册时间
            // leaseTime:`${moment(info.enterprise_leases[0].startTime).format("YYYY-MM-DD")}至${moment(info.enterprise_leases[0].endTime).format("YYYY-MM-DD")}`,
            fuHuaTimeStart:info.enterprise_fuhuas[0].startTime||0, //孵化开始时间
            fuHuaTimeEnd:info.enterprise_fuhuas[0].endTime||0, //孵化结束时间
            leaseStartTime:info.enterprise_leases[0].startTime || 0, //租赁开始时间
            leaseEndTime:info.enterprise_leases[0].endTime || 0, //租赁结束时间
            rent:info.enterprise_leases[0].rent,//月租金
            area:info.enterprise_leases[0].area,//租赁面积
            building: info.enterprise_leases[0].building || "",// 园区楼号
            roomNumber: info.enterprise_leases[0].roomNumber || "",// 室号
            logonAddress:changeAdd(JSON.parse(info.logonAddress)),//注册地址
            userName:info.enterprise_users[0].userName,//联系人
            pwd:info.enterprise_users[0].pwd,//登录密码
            phone:info.enterprise_users[0].phone,//登录手机号
            mail:info.mail,//邮箱地址
            uId:info.enterprise_users[0].uId,
        };
    });

    return {dataInfo};
}


/**
 * 入孵申请编辑
 * @param eId 
 * @param param 
 * @returns 
 */
export async function settleInEnterpriseUpdate(eId:string, param) {
    const FuncName = "修改入驻信息";
    eccFormParam(FuncName, SettleInForUpdateConfig, param );

    let userInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业用户表, {phone:param.phone}, ["uId"]);
    if (userInfo && userInfo.uId &&  userInfo.uId != param.uId) throw new BizError(ERRORENUM.手机号码重复);

    let filesList = ["eId", "enterpriseName", "uscc", "logonTime", "state", "mail"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, filesList);
    if (!resInfo || !resInfo.eId) {
        throw new BizError(ERRORENUM.数据不存在);
    }
    if (resInfo.state) throw new BizError(ERRORENUM.该企业已通过审核);

    let pinyinName = getPinyinInitials(param.enterpriseName);
    
    let updateInfo = {
        enterpriseName:param.enterpriseName,
        pinyinName,
        uscc:param.uscc,
        logonTime:param.logonTime,
        logonAddress:JSON.stringify(["", "", "", param.logonAddress]),
        mail:param.mail,
    };
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业基础信息表, updateInfo, {eId});
    
    let fuHuaInfo = {
        startTime:param.fuHuaTimeStart,
        endTime:param.fuHuaTimeEndTime,
    };
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业孵化信息, fuHuaInfo, {eId});

    let leaseInfo = {
        area:param.area,
        unitPrice: param.rent && param.area ? param.rent / param.area : param.unitPrice, 
        rent:param.rent,
        startTime:param.leaseStartTimeStart,
        endTime:param.leaseEndTime,
        building:param.building,
        roomNumber:param.roomNumber,
    }
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.租赁信息, leaseInfo, {eId});


    let addUInfo = {
        phone:param.phone,
        pwd:param.pwd,
        userName:param.userName
    };
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业用户表, addUInfo, {eId, uId:param.uId});
    
    return {isSuccess:true};
}


/**
 * 入孵申请驳回
 * @param eId 
 * @returns 
 */
export async function settleInEnterpriseOut(eId:string) {
    let filesList = ["eId", "enterpriseName", "uscc", "logonTime", "state"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, filesList);

    if (!resInfo || !resInfo.eId) {  
        throw new BizError(ERRORENUM.数据不存在);
    }
    // if (resInfo.state) throw new BizError(ERRORENUM.该企业已通过审核);

    // await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.企业用户表, {}, {eId});//
    // await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.企业孵化信息, {}, {eId});
    // await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.租赁信息, {}, {eId});
    // await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.企业基础信息表, {}, {eId});

    await operationalData( OPERATIONALDATATYPE.修改, TABLENAME.企业基础信息表,  {register: enumConfig.CHANGESTATE.已驳回 }, { eId });

    let addInfo = {
        approvalId: randomId(TABLEID.入孵申请审批表),
        eId,
        changeType: enumConfig.CHANGETYPE.入孵申请,
        changeState: enumConfig.CHANGESTATE.已驳回,
        createTimeMs: getMySqlMs()
    }
    await operationalData( OPERATIONALDATATYPE.增加, TABLENAME.入孵申请审批表, addInfo, {} );

    
    return {isSuccess:true};
}



/**
 * 入孵材料审核列表
 * @param enterpriseName 
 * @param page 
 * @returns 
 */
export async function enterpriseRegisterExamineList(enterpriseName, page) {
    let selectParam:any = {register:enumConfig.CHANGESTATE.已通过, "%or%":[{state:enumConfig.CHANGESTATE.未审核}, {state:enumConfig.CHANGESTATE.已驳回}]};
    // let selectParam:any = {register:enumConfig.STATE.是, state:enumConfig.STATE.否};
    if (enterpriseName) selectParam.enterpriseName = {"%like%":enterpriseName};

    let filesList = ["eId", "enterpriseName", "uscc", "logonTime", "randomCode", "state", "register"];

    let manyTableInfo:any = {}
    manyTableInfo[TABLENAME.租赁信息] = {column:["leaseContract", "entryPlan", "businessLicense", "agreement"], where:{} };
    manyTableInfo[TABLENAME.企业孵化信息] = {column:["state", "startTime", "endTime"], where:{} };
    // manyTableInfo[TABLENAME.入孵申请审批表] = {column:["approvalId", "changeState", "createTimeMs"], where:{"%literal%":`approval_histories.changeType = ${enumConfig.CHANGETYPE.入孵材料审批}`, "%limit%":1} };
    let resList = await selectManyTableData(OPERATIONALDATATYPE.多表分页, TABLENAME.企业基础信息表, selectParam, filesList, manyTableInfo, page );
    let allResList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, selectParam, ["eId"], manyTableInfo );

    let dataList = [];
    resList.forEach(info => {
        dataList.push({
            eId:info.eId,
            enterpriseName:info.enterpriseName,
            randomCode:info.randomCode,
            /**跳转用 */
            leaseContractUrl: info.enterprise_leases[0].leaseContract,
            entryPlanUrl: info.enterprise_leases[0].entryPlan,
            businessLicenseUrl: info.enterprise_leases[0].businessLicense,
            agreementUrl: info.enterprise_leases[0].agreement,
            /**显示用：名称 */
            leaseContract: getFileNameAndFormat(info.enterprise_leases[0].leaseContract) ||  "未提交",
            entryPlan: getFileNameAndFormat(info.enterprise_leases[0].entryPlan) ||  "未提交",
            businessLicense: getFileNameAndFormat(info.enterprise_leases[0].businessLicense) ||  "未提交",
            agreement: getFileNameAndFormat(info.enterprise_leases[0].agreement) ||  "未提交",
            status: info.state == enumConfig.CHANGESTATE.已驳回 ? "已驳回" : "未审核" // 状态映射
        });
    });
    
    return {dataList, dataCount:allResList.length};
}

/**
 * 入孵材料回显
 * @param eId 
 * @returns 
 */
export async function getRuFu(eId:string) {
    let filesList = ["eId", "uscc", "enterpriseName", "logonAddress", "logonTime"];
    let enterpriseUserInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, filesList);
    if (!enterpriseUserInfo || !enterpriseUserInfo.eId) {
        throw new BizError(ERRORENUM.请先申请入孵);
    }
    let leaseFilesList = ["leaseId", "area", "leaseContract", "entryPlan", "businessLicense", "agreement"];
    let leaseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.租赁信息, {eId}, leaseFilesList);
    enterpriseUserInfo.logonAddress = JSON.parse(enterpriseUserInfo.logonAddress);

    let zaifuList = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业孵化信息, {eId}, ["startTime", "endTime"]);
    let dataInfo:any = extractData(EnterpriseApplyForConfig, enterpriseUserInfo);

    dataInfo.logonTime = moment(enterpriseUserInfo.logonTime).format("YYYY-MM-DD");
    if (zaifuList.startTime) dataInfo.startTime = new Date(zaifuList.startTime).valueOf(); //孵化开始时间
    else dataInfo.startTime = "";
    if (zaifuList.endTime) dataInfo.endTime = new Date(zaifuList.endTime).valueOf(); //孵化结束时间
    else dataInfo.endTime = "";
    /**跳转用 */
    dataInfo.area = leaseInfo.area;
    dataInfo.leaseContractUrl = leaseInfo.leaseContract;
    dataInfo.entryPlanUrl = leaseInfo.entryPlan;
    dataInfo.businessLicenseUrl = leaseInfo.businessLicense;
    dataInfo.agreementUrl = leaseInfo.agreement;
    /**显示用：名称 */
    dataInfo.leaseContract = getFileNameAndFormat(leaseInfo.leaseContract);
    dataInfo.entryPlan = getFileNameAndFormat(leaseInfo.entryPlan);
    dataInfo.businessLicense = getFileNameAndFormat(leaseInfo.businessLicense);
    dataInfo.agreement = getFileNameAndFormat(leaseInfo.agreement);

    dataInfo.leaseContractModelUrl = "/yuyi/files/房屋租赁合同模板.docx";
    dataInfo.entryPlanModelUrl = "/yuyi/files/孵化企业入驻计划.xlsx";
    dataInfo.businessLicenseUrl = "/yuyi/files/营业执照复印件.docx";
    dataInfo.agreementModelUrl = "/yuyi/files/孵化协议模板.docx";

    return {dataInfo};
}


function getFileNameAndFormat(fileName: string | null | undefined): string {
    if (fileName === null || fileName === undefined || fileName === "未提交") {
        return "未提交";
    }

    // 提取文件名（去掉路径）
    let basename = fileName.split('/').pop() || fileName;

    // 移除时间戳（假设时间戳格式为 YYYYMMDD_HHMMSS）
    basename = basename.replace(/(\d{8}_\d{6})/, '');

    // 分割文件名和格式
    const parts = basename.split('.');
    if (parts.length < 2) {
        return basename; // 如果没有找到 . 则直接返回原字符串
    }
    const name = parts.slice(0, -1).join('.');
    const format = parts.pop();
    return `${name.trim()}.${format}`;
}
  

/**
 * 入孵材料审核通过
 * @param eId 
 * @returns 
 */
export async function enterpriseRegisterExaminePass(eId:string) {
    if (!eId) throw new BizError(ERRORENUM.参数错误);
    let manyTableInfo:any = {}
    let filesList = ["eId", "enterpriseName", "uscc", "logonTime", "state"];
    manyTableInfo[TABLENAME.租赁信息] = {column:["leaseContract", "entryPlan", "businessLicense", "agreement"], where:{} };
    let resInfo = await selectManyTableData(OPERATIONALDATATYPE.多表单个, TABLENAME.企业基础信息表, {eId}, filesList, manyTableInfo);

    if (!resInfo || !resInfo.eId) throw new BizError(ERRORENUM.数据不存在);
    
    if (!resInfo.enterprise_leases[0].leaseContract || !resInfo.enterprise_leases[0].entryPlan || !resInfo.enterprise_leases[0].businessLicense || !resInfo.enterprise_leases[0].agreement) {
        throw new BizError(ERRORENUM.请上传所有入孵材料);
    }
    
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业基础信息表, {state:enumConfig.CHANGESTATE.已通过}, {eId});

    let addInfo = {
        approvalId: randomId(TABLEID.入孵申请审批表),
        eId,
        changeType: enumConfig.CHANGETYPE.入孵材料审批,
        changeState: enumConfig.CHANGESTATE.已通过,
        createTimeMs: getMySqlMs()
    }
    await operationalData( OPERATIONALDATATYPE.增加, TABLENAME.入孵申请审批表, addInfo, {} );

    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业孵化信息, { state:enumConfig.FUHUASTATE.实体孵化 }, {eId});

    /**同步修改入孵企业面积 */
    
    /**在孵企业 当前时间小于孵化结束时间 */
    let 在孵面积 = 0;
    let araeParam = {column:["area", "unitPrice", "roomNumber", "rent"], where:{} };
    let zaifuTableInfo:any = {};
    zaifuTableInfo[TABLENAME.租赁信息] = araeParam;
    zaifuTableInfo[TABLENAME.企业孵化信息] = {column:["state", "startTime", "endTime"], where:{state:{"%ne%":enumConfig.FUHUASTATE.迁出}} };
    let zaifuResList = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业基础信息表, {state:enumConfig.CHANGESTATE.已通过}, ["eId"], zaifuTableInfo );
    
    zaifuResList.forEach( info => {
        info.enterprise_leases.forEach( lease => {
            在孵面积 += parseFloat(lease.area);
        })
    })
    let yuyiList = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.羽翼孵化器信息, {}, []);
    if (在孵面积 != yuyiList.zaifuArea) await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.羽翼孵化器信息, {zaifuArea:在孵面积}, {yId:yuyiList.yId});
    
    //发送邮件
    await systemSendMail(eId, enumConfig.MAILTYPE.通过入孵材料审核 );

    return {isSuccess:true};
}


/**
 * 入孵材料审核驳回
 * @param eId 
 * @returns 
 */
export async function enterpriseRegisterExamineOut(eId:string) {
    if (!eId) throw new BizError(ERRORENUM.参数错误);
    let filesList = ["eId", "enterpriseName", "uscc", "logonTime", "state"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, filesList);

    if (!resInfo || !resInfo.eId) throw new BizError(ERRORENUM.数据不存在);
    // if (resInfo.state) throw new BizError(ERRORENUM.该企业已通过审核);

    let updateLeaseInfo = {
        leaseContract:null, 
        entryPlan:null,
        businessLicense:null,
        agreement:null
    }
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.租赁信息, updateLeaseInfo, {eId});

    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业基础信息表, {state:enumConfig.CHANGESTATE.已驳回}, {eId});

    let addInfo = {
        approvalId: randomId(TABLEID.入孵申请审批表),
        eId,
        changeType: enumConfig.CHANGETYPE.入孵材料审批,
        changeState: enumConfig.CHANGESTATE.已驳回,
        createTimeMs: getMySqlMs()
    }
    await operationalData( OPERATIONALDATATYPE.增加, TABLENAME.入孵申请审批表, addInfo, {} );
    
    return {isSuccess:true};
}


/**
 * 编辑入孵材料
 * @param eId 
 * @param param 
 * @returns 
 */
export async function updateRuFu(eId:string, param) {
    const FuncName = "管理员修改入驻信息";
    eccFormParam(FuncName, AdminRegisterUpdateConfig, param );
    let filesList = ["eId", "enterpriseName", "uscc", "logonTime", "state"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, filesList);
    if (!resInfo || !resInfo.eId) {
        throw new BizError(ERRORENUM.数据不存在);
    }
    if (resInfo.state == enumConfig.CHANGESTATE.已通过) {
        throw new BizError(ERRORENUM.已审核请前往小程序登录)
    } 

    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.租赁信息, param, {eId});

    return {isSuccess:true};
}


/**
 * 企业注册-已弃用
 * @param param 
 * @returns 
 */
export async function enterpriseRegister(param) {
    const FuncName = "企业注册"
    eccFormParam(FuncName, RegisterUpdateConfig, param );

    let filesList = ["eId", ];
    let enterpriseUserInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc:param.uscc}, filesList);
    if (enterpriseUserInfo && enterpriseUserInfo.eId) {
        throw new BizError(ERRORENUM.企业已存在);
    }
    
    let addEInfo = {
        eId:randomId(TABLEID.企业基础信息表),
        enterpriseName:param.enterpriseName,
        logonAddress:JSON.stringify(["", "", "", param.logonAddress]),
        uscc:param.uscc,
        logonTime:getMySqlMs(param.logonTime),
        state:enumConfig.CHANGESTATE.未审核,
        register:enumConfig.CHANGESTATE.未审核,
        rent: param.rent,
        // randomCode: randomCode() // 在企业注册时生成 randomCode
    };
    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业基础信息表, addEInfo, {});

    let fuHuaInfo = {
        eId:addEInfo.eId,
        fId:randomId(TABLEID.企业孵化信息)
    };
    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业孵化信息, fuHuaInfo, {});

    let leaseInfo = {
        eId:addEInfo.eId,
        leaseId:randomId(TABLEID.租赁信息),
        startTime:getMySqlMs(param.leaseTimeStart),
        endTime:getMySqlMs(param.leaseTimeEnd),
        area:param.area
    }
    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.租赁信息, leaseInfo, {});
   
    return {isSuccess:true};
}


