/**
 * 园区活动
 */

import * as verificationEnumTools from "../util/verificationEnum";
import * as configEnum from "../config/enum";
import * as industryEnum from "../config/enum/industryEnum";
import * as activityData from "../data/activity";
import { checkChange, extractData } from "../util/piecemeal";
import * as splitResultConfig from '../config/splitResultConfig';
import { eccFormParam } from "../util/verificationParam";
import { ActivityAddConfig, ActivityUpdateConfig } from "../config/eccParam/admin";
import { randomId } from "../tools/system";
import { TABLEID } from "../config/enum/dbEnum";
import { BizError } from "../util/bizError";
import { ERRORENUM } from "../config/errorEnum";


/**
 * 园区活动-列表
 * @param title 活动标题
 * @param startTime 活动开始时间
 * @param endTime 活动结束时间
 * @param target 活动类型
 * @param state 活动状态 未开始、活动中、已结束
 * @param page 页
 */
export async function activityList(title:string, startTime:number, endTime:number, target, state:number, page:number) {
    let selectParam:any = {};
    if (title) {
        selectParam.title = {"$regex":`${title}`};
    }
    if (startTime && endTime) {
        selectParam.startTime = { "$lte": endTime };
        selectParam.endTime = { "$gte": startTime };
    }
    if (target) {
        verificationEnumTools.eccEnumValue('管理后台获取园区活动列表', 'target', configEnum.ACTIVITYTARGET, target);
        selectParam.target = {"$in":target};
    }
    // if (state) {
    //     verificationEnumTools.eccEnumValue('管理后台获取园区活动列表', 'state', configEnum.ACTIVITYSTATE, state);
    //     selectParam.state = state;
    // }

    /**需要用到的查询数据 */
    let activityDbList = await activityData.findActivityListToPage(selectParam, (page - 1) * 10);
    let allActivityDbList = await activityData.findActivityListByParam(selectParam);

    // 如果有状态筛选，过滤数据
    let filteredActivityDbList = activityDbList;
    if (state) {
        verificationEnumTools.eccEnumValue('管理后台获取园区活动列表', 'state', configEnum.ACTIVITYSTATE, state);
        filteredActivityDbList = activityDbList.filter(info => {
            const activityState = calculateActivityState(info.startTime, info.endTime);
            return activityState === state;
        });
    }

    // 重新计算总数
    let count = allActivityDbList.length;
    if (state) {
        count = allActivityDbList.filter(info => {
            const activityState = calculateActivityState(info.startTime, info.endTime);
            return activityState === state;
        }).length;
    }

    /**组合返回结果 */
    let dataList = [];
    filteredActivityDbList.forEach( info => {
        /**截取返回数据 */
        let changeData:any = extractData(splitResultConfig.activityListConfig, info, true);

        /**将枚举值转为字符 */
        let target = [];
        changeData.target.forEach( info => {
            target.push(verificationEnumTools.changeEnumValue(configEnum.ACTIVITYTARGET, info))
        })
        changeData.target = target;
        
        // 计算活动状态
        let stateType = calculateActivityState(info.startTime, info.endTime)
        changeData.state = verificationEnumTools.changeEnumValue(configEnum.ACTIVITYSTATE, stateType);

        dataList.push(changeData);
    })

    return {count, dataList};
}


/**
 * 园区活动-新增
 * @param uscc 
 * @param param 
 */
export async function activityCreate(param) {
    /**校验表单参数 */
    eccFormParam("管理后台新增园区活动企业", ActivityAddConfig, param);
    /**校验枚举 */
    if (param.target && param.target.length > 0) {
        verificationEnumTools.eccEnumValue('管理后台新增园区活动', 'target', configEnum.ACTIVITYTARGET, param.target);
    }
    
    // 校验时间
    if (param.startTime >= param.endTime) {
        throw new BizError(ERRORENUM.参数错误, '活动开始时间不能晚于或等于结束时间');
    }

    let enterpriseInfo = await activityData.findActivityByParam({title:param.title, startTime:param.startTime});
    if (enterpriseInfo && enterpriseInfo.title)  throw new BizError(ERRORENUM.该活动已存在, `${param.title}已经在库中存在`);

    let activityInfo = {
        id: randomId(TABLEID.活动),
        title: param.title,
        startTime: param.startTime,
        endTime: param.endTime,
        target: param.target,
        location: param.location,
        desc:param.desc,
    }

    await activityData.createDataByParam(activityInfo);

    return {isSuccess:true};
}


/**
 * 园区活动-回显
 * @param uscc 
 */
export async function activityInfo(id:string) {
    /**校验活动 */
    let activityDbInfo = await activityData.findActivityByParam({id});
    if (!activityDbInfo || !activityDbInfo.id) throw new BizError(ERRORENUM.未找到数据, `库中不存在id=${id}这个活动`);
    
    let dataInfo = {
        title: activityDbInfo.title,
        startTime: activityDbInfo.startTime,
        endTime: activityDbInfo.endTime,
        target: activityDbInfo.target,
        location: activityDbInfo.location,
        desc: activityDbInfo.desc,
    };

    return {dataInfo};
}


/**
 * 园区活动-修改
 * @param id 
 * @param param 
 */
export async function activityUpdate(id:string, param) {
    /**校验参数 */
    eccFormParam("管理后台修改园区活动企业", ActivityUpdateConfig, param);

    /**校验枚举 */
    if (param.target && param.target.length > 0) {
        verificationEnumTools.eccEnumValue('管理后台新增园区活动', 'target', configEnum.ACTIVITYTARGET, param.target);
    }
    
    // 校验时间
    if (param.startTime >= param.endTime) {
        throw new BizError(ERRORENUM.参数错误, '活动开始时间不能晚于或等于结束时间');
    }

    /**校验活动 */
    let activityDbInfo = await activityData.findActivityByParam({id});
    if (!activityDbInfo || !activityDbInfo.id) throw new BizError(ERRORENUM.未找到数据, `库中不存在id=${id}这个活动`);

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

    await activityDbInfo.save();

    return {isSuccess:true};
}


/**
 * 园区活动-删除
 * @param id 
 */
export async function activityDelete(id:string) {
    let activityDbInfo = await activityData.findActivityByParam({id});
    if (!activityDbInfo || !activityDbInfo.id) throw new BizError(ERRORENUM.未找到数据, `库中不存在id=${id}这个活动`);

    await activityData.removeOneData(id);

    return {isSuccess:true};
}


/**
 * 导出园区活动信息列表
 * @param title 活动标题
 * @param startTime 活动开始时间
 * @param endTime 活动结束时间
 * @param target 活动类型
 * @param state 活动状态
 * @returns 二维数组，第一行为表头，后续行为数据
 */
export async function outPutActivityData(title: string, startTime: number, endTime: number, target: number[], state: number, id:string[]) {
    /** 拼接查询条件 */
    let selectParam: any = {};
    if (title) {
        selectParam.title = { "$regex": `${title}` };
    }
    if (startTime && endTime) {
        selectParam.startTime = { "$lte": endTime };
        selectParam.endTime = { "$gte": startTime };
    } else if (startTime) {
        selectParam.startTime = { "$lte": endTime };
    } else if (endTime) {
        selectParam.endTime = { "$gte": startTime };
    }
    if (target && target.length > 0) {
        selectParam.target = { "$in": target };
    }

    /** 查询园区活动数据 */
    let activityDbList = await activityData.findActivityListByParam(selectParam);
    
    // 如果有状态筛选，在内存中过滤
    if (state) {
        activityDbList = activityDbList.filter(info => {
            const activityState = calculateActivityState(info.startTime, info.endTime);
            return activityState === state;
        });
    }
    
    // 如果有ID筛选
    if (id) {
        activityDbList = activityDbList.filter(info => id.includes(info.id));
    }

    /** 表头定义 */
    const titleList = [
        "活动标题",
        "活动状态",
        "开始时间",
        "结束时间",
        "活动类型",
        "活动地点",
        // "活动描述"
    ];

    let dataList = [titleList]; // 第一行为表头

    activityDbList.forEach(info => {
        /** 提取数据 */
        let changeData: any = extractData(splitResultConfig.activityListConfig, info, true);

        /** 枚举值转文本 */
        // 活动类型（多选）
        let targetTexts = [];
        if (changeData.target && changeData.target.length > 0) {
            changeData.target.forEach(targetId => {
                const targetText = verificationEnumTools.changeEnumValue(configEnum.ACTIVITYTARGET, targetId);
                if (targetText) {
                    targetTexts.push(targetText);
                }
            });
        }
        changeData.target = targetTexts.join("、") || "未选择";

        // 计算活动状态并转为文本
        const activityState = calculateActivityState(info.startTime, info.endTime);
        changeData.state = verificationEnumTools.changeEnumValue(configEnum.ACTIVITYSTATE, activityState) || "未选择";

        /** 时间格式化 */
        changeData.startTime = changeData.startTime ? formatDateTime(changeData.startTime) : "-";
        changeData.endTime = changeData.endTime ? formatDateTime(changeData.endTime) : "-";

        /** 处理活动描述（过长时截取） */
        if (changeData.desc && changeData.desc.length > 100) {
            changeData.desc = changeData.desc.substring(0, 100) + "...";
        }

        /** 生成一行数据 */
        let row = [
            changeData.title || "-",
            changeData.state,
            changeData.startTime,
            changeData.endTime,
            changeData.target,
            changeData.location || "-",
            // changeData.desc || "-"
        ];

        dataList.push(row);
    });

    return dataList;
}


/**
 * 时间格式化辅助函数
 * @param timestamp 时间戳
 * @returns 格式化后的时间字符串
 */
function formatDateTime(timestamp: number): string {
    const date = new Date(timestamp);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    // const hours = date.getHours().toString().padStart(2, '0');
    // const minutes = date.getMinutes().toString().padStart(2, '0');
    
    // return `${year}-${month}-${day} ${hours}:${minutes}`;
    return `${year}-${month}-${day}`;
}


/**
 * 根据活动时间计算活动状态
 * @param startTime 开始时间戳
 * @param endTime 结束时间戳
 * @returns 活动状态枚举值
 */
function calculateActivityState(startTime:number, endTime:number) {
    const now = Date.now();
    
    if (now < startTime) {
        return configEnum.ACTIVITYSTATE.未开始;
    } else if (now >= startTime && now <= endTime) {
        return configEnum.ACTIVITYSTATE.活动中;
    } else {
        return configEnum.ACTIVITYSTATE.已结束;
    }
}





