/**
 * 项目公告
 * 
 */

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();
}