package com.cftech.mp.wechat.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.accounts.model.MpAccountsEntity;
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.core.util.UploadUtils;
import com.cftech.mp.wechat.model.Imagetext;
import com.cftech.mp.wechat.service.ImagetextService;
import com.cftech.sys.model.User;
import com.cftech.sys.security.PermissionSign;
import com.cftech.sys.security.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.filters.TagNameFilter;
import org.htmlparser.tags.ImageTag;
import org.htmlparser.util.NodeList;
import org.htmlparser.util.ParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.ResponseBody;

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

/** 
 * @author 作者 lisw: 
 * @version 创建时间：2016年10月25日 下午6:32:13 
 * 图文
 */
@Controller
@RequestMapping("/a/imagetext")
public class ImageTextController {
	
	private static final Logger logger = LoggerFactory.getLogger(ImageTextController.class);
	
	@Autowired
	private ImagetextService imageService;
	
	@Autowired
	private MpAccountsService accountsService;
	

	/**
	 * 
	 * @param imageText
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/list",method = {RequestMethod.GET,RequestMethod.POST})
	@RequiresPermissions(value=PermissionSign.IMAGE_TEXT_VIEW)
	public String list(Imagetext imageText,Model model){
		model.addAttribute("imageText",imageText);
		return "managerwechat/imagetextlist";
	}
	
	/**
	 * 获取图文信息数据
	 * @param request
	 * @param iDisplayStart
	 * @param iDisplayLength
	 * @param imagetext
	 * @return
	 */
	@RequestMapping(value="/fetchData",method = {RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public JSONObject fetchData(HttpServletRequest request, int iDisplayStart, int iDisplayLength, Imagetext imagetext){
		 Long id=UserUtils.getmpaccounts(request);
		Sort sort = new Sort("updatetime", OrderType.DESC); 
		Conds conds = new Conds();
		conds.equal("accountsid", id);
		if(StringUtils.isNotBlank(imagetext.getTitle())){
			conds.like("title", imagetext.getTitle());
		}
		conds.equal("delflag", Constants.DEL_FLAG_0);
		JSONObject returnObj = new JSONObject();
		List<Imagetext> imageText = imageService.fetchSearchByPage(conds, sort, iDisplayStart, iDisplayLength);
		// 获得总数
		int userCounts = imageService.count(conds);
		returnObj.put("iTotalRecords", userCounts);
		returnObj.put("iTotalDisplayRecords", userCounts);
		returnObj.put("aaData", imageText);
		return returnObj;
	}
	
	@RequestMapping(value="/imageTextForm",method = {RequestMethod.GET,RequestMethod.POST})
	@RequiresPermissions(value=PermissionSign.IMAGE_TEXT_EDIT)
	public String fetchData(HttpServletRequest request,Model model,Imagetext imageText){
		if(imageText.getId()!=null){//修改
			imageText=imageService.fetchById(imageText.getId());
		}
		model.addAttribute("imageText", imageText);
		return "managerwechat/imagetextform";
	}
	
	
	/**
	 * 添加图文，修改图文方法
	 * @param request
	 * @param model
	 * @param imageText
	 * @return
	 */
	@RequestMapping(value="/addFileUpload",method=RequestMethod.POST)
	@RequiresPermissions(value=PermissionSign.IMAGE_TEXT_EDIT)
	@ResponseBody
	public JSONObject addFileUpload(HttpServletRequest request,Model model,Imagetext imageText){
		JSONObject rtnJson= new JSONObject();
		User user=UserUtils.getUser();
		
		Long accountsid = UserUtils.getmpaccounts(request);
		
		MpAccountsEntity entity =accountsService.getDetail(accountsid);
		
		rtnJson.put("errorNo",0);
		try {
			Map<String, Object> uploadResult =  UploadUtils.uploadImageFilesByQcloud(request,"imagetext","/aosmith/imagetext/");
			//作者
			imageText.setAuthor(uploadResult.get("author")!=null?uploadResult.get("author").toString():null);
			//内容
			imageText.setContent(uploadResult.get("editorValue")!=null?uploadResult.get("editorValue").toString():null);
			//删除标识
			imageText.setDelflag(Constants.DEL_FLAG_0);
			//描述
			imageText.setDescription(uploadResult.get("description")!=null?uploadResult.get("description").toString():null);
			//图片URL
			if(StringUtils.isNotBlank(uploadResult.get("picUrl").toString())){
//				/**
//				 * 上传图片后，如果需要上传到MP，上传
//				 */
				imageText.setPicUrl(uploadResult.get("picUrl").toString());
//				if(StringUtils.equals(imageText.getIsThumbMedia(),"1")){
//					WxMediaForMaterial wx = new WxMediaForMaterial();
//					File file = new File(uploadResult.get("picUrl").toString());
//					InputStream stream = FileUtils.getInputStream(uploadResult.get("picUrl").toString());
//					wx.setFileName(file.getName());
//					wx.setInputStream(stream);
//					wx.setType("image");
//					WxMediaForMaterialResponse response = JwMediaAPI.uploadMediaFileByMaterial(entity.getAccesstoken(), wx);
//					if(response!=null){
//						imageText.setThumbMediaId(response.getMedia_id());
//					}else{
//						rtnJson.put("errorNo", 3);
//						return rtnJson;
//					}
//				}
			}
			//阅读全文
			imageText.setReadDetail(uploadResult.get("readDetail")!=null?uploadResult.get("readDetail").toString():null);
			//标题
			imageText.setTitle(uploadResult.get("title")!=null?uploadResult.get("title").toString():null);
			
			
			
			if(StringUtils.isNotBlank(uploadResult.get("id").toString())){//修改
//				Imagetext imageTemp =  imageService.fetchById(Long.valueOf(uploadResult.get("id").toString()));
//				if(StringUtils.equals(imageTemp.getIsThumbMedia(),"0") && StringUtils.equals(imageText.getIsThumbMedia(), "1") &&StringUtils.isBlank(uploadResult.get("picUrl").toString())){
//					/**
//					 * 如果原本未上传到温馨，并且此次未更改图片且改为上传到微信，此时上传到微信
//					 * 更改图片，上传到操作，见上面操作
//					 */
//					WxMediaForMaterial wx = new WxMediaForMaterial();
//					File file = new File(imageTemp.getPicUrl());
//					InputStream stream = FileUtils.getInputStream(imageTemp.getPicUrl());
//					wx.setFileName(file.getName());
//					wx.setInputStream(stream);
//					wx.setType("image");
//					WxMediaForMaterialResponse response = JwMediaAPI.uploadMediaFileByMaterial(entity.getAccesstoken(), wx);
//					if(response!=null){
//						imageText.setThumbMediaId(response.getMedia_id());
//					}else{
//						rtnJson.put("errorNo", 3);
//						return rtnJson;
//					}
//				} 
				
				//修改者
				imageText.setId(Long.valueOf(uploadResult.get("id").toString()));
				imageText.setUpdateBy(user.getId());
				imageService.update(imageText);
				rtnJson.put("errorNo", 2);
			}else{//保存
				//公众号ID 
				imageText.setAccountsid(UserUtils.getmpaccounts(request));
				//创建者
				imageText.setCreateBy(user.getId());
				//修改者
				imageText.setUpdateBy(user.getId());
				imageService.save(imageText);
			}
		} catch (Exception e) {
			rtnJson.put("errorNo",1);
			logger.info(e.getMessage());
		}
		return rtnJson;
	}
	
	@RequestMapping(value="/remove",method = {RequestMethod.POST})
	@ResponseBody
	@RequiresPermissions(value=PermissionSign.IMAGE_TEXT_EDIT)
	public JSONObject remove(Long id){
		JSONObject rtnJson = new JSONObject();
		rtnJson.put("errorNo",0);
		try {
			if(id!=null){
				imageService.delete(id);
			}
		} catch (Exception e) {
			rtnJson.put("errorNo",1);
			logger.info("删除图文出现异常:"+e.getMessage());
		}
		return rtnJson;
	} 
	/**
	 * 多个ID查询图文集合
	 * @return
	 */
	@RequestMapping(value="/seachImageText",method = {RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public JSONObject seachImageText(String ids){
		String[] id = ids.split(",");
		JSONObject rtnJson = new JSONObject();
		rtnJson.put("errorNo",0);
		Conds conds = new Conds();
		conds.in("id",id);
		List<Imagetext> imageText = imageService.fetchSearchByInPage(conds,ids.substring(0,ids.length()-1));
//		JsonConfig jsonConfig = new JsonConfig();
//		jsonConfig.registerJsonValueProcessor(java.sql.Timestamp.class,
//				new JsonDateValueProcessor());
//		JSONArray array = JSONArray.fromObject(imageText,jsonConfig);
//		rtnJson.put("data",array);
		rtnJson.put("data",imageText);
		return rtnJson;
	}
	
	
	
	/**
	 * 将HTML内容中的img标签，全部上传到微信官方。
	 * @param args
	 * @throws ParserException
	 */
	
	
	public static void main(String[] args) throws ParserException {
		 Parser parser =new Parser("<img src='123'><img src='123'><img src='123'>");
         NodeFilter filter = new TagNameFilter ("img");  
         NodeList nodes = parser.extractAllNodesThatMatch(filter);
         Node eachNode = null;  
         ImageTag imageTag = null;  
         String oldSrcPath = null;   
         if (nodes != null)  
         {  
//           遍历所有的img节点  
             for (int i = 0; i < nodes.size(); i++)   
             {  
                 eachNode = (Node)nodes.elementAt(i);  
                 if (eachNode instanceof ImageTag)   
                 {  
                     imageTag = (ImageTag)eachNode;  
//                   获得html文本的原来的src属性  
                     oldSrcPath = imageTag.getAttribute("src");  
                     System.out.println(oldSrcPath);
                 }  
             }  
         }  
	}
}
 