/**
 * 管理后台-标签系统-标签管理
 * 6.0功能
 */

import { LABELGOAL, LABELTYPE } from "../../config/enum/labelEnum";
import { ERRORENUM } from "../../config/errorEnum";
import { createLabel, findOnceLabel, selectLabelCount, selectLabelListToPage } from "../../data/label";
import { getLabelId } from "../../tools/system";
import { BizError } from "../../util/bizError";
import { changeEnumValue, eccEnumValue } from "../../util/verificationEnum";


/**
 * 创建自定义标签
 */
export async function addLabel(name:string, goal:number) {
    eccEnumValue("创建标签", "goal", LABELGOAL, goal);

    let labelId = getLabelId();
    await createLabel(goal, LABELTYPE.自定义标签, name, labelId);

    return {isSuccess:true};
}


/**
 * 修改自定义标签名字
 * @param id 
 * @param name 
 */
export async function updateLabelName(id:string, name:string) {
    let labelInfo = await findOnceLabel(id);
    labelInfo.labelName = name;

    await labelInfo.save();

    return {isSuccess:true}; 
}


/**
 * 自定义标签列表列表
 * @returns 
 */
export async function labelList(pageNumber:number) {
    
    let selectParam = {state:false, labelType:LABELTYPE.自定义标签};
    let dbList = await selectLabelListToPage(selectParam, (pageNumber-1)*10);
    let dataCount = await selectLabelCount(selectParam);

    let dataList = [];
    dbList.forEach(info => {
        dataList.push({
            labelName:info.labelName,
            goal:changeEnumValue(LABELGOAL, info.goal),
            id:info.id
        });
    });

    return {dataList, dataCount};
}


/**
 * 删除自定义标签
 * @param id 
 * @returns 
 */
export async function deleteLabel(id:string) {
    let labelInfo = await findOnceLabel(id);
    if (!labelInfo || !labelInfo.id) throw new BizError(ERRORENUM.目标数据不存在);
    if (labelInfo.labelType != LABELTYPE.自定义标签) throw new BizError(ERRORENUM.不能删除非自定义标签)

    labelInfo.state = true;

    await labelInfo.save();

    return {isSuccess:true};
}