package com.pqs9900.controller.root;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.njcn.pojo.commons.HttpResult;
import com.njcn.pojo.commons.SimpleValue;
import com.njcn.pojo.system.Theme;
import com.njcn.service.system.ThemeService;
import com.njcn.utils.PubUtils;
import com.njcn.utils.XssFilterUtil;

/**
 * @author hongawen
 * @date: 2019/9/27 10:47
 */
@Controller
@RequestMapping("theme")
public class ThemeController {
    private static final Logger logger = LoggerFactory.getLogger(ThemeController.class);

    @Resource
    private ThemeService themeService;
    
    private String logoName;
    private String faviconName;

    /**
     * 跳转修改主题页面
     */
    @GetMapping("modifytheme")
    public String modifyTheme() {
        return "business/root/modifyTheme";
    }


    /**
     * 获取logo图片
     */
    @PostMapping("logo")
    public void logo(HttpServletResponse resp, HttpSession session) {
        ServletOutputStream out;
        FileInputStream inStream = null;
        try {
            out = resp.getOutputStream();
            if (null != out) {
                String logPath = "/images/logo.png";
                logPath = session.getServletContext().getRealPath(logPath);
                inStream = new FileInputStream(logPath);
                BufferedImage image = ImageIO.read(inStream);
                ImageIO.write(image, "png", out);
            }
        } catch (IOException e) {
            logger.error("获取logo异常，原因为：" + e.toString());
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException e) {
                    logger.error("关闭输入流异常，异常为：" + e.toString());
                }
            }
        }
    }

    /**
     * 获取主题色
     */
    @PostMapping("getColor")
    @ResponseBody
    public HttpResult getColor() {
        HttpResult result;
        String color;
        try {
            color = themeService.getThemeColor();
            result = PubUtils.assignmentResult(color, 200, "获取主题色成功");
        } catch (Exception e) {
            logger.error(e.toString());
            result = PubUtils.assignmentResult("#006565", 500, "获取主题色失败");
        }

        return result;
    }

    /**
     * 获取主题信息
     */
    @PostMapping("getThemeInfo")
    @ResponseBody
    public HttpResult getThemeInfo() {
        HttpResult result;
        SimpleValue simpleValue;
        try {
            simpleValue = themeService.getThemeInfo();
            result = PubUtils.assignmentResult(simpleValue, 200, "获取主题信息成功");
        } catch (Exception e) {
            logger.error(e.toString());
            simpleValue = new SimpleValue();
            simpleValue.setName("国网主题");
            simpleValue.setValue("#006565");
            result = PubUtils.assignmentResult(simpleValue, 500, "获取主题信息失败");
        }
        return result;
    }

    /**
     * 获取主题信息
     */
    @PostMapping("getThemeList")
    @ResponseBody
    public HttpResult getThemeList() {
        HttpResult result;
        List<Theme> themes = new ArrayList<>();	
        try {
        	themes = themeService.getThemeList();
            result = PubUtils.assignmentResult(themes, 200, "获取主题信息成功");
        } catch (Exception e) {
            logger.error(e.toString());
            Theme theme = new Theme();	
            theme.setThemeDesc("国网");
            theme.setThemeColor("#006565");
            theme.setLogoName("gwlogo");
            theme.setFaviconName("gwfavicon");
            themes.add(theme);
            result = PubUtils.assignmentResult(themes, 500, "获取主题信息失败");
        }
        return result;
    }
    
    /**
     * 删除主题
     */
    @PostMapping("deleteTheme")
    @ResponseBody
    public HttpResult deleteTheme(String themeIndex) {
        HttpResult result;
        try {
        	themeService.deleteTheme(themeIndex);
            result = PubUtils.assignmentResult(null, 200, "激活主题成功");
        } catch (Exception e) {
            logger.error(e.toString());
            result = PubUtils.assignmentResult(null, 500, "激活主题失败");
        }
        return result;
    }
    
    /**
     * 激活主题
     */
    @PostMapping("activate")
    @ResponseBody
    public HttpResult activate(String themeIndex, HttpSession session) {
        HttpResult result;
        try {
        	Theme theme = themeService.activate(themeIndex);
        	this.logoName = theme.getLogoName();
        	this.faviconName = theme.getFaviconName();
            //更新没问题后，替换图片流
            replaceLogo(session);
            replaceFavicon(session);
            result = PubUtils.assignmentResult(null, 200, "激活主题成功");
        } catch (Exception e) {
            logger.error(e.toString());
            result = PubUtils.assignmentResult(null, 500, "激活主题失败");
        }
        return result;
    }
    
    /**
     * 上传logo
     */
    @PostMapping("/uploadLogo")
    @ResponseBody
    public HttpResult uploadLogo(@RequestParam(value = "file", required = false) MultipartFile file, HttpSession session) throws IOException {
        HttpResult result;
        String contentType = file.getContentType().substring(6);
        if (file.getSize() == 0) {
            result = PubUtils.assignmentResult(null, 501, "logo图片为空");
            return result;
        }
        //判断文件格式是否正确
        if (contentType.equalsIgnoreCase("png") || contentType.equalsIgnoreCase("jpg") || contentType.equalsIgnoreCase("jpeg")) {
            //临时logo的位置
            String logPath = "/images";
            logPath = session.getServletContext().getRealPath(logPath);
            String filename = file.getOriginalFilename();
            filename = filename.substring(filename.lastIndexOf(File.separator)+1);
            String tempLogPath = logPath + File.separator + filename;
            File temp = new File(tempLogPath);
            if (temp.isFile() && temp.exists()) {
                temp.delete();
            }
            file.transferTo(temp);
            this.logoName=filename;
            result = PubUtils.assignmentResult(filename, 200, "logo图片上传成功");
        } else {
            result = PubUtils.assignmentResult(null, 501, "logo图片格式非法");
        }
        return result;
    }

    /**
     * 上传favicon
     */
    @PostMapping("/uploadFavicon")
    @ResponseBody
    public HttpResult uploadFavicon(@RequestParam(value = "file", required = false) MultipartFile file, HttpSession session) throws IOException {
        HttpResult result;
        String contentType = file.getContentType().substring(6);
        if (file.getSize() == 0) {
            result = PubUtils.assignmentResult(null, 501, "图标为空");
            return result;
        }
        //判断文件格式是否正确
        if (contentType.equalsIgnoreCase("x-icon")) {
            //临时logo的位置
            String faviconPath = "/images";
            faviconPath = session.getServletContext().getRealPath(faviconPath);
            String filename = file.getOriginalFilename();
            filename = filename.substring(filename.lastIndexOf(File.separator)+1);
            String tempFaviconPath = faviconPath + File.separator + filename;
            File temp = new File(tempFaviconPath);
            if (temp.isFile() && temp.exists()) {
                temp.delete();
            }
            file.transferTo(temp);
            this.faviconName=filename;
            result = PubUtils.assignmentResult(filename, 200, "图标上传成功");
        } else {
            result = PubUtils.assignmentResult(null, 501, "图标格式非法");
        }
        return result;
    }

    /**
     * 更新主题
     */
    @PostMapping("/updateTheme")
    @ResponseBody
    public HttpResult updateTheme(String themeDesc, String color, HttpSession session) {
        HttpResult result;
        themeDesc = XssFilterUtil.dealString(themeDesc);
        color = XssFilterUtil.dealString(color);
        if (!PubUtils.patternDes10(themeDesc)) {
            result = PubUtils.assignmentResult(null, 500, "请输入1-10位的主题描述");
            return result;
        }
        if (!PubUtils.patternDes10(color)) {
            result = PubUtils.assignmentResult(null, 500, "请输入16进制颜色");
            return result;
        }
        try {
            themeService.updateTheme(themeDesc, color, this.logoName, this.faviconName);
//            //更新没问题后，替换图片流
//            replaceLogo(session);
//            replaceFavicon(session);
            result = PubUtils.assignmentResult(null, 200, "主题更新成功");
        } catch (Exception e) {
            logger.error("主题更新异常" + e.toString());
            result = PubUtils.assignmentResult(null, 500, "主题更新异常");
        }

        return result;
    }

    /**
     * 将刚刚上传的logo临时文件替换为正式logo
     */
    private void replaceLogo(HttpSession session) {
        //临时logo
        String imagePath = "/images";
        imagePath = session.getServletContext().getRealPath(imagePath);
        String tempLogoPath = imagePath + File.separator + this.logoName;
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(tempLogoPath);
            //目标logo
            String targetLogoPath = imagePath + File.separator + "logo.png";
            outputStream = new FileOutputStream(targetLogoPath);
            //进行复制操作
            int len = 0;
            byte[] byts = new byte[1024];
            while ((len = inputStream.read(byts)) != -1) {
                //注意：字节流会直接写入到文件当中，不用刷新缓存
                outputStream.write(byts, 0, len);
            }
        } catch (Exception e) {
            logger.error("替换logo图片流异常，异常为：" + e.toString());
        } finally {
            try {
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (Exception e) {
                logger.error("关闭流异常，异常为：" + e.toString());
            }
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
            } catch (Exception e) {
                logger.error("关闭流异常，异常为：" + e.toString());
            }
        }


    }


    /**
     * 将刚刚上传的图标临时文件替换为正式图标
     */
    private void replaceFavicon(HttpSession session) {
        //临时图标
        String imagePath = "/images";
        imagePath = session.getServletContext().getRealPath(imagePath);
        String tempFaviconPath = imagePath + File.separator + this.faviconName;
        //目标图标
        String targetFaviconPath = imagePath + File.separator + "favicon.ico";
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(tempFaviconPath);
            outputStream = new FileOutputStream(targetFaviconPath);
            int len;
            byte[] byts = new byte[1024];
            while ((len = inputStream.read(byts)) != -1) {
                outputStream.write(byts, 0, len);
            }
        } catch (IOException e) {
            logger.error("上传的图标替换为正式图标失败，原因为：" + e.toString());
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                logger.error("关闭流异常，异常为：" + e.toString());
            }
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                logger.error("关闭流异常，异常为：" + e.toString());
            }
        }
    }
}
