package com.house365.web.controller;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.house365.beans.entity.BaseAttachment;
import com.house365.beans.entity.UserEntity;
import com.house365.commons.system.FastDFSUtil;
import com.house365.rest.exception.ServiceException;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.FileLocationAttribute;
import com.house365.web.util.HttpUtil;
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.beans.response.UserResponse;
import com.house365.ws.interfaces.server.IAttachmentInterface;
import com.house365.ws.interfaces.server.IUser;
import com.house365.ws.system.ReturnResult;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 图片控制器<br>
 * 用于图片上传及列表展示
 *
 * @author chengjianfang
 * @version [v1.0.0, 2015年2月3日]
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Controller
@RequestMapping("/image")
public class ImageController extends BaseController {

    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ImageController.class);

    @Autowired
    private IAttachmentInterface attachmentInterface;

    @Autowired
    private IUser user;

    /**
     * 配置的最大上传文件大小
     */
    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字节) 修改为默认限定10M
        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 = 10485760;
        }
    }

    /**
     * 功能描述: <br>
     * 保存附件
     *
     * @param request
     * @author chengjianfang
     * @version [v1.0.0, 2015年1月29日]
     * @since [产品/模块版本](可选)
     */
    @RequestMapping(value = "addImage", method = {RequestMethod.POST})
    @ResponseBody
    public void addImage(MultipartHttpServletRequest request, PrintWriter out) {
        try {
            MultipartFile file = request.getFile("file");
            try {
                FileLocationAttribute fileLocationAttribute = new FileLocationAttribute(file);
                long fileSize = fileLocationAttribute.getSize();
                if (fileSize > MAX_SIZE_OF_UPLOAD_FILE) {
                    out.print("MAX_SIZE");
                } else {
                    String remotePath = FastDFSUtil.uploadFileByStream(file.getInputStream(), file.getOriginalFilename());
                    out.print(remotePath);
                }
            } catch (Exception ex) {
                LOGGER.error(ex.getMessage(), ex);
                out.print("failed");
            }
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            out.print("failed");
        }
    }

    @RequestMapping(value = "listSection/{resourceType}/{resourceId}/{bizType}/{maxSize}/{editAble}", method = {RequestMethod.GET, RequestMethod.POST})
    public String listSection(
            @PathVariable("resourceType") String resourceType, @PathVariable("resourceId") Integer resourceId,
            @PathVariable("bizType") Integer bizType, @PathVariable("maxSize") Integer maxSize,
            @PathVariable("editAble") boolean editAble, Model model
    ) {
        // 获取查询条件
        Map<String, Object> searchParams = new HashMap<>();
        searchParams.put("EQ_resourceType", resourceType);
        searchParams.put("EQ_resourceId", resourceId);
        searchParams.put("EQ_bizType", bizType);
        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("bizType", bizType);
        model.addAttribute("maxSize", maxSize);
        model.addAttribute("editAble", editAble);
        model.addAttribute("attachmentList", response.getObjectList());
        return getAutoUrl();
    }

    @RequestMapping(value = "addSection", method = {RequestMethod.POST})
    @ResponseBody
    public String addSection(MultipartHttpServletRequest request, BaseAttachment attachment) {
        try {
            Integer resourceId = attachment.getResourceId();
            Integer bizType = attachment.getBizType();
            LOGGER.error("******resourceId*******" + resourceId + "***********bizType**********" + bizType);
            MultipartFile file = request.getFile(attachment.getBizType() + "_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());
                String remotePath = FastDFSUtil.uploadFileByStream(file.getInputStream(), file.getOriginalFilename());
                attachment.setRemotePath(remotePath);
            } catch (Exception e) {
                throw new Exception(e.getMessage());
            }
            AttachmentRequest req = new AttachmentRequest();
            req.setAttachment(attachment);

            attachmentInterface.addAttachment(req);
            if (bizType == 1) {
                //通知IM
                UserEntity userEntity = new UserEntity();
                UserResponse userResponse = user.getUserById(resourceId);
                if (userResponse.getEntity() != null) {
                    userEntity = userResponse.getEntity();
                }
                String accId = userEntity.getAccId();
                String deciceId = com.house365.web.util.StringUtils.getRandomNumber(10);
                String randStr = com.house365.web.util.StringUtils.getRandomChars(13);
                String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
                String signature = HttpUtil.getSignature2(deciceId, randStr, timestamp);
                //获取accesstoken
                HashMap<String, String> accesstokenMap = new HashMap<>(5);
                accesstokenMap.put("version", "v3.0");
                //获取acceToken接口URl
                String getAccessTokenUrl = "http://yunxinim.house365.com/api/5b0cc34464a64";
                List<NameValuePair> tokenInParam = new ArrayList<>();
                tokenInParam.add(new BasicNameValuePair("app_id", "89962055"));
                tokenInParam.add(new BasicNameValuePair("app_secret", "pMHTUWAoOGSjaToIhHKwmQJKWZcAAvjN"));
                tokenInParam.add(new BasicNameValuePair("device_id", deciceId));
                tokenInParam.add(new BasicNameValuePair("rand_str", randStr));
                tokenInParam.add(new BasicNameValuePair("timestamp", timestamp));
                tokenInParam.add(new BasicNameValuePair("signature", signature));

                List<String> newTokenParams = new ArrayList<>();
                for (NameValuePair pair : tokenInParam) {
                    newTokenParams.add(pair.getName() + "=" + pair.getValue());
                }
                String newTokenUrl = getAccessTokenUrl + "?" + Joiner.on("&").join(newTokenParams);
                String tokenResult = "";
                tokenResult = HttpUtil.getHttpRequest(newTokenUrl, accesstokenMap, 100000, "utf-8");
                if (Strings.isNullOrEmpty(tokenResult)) {
                    throw new ServiceException("get token failed");
                }
                JSONObject json = JSONObject.fromObject(tokenResult);
                JSONObject jo = json.getJSONObject("data");
                String accessToken = jo.getString("access_token");
                LOGGER.error("******ACCESS_TOKEN*******" + accessToken);
                LOGGER.error("******RemotePath*******" + attachment.getRemotePath());
                //2.通知IM更新用户
                List<NameValuePair> cornetInParam = new ArrayList<>();
                cornetInParam.add(new BasicNameValuePair("accid", accId));
                cornetInParam.add(new BasicNameValuePair("avatar", attachment.getRemotePath()));
                HttpUtil.doPostWithHeader("http://yunxinim.house365.com/api/5b9235bea9f88", cornetInParam, accessToken, "");
            }
        } catch (Exception se) {
            se.getStackTrace();
        }
        return getAutoUrl("customerInfo");
    }

    /**
     * 删除方法
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "delete/{id}", method = {RequestMethod.GET})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public String deleteAttachment(@PathVariable(value = "id") Integer id) {
        // create request and response
        AttachmentResponse rsp = attachmentInterface.deleteAttachment(id);
        // 直接返回结果码，页面会根据结果码来处理
        return rsp.getResultCode();
    }


}
