package com.cftech.mp.wechat.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.accounts.service.MpAccountsService;
import com.cftech.core.scope.OrderType;
import com.cftech.core.sql.Conds;
import com.cftech.core.sql.Sort;
import com.cftech.core.util.Constants;
import com.cftech.core.util.StringUtils;
import com.cftech.mp.wechat.model.Image;
import com.cftech.mp.wechat.service.ImageService;
import com.cftech.sys.security.PermissionSign;
import com.cftech.sys.security.UserUtils;
import net.sf.json.JSONArray;
import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.mp.api.wxsendmsg.JwSendMessageAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/** 
 * @author 作者 lisw: 
 * @version 创建时间：2016年11月30日 上午10:58:06 
 * 类说明 
 */
@RequestMapping("/a/imageMedia")
@Controller
public class ImageController {
	
	
	@Autowired
	private ImageService imageService;
	
	@Autowired
	private MpAccountsService accountsService;

	@RequestMapping(value = "/imageMediaList",method = {RequestMethod.GET,RequestMethod.POST})
	@RequiresPermissions(value=PermissionSign.IMAGMEDIA_VIEW)
	public String imageMediaList(){
		return "managerwechat/ImageMediaList";
	}
	
	
	@RequestMapping(value="/fetchData",method = {RequestMethod.GET,RequestMethod.POST})
	@RequiresPermissions(value=PermissionSign.IMAGMEDIA_VIEW)
	@ResponseBody
	public JSONObject imageMediaFetchData(HttpServletRequest request, int iDisplayStart, int iDisplayLength){
		 Long id=UserUtils.getmpaccounts(request);
			Sort sort = new Sort("updatetime", OrderType.DESC); 
			Conds conds = new Conds();
			conds.equal("accountsid", id);
			conds.equal("delflag", Constants.DEL_FLAG_0);
			JSONObject returnObj = new JSONObject();
			List<Image> images = imageService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
			// 获得总数
			int userCounts = imageService.count(conds);
			returnObj.put("iTotalRecords", userCounts);
			returnObj.put("iTotalDisplayRecords", userCounts);
			returnObj.put("aaData", images);
			return returnObj;
	}
	
	@RequestMapping(value="/imageForm",method = {RequestMethod.GET,RequestMethod.POST})
	@RequiresPermissions(value=PermissionSign.IMAGMEDIA_EDIT)
	public String imageForm(Image image,Model model){
		if(image.getId()!=null){
			image = imageService.fetchById(image.getId());
			model.addAttribute("image", image);
		}
		return "managerwechat/ImageMediaForm";
	}
	
	@RequestMapping(value="/addImageForm",method=RequestMethod.POST)
	@RequiresPermissions(value=PermissionSign.IMAGE_TEXT_EDIT)
	@ResponseBody
	public JSONObject imageForm(HttpServletRequest request,Image image,@RequestParam(value="file",required=false) MultipartFile file){
		JSONObject rtnJson = new JSONObject();
		Long id = UserUtils.getmpaccounts(request);
		if(file.getSize()>1000*1000){//文件过大
			rtnJson.put("errorNo",3);
			return rtnJson;
		}
		if(file!=null){
			if((StringUtils.equals(file.getContentType(), "image/jpeg") || StringUtils.equals(file.getContentType(), "image/png"))){
				try {
					//图片上传到微信官方
					String url=JwSendMessageAPI.UploadImageurl(accountsService.getDetail(id).getAccesstoken(), file.getInputStream(), file.getOriginalFilename());

					//Map<String,Object> map = UploadUtils.uploadImageFilesByQcloudInputStearm(request, "wechat", file,"/aosmith/wechatImage/");
					Map<String,Object> map = new HashedMap();
					//图片存到本地服务器
					if(map!=null && map.containsKey("fileUrl")){
						String fileUrl=map.get("fileUrl").toString();
						image.setQcloudUrl(fileUrl);
					}
					if(StringUtils.isNotBlank(url)){
						image.setWxUrl(url);
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				rtnJson.put("errorNo",4);
			}
			
		}
		try {
			if(image.getId()!=null){//修改
				
				imageService.update(image);
				rtnJson.put("errorNo",2);
			}else{
				image.setCreateby(UserUtils.getUser().getId());
				image.setUpdateby(UserUtils.getUser().getId());
				image.setDelflag(Constants.DEL_FLAG_0);
				image.setAccountsid(id);
				imageService.save(image);
				rtnJson.put("errorNo",0);
			}
		} catch (Exception e) {
			e.printStackTrace();
			rtnJson.put("errorNo",1);
		}
		return rtnJson;
	}
	
	
	@RequestMapping(value="/imageDel",method = {RequestMethod.POST})
	@RequiresPermissions(value=PermissionSign.IMAGMEDIA_EDIT)
	@ResponseBody
	public JSONObject imageDel(Long id){
		JSONObject rtnJson = new JSONObject();
		try {
			imageService.delete(id);
			rtnJson.put("errorNo",0);
		} catch (Exception e) {
			rtnJson.put("errorNo",1);
		}
		return rtnJson;
	}
}
 