/**
 * 下载专区
 */

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;
    form.ct = 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;
    }
    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", "name", "ct"] , pageNumber);
    let dataCount = await findCount(TABLEENUM.下载专区, {agencyId});

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