/**
 * 企业信息汇总
 * */
 
import { EnterpriseFaRenInfoUpdateConfig, EnterpriseInfomationUpdateConfig, enterpriseLeaseUpdateConfig, EnterpriseManageInfoAddConfig, EnterpriseManageInfoUpdateConfig, EnterpriseServiceUpdateConfig} from "../config/eccParam/enterprise";
import { OPERATIONALDATATYPE, TABLEID, TABLENAME } from "../config/enum/dbEnum";
import * as enumConfig from "../config/enum/enum";
import { EnterpriseBaseResConfig, EnterpriseFaRenInfoResConfig, EnterpriseInfomationResConfig, EnterpriseLeaseInfoResConfig, EnterpriseQualificationInfoResConfig } from "../config/splitResult/enterprise";
import { operationalData, selectData, selectManyTableData } from "../data/operationalData";
import { BizError } from "../util/bizError";
import { checkChange, extractData } from "../util/piecemeal";
import { changeEnumValue, eccEnumValue } from "../util/verificationEnum";
import { eccFormParam } from "../util/verificationParam";
import { ERRORENUM } from "../config/enum/errorEnum";
import { getAddresList, getDeclarationTime, getLastDeclarationTime, getMySqlMs, getPwdMd5, getToken, randomId } from "../tools/system";
import moment = require("moment");
import { sendVerificationCode } from "./mail";

//==登录登出
/**
 * 使用加密后的密码判断登录
 * @param phone 
 * @param pwd 
 * @returns 
 */
export async function enterpriseLogin(phone: string, pwd: string) {
    let filesList = ["userName", "eId", "pwd", "uId", "phone", "uscc"];
    let userDbData = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业用户表, { phone }, filesList);
    
    if (!userDbData.length) throw new BizError(ERRORENUM.账号或密码错误);
    
    let eId = "";
    let enterpriseUserInfo;
    
    if (userDbData.length > 1) {
        let includePhoneConf = {};
        // includePhoneConf[TABLENAME.企业孵化信息] = {colum:["state", "startTime", "endTime"], where:{state:{"%ne%":enumConfig.FUHUASTATE.迁出}} };
        includePhoneConf[TABLENAME.企业孵化信息] = {colum:["state", "startTime", "endTime"], where:{} };
        includePhoneConf[TABLENAME.企业用户表] = {colum:filesList, where:{phone}};
        
        let userEnterpriseData = await selectManyTableData(
            OPERATIONALDATATYPE.多表单个, 
            TABLENAME.企业基础信息表, 
            {state:enumConfig.CHANGESTATE.已通过}, 
            ["enterpriseName"], 
            includePhoneConf
        );
        
        eId = userEnterpriseData.enterprise_users[0].eId;
        enterpriseUserInfo = userEnterpriseData.enterprise_users[0];
    } else {
        eId = userDbData[0].eId;
        enterpriseUserInfo = userDbData[0];
    }
    console.log(eId);
    if (!eId) throw new BizError(ERRORENUM.账号或密码错误);
    
    let enterpriseInfo = await selectData(
        OPERATIONALDATATYPE.查询单个, 
        TABLENAME.企业基础信息表, 
        {state:enumConfig.CHANGESTATE.已通过, eId}, 
        ["enterpriseName"]
    );

    if (!enterpriseInfo || !enterpriseInfo.enterpriseName) {
        throw new BizError(ERRORENUM.账号或密码错误);
    }
    
    if (!enterpriseUserInfo || !enterpriseUserInfo.phone) {
        throw new BizError(ERRORENUM.账号或密码错误);
    }
    
    //使用uId作为盐值进行加密
    const encryptedInputPwd = getPwdMd5(enterpriseUserInfo.uId, pwd);
    if (enterpriseUserInfo.pwd !== encryptedInputPwd) {
        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,
    };

    return {dataInfo: userInfo};
}



//企业用户表没有存uscc字段，先查询到企业eId，然后到用户表查询密码判断是否登录成功
// export async function enterpriseLogin(phone:string, pwd:string) {
//     let filesList = ["userName", "eId", "pwd", "uId",  "phone"];
//     let userDbData = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业用户表, { phone }, filesList);
//     if (!userDbData.length) throw new BizError(ERRORENUM.账号或密码错误);
//     let userEnterpriseData = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业用户表, { phone }, filesList);
//     let eId = "";
//     let enterpriseUserInfo;
//     if (userDbData.length > 1) {
//         let includePhoneConf = {};
//         includePhoneConf[TABLENAME.企业孵化信息] = {colum:["state", "startTime", "endTime"], where:{state:{"%ne%":enumConfig.FUHUASTATE.迁出}} };
//         includePhoneConf[TABLENAME.企业用户表] = {colum:filesList, where:{phone}};
//         userEnterpriseData = await selectManyTableData(OPERATIONALDATATYPE.多表单个, TABLENAME.企业基础信息表, {state:enumConfig.CHANGESTATE.已通过}, ["enterpriseName"], includePhoneConf);
//         eId = userEnterpriseData.enterprise_users[0].eId;
//         enterpriseUserInfo = userEnterpriseData.enterprise_users[0];
//     } else {
//         eId = userEnterpriseData[0].eId;
//         enterpriseUserInfo = userEnterpriseData[0];
//     }
    
//     if (!eId) throw new BizError(ERRORENUM.账号或密码错误);
//     let includeConf = {};
//     includeConf[TABLENAME.企业孵化信息] = {colum:["state", "startTime", "endTime"], where:{state:{"%ne%":enumConfig.FUHUASTATE.迁出}} };
//     let enterpriseInfo = await selectManyTableData(OPERATIONALDATATYPE.多表单个, TABLENAME.企业基础信息表, {state:enumConfig.CHANGESTATE.已通过, eId}, ["enterpriseName"], includeConf);

//     // includeConf[TABLENAME.企业孵化信息] = {colum:["state", "startTime", "endTime"], where:{state:{"%ne%":enumConfig.FUHUASTATE.迁出}} };
//     // includeConf[TABLENAME.企业用户表] = {colum:filesList, where:{phone} };
//     // let enterpriseInfo = await selectManyTableData(OPERATIONALDATATYPE.多表单个, TABLENAME.企业基础信息表, {state:enumConfig.CHANGESTATE.已通过}, ["enterpriseName"], includeConf);

//     if (!enterpriseInfo || !enterpriseInfo.enterpriseName) {
//         throw new BizError(ERRORENUM.账号或密码错误);
//     }
//     // let {enterprise_users} = enterpriseInfo;
//     // let enterpriseUserInfo = enterprise_users[0];
    
//     if (!enterpriseUserInfo || !enterpriseUserInfo.phone) {
//         throw new BizError(ERRORENUM.账号或密码错误);
//     }
//     if (enterpriseUserInfo.pwd != pwd) {
//         throw new BizError(ERRORENUM.账号或密码错误);
//     }

//     let updateUserInfo = {
//         token : getToken(enterpriseInfo.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,
//     };

//     return {dataInfo:userInfo};
// }

// export async function enterpriseLogin(phone:string, pwd:string) {
//     let filesList = ["userName", "eId", "pwd", "uId",  "phone"];
//     let userDbData = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业用户表, { phone }, filesList);
//     if (!userDbData.length) throw new BizError(ERRORENUM.账号或密码错误);
//     let eId = userDbData[0].eId;
//     let enterpriseUserInfo = userDbData[0];
//     // if (userDbData.length > 1) {
//     //     if (phone == "13601665163") {
//     //         eId = userDbData[1].eId;
//     //         enterpriseUserInfo = userDbData[1];
//     //     }
//     // }
//     if (!eId) throw new BizError(ERRORENUM.账号或密码错误);
//     let includeConf = {};
//     includeConf[TABLENAME.企业孵化信息] = {colum:["state", "startTime", "endTime"], where:{state:{"%ne%":enumConfig.FUHUASTATE.迁出}} };
//     let enterpriseInfo = await selectManyTableData(OPERATIONALDATATYPE.多表单个, TABLENAME.企业基础信息表, {state:enumConfig.CHANGESTATE.已通过, eId}, ["enterpriseName"], includeConf);

//     // includeConf[TABLENAME.企业孵化信息] = {colum:["state", "startTime", "endTime"], where:{state:{"%ne%":enumConfig.FUHUASTATE.迁出}} };
//     // includeConf[TABLENAME.企业用户表] = {colum:filesList, where:{phone} };
//     // let enterpriseInfo = await selectManyTableData(OPERATIONALDATATYPE.多表单个, TABLENAME.企业基础信息表, {state:enumConfig.CHANGESTATE.已通过}, ["enterpriseName"], includeConf);

//     if (!enterpriseInfo || !enterpriseInfo.enterpriseName) {
//         throw new BizError(ERRORENUM.账号或密码错误);
//     }
//     // let {enterprise_users} = enterpriseInfo;
//     // let enterpriseUserInfo = enterprise_users[0];
    
//     if (!enterpriseUserInfo || !enterpriseUserInfo.phone) {
//         throw new BizError(ERRORENUM.账号或密码错误);
//     }
//     if (enterpriseUserInfo.pwd != pwd) {
//         throw new BizError(ERRORENUM.账号或密码错误);
//     }

//     let updateUserInfo = {
//         token : getToken(enterpriseInfo.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,
//     };

//     return {dataInfo:userInfo};
// }


/**
 * 修改密码
 * @param uId 
 * @param pwd 原密码
 * @param newPwd 新密码
 * @param confirmPwd 再次确认密码
 * @returns 
 */
export async function changePassword(uId:string, pwd:string, newPwd:string, confirmPwd:string) {
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业用户表, { uId }, ["userName", "uId", "pwd"]);
    if (!enterpriseInfo.uId) throw new BizError(ERRORENUM.数据不存在);

    /**验证当前密码 */
    const encryptedInputPwd = getPwdMd5(enterpriseInfo.uId, pwd);
    if (enterpriseInfo.pwd !== encryptedInputPwd) {
        throw new BizError(ERRORENUM.原密码错误);
    }
    // if (pwd != enterpriseInfo.pwd) throw new BizError(ERRORENUM.原密码错误);

    if (newPwd != confirmPwd) throw new BizError(ERRORENUM.密码不一致);
    if (newPwd.search(/^[A-Za-z0-9]{6,18}$/) < 0) throw new BizError(ERRORENUM.密码只能由6至18位字符和数字组成);

    let encryptedInputNewPwd = getPwdMd5(enterpriseInfo.uId, newPwd);
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业用户表, {pwd:encryptedInputNewPwd}, { uId });

    return {isSuccess:true};
}


/**
 * 小程序登录改为邮箱认证--todo
 * @param email 邮箱
 * @param code 验证码
 * @returns
 */
export async function enterpriseEmailLogin(email: string, code: string) {

    let filesList = ["userName", "eId", "code", "uId", "email", "codeMs"];
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业用户表, { email }, filesList);

    if (!enterpriseInfo || !enterpriseInfo.eId) {
        throw new BizError(ERRORENUM.账号或密码错误);
    }

    // 检查验证码是否存在
    if (!enterpriseInfo.code || !enterpriseInfo.codeMs) {
        throw new BizError(ERRORENUM.验证码不存在);
    }

    // 获取当前时间戳（毫秒）
    const currentMs = Date.parse(getMySqlMs());
    console.log("currentMs", currentMs);

    // 检查验证码时效（假设5分钟过期）
    if (currentMs - enterpriseInfo.codeMs > 5 * 60 * 1000) {
        throw new BizError(ERRORENUM.验证码过期);
    }

    // 验证码校验
    if (enterpriseInfo.code !== code) {
        throw new BizError(ERRORENUM.code无效);
    }

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

    let userInfo = {
        userId: enterpriseInfo.uId,
        userName: enterpriseInfo.userName,
        email: enterpriseInfo.email,
        token: updateUserInfo.token,
    };

    return { dataInfo: userInfo };
}

/**
 * 请求发送验证码到指定邮箱
 * @param email 用户邮箱
 * @returns
 */
export async function requestVerificationCode(email: string) {
    try {
        const code = await sendVerificationCode(email);
        console.log(`验证码已发送到邮箱: ${email}, ${code}`);
        // 可以将验证码存储在会话中或前端缓存中，以便后续验证
    } catch (error) {
        console.error('发送验证码失败:', error);
        throw new BizError(ERRORENUM.验证码发送失败);
    }

    return { result: "验证码已发送到邮箱" };
}

export async function enterpriseLogout(uId) {
    let filesList = ["userName", "eId", "pwd", "uId"];
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业用户表, {uId}, filesList);
    let updateUserInfo = {
        token : getToken(enterpriseInfo.uId),
        tokenMs : getMySqlMs()
    };
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业用户表, updateUserInfo, {uId:enterpriseInfo.uId});

    return {isSuccess:true};

}


/**
 * 登录手机号绑定的其他企业列表
 * @param phone 
 * @returns 
 */
export async function enterpriseByPhone(phone:string) {
    let manyTableInfo:any = {};
    manyTableInfo[TABLENAME.企业基础信息表] = {column: ["enterpriseName", "uscc"], where:{} };

    let filesList = ["userName", "eId"];
    let enterpriseInfo = await selectManyTableData(OPERATIONALDATATYPE.多表联查, TABLENAME.企业用户表, {phone}, filesList, manyTableInfo);
    
    let dataList = [];
    enterpriseInfo.forEach( info => {
        let {enterprise} = info;

        dataList.push({
            enterpriseName:enterprise.enterpriseName,
            eId:info.eId,
            uscc:enterprise.uscc
        });
    })

    return dataList;

}


//===首页

/**
 * 首页获取企业基本信息
 * @param uscc 
 */
 export async function homePageBaseInfo(eId) {
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, ["uscc", "enterpriseName", "logonAddress"]);
    let fuhuaInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业孵化信息, {eId}, ["startTime", "endTime"]);

    let logonAddress = [];
    if (enterpriseInfo.logonAddress) {
        logonAddress = getAddresList(enterpriseInfo.logonAddress);
    }
    
    let dataInfo = {
        uscc: enterpriseInfo.uscc,
        logonAddress: logonAddress,
        fuhuaTime: `${moment(fuhuaInfo.startTime).format("YYYY/MM/DD")}-${moment(fuhuaInfo.endTime).format("YYYY/MM/DD")}`,
    };

    return {dataInfo};
}


export async function homePage(eId:string) {
    let filesList = ["enterpriseName", "eId"];
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, filesList);
    let canBaoFileList = ["annual", "zhuanKe", "benKe", "shuoshi", "boShi", "qiTa", "boshiyishang"];
    let canBaoInfo = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.参保记录, {eId}, canBaoFileList);

    canBaoInfo.sort( (a, b) => {return new Date(b.annual).valueOf() - new Date(a.annual).valueOf()});
    
    let chongYeRenYuan = 0;
    if (canBaoInfo[0]) {
        if (canBaoInfo[0].zhuanKe) chongYeRenYuan += canBaoInfo[0].zhuanKe;
        if (canBaoInfo[0].benKe) chongYeRenYuan += canBaoInfo[0].benKe;
        if (canBaoInfo[0].shuoshi) chongYeRenYuan += canBaoInfo[0].shuoshi;
        if (canBaoInfo[0].boShi) chongYeRenYuan += canBaoInfo[0].boShi;
        if (canBaoInfo[0].boshiyishang) chongYeRenYuan += canBaoInfo[0].boshiyishang;
        if (canBaoInfo[0].qiTa) chongYeRenYuan += canBaoInfo[0].qiTa;
    }
    canBaoInfo.sort( (a, b) => {return new Date(b.annual).valueOf() - new Date(a.annual).valueOf()});

    //只返回前五条
    let zhengCeInfo = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.政策表, {}, []);
    
    let zhengCeList = [];
    zhengCeInfo.forEach(info => {
        let {poId, title, source, createTimeMs,closeTimeMs, coverImg,isPermanent} = info;
        let coverImgDefault = JSON.parse(coverImg)[0];
        if (!coverImgDefault) coverImgDefault = "/yuyi/files/默认图片.png";
        // 判断是否为永久有效政策
        let formattedCloseTime = isPermanent == 1 ? "永久有效" : moment(closeTimeMs).format("YYYY-MM-DD");
        if (isPermanent == 1 || (isPermanent == 0 && closeTimeMs > getMySqlMs())) {
            zhengCeList.push( {
                poId,
                title, 
                source, 
                createTimeMs: createTimeMs ? moment(createTimeMs).format("YYYY-MM-DD") : "",
                closeTimeMs:formattedCloseTime, 
                coverImg:coverImgDefault
            });
        }
    })

    zhengCeList = zhengCeList.slice(0, 5);

    let dataInfo = {
        name:enterpriseInfo.enterpriseName,
        chongYeRenYuan,
        zhengCeList:zhengCeList,
        manage:{
            // lastYear:{BI:"未填报", TXP:"未填报", RD:"未填报"},
            thisYear:{BI:"未填报", TXP:"未填报", RD:"未填报"}
        }
    }

    let thisYear = new Date().getFullYear();
    let jysjFile = ["BI", "TXP", "RD", "mId","annual","quarter"];

    // 修改为获取本年度的数据，不再按季度查询
    let thisYearStartTime = getMySqlMs(`${thisYear}-01-01 00:00:00`);
    let thisYearJysjList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业经营信息, { 
        eId, 
        isSubmit:1, 
        annual: thisYearStartTime
    }, jysjFile);

    if (thisYearJysjList && thisYearJysjList.length > 0) {
        // 汇总本年度的数据
        let totalBI = 0;
        let totalTXP = 0;
        let totalRD = 0;
        let count = 0;
        
        thisYearJysjList.forEach(item => {
            if (!isNaN(parseFloat(item.BI))) {
                totalBI += parseFloat(item.BI);
            }
            if (!isNaN(parseFloat(item.TXP))) {
                totalTXP += parseFloat(item.TXP);
            }
            if (!isNaN(parseFloat(item.RD))) {
                totalRD += parseFloat(item.RD);
            }
            count++;
        });

        // 计算平均值或总和，根据业务需求选择
        // 如果是要显示累计值，直接使用总和
        dataInfo.manage.thisYear.BI = count > 0 ? totalBI.toFixed(2) : "未填报";
        dataInfo.manage.thisYear.TXP = count > 0 ? totalTXP.toFixed(2) : "未填报";
        dataInfo.manage.thisYear.RD = count > 0 ? totalRD.toFixed(2) : "未填报";
        
        // 或者如果要显示平均值：
        // dataInfo.manage.thisYear.BI = count > 0 ? (totalBI / count).toFixed(2) : "未填报";
        // dataInfo.manage.thisYear.TXP = count > 0 ? (totalTXP / count).toFixed(2) : "未填报";
        // dataInfo.manage.thisYear.RD = count > 0 ? (totalRD / count).toFixed(2) : "未填报";
    }

    // let thisQuarter = getDeclarationTime();
    // let thisYearjJysjInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业经营信息, { eId, isSubmit:1, annual:thisQuarter.declarationYear, quarter:thisQuarter.declarationQuarter }, jysjFile);

    // if (thisYearjJysjInfo && thisYearjJysjInfo.mId) {
    //     dataInfo.manage.thisYear.BI = !isNaN(thisYearjJysjInfo.BI) ? thisYearjJysjInfo.BI : "未填报";
    //     dataInfo.manage.thisYear.TXP = !isNaN(thisYearjJysjInfo.TXP) ? thisYearjJysjInfo.TXP : "未填报";
    //     dataInfo.manage.thisYear.RD = !isNaN(thisYearjJysjInfo.RD) ? thisYearjJysjInfo.RD : "未填报";
    // }

    // let laseQuarter = getLastDeclarationTime();
    // let lastYearjJysjInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业经营信息, { eId, isSubmit:1, annual:laseQuarter.declarationYear, quarter:laseQuarter.declarationQuarter }, jysjFile);
    // // let lastYearjJysjInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业经营信息, { eId, state:1, annual:getMySqlMs(`${thisYear-1}-01-01 00:00:00`)}, jysjFile);
    // if (lastYearjJysjInfo && lastYearjJysjInfo.mId) {
    //     dataInfo.manage.lastYear.BI = !isNaN(lastYearjJysjInfo.BI) ? lastYearjJysjInfo.BI : "未填报";
    //     dataInfo.manage.lastYear.TXP = !isNaN(lastYearjJysjInfo.TXP) ? lastYearjJysjInfo.TXP : "未填报";
    //     dataInfo.manage.lastYear.RD = !isNaN(lastYearjJysjInfo.RD) ? lastYearjJysjInfo.RD : "未填报";
    // }

    return { dataInfo }
}


/**
 * 检查当前时间是否在填报时间内
 * @param year 年份
 * @param quarter 季度
 * @returns 是否在填报时间内
 */
function isInDeclarationPeriod(year: number, quarter: number): boolean {
    const timeRange = getQuarterTaskTimeRange(year, quarter);
    const currentTime = moment();
    const startTime = moment(timeRange.startTime);
    const endTime = moment(timeRange.endTime).endOf('day'); // 包含当天的最后一刻
    
    return currentTime.isBetween(startTime, endTime, null, '[]'); // [] 表示包含边界
}


/**
 * 获取季度任务的开始和结束时间（填报期为一个月）
 * @param year 年份
 * @param quarter 季度 (1-4)
 * @returns 包含开始时间和结束时间的对象
 */
function getQuarterTaskTimeRange(year: number, quarter: number) {
    let startTime: moment.Moment;
    let endTime: moment.Moment;
    
    switch(quarter) {
        case 1: // 第一季度任务在第二季度第一天开始填报，填报一个月
            startTime = moment(`${year}-04-01`); // 第二季度第一天
            endTime = moment(`${year}-04-01`).add(1, 'month').subtract(1, 'day'); // 第二季度第一个月最后一天
            break;
        case 2: // 第二季度任务在第三季度第一天开始填报，填报一个月
            startTime = moment(`${year}-07-01`); // 第三季度第一天
            endTime = moment(`${year}-07-01`).add(1, 'month').subtract(1, 'day'); // 第三季度第一个月最后一天
            break;
        case 3: // 第三季度任务在第四季度第一天开始填报，填报一个月
            startTime = moment(`${year}-10-01`); // 第四季度第一天
            endTime = moment(`${year}-10-01`).add(1, 'month').subtract(1, 'day'); // 第四季度第一个月最后一天
            break;
        case 4: // 第四季度任务在明年第一季度第一天开始填报，填报一个月
            startTime = moment(`${year + 1}-01-01`); // 明年第一季度第一天
            endTime = moment(`${year + 1}-01-01`).add(1, 'month').subtract(1, 'day'); // 明年第一季度第一个月最后一天
            break;
        default:
            startTime = moment();
            endTime = moment();
    }
    
    return {
        startTime: startTime.format("YYYY-MM-DD"),
        endTime: endTime.format("YYYY-MM-DD")
    };
}


/**
 * 获取填报状态
 * @param year 年份
 * @param quarter 季度
 * @param isSubmitted 是否已提交
 * @returns 填报状态
 */
function getDeclarationStatus(year: number, quarter: number, isSubmitted: boolean): string {
    if (isSubmitted) {
        return "已填报";
    }
    
    const timeRange = getQuarterTaskTimeRange(year, quarter);
    const currentTime = moment();
    const startTime = moment(timeRange.startTime);
    const endTime = moment(timeRange.endTime).endOf('day');
    
    if (currentTime.isBefore(startTime)) {
        return "未开始";
    } else if (currentTime.isAfter(endTime)) {
        return "已结束";
    } else {
        const daysLeft = endTime.diff(currentTime, 'days');
        if (daysLeft <= 15) {
            return `距离结束${daysLeft}天`;
        } else {
            return "填报中";
        }
    }
}


/**
 * 检查是否可以提交
 * @param year 年份
 * @param quarter 季度
 * @param isSubmitted 是否已提交
 * @returns 是否可以提交
 */
function canSubmitTask(year: number, quarter: number, isSubmitted: boolean): boolean {
    if (isSubmitted) {
        return false;
    }
    
    const timeRange = getQuarterTaskTimeRange(year, quarter);
    const currentTime = moment();
    const startTime = moment(timeRange.startTime);
    const endTime = moment(timeRange.endTime).endOf('day');
    
    return currentTime.isBetween(startTime, endTime, null, '[]');
}


/**
 * 任务列表
 * @param eId 企业ID
 * @param annual 年份
 * @returns 
 */
export async function taskList(eId: string, annual: string) {
    const year = parseInt(annual);
    const quarterConf = ["第一季度", "第二季度", "第三季度", "第四季度"];
    let dataList: any[] = [];

    // 查询该年度所有季度的任务
    let jysjFile = ["BI", "TXP", "RD", "mId", "state", "isSubmit", "annual", "quarter"];
    let selectParam = { 
        eId, 
        annual: getMySqlMs(`${year}-01-01 00:00:00`) 
    };

    let manageList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业经营信息, selectParam, jysjFile);

    // 为每个季度创建或获取任务信息
    for (let quarter = 1; quarter <= 4; quarter++) {
        const quarterName = quarterConf[quarter - 1];
        
        // 查找是否已存在该季度的任务
        let existingTask = manageList.find(task => task.quarter === quarter);
        
        if (!existingTask) {
            // 创建新的填报任务
            let itemInfo = {
                eId,
                mId: randomId(TABLEID.企业经营信息),
                annual: getMySqlMs(`${year}-01-01 00:00:00`),
                quarter,
                BI: 0,
                TXP: 0,
                RD: 0,
                createTime: getMySqlMs(),
                state: 1,
                isSubmit: 0,
                isUpdate: 0
            };
            
            await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业经营信息, itemInfo, {});
            
            // 重新查询新创建的任务
            const newTask = await selectData(
                OPERATIONALDATATYPE.查询单个, 
                TABLENAME.企业经营信息, 
                { eId, annual: getMySqlMs(`${year}-01-01 00:00:00`), quarter }, 
                jysjFile
            );
            
            existingTask = newTask;
        }

        const timeRange = getQuarterTaskTimeRange(year, quarter);
        const isSubmitted = existingTask.isSubmit === 1;
        const declarationStatus = getDeclarationStatus(year, quarter, isSubmitted);
        const canSubmit = canSubmitTask(year, quarter, isSubmitted);

        dataList.push({
            mId: existingTask.mId, // 任务ID
            annual: moment(existingTask.annual).format("YYYY"), // 年份
            quarter: quarter, // 季度
            quarterName: quarterName, // 季度名称
            state: existingTask.isSubmit, // 任务状态
            isSubmit: isSubmitted, // 是否已提交
            declarationStatus: declarationStatus, // 填报状态
            canSubmit: canSubmit, // 是否可以提交
            declarationPeriod: `${timeRange.startTime} 至 ${timeRange.endTime}`, // 填报期限
            deadline: timeRange.endTime, // 截止日期
            // 经营数据字段
            BI: existingTask.BI, // 营收（万元）
            TXP: existingTask.TXP, // 纳税（万元）
            RD: existingTask.RD // 研发投入（万元）
        });
    }

    // 按季度顺序排序
    dataList.sort((a, b) => a.quarter - b.quarter);

    return {
        dataList
    };
}


/**
 * 经营信息提交（增加时间校验）
 * @param eId 
 * @param mId 
 */
export async function submitTask(eId: string, mId: string, param) {
    const FuncName = "企业提交企业营收记录"
    eccFormParam(FuncName, EnterpriseManageInfoUpdateConfig, param );

    let filesList = ["mId", "isSubmit", "annual", "quarter"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业经营信息, { eId, mId }, filesList);
    
    if (!resInfo || !resInfo.mId) {
        throw new BizError(ERRORENUM.数据不存在);
    }
    
    if (resInfo.isSubmit == 1) throw new BizError(ERRORENUM.不可重复提交);
    
    // 检查是否在填报时间内
    const year = moment(resInfo.annual).year();
    const canSubmit = canSubmitTask(year, resInfo.quarter, false);
    
    if (!canSubmit) {
        const timeRange = getQuarterTaskTimeRange(year, resInfo.quarter);
        const status = getDeclarationStatus(year, resInfo.quarter, false);
        throw new BizError(ERRORENUM.当前不在填报时间内, `状态：${status}`);
    }

    let addInfo = {
        BI:param.BI,
        TXP:param.TXP,
        RD:param.RD,
        isSubmit: 1
    };

    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业经营信息, addInfo, { eId, mId });

    return { isSuccess: true };
}


/**
 * 获取当前可填报的任务列表
 * @param eId 企业ID
 */
export async function getCurrentDeclarableTasks(eId: string) {
    const currentYear = moment().year();
    const dataList = [];
    
    // 检查最近4个季度的任务
    for (let year = currentYear - 1; year <= currentYear + 1; year++) {
        for (let quarter = 1; quarter <= 4; quarter++) {
            const isInPeriod = isInDeclarationPeriod(year, quarter);
            if (isInPeriod) {
                const timeRange = getQuarterTaskTimeRange(year, quarter);
                const quarterConf = ["第一季度", "第二季度", "第三季度", "第四季度"];
                
                // 检查该任务是否已存在
                const existingTask = await selectData(
                    OPERATIONALDATATYPE.查询单个, 
                    TABLENAME.企业经营信息, 
                    { eId, annual: getMySqlMs(`${year}-01-01 00:00:00`), quarter }, 
                    ["mId", "isSubmit"]
                );
                
                dataList.push({
                    year,
                    quarter,
                    quarterName: quarterConf[quarter - 1],
                    declarationPeriod: `${timeRange.startTime} 至 ${timeRange.endTime}`,
                    canDeclare: true,
                    hasTask: !!existingTask?.mId,
                    isSubmitted: existingTask?.isSubmit === 1,
                    mId: existingTask?.mId
                });
            }
        }
    }
    
    return { dataList };
}


/**
 * 获取企业基本信息
 * 回显
 * @param uscc 
 */
export async function enterpriseBaseInfo(eId) {
    let filesList = ["uscc", "enterpriseName", "logonTime", "logonAddress", "operatingAddress", "oldLogonAddress", "zhuCeHao", "zuZhiJiGouDaiMa", "dengJiJiGuan"];
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, filesList);

    let logonAddress = [];
    if (enterpriseInfo.logonAddress) {
        logonAddress = getAddresList(enterpriseInfo.logonAddress);
    }
    
    enterpriseInfo.logonAddress = logonAddress;
    enterpriseInfo.operatingAddress = enterpriseInfo.operatingAddress || "-";
    enterpriseInfo.oldLogonAddress = JSON.parse(enterpriseInfo.oldLogonAddress||'[]');
    enterpriseInfo.logonTime = moment(enterpriseInfo.logonTime).format("YYYY-MM-DD");
    let dataInfo = extractData(EnterpriseBaseResConfig, enterpriseInfo);

    return {dataInfo};
}


/**
 * 获取企业-我的信息
 * 回显
 * @param uscc 
 */
export async function enterpriseInfomation(eId) {
    let filesList = ["tongXinDiZhi", "industry", "mail", "liaison", "liaisonPhone", "gengDuoDianHua", "jianJie", "mainBusiness"];
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, filesList);

    enterpriseInfo.industry = JSON.parse(enterpriseInfo.industry || '[]');
    enterpriseInfo.tongXinDiZhi = JSON.parse(enterpriseInfo.tongXinDiZhi);
    let dataInfo = extractData(EnterpriseInfomationResConfig, enterpriseInfo);

    return {dataInfo};
}



/**
 * 修改企业我的信息
 * @param uscc 企业统一信用代码
 * @param param 表单
 * @returns 
 */
export async function updateEnterpriseInfomation(eId, param) {
    const FuncName = "企业修改我的信息"
    eccFormParam(FuncName, EnterpriseInfomationUpdateConfig, param );
    eccEnumValue(FuncName, 'industry', enumConfig.INDUSTRY, param.industry);

    let filesList = ["tongXinDiZhi", "industry", "mail", "liaison", "liaisonPhone", "gengDuoDianHua", "jianJie", "mainBusiness"];
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业基础信息表, {eId}, filesList);

    param.tongXinDiZhi = JSON.stringify(param.tongXinDiZhi);
    param.industry = JSON.stringify(param.industry); //param.industry[0]; JSON.stringify();
    /**修改字段 */
    let changeList = checkChange(param, enterpriseInfo);
    if ( !changeList.length ) return {isSuccess:true};

    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业基础信息表, param, {eId});
    
    return {isSuccess:true};
}



/**
 * 获取企业-法人信息
 * 回显
 * @param uscc 
 */
export async function enterpriseFaRenInfo(eId) {
    let filesList = ["name", "idCard", "domicile", "degree", "politicalStatus", "phone"];
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.法人信息表, {eId}, filesList);

    let dataInfo = extractData(EnterpriseFaRenInfoResConfig, enterpriseInfo);

    return {dataInfo};
}



/**
 * 修改企业法人信息
 * @param uscc 企业统一信用代码
 * @param param 表单
 * @returns 
 */
export async function updateEnterpriseFaRenInfo(eId, param) {
    const FuncName = "企业修改法人信息"
    eccFormParam(FuncName, EnterpriseFaRenInfoUpdateConfig, param );
    eccEnumValue(FuncName, 'degree', enumConfig.DEGREE, param.degree);
    eccEnumValue(FuncName, 'politicalStatus', enumConfig.ZZMM, param.politicalStatus);

    let filesList = ["name", "idCard", "domicile", "degree", "politicalStatus", "phone"];
    let enterpriseInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.法人信息表, {eId}, filesList);

    /**修改字段 */
    let changeList = checkChange(param, enterpriseInfo);
    if ( !changeList.length ) return {isSuccess:true};

    if (!enterpriseInfo || !enterpriseInfo.name) {
        param.legalId = randomId(TABLEID.法人信息表);
        param.eId = eId;
        await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.法人信息表, param, {});
    } else {
        await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.法人信息表, param, {eId});
    }
    
    return {isSuccess:true};
}


/**
 * 获取企业-入驻信息
 * 回显
 * @param uscc 
 */
export async function enterpriseLeaseInfo(eId) {
    // let filesList = ["area", "unitPrice", "startTime", "endTime", "building", "roomNumber","rent"];
    let filesList = ["area", "startTime", "endTime", "building", "roomNumber","rent"];
    let includeConf = {};
    includeConf[TABLENAME.租赁信息] = {colum:filesList, where:{} };
    // includeConf[TABLENAME.企业孵化信息] = {colum:["state", "startTime", "endTime"], where:{} };
    includeConf[TABLENAME.企业孵化信息] = {colum:["startTime", "endTime"], where:{} };
    let enterpriseInfo = await selectManyTableData(OPERATIONALDATATYPE.多表单个, TABLENAME.企业基础信息表, {eId}, ["enterpriseName"], includeConf);
    
    let dataInfo:any = extractData(EnterpriseLeaseInfoResConfig, enterpriseInfo.enterprise_leases[0]);

    dataInfo.enterpriseName = enterpriseInfo.enterpriseName;
    // dataInfo.state = changeEnumValue(enumConfig.FUHUASTATE, enterpriseInfo.enterprise_fuhuas[0].state);

    //如果 startTime 或 endTime 为空或无效，可以设置默认值或提示信息：
    if (enterpriseInfo.enterprise_leases) {
        const startTime = moment(enterpriseInfo.enterprise_leases[0].startTime);
        const endTime = moment(enterpriseInfo.enterprise_leases[0].endTime);
    
        if (startTime.isValid() && endTime.isValid()) {
            // dataInfo.leaseTime = `${startTime.format("YYYY-MM-DD")}至${endTime.format("YYYY-MM-DD")}`;
            dataInfo.leaseStartTime = startTime.format("YYYY-MM-DD");
            dataInfo.leaseEndTime = endTime.format("YYYY-MM-DD");
        } else {
            // dataInfo.leaseTime = '未设置租赁日期';
            dataInfo.leaseStartTime = '-';
            dataInfo.leaseEndTime = '-';
        }
    } else {
        dataInfo.leaseStartTime = '-';
        dataInfo.leaseEndTime = '-';
    }
    // if (enterpriseInfo.enterprise_leases) dataInfo.leaseTime = `${moment(enterpriseInfo.enterprise_leases[0].startTime).format("YYYY-MM-DD")}至${moment(enterpriseInfo.enterprise_leases[0].endTime).format("YYYY-MM-DD")}`;
    if (enterpriseInfo.enterprise_fuhuas) {
        const startTime = moment(enterpriseInfo.enterprise_fuhuas[0].startTime);
        const endTime = moment(enterpriseInfo.enterprise_fuhuas[0].endTime);
    
        if (startTime.isValid() && endTime.isValid()) {
            // dataInfo.leaseTime = `${startTime.format("YYYY-MM-DD")}至${endTime.format("YYYY-MM-DD")}`;
            dataInfo.fuHuaStartTime = startTime.format("YYYY-MM-DD");
            dataInfo.fuHuaEndTime = endTime.format("YYYY-MM-DD");
        } else {
            dataInfo.fuHuaStartTime = '-';
            dataInfo.fuHuaEndTime = '-';
        }
        // dataInfo.fuHuaTime = `${moment(enterpriseInfo.enterprise_fuhuas[0].startTime).format("YYYY-MM-DD")}至${moment(enterpriseInfo.enterprise_fuhuas[0].endTime).format("YYYY-MM-DD")}`;
    } else {
        dataInfo.fuHuaStartTime = '-';
        dataInfo.fuHuaEndTime = '-';
    }
    

    return {dataInfo};
}


/**
 * 修改企业入驻信息
 * @param eId 
 */
export async function enterpriseLeaseUpdate(eId, param) {
    const FuncName = "修改企业入驻信息"
    eccFormParam(FuncName, enterpriseLeaseUpdateConfig, param );
    eccEnumValue(FuncName, 'building', enumConfig.BUILDING, param.building);

    let leaseParam = {
        area:param.area,
        building:param.building,
        roomNumber:param.roomNumber,
        rent:param.rent,
        startTime:param.leaseStartTime,
        endTime:param.leaseEndTime
    }
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.租赁信息, leaseParam, {eId});

    let fuhuaParam = {
        startTime:param.startTime,
        endTime:param.endTime
    }
    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.企业孵化信息, fuhuaParam, {eId});
    
    return {isSuccess:true};
}


//===============================================企业服务


/**
 * 企业服务-列表
 * 回显
 * @param uscc 
 */
export async function enterpriseServiceList(eId) { 
    let filesList = ["esId", "needCategory", "applyTime", "followUpStatus", "needContent"];

    let iprList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.企业服务表, {eId}, filesList);

    let dataList:any[] = [];
    iprList.forEach(item => {
        let {esId, needCategory, applyTime, followUpStatus, needContent} = item;

        dataList.push({
            esId,
            needCategory,
            applyTime:moment(applyTime).format("YYYY-MM-DD"),
            followUpStatus:changeEnumValue(enumConfig.FOLLOWUPSTATUS, followUpStatus),
            needContent
        });
    });

    return {dataList};
}


/**
 * 企业服务-回显
 * @param uscc 企业统一信用代码
 * @param param 表单
 * @returns 
 */
export async function enterpriseServiceInfo(eId, esId) {

    let filesList = [ "esId", "needCategory", "applyTime", "followUpStatus", "needContent", "fangKui", "outcome", "desc"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业服务表, {esId, eId}, filesList)
    if (!resInfo || !resInfo.esId) throw new BizError(ERRORENUM.当前数据不存在);

    let dataInfo = {
        esId:resInfo.esId,
        needCategory:resInfo.needCategory,
        applyTime:moment(resInfo.applyTime).format("YYYY-MM-DD"),
        followUpStatus:changeEnumValue(enumConfig.FOLLOWUPSTATUS, resInfo.followUpStatus),
        needContent:resInfo.needContent,
        dealResult:resInfo.fangKui,
    }
    if(resInfo.followUpStatus == enumConfig.FOLLOWUPSTATUS.已完成) {
        dataInfo.dealResult = `已处理${resInfo.outcome ? "已解决" : "未解决"}`;
        console.log("dealResult", dataInfo.dealResult);
        if (resInfo.desc) dataInfo.dealResult += `，${resInfo.desc}`;
    }
    
    return {dataInfo};
}


/**
 * 企业服务-添加
 * @param uscc 企业统一信用代码
 * @param param 表单
 * @returns 
 */
export async function createEnterpriseServiceInfo(eId, param) {
    const FuncName = "企业添加企业服务"
    eccFormParam(FuncName, EnterpriseServiceUpdateConfig, param );

    let addInfo = {
        esId:randomId(TABLEID.企业服务表),
        eId,
        needCategory:param.needCategory,
        needContent:param.needContent,
        applyTime:getMySqlMs(),
        followUpStatus:enumConfig.FOLLOWUPSTATUS.未受理
    };

    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.企业服务表, addInfo, {});
    
    return {isSuccess:true};
}


/**
 * 企业服务-删除
 * @param param0 
 * @returns 
 */
export async function deleteEnterpriseServiceInfo(eId, esId) {
    let filesList = ["esId", "needCategory", "applyTime", "followUpStatus", "needContent"];
    let iprInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.企业服务表, {esId, eId}, filesList)
    if (!iprInfo || !iprInfo.esId) throw new BizError(ERRORENUM.当前数据不存在);

    await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.企业服务表, {}, {esId, eId});
    
    return {isSuccess:true};
}


//===========================================政策速递

/**
 * 政策速递列表
 * @param state 1：进行中，2：往期速递
 * @returns 
 */
export async function enterprisePolicyList(state, policyType) {
    let filesList = ["poId", "title", "source", "createTimeMs", "closeTimeMs", "coverImg", "isPermanent", "policyType"];
    let selectParam:any = {};
    if (policyType != enumConfig.CLIENTPOLICYTYPE.全部) selectParam.policyType = policyType;
    let resList = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.政策表, selectParam, filesList);

    let dataList = [];
    resList.forEach(info => {
        let { poId, title, source,createTimeMs, closeTimeMs, coverImg, isPermanent, policyType } = info;
        // 判断是否为永久有效政策
        let formattedCreateTime = "-";
        if (isPermanent == 1) formattedCreateTime = "永久有效";
        else formattedCreateTime = moment(closeTimeMs).format("YYYY-MM-DD");

        if (state == 1) {
            if (isPermanent == 1 || closeTimeMs > getMySqlMs()) {
                dataList.push( {
                    poId,
                    title, 
                    source,
                    createTimeMs:createTimeMs ? moment(createTimeMs).format("YYYY-MM-DD") : "",
                    closeTimeMs:formattedCreateTime, 
                    coverImg:coverImg ? JSON.parse(coverImg)[0] :'',
                    isPermanent,
                    policyType:changeEnumValue(enumConfig.CLIENTPOLICYTYPE, policyType)
                });
            }
        } else if (state == 2) {
            if (isPermanent == 0 && getMySqlMs() > closeTimeMs) {
                dataList.push( {
                    poId,
                    title, 
                    source,
                    createTimeMs:createTimeMs ? moment(createTimeMs).format("YYYY-MM-DD") : "",
                    closeTimeMs:formattedCreateTime, 
                    coverImg:coverImg ? JSON.parse(coverImg)[0] :'',
                    isPermanent,
                    policyType:changeEnumValue(enumConfig.CLIENTPOLICYTYPE, policyType)
                } );
            }
        }
        
    });

    
    return {dataList};
    
}



export async function enterprisePolicyInfo(poId) {
    let filesList = ["poId", "desc", "title", "source", "closeTimeMs", "coverImg","isPermanent", "createTimeMs","policyType"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.政策表, {poId}, filesList);
    if (!resInfo || !resInfo.poId) {
        throw new BizError(ERRORENUM.数据不存在);
    }

    let {closeTimeMs, isPermanent, policyType } = resInfo;

    // 判断是否为永久有效政策
    let formattedCreateTime = isPermanent ? "永久有效" :  moment(closeTimeMs).format("YYYY-MM-DD");

    let dataInfo = {
        poId:resInfo.poId, 
        desc:resInfo.desc, 
        title:resInfo.title,
        source:resInfo.source, 
        closeTimeMs: formattedCreateTime, 
        coverImg:JSON.parse(resInfo.coverImg),
        // createTimeMs:moment(closeTimeMs).format("YYYY-MM-DD")
        policyType:changeEnumValue(enumConfig.CLIENTPOLICYTYPE, policyType)
    }


    return {dataInfo};
}


/**
 * 通知列表
 * @param gnId 
 * @returns 
 */
export async function gardenNoticeList(eId:string) {
    let nowTime = getMySqlMs();
    let filesList = ["gnId", "title", "isPublished", "content", "publishStartTime", "publishEndTime", "relatedEnterprise"];
    let selectParam = {
        isPublished:enumConfig.STATE.是, 
        relatedEnterprise:{"%like%":eId},
        publishStartTime:{"%lte%":nowTime},
        publishEndTime:{"%gte%":nowTime}
    };
    let resData = await selectData(OPERATIONALDATATYPE.查询多个, TABLENAME.园区通知表, selectParam, filesList);

    let dataList = [];
    resData.forEach( info => {
        let dataInfo = {
            gnId:info.gnId,//id
            title:info.title,//标题
            content:info.content,//内容
            isPublished:info.isPublished,//是否发布（1：是，0：否）
            publishTime:`${moment(info.publishStartTime).format("YYYY-MM-DD")}-${moment(info.publishEndTime).format("YYYY-MM-DD")}`,//发布时间
        };

        dataList.push(dataInfo);
    })
    
    return {dataList}
}


/**
 * 通知详情
 * @param gnId 
 * @returns 
 */
export async function gardenNoticeInfo(gnId:string) {
    let filesList = ["gnId", "title", "isPublished", "content", "publishStartTime", "publishEndTime", "relatedEnterprise"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.园区通知表, {gnId}, filesList);

    let dataInfo = {
        gnId:resInfo.gnId,//id
        title:resInfo.title,//标题
        content:resInfo.content,//内容
        isPublished:resInfo.isPublished,//是否发布（1：是，0：否）
        publishStartTime:resInfo.publishStartTime,//发布时间
        publishEndTime:resInfo.publishEndTime,//发布时间
        relatedEnterprise:JSON.parse(resInfo.relatedEnterprise || '[]'),//关联企业
    };
    return {dataInfo}
}



