/**
 * 机构管理
 * 排序，后一个排序会与修改前的排序互换
 */
import { ERRORENUM } from "../../../config/errorEnum";
import { addOneData } from "../../../data/add";
import { deleteManyData, 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}) {
    let oldRankInfo = await findOnce(TABLEENUM.机构管理, {rank:form.rank});
    if(oldRankInfo && oldRankInfo.id) {
        /**存在原来的排名，将上一个去掉 */
        await deleteOneData(TABLEENUM.机构管理, {id:oldRankInfo.id});
    }
    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.目标数据不存在);
    if (oldInfo.rank != form.rank) {
        //排名发生变化
        let oldRankInfo = await findOnce(TABLEENUM.机构管理, {rank:form.rank});
        await updateOneData(TABLEENUM.机构管理, {id:oldRankInfo.id}, {rank:oldInfo.rank});
    }
    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});
    await deleteManyData(TABLEENUM.工作动态, {agencyId:id});
    await deleteManyData(TABLEENUM.委员名单, {agencyId:id});
    return successResult();
}


export async function list({pageNumber}) {
    let dbList = await findToPage(TABLEENUM.机构管理, {}, ["id", "rank", "name", "logoUrl", "desc", "createTime"], pageNumber);
    let dataCount = await findCount(TABLEENUM.机构管理, {});
    let dataList = [];
    dbList.forEach(info => {
        let item = extractData(info, ["id", "rank", "name", "logoUrl", "desc", "createTime"]);
        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", "rank", "name", "desc", "logoUrl", "createTime"]);
    /**获取上下3位的排名列表 */

    return { dataInfo };
}
