/**
 * 芳华杯
 */

import moment = require("moment");
import { ERRORENUM } from "../../../config/errorEnum";
import { addOneData } from "../../../data/add";
import { deleteOneData } from "../../../data/delete";
import { TABLEENUM } from "../../../data/models/model";
import { find, findOnce } 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(secureArgs) {
    let {userId, form} = secureArgs;
    form.id = generateSystemId(TABLEENUM.芳华杯, userId);
    await addOneData(TABLEENUM.芳华杯, form);

    return successResult();
}


/**
 * 修改芳华杯信息
 * @param userId 
 * @param id 
 * @param updateParam 
 * @returns 
 */
export async function update(secureArgs:any) {
    let {userId, id, form} = secureArgs;
    let oldInfo = await findOnce(TABLEENUM.芳华杯, {id});
    if (!oldInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
    
    await updateOneData(TABLEENUM.芳华杯, {id}, form);
    return successResult();
}


export async function del(secureArgs:any) {
    let {userId, id} = secureArgs;
    let dataInfo = await findOnce(TABLEENUM.芳华杯, {id});
    if (!dataInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
    await deleteOneData(TABLEENUM.芳华杯, {id});
    return successResult();
}


export async function list({desc, worksType, year}) {
    let param:any = {};
    if (desc) param.desc = {"$regex":`${desc}`};
    if (worksType) param.worksType = worksType;
    if (year) {
        let st = new Date(`${year}-01-01 00:00:00`).valueOf();
        let et = new Date(`${year+1}-01-01 00:00:00`).valueOf();
        param["$and"] = [
            {awardTime:{"$gt":st}},
            {awardTime:{"$lt":et}}
        ];
    }
    let dbList = await find(TABLEENUM.芳华杯, param);

    let dataList = [];
    dbList.forEach(info => {
        let item:any = extractData(info, ["id", "name", "works", "worksType", "awardTime", "desc"]);
        // item.awardTime = moment(item.awardTime).format("YYYY-MM-DD");
        dataList.push(item);
    });

    return dataList;
}

/**
 * 回显
 * @param id 
 */
export async function info(secureArgs:any) {
    let {id} = secureArgs;
    let oldInfo = await findOnce(TABLEENUM.芳华杯, {id});
    let dataInfo = extractData(oldInfo, ["id", "name", "works", "worksType", "awardTime", "desc"]);

    return { dataInfo };
}
