package com.inkasso.factoring.common.dict.impl;

import com.inkasso.adapter.util.CodeUtil;
import com.inkasso.auth.exception.ValidatorException;
import com.inkasso.factoring.common.dict.Dict;
import com.inkasso.factoring.dict.entity.Dictionary;
import com.inkasso.factoring.dict.service.DictionaryService;

/**
 * @author JiaYf
 * @date 2021.10.19
 */
public class InvoiceDict extends Dict {
    /**
     * 编码
     */
    public static String CODE = "invoiceStatus";
    /**
     * 中文名称
     */
    public static String CNAME = "销售发票状态";

    /**
     * 子项枚举
     */
    public static enum ChildEnum {
        /**
         * 已创建
         */
        CREATE("invoice_create", "已申请"),

        /**
         * 已驳回
         **/
        OVERRULE("invoice_overrule", "已驳回"),

        /**
         * 已通过
         */
        PASS("invoice_pass", "已开票");
        /**
         * 编码
         */
        private String code;
        /**
         * 名称
         */
        private String cname;

        ChildEnum(String code, String cname) {
            this.code = code;
            this.cname = cname;
        }

        public String getCode() {
            return code;
        }

        public String getCname() {
            return cname;
        }
    }

    @Override
    public void add(int gradation) {
        Dictionary domain = addDomainDictionary(null, gradation, dictionaryService);
        if (domain == null) {
            throw new ValidatorException(CodeUtil.FAIL, "验收单状态字典新增失败");
        }
        for (FileModuleDict.ChildEnum child : FileModuleDict.ChildEnum.values()) {
            addChildEnumDictionary(domain.getId(), child);
        }
    }

    private Dictionary addChildEnumDictionary(Long parentId, FileModuleDict.ChildEnum child) {
        Dictionary dictionary = new Dictionary();
        dictionary.setParentId(parentId);
        dictionary.setName(child.getCname());
        dictionary.setCode(child.getCode());
        dictionary.setGradation(child.ordinal());
        return dictionaryService.add(dictionary);
    }

    private Dictionary addDomainDictionary(Long parentId, int gradation, DictionaryService dictionaryService) {
        Dictionary dictionary = new Dictionary();
        dictionary.setParentId(parentId);
        dictionary.setName(CNAME);
        dictionary.setCode(CODE);
        dictionary.setGradation(gradation);
        return dictionaryService.add(dictionary);
    }
}
