package com.house365.web.controller;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.house365.beans.po.BaseAttachment;
import com.house365.commons.system.FastDFSUtil;
import com.house365.rest.context.CmConstant;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.FileLocationAttribute;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.ws.beans.request.AttachmentListRequest;
import com.house365.ws.beans.request.AttachmentRequest;
import com.house365.ws.beans.response.AttachmentListResponse;
import com.house365.ws.beans.response.AttachmentResponse;
import com.house365.ws.interfaces.server.IAttachmentInterface;
import com.house365.ws.system.ReturnResult;

/**
 * 图片控制器<br>
 * 用于图片上传及列表展示
 *
 * @author chengjianfang
 * @version [v1.0.0, 2015年2月3日]
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/image")
public class ImageController extends BaseController {
    /**
     * 配置的最大上传文件大小
     */
    private static final String MAX_SIZE_UPLOAD_FILE = MemoryPropertyPlaceholderConfigurer.getContextProperty(
            "upload.file.maxsize");

    /**
     * 最大上传文件大小
     */
    private static final long MAX_SIZE_OF_UPLOAD_FILE;

    static {
        // 如果配置了大小，则使用配置大小，如果没有配置，则限定为2M(2*1024*1024字节)
        if (StringUtils.isNotEmpty(MAX_SIZE_UPLOAD_FILE) && NumberUtils.isNumber(MAX_SIZE_UPLOAD_FILE)) {
            MAX_SIZE_OF_UPLOAD_FILE = Long.parseLong(MAX_SIZE_UPLOAD_FILE);
        } else {
            MAX_SIZE_OF_UPLOAD_FILE = 2097152;
        }
    }

    @Autowired
    IAttachmentInterface attachmentInterface;

    /**
     * 功能描述: <br>
     * 简单附件列表查询
     *
     * @param resourceType 资源类型
     * @param resourceId   资源ID
     * @param maxSize      最大允许上传图片数
     * @param editAble     是否可编辑
     * @param model        视图模型
     * @param request      请求
     * @return
     * @author chengjianfang
     * @version [v1.0.0, 2015年1月28日]
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "listSection/{resourceType}/{resourceId}/{maxSize}/{editAble}/{isCreate}", method = {RequestMethod.GET, RequestMethod.POST})
    public String listSection(
            @PathVariable("resourceType") String resourceType, @PathVariable("resourceId") Integer resourceId,
            @PathVariable("maxSize") Integer maxSize, @PathVariable("editAble") boolean editAble,
            @PathVariable("isCreate") boolean isCreate, Model model, HttpServletRequest request
    ) {
        // 获取查询条件
        Map<String, Object> searchParams = new HashMap<String, Object>();
        searchParams.put("EQ_resourceType", resourceType);
        searchParams.put("EQ_resourceId", resourceId);
        //searchParams.put("EQ_remark", userId);
        AttachmentListRequest req = new AttachmentListRequest();
        req.setSearchParams(searchParams);
        req.setOrderColumn("id");
        req.setOrderMode("asc");
        AttachmentListResponse response = attachmentInterface.getAttachments(req);
        // 业务异常，直接跳转到列表页面
        if (!StringUtils.equals(response.getResultCode(), ReturnResult.SUCCESS.getResultCode())) {
            addErrorMessage(model, ReturnResult.FAIL.getResultMessage() + response.getResultMessage());
            return getAutoUrl();
        }
        model.addAttribute("resourceType", resourceType);
        model.addAttribute("resourceId", resourceId);
        model.addAttribute("maxSize", maxSize);
        model.addAttribute("editAble", editAble);
        model.addAttribute("attachmentList", response.getObjectList());
        /*if(isCreate)//创建页面每次清空
        {
        	model.addAttribute("attachmentList", null);
        }
        else
        {
        	model.addAttribute("attachmentList", response.getObjectList());
        }*/
        return getAutoUrl();
    }

    /**
     * 功能描述: <br>
     * 保存附件
     *
     * @param request
     * @param attachment
     * @param model
     * @author chengjianfang
     * @version [v1.0.0, 2015年1月29日]
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "addSection", method = {RequestMethod.POST})
    @ResponseBody
    public String addSection(MultipartHttpServletRequest request, BaseAttachment attachment, Model model) {
        String remotePath = "";
        String isGetImageInfo = request.getParameter("getImageInfo");
        BufferedImage sourceImg = null;
        try {
            MultipartFile file = request.getFile(attachment.getResourceType() + "_file");
            try {
                FileLocationAttribute fileLocationAttribute = new FileLocationAttribute(file);
                long fileSize = fileLocationAttribute.getSize();
                if (fileSize > MAX_SIZE_OF_UPLOAD_FILE) {
                    return "MAX_SIZE";
                }
                attachment.setSize(fileSize);
                attachment.setSuffix(fileLocationAttribute.getSuffix());
                remotePath = FastDFSUtil.uploadFileByStream(file.getInputStream(), file.getOriginalFilename());
                if (isGetImageInfo != null && "true".equals(isGetImageInfo)) {
                    sourceImg = ImageIO.read(file.getInputStream());
                }

                attachment.setRemotePath(remotePath);
                attachment.setRemark(String.valueOf(request.getSession().getAttribute(CmConstant.USERID)));
            } catch (Exception e) {
                throw new Exception(e.getMessage());
            }
            AttachmentRequest req = new AttachmentRequest();
            req.setAttachment(attachment);
            attachmentInterface.addAttachment(req);

            model.addAttribute("remotePath", remotePath);
        } catch (Exception se) {
            se.getStackTrace();
            return "{\"error\":1}";
        }
        if (isGetImageInfo != null && "true".equals(isGetImageInfo) && sourceImg != null) {
            return "{\"error\":0, \"url\":\"" + remotePath + "\", \"width\":\"" + sourceImg.getWidth() + "\", \"height\":\"" + sourceImg.getHeight() + "\"}";
        }
        return "{\"error\":0, \"url\":\"" + remotePath + "\"}";
    }


    /**
     * 功能描述: <br>
     * 保存网页评论图片
     *
     * @param request
     * @param attachment
     * @param model
     * @author chengjianfang
     * @version [v1.0.0, 2015年1月29日]
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "addWebCommentSection", method = {RequestMethod.POST})
    @ResponseBody
    public String addWebCommentSection(MultipartHttpServletRequest request, BaseAttachment attachment, Model model) {
        //基础宽高
        int baseHeight = 480;
        int baseWidth = 320;
        String remotePath = "";
        String isGetImageInfo = request.getParameter("getImageInfo");
        BufferedImage sourceImg = null;
        try {
            MultipartFile file = request.getFile(attachment.getResourceType() + "_file");

            //图片转换
            //ImageCompress imp = new ImageCompress(file.getInputStream());

            try {
                FileLocationAttribute fileLocationAttribute = new FileLocationAttribute(file);
                long fileSize = fileLocationAttribute.getSize();
                if (fileSize > MAX_SIZE_OF_UPLOAD_FILE) {
                    return "MAX_SIZE";
                }
                attachment.setSize(fileSize);
                attachment.setSuffix(fileLocationAttribute.getSuffix());
                remotePath = FastDFSUtil.uploadFileByStream(file.getInputStream(), file.getOriginalFilename());
                if (isGetImageInfo != null && "true".equals(isGetImageInfo)) {
                    sourceImg = ImageIO.read(file.getInputStream());
                }
                attachment.setRemotePath(remotePath);
                attachment.setRemark(String.valueOf(request.getSession().getAttribute(CmConstant.USERID)));
            } catch (Exception e) {
                throw new Exception(e.getMessage());
            }
            AttachmentRequest req = new AttachmentRequest();
            req.setAttachment(attachment);
            attachmentInterface.addAttachment(req);

            model.addAttribute("remotePath", remotePath);
        } catch (Exception se) {
            se.getStackTrace();
            return "{\"error\":1}";
        }
        if (isGetImageInfo != null && "true".equals(isGetImageInfo) && sourceImg != null) {
            return "{\"error\":0, \"url\":\"" + remotePath + "\", \"width\":\"" + sourceImg.getWidth() + "\", \"height\":\"" + sourceImg.getHeight() + "\"}";
        }
        return "{\"error\":0, \"url\":\"" + remotePath + "\"}";
    }

    /**
     * 功能描述: <br>
     * 保存kindeditor上传的文件
     *
     * @param request
     * @param attachment
     * @param model
     * @author chengjianfang
     * @version [v1.0.0, 2015年1月29日]
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "addSectionPic", method = {RequestMethod.POST}, produces = "text/html;charset=UTF-8;")
    @ResponseBody
    public String addSectionPic(MultipartHttpServletRequest request, BaseAttachment attachment, Model model) {
        String remotePath = "";
        try {
            MultipartFile file = request.getFile("imgFile");

            try {
                FileLocationAttribute fileLocationAttribute = new FileLocationAttribute(file);
                long fileSize = fileLocationAttribute.getSize();
                if (fileSize > MAX_SIZE_OF_UPLOAD_FILE) {
                    return "MAX_SIZE";
                }

                remotePath = FastDFSUtil.uploadFileByStream(file.getInputStream(), file.getOriginalFilename());
            } catch (Exception e) {
                throw new Exception(e.getMessage());
            }
            model.addAttribute("remotePath", remotePath);
        } catch (Exception se) {
            se.getStackTrace();
        }

        return "{\"error\":0, \"url\":\"" + remotePath + "\"}";
    }


    /**
     * 功能描述: <br>
     * 删除附件
     *
     * @param id    附件编号
     * @param model 数据模型
     * @return
     * @author chengjianfang
     * @version [v1.0.0, 2015年2月3日]
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "delete/{id}", method = {RequestMethod.DELETE})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public String deleteAttachment(@PathVariable(value = "id") Integer id, Model model) {
        // create request and response
        AttachmentResponse rsp = new AttachmentResponse();
        rsp = attachmentInterface.deleteAttachment(id);
        // 直接返回结果码，页面会根据结果码来处理
        return rsp.getResultCode();
    }

    /**
     * 功能描述: <br>
     * 获取路径
     *
     * @param id 附件编号
     * @return
     * @author chengjianfang
     * @version [v1.0.0, 2015年1月29日]
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "getUrl/{id}", method = {RequestMethod.GET})
    @ResponseBody
    public String getUrl(@PathVariable("id") Integer id) {
        AttachmentResponse rsp = attachmentInterface.getAttachment(id);
        BaseAttachment attachment = rsp.getAttachment();
        if (null == attachment) {
            return null;
        }
        return attachment.getRemotePath();
    }
}
