package com.microservices.cms.doc.domain;

import com.microservices.cms.utils.CmsConstants;
import com.microservices.common.core.exception.ServiceException;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author otto
 */
@Data
@ApiModel("文章输入对象")
public class CmsDocInputDto {
    /**
     * 文章名称
     */

    @ApiModelProperty(value = "文章名称", required = true)
    private String name;
    /**
     * 文章内容
     */

    @ApiModelProperty(value = "文章内容", required = true)
    private String content;
    /**
     * 文章头图
     */

    @ApiModelProperty(value = "文章头图")
    private String headImg;

    /**
     * 文章概要
     */
    @ApiModelProperty("文章概要")
    private String summary;

    /**
     * 文本编辑器类型
     */
    @ApiModelProperty("文本编辑器类型")
    private String editorType;
    /**
     * 关键词
     */
    @ApiModelProperty("关键词")
    private String keywords;

    public String getContent() {
        String base64decodedString;
        try {
            // 解码
            byte[] base64decodedBytes = Base64.getDecoder().decode(this.content);
            base64decodedString = new String(base64decodedBytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new ServiceException("文章内容的Base64编码格式不正确");
        }
        return base64decodedString;
    }

    public String getName() {
        if (name != null) {
            name = name.replaceAll(CmsConstants.DIR_SEPARATOR,
                    CmsConstants.DIR_SEPARATOR_REPLACE);
        }
        return name;
    }

    public CmsDoc toCmsDoc(CmsDoc dirDoc) {
        CmsDoc cmsDoc = new CmsDoc();
        cmsDoc.setName(this.getName());
        String fileName = this.getName() + CmsConstants.MARKDOWN_SUFFIX;
        cmsDoc.setFileName(fileName);
        cmsDoc.setFilePath(dirDoc.getName() + CmsConstants.DIR_SEPARATOR + fileName);
        cmsDoc.setSummary(this.getSummary());
        cmsDoc.setDirName(dirDoc.getName());
        cmsDoc.setIsDir(false);
        cmsDoc.setHeadImg(this.getHeadImg());
        cmsDoc.setDeptId(dirDoc.getDeptId());
        cmsDoc.setEditorType(this.editorType);
        cmsDoc.setKeywords(this.keywords);
        return cmsDoc;
    }
}
