/**
 * 网页端企业自己申请入孵
 */

import moment = require("moment");
import { eccFormParam } from "../util/verificationParam";
import { AdminRegisterAddConfig, AdminRegisterUpdateConfig, UserRegisterAddConfig } from "../config/eccParam/enterprise";
import { OPERATIONALDATATYPE, TABLEID, TABLENAME } from "../config/enum/dbEnum";
import { operationalData, selectData, selectManyTableData } from "../data/operationalData";
import { BizError } from "../util/bizError";
import { ERRORENUM } from "../config/enum/errorEnum";
import { getMySqlMs, getPinyinInitials, getToken, randomId } from "../tools/system";
import { changeAdd, extractData } from "../util/piecemeal";
import { EnterpriseApplyForConfig } from "../config/splitResult/enterprise";
import { CHANGESTATE, CHANGETYPE, FUHUASTATE, RUFUSTATE, STATE } from "../config/enum/enum";


/**
 * 注册
 * @param phone 
 * @param pwd 
 * @returns 
 */
 export async function enterpriseRegister(userName:string, phone:string, pwd:string) {
    /**校验密码 */
    if (pwd.search(/^[A-Za-z0-9]{6,18}$/) < 0) throw new BizError(ERRORENUM.密码只能由6至18位字符和数字组成);

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

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


/**
 * 登录
 * @param phone 
 * @param pwd 
 * @returns 
 */
export async function enterpriseLogin(phone:string, pwd:string) {
    let enterpriseUserInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业用户表, {phone}, ["uId", "phone", "pwd", "eId"]);

    if (!enterpriseUserInfo || !enterpriseUserInfo.uId) throw new BizError(ERRORENUM.账号不存在);
    if (enterpriseUserInfo.pwd != pwd) throw new BizError(ERRORENUM.账号或密码错误);

    let updateUserInfo = {
        token : getToken(enterpriseUserInfo.uId),
        tokenMs : getMySqlMs()
    };
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业用户表, updateUserInfo, {uId:enterpriseUserInfo.uId});

    let userInfo = {
        userId:enterpriseUserInfo.uId,
        userName:enterpriseUserInfo.userName,
        phone:enterpriseUserInfo.phone,
        token:updateUserInfo.token,
        eId:enterpriseUserInfo.eId || ""
    };

    return {dataInfo:userInfo};
}


/**
 * 获取入孵流程状态
 * @param uId 
 * @returns 
 */
export async function getRuFuState(uId) {
    let ruFuState = 0;
    if (!uId) return {ruFuState};
    let enterpriseUserInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业用户表, {uId}, ["uId", "phone", "pwd", "eId"]);

    //没有eId数据代表未填写过入孵申请
    if (!enterpriseUserInfo.eId) {
        ruFuState = RUFUSTATE.入孵申请信息填写;
    } else {
        let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId:enterpriseUserInfo.eId}, ["enterpriseName", "eId", "state", "register"]);
        if (enterpriseInfo.state == CHANGESTATE.未审核 && enterpriseInfo.register == CHANGESTATE.未审核) {
            ruFuState = RUFUSTATE.入孵申请信息审核中;
        }
        if (enterpriseInfo.state == CHANGESTATE.未审核 && enterpriseInfo.register == CHANGESTATE.已驳回) {
            ruFuState = RUFUSTATE.入孵申请信息驳回; //需要回显
        }

        if (enterpriseInfo.state == CHANGESTATE.未审核 && enterpriseInfo.register == CHANGESTATE.已通过) {
            let leaseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.租赁信息, {eId:enterpriseUserInfo.eId}, []);
            //如果入孵申请已通过，并且入孵材料还未上传，进入材料上传界面
            if (!leaseInfo.leaseContract && !leaseInfo.entryPlan || !leaseInfo.businessLicense || !leaseInfo.agreement) {
                ruFuState = RUFUSTATE.入孵材料填写;
            } else {
                ruFuState = RUFUSTATE.入孵材料审核中;
            }
        }
        if (enterpriseInfo.state == CHANGESTATE.已驳回 && enterpriseInfo.register == CHANGESTATE.已通过) {
            ruFuState = RUFUSTATE.入孵材料驳回; //需要回显
        }
        if (enterpriseInfo.state == CHANGESTATE.已通过 && enterpriseInfo.register == CHANGESTATE.已通过) ruFuState = RUFUSTATE.入孵材料审核成功;        
        
        // if (enterpriseInfo.state == STATE.否 && enterpriseInfo.register == STATE.否) ruFuState = RUFUSTATE.信息审核中;
        // if (enterpriseInfo.state == STATE.否 && enterpriseInfo.register == STATE.是) {
        //     let leaseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.租赁信息, {eId:enterpriseUserInfo.eId}, []);
        //     if (!leaseInfo.leaseContract && !leaseInfo.entryPlan || !leaseInfo.businessLicense || !leaseInfo.agreement) ruFuState = RUFUSTATE.补充材料;
        //     else ruFuState = RUFUSTATE.材料已提交;
        // }
        // // if (enterpriseInfo.register == 2) ruFuState = RUFUSTATE.材料审核驳回;
        // if (enterpriseInfo.state == STATE.是 && enterpriseInfo.register == STATE.是) ruFuState = RUFUSTATE.材料审核完成;
    }
    
    return {ruFuState};
}


/**
 * 添加信息填写
 */
export async function createRuFu(uId, param) {
    const FuncName = "网页添加信息填写"
    eccFormParam(FuncName, UserRegisterAddConfig, param );

    let filesList = ["eId", "uscc"];
    let enterpriseUserInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {uscc:param.uscc, register:{"%ne%":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:CHANGESTATE.未审核,
        register:CHANGESTATE.未审核
    };
    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业基础信息表, addEInfo, {});

    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业用户表, {eId:addEInfo.eId}, {uId});

    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,
        area: param.area || null, // 可为空
        unitPrice:param.unitPrice,
        // roomNumber:param.roomNumber,
        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: CHANGETYPE.入孵申请,
        changeState: CHANGESTATE.未审核,
        createTimeMs: getMySqlMs()
    }
    await operationalData( OPERATIONALDATATYPE.增加, TABLENAME.入孵申请审批表, addInfo, {} );

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

    return {eId:addEInfo.eId};
    
}


/**
 * 入孵申请回显
 * @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:moment(info.enterprise_fuhuas[0].startTime).format("YYYY-MM-DD") ||0, //孵化开始时间
            fuHuaTimeEnd:moment(info.enterprise_fuhuas[0].endTime).format("YYYY-MM-DD") ||0, //孵化结束时间
            leaseStartTime:moment(info.enterprise_leases[0].startTime).format("YYYY-MM-DD") || 0, //租赁开始时间
            leaseEndTime:moment(info.enterprise_leases[0].endTime).format("YYYY-MM-DD") || 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 
 * @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 = "";
    // if (zaifuList.startTime || zaifuList.endTime) dataInfo.leaseTime = `${moment(zaifuList.startTime).format("YYYY-MM-DD")}至${moment(zaifuList.endTime).format("YYYY-MM-DD")}`;
    
    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};
}


/**
 * 编辑入孵材料
 * @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 == CHANGESTATE.已通过) {
        throw new BizError(ERRORENUM.已审核请前往小程序登录)
    }
    
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业基础信息表, {state:CHANGESTATE.未审核}, {eId});
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.租赁信息, param, {eId});

    return {isSuccess:true};
}




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

