/**
 * 分支机构-机构管理-内容管理-委员名单
 */

import { BRANCHPOSITION } from "../../../config/enum";
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, findToSortToPage } from "../../../data/select";
import { updateOneData } from "../../../data/update";
import { generateSystemId, successResult } from "../../../tools/system";
import { BizError } from "../../../util/bizError";
import { extractData } from "../../../util/piecemeal";
import { changeEnumValue } from "../../../util/verificationEnum";


/**
 * 创建委员名单
 * @param userId 
 * @param param 
 * @returns 
 */
export async function create({userId, agencyId, form}) { 
    form.id = generateSystemId(TABLEENUM.委员名单, userId);
    form.agencyId = agencyId;
    form.branchDuties.sort();
    form.ut = new Date().valueOf();
    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;
    }
    form.branchDuties.sort();
    form.ut = new Date().valueOf();
    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 dbList = await findToSortToPage(TABLEENUM.委员名单, {agencyId}, ["id", "name", "branchDuties", "unit", "unitDuties"], {branchDuties:1}, pageNumber);
    let dataCount = await findCount(TABLEENUM.委员名单, {agencyId});

    let dataList = [];
    dbList.forEach(info => {
        let item:any = extractData(info, ["id", "name", "branchDuties", "unit", "unitDuties"]);
        item.branchDuties = changeEnumValue(BRANCHPOSITION, item.branchDuties);
        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", "name", "branchDuties", "unit", "unitDuties"]);
    
    return { dataInfo };
}
