/**
 * 新入孵
 */

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.未审核,
        // createTime:getMySqlMs(),
    };
    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 || null,
        unitPrice:param.unitPrice || null,
        building: param.building || null, // 楼号
        roomNumber:param.roomNumber || null,
        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")}`,
            // 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, {} );

    //发送邮件
    await systemSendMail(eId, enumConfig.MAILTYPE.通过入孵申请 );

    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 || null,
        unitPrice: param.rent && param.area ? param.rent / param.area : param.unitPrice, 
        rent:param.rent,
        startTime:param.leaseStartTimeStart,
        endTime:param.leaseEndTime,
        building:param.building || null,
        roomNumber:param.roomNumber || null,
    }
    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 
 * @param descType 驳回类型 [1, 2]
 * @param desc 
 * @returns 
 */
export async function settleInEnterpriseOut(eId:string, descType, desc:string) {
    let filesList = ["eId", "enterpriseName", "uscc", "logonTime", "state"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, filesList);

    if (!resInfo || !resInfo.eId) {  
        throw new BizError(ERRORENUM.数据不存在);
    }

    await operationalData( OPERATIONALDATATYPE.修改, TABLENAME.企业基础信息表,  {register: enumConfig.CHANGESTATE.已驳回 }, { eId });
    
    let descStr = "";
    for(let i = 0; i < descType.length; i++) {
        if (descType[i] == enumConfig.DESCTYPE.其他) {
            if (desc) descStr += `${desc}；`
        } else {
            descStr += `${changeEnumValue(enumConfig.DESCTYPE, descType[i])}；`;
        }
    }
    let descTypeStr = JSON.stringify(descType) || '[]';

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

    /**发送邮件 */
    let mailStr = "";
    mailStr += "<p>感谢贵公司对【雨艺孵化器】的关注与信任。经我们初步审核，遗憾地通知您，贵公司此次入孵申请<span style='font-weight: 700;'>未通过初审</span>。主要原因为：</p>";
    mailStr += `<ul>`;
    mailStr += `<li>${descStr}</li>`;
    mailStr += `</ul>`;
    mailStr += `<p>以上内容仅作为此次审核意见供参考，您可根据反馈进行优化调整。如后续有相关优化材料或补充说明，欢迎重新提交申请。</p>`;
    mailStr += `<p>我们期待未来与贵公司的合作机会，衷心祝愿贵公司业务发展顺利！</p>`;
    await systemSendMail(resInfo.eId, enumConfig.MAILTYPE.驳回入孵申请, mailStr );
    
    /**设置7天后再次提醒 */
    setTimeout( async() => {
        try {
            //检查企业状态是否仍然是已驳回（未重新提交）
            let currentInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, ["register"]);
            if (currentInfo && currentInfo.register === enumConfig.CHANGESTATE.已驳回) {
                let reminderMailStr = "";
                reminderMailStr += "<p>【雨艺孵化器】入孵申请提醒</p>";
                reminderMailStr += "<p>尊敬的客户：</p>";
                reminderMailStr += "<p>我们注意到您在7天前提交的入孵申请未通过初审，目前尚未收到您的重新提交。</p>";
                reminderMailStr += `<p>驳回原因：${descStr}</p>`;
                reminderMailStr += "<p>如果您仍有入驻意向，请根据审核意见完善资料后重新提交申请。</p>";
                reminderMailStr += "<p>如有任何疑问，欢迎随时联系我们。</p>";
                reminderMailStr += "<p>期待您的回复！</p>";
                
                await systemSendMail(resInfo.eId, enumConfig.MAILTYPE.驳回入孵申请, reminderMailStr);
                console.log(`7天后入孵申请驳回提醒邮件已发送给企业 ${resInfo.eId}`);
            }
        } catch (error) {
            console.error(`发送7天后入孵申请驳回提醒邮件失败:`, error);
        }
    }, 7 * 24 * 60 * 60 * 1000); // 7天后的毫秒数
    
    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 leaseConf = ["sanFangXieYi", "fuHuaXieYi", "fangWuZuLing", "fuHuaXieYiBuChong", "chengXinChengNuoHan", "yingYeZhiZhao", "ruFuZiLiao", "ruZhuJiHua", "yaJinZhiFu", "cardCopy"];
    let manyTableInfo:any = {}
    manyTableInfo[TABLENAME.租赁信息] = {column:leaseConf, 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 leaseConfSome = ["sanFangXieYi", "fuHuaXieYi", "fangWuZuLing", "fuHuaXieYiBuChong", "chengXinChengNuoHan", "yingYeZhiZhao", "ruFuZiLiao", "ruZhuJiHua", "cardCopy"];
    let dataList = [];
    resList.forEach(info => {
        let state = "待审核";
        
        if (leaseConfSome.some(key => !info.enterprise_leases[0][key])) {
            state = "未提交";
        }
        // if (!info.enterprise_leases[0].leaseContract || !info.enterprise_leases[0].entryPlan 
        //     || !info.enterprise_leases[0].businessLicense || !info.enterprise_leases[0].agreement 
        //     || !info.enterprise_leases[0].tripartiteAgreement) {
        //         state = "未提交";
        // }
        if (info.state == enumConfig.CHANGESTATE.已驳回) state = "已驳回";

        dataList.push({
            eId:info.eId,
            enterpriseName:info.enterpriseName,
            randomCode:info.randomCode,
            /**跳转用 */
            sanFangXieYiUrl: info.enterprise_leases[0].sanFangXieYi,
            fuHuaXieYiUrl: info.enterprise_leases[0].fuHuaXieYi,
            fangWuZuLingUrl: info.enterprise_leases[0].fangWuZuLing,
            fuHuaXieYiBuChongUrl: info.enterprise_leases[0].fuHuaXieYiBuChong,
            chengXinChengNuoHanUrl: info.enterprise_leases[0].chengXinChengNuoHan,
            yingYeZhiZhaoUrl: info.enterprise_leases[0].yingYeZhiZhao,
            ruFuZiLiaoUrl: info.enterprise_leases[0].ruFuZiLiao,
            ruZhuJiHuaUrl: info.enterprise_leases[0].ruZhuJiHua,
            yaJinZhiFuUrl: info.enterprise_leases[0].yaJinZhiFu,
            cardCopyUrl: info.enterprise_leases[0].cardCopy,
            // leaseContractUrl: info.enterprise_leases[0].leaseContract,
            // entryPlanUrl: info.enterprise_leases[0].entryPlan,
            // businessLicenseUrl: info.enterprise_leases[0].businessLicense,
            // agreementUrl: info.enterprise_leases[0].agreement,
            // tripartiteAgreementUrl: info.enterprise_leases[0].tripartiteAgreement,

            /**显示用：名称 */
            sanFangXieYi: getFileNameAndFormat(info.enterprise_leases[0].sanFangXieYi) || "未提交",
            fuHuaXieYi: getFileNameAndFormat(info.enterprise_leases[0].fuHuaXieYi) || "未提交",
            fangWuZuLing: getFileNameAndFormat(info.enterprise_leases[0].fangWuZuLing) || "未提交",
            fuHuaXieYiBuChong: getFileNameAndFormat(info.enterprise_leases[0].fuHuaXieYiBuChong) || "未提交",
            chengXinChengNuoHan: getFileNameAndFormat(info.enterprise_leases[0].chengXinChengNuoHan) || "未提交",
            yingYeZhiZhao: getFileNameAndFormat(info.enterprise_leases[0].yingYeZhiZhao) || "未提交",
            ruFuZiLiao: getFileNameAndFormat(info.enterprise_leases[0].ruFuZiLiao) || "未提交",
            ruZhuJiHua: getFileNameAndFormat(info.enterprise_leases[0].ruZhuJiHua) || "未提交",
            yaJinZhiFu: getFileNameAndFormat(info.enterprise_leases[0].yaJinZhiFu) || "未提交",
            cardCopy: getFileNameAndFormat(info.enterprise_leases[0].cardCopy) || "未提交",
            // 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) ||  "未提交",
            // tripartiteAgreement: getFileNameAndFormat(info.enterprise_leases[0].tripartiteAgreement) ||  "未提交",
            status: state // 状态映射
        });
    });
    
    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", 
    "sanFangXieYi", "fuHuaXieYi", "fangWuZuLing", "fuHuaXieYiBuChong", "chengXinChengNuoHan", "yingYeZhiZhao", "ruFuZiLiao", "ruZhuJiHua", "yaJinZhiFu", "cardCopy"];
    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.sanFangXieYiUrl = leaseInfo.sanFangXieYi;
    dataInfo.fuHuaXieYiUrl = leaseInfo.fuHuaXieYi;
    dataInfo.fangWuZuLingUrl = leaseInfo.fangWuZuLing;
    dataInfo.fuHuaXieYiBuChongUrl = leaseInfo.fuHuaXieYiBuChong;
    dataInfo.chengXinChengNuoHanUrl = leaseInfo.chengXinChengNuoHan;
    dataInfo.yingYeZhiZhaoUrl = leaseInfo.yingYeZhiZhao;
    dataInfo.ruFuZiLiaoUrl = leaseInfo.ruFuZiLiao;
    dataInfo.ruZhuJiHuaUrl = leaseInfo.ruZhuJiHua;
    dataInfo.yaJinZhiFuUrl = leaseInfo.yaJinZhiFu;
    dataInfo.cardCopyUrl = leaseInfo.cardCopy;
    /**显示用：名称 */
    dataInfo.sanFangXieYi = getFileNameAndFormat(leaseInfo.sanFangXieYi);
    dataInfo.fuHuaXieYi = getFileNameAndFormat(leaseInfo.fuHuaXieYi);
    dataInfo.fangWuZuLing = getFileNameAndFormat(leaseInfo.fangWuZuLing);
    dataInfo.fuHuaXieYiBuChong = getFileNameAndFormat(leaseInfo.fuHuaXieYiBuChong);
    dataInfo.chengXinChengNuoHan = getFileNameAndFormat(leaseInfo.chengXinChengNuoHan);
    dataInfo.yingYeZhiZhao = getFileNameAndFormat(leaseInfo.yingYeZhiZhao);
    dataInfo.ruFuZiLiao = getFileNameAndFormat(leaseInfo.ruFuZiLiao);
    dataInfo.ruZhuJiHua = getFileNameAndFormat(leaseInfo.ruZhuJiHua);
    dataInfo.yaJinZhiFu = getFileNameAndFormat(leaseInfo.yaJinZhiFu);
    dataInfo.cardCopy = getFileNameAndFormat(leaseInfo.cardCopy);
    /**下载用：模板 */
    dataInfo.sanFangXieYiModelUrl = "/yuyi/files/三方协议.docx"
    dataInfo.fuHuaXieYiModelUrl = "/yuyi/files/孵化协议最新版.docx"
    // dataInfo.fangWuZuLingModelUrl = ""
    dataInfo.fuHuaXieYiBuChongModelUrl = "/yuyi/files/孵化协议补充协议书.docx"
    dataInfo.chengXinChengNuoHanModelUrl = "/yuyi/files/诚信承诺函.docx"
    // dataInfo.yingYeZhiZhaoModelUrl = ""
    dataInfo.ruFuZiLiaoModelUrl = "/yuyi/files/入孵资料明细.xls"
    dataInfo.ruZhuJiHuaModelUrl = "/yuyi/files/孵化企业入驻计划.xlsx"
    // dataInfo.yaJinZhiFuModelUrl = ""
    // dataInfo.cardCopyModelUrl = ""

    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:["sanFangXieYi", "fuHuaXieYi", "fangWuZuLing", "fuHuaXieYiBuChong", "chengXinChengNuoHan", "yingYeZhiZhao", "ruFuZiLiao", "ruZhuJiHua", "yaJinZhiFu", "cardCopy"], 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 
    //     || !resInfo.enterprise_leases[0].tripartiteAgreement) {
    //     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 
 * @param descType 驳回类型 [1, 2]
 * @param desc 
 * @returns 
 */
export async function enterpriseRegisterExamineOut(eId:string, descType, desc:string) {
    if (!eId) throw new BizError(ERRORENUM.参数错误);
    if (!descType.length) 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.数据不存在);
    let leaseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.租赁信息, {eId}, []);

    let leaseConf = ["sanFangXieYi", "fuHuaXieYi", "fangWuZuLing", "fuHuaXieYiBuChong", "chengXinChengNuoHan", "yingYeZhiZhao", "ruFuZiLiao", "ruZhuJiHua", "cardCopy"];
    for (let i = 0; i < leaseConf.length; i++) {
        if(!leaseInfo[leaseConf[i]]) {
            throw new BizError(ERRORENUM.该企业暂未提交入孵材料);
        }
    }

    let updateLeaseInfo:any = {yaJinZhiFu:null};
    for (let i = 0; i < leaseConf.length; i++) {
        updateLeaseInfo[leaseConf[i]] = null;
    }
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.租赁信息, updateLeaseInfo, {eId});

    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业基础信息表, {state:enumConfig.CHANGESTATE.已驳回}, {eId});
    
    let descStr = "";
    for(let i = 0; i < descType.length; i++) {
        if (descType[i] == enumConfig.FILEDESCTYPE.其他) {
            if (desc) descStr += `${desc}；`
        } else {
            descStr += `${changeEnumValue(enumConfig.FILEDESCTYPE, descType[i])}；`;
        }
    }
    let descTypeStr = JSON.stringify(descType) || '[]';

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

    /**发送邮件 - 首次驳回通知 */
    let mailStr = "";
    mailStr += "<p>感谢贵公司积极配合入孵流程。经审核，贵公司提交的入孵材料<span style='font-weight: 700;'>暂未通过审核</span>，主要原因如下：</p>";
    mailStr += `<ul>`;
    mailStr += `<li>${descStr}</li>`;
    mailStr += `</ul>`;
    mailStr += `<p>如贵司愿意继续推进入孵流程，可根据上述意见进行材料完善并重新提交。</p>`;
    mailStr += `<p>我们期待贵公司尽快完善材料，并欢迎继续申请入驻。</p>`;
    mailStr += `<p>感谢理解与配合！</p>`;
    await systemSendMail(resInfo.eId, enumConfig.MAILTYPE.驳回入孵材料申请, mailStr );
    
    /**设置7天后再次提醒 */
    setTimeout(async () => {
        try {
            // 检查企业状态是否仍然是已驳回（未重新提交材料）
            let currentInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, ["state"]);
            if (currentInfo && currentInfo.state === enumConfig.CHANGESTATE.已驳回) {
                let reminderMailStr = "";
                reminderMailStr += "<p>【雨艺孵化器】入孵材料审核提醒</p>";
                reminderMailStr += "<p>尊敬的客户：</p>";
                reminderMailStr += "<p>我们注意到您在7天前提交的入孵材料未通过审核，目前尚未收到您重新提交的完善材料。</p>";
                reminderMailStr += `<p>驳回原因：${descStr}</p>`;
                reminderMailStr += "<p>请您根据审核意见尽快完善相关材料并重新提交，以便我们继续为您处理入孵申请。</p>";
                reminderMailStr += "<p>如有任何疑问，欢迎随时联系我们。</p>";
                reminderMailStr += "<p>期待您的完善材料！</p>";
                
                await systemSendMail(resInfo.eId, enumConfig.MAILTYPE.驳回入孵材料申请, reminderMailStr);
                console.log(`7天后入孵材料驳回提醒邮件已发送给企业 ${resInfo.eId}`);
            }
        } catch (error) {
            console.error(`发送7天后入孵材料驳回提醒邮件失败:`, error);
        }
    }, 7 * 24 * 60 * 60 * 1000); // 7天后的毫秒数

    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});

    // await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业基础信息表, {state:enumConfig.CHANGESTATE.未审核}, {});

    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};
}


