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.mp.wechat.model.Qrcode;
import com.cftech.mp.wechat.model.QrcodeDto;
import com.cftech.mp.wechat.service.QrcodeService;
import com.cftech.sys.security.PermissionSign;
import com.cftech.sys.security.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.mp.api.core.exception.WexinReqException;
import org.mp.api.wxaccount.JwAccountAPI;
import org.mp.api.wxaccount.model.WxQrcode;
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.sql.Timestamp;
import java.util.Date;
import java.util.List;

/** 
 * @author 作者 mb: 
 * @version 创建时间：2016年10月31日 上午11:00:34 
 * 二维码 
 */
@Controller
@RequestMapping("/a/wx/qrcode")
public class QrcodeController {
	
	@Autowired
	private QrcodeService qrcodeService;
	
	@Autowired
	private MpAccountsService mpAccountService;
	
	
	@RequestMapping(value={"list",""},method={RequestMethod.GET,RequestMethod.POST})
	@RequiresPermissions(value=PermissionSign.QRCODE_VIEW)
	public String list(Model model,QrcodeDto qrcode){
		model.addAttribute("qrcode",qrcode);
		return "managerwechat/qrcodelist";
	}
	
	@RequestMapping(value="fetchData",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public JSONObject fetchData(HttpServletRequest request, int iDisplayStart, int iDisplayLength, QrcodeDto qrCode){
		 Long id=UserUtils.getmpaccounts(request);
			Sort sort = new Sort("update_time", OrderType.DESC); 
			Conds conds = new Conds();
			conds.equal("t.accountsid", id);
			if(StringUtils.isNotBlank(qrCode.getStoreName())){//门店名字搜索
				conds.like("s.name",qrCode.getStoreName());
			}
			if(StringUtils.isNotBlank(qrCode.getSence())){//ID
				conds.equal("t.sence", qrCode.getSence());
			}
			conds.equal("t.del_flag", Constants.DEL_FLAG_0);
		    JSONObject returnObj = new JSONObject();
			List<QrcodeDto> imageText = qrcodeService.fetchSearchByPageStore(conds, sort, iDisplayStart, iDisplayLength);
			// 获得总数
			int userCounts = qrcodeService.countStore(conds);
			returnObj.put("iTotalRecords", userCounts);
			returnObj.put("iTotalDisplayRecords", userCounts);
			returnObj.put("aaData", imageText);
			return returnObj;
	}
	
	@RequestMapping(value="qrcodeform",method={RequestMethod.GET,RequestMethod.POST})
	@RequiresPermissions(value=PermissionSign.QRCODE_VIEW)
	public String replyform(Qrcode qrcode,Model model){
		if(qrcode!=null && qrcode.getId()!=null){
			qrcode = qrcodeService.fetchById(qrcode.getId());
		}
		model.addAttribute("qrcode", qrcode);
		return "managerwechat/qrcodeform";
	}
	
	@RequestMapping(value="addqrcode",method={RequestMethod.POST})
	@RequiresPermissions(value=PermissionSign.QRCODE_EDIT)
	@ResponseBody
	public JSONObject addqrcode(Qrcode qrcode,HttpServletRequest request){
		WxQrcode wxqrcode=null;
		JSONObject rtnJson = new JSONObject();
		MpAccountsEntity accounts= mpAccountService.getDetail(UserUtils.getmpaccounts(request));
		rtnJson.put("errorNo", 0);
		try {
			if(StringUtils.equals(qrcode.getReplyType(),"text")){
				qrcode.setContentSource(qrcode.getContentSource().replace("\n","<br/>"));
			}
			if(qrcode.getId()!=null){//修改
				Conds conds=new Conds();
				Qrcode qrcodeUpdate = qrcodeService.fetchById(qrcode.getId());
				qrcodeUpdate.setId(qrcodeUpdate.getId());
				qrcodeUpdate.setReplyType(qrcode.getReplyType());
				qrcodeUpdate.setContentSource(qrcode.getContentSource());
				qrcodeUpdate.setUpdateBy(UserUtils.getUser().getId());
				qrcode.setDelFlag(Constants.DEL_FLAG_0);
				conds.equal("id",qrcode.getId());
				qrcodeService.update(qrcodeUpdate);
				rtnJson.put("errorNo",2);
			}else{ //添加
				Timestamp nowTemp=new Timestamp(new Date().getTime());
				if(!qrcode.getActionName().equals("QR_LIMIT_SCENE")){
					int esTemp = Math.round((qrcode.getEsEndtime().getTime()-nowTemp.getTime())/1000);
					qrcode.setExpireSeconds(esTemp);
				}else{
					qrcode.setEsEndtime(new Timestamp(new Date().getTime()));
				}
				Conds conds = new Conds();
				conds.equal("action_name",qrcode.getActionName());
				int count = qrcodeService.count(conds);
				wxqrcode=JwAccountAPI.createQrcodeScene(accounts.getAccesstoken(),(long)count, qrcode.getActionName().toUpperCase(),qrcode.getExpireSeconds()+"");
				String tempTicket="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+wxqrcode.getTicket();
				String shortUrl=JwAccountAPI.getShortUrl(accounts.getAccesstoken(),tempTicket);
				qrcode.setCreateBy(UserUtils.getUser().getId());
				qrcode.setUpdateBy(UserUtils.getUser().getId());
				qrcode.setSence(String.valueOf(count));
				qrcode.setCreateTime(nowTemp);
				qrcode.setUpdateTime(nowTemp);
				qrcode.setShortUrl(shortUrl);
				qrcode.setTicket(wxqrcode.getTicket());
				qrcode.setAccountsid(UserUtils.getmpaccounts(request));
				qrcode.setDelFlag(Constants.DEL_FLAG_0);
				qrcodeService.save(qrcode);
			}
		} catch (WexinReqException e) {
			e.printStackTrace();
			rtnJson.put("errorNo",1);
		}
		return rtnJson;
	}
	@RequestMapping(value="removeqrcode",method={RequestMethod.POST})
	@RequiresPermissions(value=PermissionSign.QRCODE_EDIT)
	@ResponseBody
	public JSONObject removeqrcode(Long id){
		JSONObject rtnJson = new JSONObject();
		rtnJson.put("errorNo",0);
		try {
			if(id!=null){
				qrcodeService.delete(id);
			}
		} catch (Exception e) {
			e.printStackTrace();
			rtnJson.put("errorNo",1);
		}
		return rtnJson;
	}
}
 