package com.hfkj.service.impl;

import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.Base64Util;
import com.hfkj.dao.CmsContentMapper;
import com.hfkj.entity.*;
import com.hfkj.model.CmsContentModel;
import com.hfkj.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.FileTemplateResolver;

import javax.annotation.Resource;
import java.io.FileWriter;
import java.util.*;

@Service(value = "cmsContentService")
public class CmsContentServiceImpl implements CmsContentService {

    @Resource
    private CmsContentMapper cmsContentMapper;
    @Resource
    private CmsCategoryService cmsCategoryService;
    @Resource
    private CmsPatchService cmsPatchService;
    @Resource
    private FileUploadService fileUploadService;
    @Resource
    private CmsCategoryModuleService cmsCategoryModuleService;

    @Override
    @Transactional
    public int addContent(CmsContent cmsContent, List<CmsPatch> patchList, Map<String, String> paramsMap, String cmsPath) throws Exception {

        // 获取分类信息
        CmsCategory category = cmsCategoryService.getCategoryById(cmsContent.getCategoryId());
        if (category == null || category.getStatus() == 0) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.CMS_CATEGORY_NOT_FOUND, "");
        }
        cmsContent.setCategoryCode(category.getCode());

        // 添加内容
        cmsContentMapper.insertSelective(cmsContent);
        // 添加附件信息
        if (patchList != null && patchList.size() > 0) {
            cmsPatchService.addListPatch(patchList, cmsContent.getId());
        }

        // 发布内容
        if (cmsContent.getStatus() == 2) {
            String jumpUrl = createHtml(cmsContent.getId(), paramsMap,cmsPath);
            if (StringUtils.isNotBlank(jumpUrl)) {
                cmsContent.setJumpUrl(jumpUrl);
                cmsContentMapper.updateByPrimaryKey(cmsContent);
            }
        }

        return 1;
    }

    @Override
    public int updateContent(CmsContent cmsContent, String updateType, Map<String, String> paramsMap,String cmsPath) throws Exception {
        CmsContent content = cmsContentMapper.selectByPrimaryKey(cmsContent.getId());
        if (content == null || content.getStatus() == 0) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.CMS_CONTENT_NOT_FOUND, "");
        }

        if ("updateContent".equals(updateType)) {

            // 获取分类信息
            CmsCategory category = cmsCategoryService.getCategoryById(cmsContent.getCategoryId());
            if (category == null || category.getStatus() == 0) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.CMS_CATEGORY_NOT_FOUND, "");
            }
            cmsContent.setCategoryCode(category.getCode());

        } else if ("updateStatusOfContent".equals(updateType)) {

            // 发布内容
            if (cmsContent.getStatus() == 2) {
                String jumpUrl = createHtml(cmsContent.getId(), paramsMap,cmsPath);
                cmsContent.setJumpUrl(jumpUrl);
            } else {
                if (StringUtils.isNotBlank(content.getJumpUrl())) {
                    cmsContent.setJumpUrl(null);
                    fileUploadService.deleteFile(cmsPath + cmsContent.getJumpUrl());
                }
            }

        }

        return cmsContentMapper.updateByPrimaryKeyWithBLOBs(cmsContent);
    }

    @Override
    @Transactional
    public int delContent(Long id,String cmsPath) throws Exception {
        CmsContent content = cmsContentMapper.selectByPrimaryKey(id);
        if (content == null || content.getStatus() == 0) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.CMS_CONTENT_NOT_FOUND, "");
        }

        // 删除内容下的附件
        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("contentId", content.getId().toString());
        cmsPatchService.delPatchesByContentId(paramsMap);
        // 删除生成的页面
        if (StringUtils.isNotBlank(content.getJumpUrl())) {
            content.setJumpUrl(null);
            fileUploadService.deleteFile(cmsPath + content.getJumpUrl());
        }
        content.setStatus(0);
        content.setUpdateTime(new Date());
        return cmsContentMapper.updateByPrimaryKey(content);
    }

    @Override
    public CmsContent getContentById(Long id) throws Exception {
        return cmsContentMapper.selectByPrimaryKey(id);
    }

    @Override
    public CmsContentModel getContentDetail(Long id, String queryType) throws Exception {
        CmsContent content = cmsContentMapper.selectByPrimaryKey(id);
        if (content == null || content.getStatus() == 0) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.CMS_CONTENT_NOT_FOUND, "");
        }
        CmsContentModel contentModel = new CmsContentModel();
        BeanUtils.copyProperties(content, contentModel);

        // 查询分类信息
        CmsCategory category = cmsCategoryService.getCategoryById(content.getCategoryId());
        contentModel.setCategoryName(category.getName());

        if ("queryWithPatches".equals(queryType)) {
            // 查询内容的附件列表
            Map<String, String> paramsMap = new HashMap<>();
            paramsMap.put("contentId", id.toString());
            List<CmsPatch> patchList = cmsPatchService.getListPatch(paramsMap);

            contentModel.setPictures(new ArrayList<>());
            contentModel.setMusics(new ArrayList<>());
            contentModel.setVideos(new ArrayList<>());
            contentModel.setDocuments(new ArrayList<>());
            contentModel.setOthers(new ArrayList<>());
            for (CmsPatch patch : patchList) {
                switch (patch.getPatchType()){
                    case 1:
                        contentModel.getPictures().add(patch);
                        break;
                    case 2:
                        contentModel.getMusics().add(patch);
                        break;
                    case 3:
                        contentModel.getVideos().add(patch);
                        break;
                    case 4:
                        contentModel.getDocuments().add(patch);
                        break;
                    case 5:
                        contentModel.getOthers().add(patch);
                        break;
                }
            }
        }

        return contentModel;
    }

    @Override
    public List<CmsContentModel> getListContent(Map<String, String> paramsMap) throws Exception {
        return cmsContentMapper.getListContent(paramsMap);
    }

    @Override
    public List<CmsContent> getCorporateAdvertising() {
        CmsContentExample example = new CmsContentExample();
        example.createCriteria().andCategoryCodeEqualTo("CMS_CAROUSEL").andStatusEqualTo(2);
        example.setOrderByClause("create_time desc");
        List<CmsContent> cmsContents = cmsContentMapper.selectByExample(example);
        return cmsContents;
    }

    /**
     *  生成Html页面
     *  @params id-内容id
     */
    private String createHtml(Long id, Map<String, String> paramsMap,String cmsPath) throws Exception {
        if (id == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
        } else if (StringUtils.isBlank(paramsMap.get("moduleId"))) {
            return null;
        }

        // 查询内容详情
        CmsContentModel contentModel = getContentDetail(id, "queryWithPatches");
        // 查询模板信息
        Long moduleId = Long.valueOf(paramsMap.get("moduleId"));
        CmsCategoryModule categoryModule = cmsCategoryModuleService.getCategoryModuleById(moduleId);
        if (contentModel == null || categoryModule == null) {
            throw ErrorHelp.genException(SysCode.System, ErrorCode.CMS_CREATE_HTML_ERROR, "");
        }

        // 配置Thymeleaf解释器
        FileTemplateResolver resolver = new FileTemplateResolver();
        resolver.setPrefix(cmsPath);
        TemplateEngine engine = new TemplateEngine();
        engine.setTemplateResolver(resolver);
        Context ctx = new Context();
        ctx.setVariable("content", contentModel);

        // 渲染模板
        String strContentId = Base64Util.encode(contentModel.getId().toString());
        String filePath = cmsPath +  "/CMS/html/" + strContentId + ".html";
        FileWriter write = new FileWriter(filePath);
        engine.process(categoryModule.getModulePath(), ctx, write);

        return "/CMS/html/" + strContentId + ".html";
    }

}
