/**
 * 分支机构-机构管理-内容管理-工作动态
 */

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, agencyId, form}) { 
    form.id = generateSystemId(TABLEENUM.工作动态, userId);
    form.agencyId = agencyId;
    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.目标数据不存在);
    if (form.agencyId) {
        delete form.agencyId;
    }
    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, agencyId, pageNumber}) {
    
    let jiGouNameMap = await getJiGouMap();
    let dbList = await findToPage(TABLEENUM.工作动态, {agencyId}, ["id", "title", "activityTime", "isUse"], pageNumber);
    let dataCount = await findCount(TABLEENUM.工作动态, {agencyId});

    let dataList = [];
    dbList.forEach(info => {
        let item:any = extractData(info, ["id", "title", "activityTime", "isUse"]);
        item.jiGouName = jiGouNameMap[info.agencyId];
        dataList.push(item);
    });

    return {dataList, dataCount};
}

async function getJiGouMap() {
    let jiGouList = await find(TABLEENUM.机构管理, {});
    let map = {};
    jiGouList.forEach(info => {
        let {id, name} = info;
        map[id] = name;
    });

    return map;
}

/**
 * 回显
 * @param id 
 */
export async function info({id}) {
    let oldInfo = await findOnce(TABLEENUM.工作动态, {id});
    let dataInfo = extractData(oldInfo, ["id", "title", "activityTime", "imgUrl", "isUse", "desc"]);
    
    return { dataInfo };
}


export async function changeUse({id}) {
    let oldInfo = await findOnce(TABLEENUM.工作动态, {id});
    if (!oldInfo.id) throw new BizError(ERRORENUM.目标数据不存在);

    let newPush = oldInfo.isUse == 1 ? 0 : 1;
    await updateOneData(TABLEENUM.工作动态, {id}, {isUse:newPush});

    return successResult();
}