/**
 * 政策
 */

import moment = require("moment");
import { OPERATIONALDATATYPE, TABLEID, TABLENAME } from "../config/enum/dbEnum";
import { ERRORENUM } from "../config/enum/errorEnum";
import { operationalData, selectData } from "../data/operationalData";
import { getMySqlMs, randomId } from "../tools/system";
import { BizError } from "../util/bizError";
import { eccFormParam } from "../util/verificationParam";
import { PolicyUpdateConfig } from "../config/eccParam/enterprise";
import { POLICYTYPE } from "../config/enum/enum";
import { changeEnumValue } from "../util/verificationEnum";

/**
 * 政策列表
 * @param keywords 模糊搜索关键词
 * @param state 筛选状态: 1=进行中 2=往期 其他=全部
 * @param policyType 筛选政策类型: 1=财政补贴 2=资质申报 3=政策扶持
 * @param page 页码
 */
export async function enterprisePolicyList(keywords:string, state:number, policyType:number, page:number) {
 let selectParam:any = {};
    if (keywords) selectParam.title = {"%like%":keywords};
    if (policyType) selectParam.policyType = policyType;//政策类型
    let filesList = ["poId", "title", "source", "createTimeMs", "closeTimeMs", "isPermanent","coverImg" ,"policyType"];
    let resList = await selectData(OPERATIONALDATATYPE.分页查询, TABLENAME.政策表, selectParam, filesList, page);
    let dataCount = await selectData(OPERATIONALDATATYPE.查询数据量, TABLENAME.政策表, selectParam, null);

    let dataList = []; 
    const now = moment().valueOf(); // 获取当前时间戳
    resList.forEach(info => {
        // 格式化日期前检查closeTimeMs是否为'永久有效'或'-'
        // 判断是否为永久有效政策
        let formattedCreateTime = "-";
        if (info.isPermanent == 1) formattedCreateTime = "永久有效";
        else formattedCreateTime = moment(info.closeTimeMs).format("YYYY-MM-DD");

        // 判断政策是进行中还是往期
        let status = '';
        if (info.isPermanent == 1) {
            status = '正在进行';
        } else {
            if (info.closeTimeMs > getMySqlMs()) {
                status = '正在进行';
            }
            if (getMySqlMs() > info.closeTimeMs) {
                status = '已结束';
            }
        }

        if (state == 1) {
            if (info.isPermanent == 1 || info.closeTimeMs > getMySqlMs()) {
                dataList.push({
                    poId:info.poId,
                    title:info.title,
                    source:info.source,
                    createTimeMs: info.createTimeMs ? moment(info.createTimeMs).format("YYYY-MM-DD") : "-",
                    closeTimeMs:formattedCreateTime,
                    isPermanent: info.isPermanent,
                    policyType: changeEnumValue(POLICYTYPE, info.policyType),//政策类型
                    //图片
                    coverImg:JSON.parse(info.coverImg),
                    //coverImg:info.coverImg ?  JSON.parse(info.coverImg) : [],
                    status, // 发布状态
                });
            }
        } else if (state == 2) {
            if (info.isPermanent == 0 && getMySqlMs() > info.closeTimeMs) {
                dataList.push({
                    poId:info.poId,
                    title:info.title,
                    source:info.source,
                    createTimeMs: info.createTimeMs ? moment(info.createTimeMs).format("YYYY-MM-DD") : "-",
                    closeTimeMs:formattedCreateTime,
                    isPermanent: info.isPermanent,
                    policyType: changeEnumValue(POLICYTYPE, info.policyType),//政策类型
                    //图片
                    coverImg:JSON.parse(info.coverImg),
                    //coverImg:info.coverImg ?  JSON.parse(info.coverImg) : [],
                    status, // 发布状态
                });
            }
        } else {
            dataList.push({
                poId:info.poId,
                title:info.title,
                source:info.source,
                createTimeMs: info.createTimeMs ? moment(info.createTimeMs).format("YYYY-MM-DD") : "-",
                closeTimeMs:formattedCreateTime,
                isPermanent: info.isPermanent,
                policyType: changeEnumValue(POLICYTYPE, info.policyType),//政策类型
                //图片
                coverImg:JSON.parse(info.coverImg),
                //coverImg:info.coverImg ?  JSON.parse(info.coverImg) : [],
                status, // 发布状态
            });
        }
        
    });
    
    return {dataList, dataCount};
}


export async function enterprisePolicyInfo(poId:string) {
    let filesList = ["poId", "title", "source", "createTimeMs", "closeTimeMs", "isPermanent", "coverImg", "desc", "policyType"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.政策表, {poId}, filesList);

    let status = '';
    if (resInfo.isPermanent == 1) {
        status = '正在进行';
    } else if (resInfo.closeTimeMs > getMySqlMs()) {
        status = '正在进行';
    } else {
        status = '已结束';
    }


    let dataInfo = {
        title:resInfo.title,
        source:resInfo.source,
        desc:resInfo.desc,
        coverImg:resInfo.coverImg ?  JSON.parse(resInfo.coverImg) : [],
        // closeTimeMs:new Date(resInfo.closeTimeMs).valueOf(),
        closeTimeMs: resInfo.closeTimeMs ? new Date(resInfo.closeTimeMs).valueOf() : null,
        isPermanent:resInfo.isPermanent,
        policyType:resInfo.policyType,//政策类型
        // policyType: changeEnumValue(POLICYTYPE, resInfo.policyType),
        status, // 发布状态
    };
    
    

    return {dataInfo};
}



export async function enterprisePolicyUpdate(poId:string, param) {
    const FuncName = "修改政策表"
    eccFormParam(FuncName, PolicyUpdateConfig, param );
    let filesList = ["poId", "title", "desc", "source", "coverImg", "closeTimeMs", "isPermanent"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.政策表, {poId}, filesList);
    if (!resInfo || !resInfo.poId) throw new BizError(ERRORENUM.数据不存在);

    // param.closeTimeMs = getMySqlMs(param.closeTimeMs);
    // 修改后
    if (param.closeTimeMs) {
        param.closeTimeMs = getMySqlMs(param.closeTimeMs);
    } else if (param.isPermanent === 0) { // 阶段有效但未传时间时设为 null
        param.closeTimeMs = null;
    }

    if (!param.coverImg) param.coverImg = '[]';
    else param.coverImg = JSON.stringify(param.coverImg);


    await operationalData(OPERATIONALDATATYPE.修改, TABLENAME.政策表, param, {poId});

    return {isSuccess:true};
}

export async function enterprisePolicyAdd( param) {
    const FuncName = "添加政策表"
    eccFormParam(FuncName, PolicyUpdateConfig, param );
  
    if (param.closeTimeMs) param.closeTimeMs = getMySqlMs(param.closeTimeMs);
    // param.createTimeMs = getMySqlMs(); //没有传时间不能调用格式转换方法，会默认时间1970-01-01
    if (!param.coverImg.length) param.coverImg =  "[\"/yuyi/files/默认图片.png\"]";
    else param.coverImg = JSON.stringify(param.coverImg);
    param.poId = randomId(TABLEID.政策表);
    param.createTimeMs = getMySqlMs();

    await operationalData(OPERATIONALDATATYPE.增加, TABLENAME.政策表, param, {});

    return {isSuccess:true};
}


export async function enterprisePolicyDelete(poId:string) {
    let filesList = ["poId"];
    let resInfo = await selectData(OPERATIONALDATATYPE.查询单个, TABLENAME.政策表, {poId}, filesList);
    if (!resInfo || !resInfo.poId) throw new BizError(ERRORENUM.数据不存在);

    await operationalData(OPERATIONALDATATYPE.删除, TABLENAME.政策表, {}, {poId});

    return {isSuccess:true};
}