package com.njcn.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.oss.constant.OssPath;
import com.njcn.oss.utils.FileStorageUtil;
import com.njcn.system.enums.ThemeEnum;
import com.njcn.system.mapper.ThemeMapper;
import com.njcn.system.pojo.constant.ThemeState;
import com.njcn.system.pojo.param.ThemeParam;
import com.njcn.system.pojo.po.Theme;
import com.njcn.system.service.IThemeService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hongawen
 * @since 2021-12-13
 */
@Service
@RequiredArgsConstructor
public class ThemeServiceImpl extends ServiceImpl<ThemeMapper, Theme> implements IThemeService {

    private final FileStorageUtil fileStorageUtil;

    @Override
    public boolean addTheme(ThemeParam themeParam) {
        checkThemeParam(themeParam,false);
        Theme theme = new Theme();
        theme.setName(themeParam.getName());
        theme.setColor(themeParam.getColor());
        theme.setActive(ThemeState.INACTIVATED);
        theme.setRemark(themeParam.getRemark());
        theme.setState(ThemeState.NORMAL);
        theme.setLogoUrl(generateBase64(themeParam.getLogoFile()));
        theme.setFaviconUrl(generateBase64(themeParam.getFaviconFile()));
        //v3参数
        theme.setMainAnimation(themeParam.getMainAnimation());
        theme.setElementUiPrimary(String.join(",", themeParam.getElementUiPrimary()));
        theme.setTableHeaderBackground(String.join(",", themeParam.getTableHeaderBackground()));
        theme.setTableHeaderColor(String.join(",", themeParam.getTableHeaderColor()));
        theme.setTableCurrent(String.join(",", themeParam.getTableCurrent()));
        theme.setMenuBackground(String.join(",", themeParam.getMenuBackground()));
        theme.setMenuColor(String.join(",", themeParam.getMenuColor()));
        theme.setMenuActiveBackground(String.join(",", themeParam.getMenuActiveBackground()));
        theme.setMenuActiveColor(String.join(",", themeParam.getMenuActiveColor()));
        theme.setMenuTopBarBackground(String.join(",", themeParam.getMenuTopBarBackground()));
        theme.setHeaderBarTabColor(String.join(",", themeParam.getHeaderBarTabColor()));
        theme.setHeaderBarBackground(String.join(",", themeParam.getHeaderBarBackground()));
        theme.setLogoPath(fileStorageUtil.uploadMultipart(themeParam.getLogoFile(), OssPath.THEME));
        theme.setFaviconPath(fileStorageUtil.uploadMultipart(themeParam.getFaviconFile(), OssPath.THEME));
        return this.save(theme);
    }

    @Override
    public boolean updateTheme(ThemeParam.ThemeUpdateParam themeParam) {
        checkThemeParam(themeParam,true);
        Theme theme = new Theme();
        theme.setLogoUrl(generateBase64(themeParam.getLogoFile()));
        theme.setFaviconUrl(generateBase64(themeParam.getFaviconFile()));
        BeanUtil.copyProperties(themeParam, theme);
        //v3参数
        theme.setMainAnimation(themeParam.getMainAnimation());
        theme.setElementUiPrimary(String.join(",", themeParam.getElementUiPrimary()));
        theme.setTableHeaderBackground(String.join(",", themeParam.getTableHeaderBackground()));
        theme.setTableHeaderColor(String.join(",", themeParam.getTableHeaderColor()));
        theme.setTableCurrent(String.join(",", themeParam.getTableCurrent()));
        theme.setMenuBackground(String.join(",", themeParam.getMenuBackground()));
        theme.setMenuColor(String.join(",", themeParam.getMenuColor()));
        theme.setMenuActiveBackground(String.join(",", themeParam.getMenuActiveBackground()));
        theme.setMenuActiveColor(String.join(",", themeParam.getMenuActiveColor()));
        theme.setMenuTopBarBackground(String.join(",", themeParam.getMenuTopBarBackground()));
        theme.setHeaderBarTabColor(String.join(",", themeParam.getHeaderBarTabColor()));
        theme.setHeaderBarBackground(String.join(",", themeParam.getHeaderBarBackground()));
        theme.setLogoPath(fileStorageUtil.uploadMultipart(themeParam.getLogoFile(), OssPath.THEME));
        theme.setFaviconPath(fileStorageUtil.uploadMultipart(themeParam.getFaviconFile(), OssPath.THEME));
        return this.updateById(theme);
    }

    @Override
    public List<Theme> getAllThemes() {
        return this.lambdaQuery().eq(Theme::getState,ThemeState.NORMAL).select().list();
    }

    @Override
    public Theme getTheme() {
        return this.lambdaQuery()
                .eq(Theme::getActive,ThemeState.ACTIVATION).one();
    }

    @Override
    public boolean deleteTheme(String id) {
        return this.lambdaUpdate()
                .set(Theme::getState, ThemeState.DELETE)
                .in(Theme::getId,id)
                .update();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean activateTheme(String id) {
        this.lambdaUpdate()
                .eq(Theme::getActive,ThemeState.ACTIVATION)
                .set(Theme::getActive, ThemeState.INACTIVATED)
                .update();
        return this.lambdaUpdate()
                .set(Theme::getActive, ThemeState.ACTIVATION)
                .in(Theme::getId,id)
                .update();
    }

    /**
     * 校验参数，
     * 1.检查是否存在相同名称的主题
     * 2.检查图片是否为空
     */
    private void checkThemeParam(ThemeParam themeParam, boolean isExcludeSelf) {
        if (themeParam.getLogoFile().isEmpty()) {
            throw new BusinessException(ThemeEnum.LOGO_FILE_BLANK);
        }
        if (themeParam.getFaviconFile().isEmpty()) {
            throw new BusinessException(ThemeEnum.FAVICON_FILE_BLANK);
        }
//        LambdaQueryWrapper<Theme> themeLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        themeLambdaQueryWrapper
//                .eq(Theme::getName, themeParam.getName())
//                .eq(Theme::getState, ThemeState.NORMAL);
//        //更新的时候，需排除当前记录
//        if (isExcludeSelf) {
//            if (themeParam instanceof ThemeParam.ThemeUpdateParam) {
//                themeLambdaQueryWrapper.ne(Theme::getId, ((ThemeParam.ThemeUpdateParam) themeParam).getId());
//            }
//        }
//        int countByAccount = this.count(themeLambdaQueryWrapper);
//        //大于等于1个则表示重复
//        if (countByAccount >= 1) {
//            throw new BusinessException(ThemeEnum.SAME_THEME_NAME);
//        }
    }

    /**
     * MultipartFile转换成base64
     */
    public static String generateBase64(MultipartFile file){
        String base64EncoderImg= null;
        try {
            BASE64Encoder bEncoder=new BASE64Encoder();
            String[] suffixArra= Objects.requireNonNull(file.getOriginalFilename()).split("\\.");
            String preffix="data:image/jpg;base64,".replace("jpg", suffixArra[suffixArra.length - 1]);
            base64EncoderImg = preffix + bEncoder.encode(file.getBytes()).replaceAll("[\\s*\t\n\r]", "");
        } catch (IOException e) {
            e.getMessage();
        }
        return base64EncoderImg;
    }


}
