/**
 * 活动通知
 */

import { ERRORENUM } from "../../../config/errorEnum";
import { addOneData } from "../../../data/add";
import { deleteOneData } from "../../../data/delete";
import { TABLEENUM } from "../../../data/models/model";
import { find, findCount, findOnce, findToPage } from "../../../data/select";
import { updateOneData } from "../../../data/update";
import { generateSystemId, successResult } from "../../../tools/system";
import { BizError } from "../../../util/bizError";
import { extractData } from "../../../util/piecemeal";

/**
 * 创建活动通知
 * @param userId 
 * @param param 
 * @returns 
 */
export async function create({userId, form}) {
    form.ct = new Date().valueOf();
    form.id = generateSystemId(TABLEENUM.活动通知, userId);
    await addOneData(TABLEENUM.活动通知, form);

    return successResult();
}


/**
 * 修改
 * @param userId 
 * @param id 
 * @param updateParam 
 * @returns 
 */
export async function update({userId, id, form}) {
    let oldInfo = await findOnce(TABLEENUM.活动通知, {id});
    if (!oldInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
   
    await updateOneData(TABLEENUM.活动通知, {id}, form);
    return successResult();
}


export async function del({userId, id}) {
    let dataInfo = await findOnce(TABLEENUM.活动通知, {id});
    if (!dataInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
    await deleteOneData(TABLEENUM.活动通知, {id});
    return successResult();
}


export async function list({userId, desc, pageNumber}) {
    let selectParam:any = {};
    if (desc) selectParam.desc = {"$regex":desc}
    let dbList = await findToPage(TABLEENUM.活动通知, selectParam, ["id", "name", "st", "addrest", "members", "push", "desc"], pageNumber);
    let dataCount = await findCount(TABLEENUM.活动通知, selectParam);
    
    let dataList = [];
    dbList.forEach(info => {
        let item = extractData(info, ["id", "name", "st", "addrest", "members", "push", "desc"]);
        dataList.push(item);
    });

    dataList.sort((a, b) => {return a.rank - b.rank});

    return {dataList, dataCount};
}

/**
 * 回显
 * @param id 
 */
export async function info({id}) {
    let oldInfo = await findOnce(TABLEENUM.活动通知, {id});
    let dataInfo = extractData(oldInfo, ["id", "name", "st", "addrest", "members", "push", "desc"]);

    return { dataInfo };
}

export async function changePush({id}) {
    let oldInfo = await findOnce(TABLEENUM.活动通知, {id});
    if (!oldInfo.id) throw new BizError(ERRORENUM.目标数据不存在);

    let newPush = oldInfo.push == 1 ? 0 : 1;
    await updateOneData(TABLEENUM.活动通知, {id}, {push:newPush});

    return successResult();
}