package com.engine.organization.entity.codesetting.bo;

import com.engine.organization.entity.codesetting.param.CodeBaseParam;
import com.engine.organization.entity.codesetting.param.CodeSaveDetailParam;
import com.engine.organization.entity.codesetting.param.CodeSaveParam;
import com.engine.organization.entity.codesetting.po.CodeRuleDetailPO;
import com.engine.organization.entity.codesetting.po.CodeRulePO;
import com.engine.organization.enums.DeleteTypeEnum;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import weaver.general.Util;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author weaver_cl
 * @Description:
 * @Date 2022/5/31
 * @Version V1.0
 **/
public class CodeSettingBO {

    public static CodeRulePO buildCodeRule(CodeSaveParam params,Long uid,Long codeRuleId) {

        StringBuilder sb = new StringBuilder();
        parseOneSelfType(params.getDateSerial(), sb);
        parseOneSelfType(params.getDeptSerial(), sb);
        parseOneSelfType(params.getJobtitlesSerial(), sb);

        CodeRulePO codeRulePO = CodeRulePO.builder()
                .serialType(params.getSerialType())
                .serialEnable(Optional.of(params.getSerialEnable()).orElse("0"))
                .oneselfType(sb.toString())
                .creator(uid)
                .deleteType(DeleteTypeEnum.NOT_DELETED.getValue())
                .updateTime(new Date())
                .build();
        if (codeRuleId == null) {
            codeRulePO.setCreateTime(new Date());
        }else {
            codeRulePO.setId(codeRuleId);
        }
        return codeRulePO;

    }

    public static List<CodeRuleDetailPO> bulidCodeDetailList(List<CodeSaveDetailParam> codeSaveDetailParams, Long uid,Long codeRuleId) {
        if(CollectionUtils.isEmpty(codeSaveDetailParams)) {
            return null;
        }

        return codeSaveDetailParams.stream().map(e -> CodeRuleDetailPO.builder()
                .coderuleId(codeRuleId)
                .ruleType(e.getRuletype())
                .ruleValue(e.getRulevalue())
                .showOrder(e.getShoworder())
                .creator(uid)
                .deleteType(DeleteTypeEnum.NOT_DELETED.getValue())
                .createTime(new Date())
                .updateTime(new Date())
                .build()
        ).collect(Collectors.toList());
    }


    /**
     * 解析构建单独流程类型
     * @param param
     * @param sb
     */
    private static void parseOneSelfType(CodeBaseParam param, StringBuilder sb) {
        if(Objects.nonNull(param)) {
            String enable = Util.null2String(param.getEnable(),"0");
            String key = param.getKey();
            if ("1".equals(enable) && StringUtils.isNotEmpty(key)) {
                sb.append(key);
                sb.append(",");
            }
        }
    }


}
