package com.ssj.sys.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ssj.bean.common.framework.core.domain.Response;
import com.ssj.bean.weixin.card.domain.LibCardInfo;
import com.ssj.framework.basic.common.bean.SplitPage;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.core.util.SystemResourceLocator;
import com.ssj.framework.weixin.card.bean.*;
import com.ssj.framework.weixin.card.util.CardUtil;
import com.ssj.framework.weixin.util.MUDload;
import com.ssj.service.weixin.card.service.ILibMainCardService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
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 javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("sys/wxcard")
@Controller
public class WxcardController extends BaseController {
	
	private static Logger log = LoggerFactory.getLogger(WxcardController.class);
	
	@Autowired
	private ILibMainCardService cardService;
	
	@Autowired
	private TokenManager tokenManager;
	
	/**
	 * 图书馆VIP会员卡管理列表
	 * @param model
	 * @param pageSize
	 * @param pageNo
	 * @param
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/wxcardList")
	public String wxcardList(Model model,
			@RequestParam(required = false, defaultValue = "10") int pageSize,
			@RequestParam(required = false, defaultValue = "1") int pageNo)
					throws Exception {
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("type",request.getParameter("type") == null ? "" : request.getParameter("type"));
		params.put("auditStat",request.getParameter("auditStat") == null ? "" : request.getParameter("auditStat"));
		 
		SplitPage sp = new SplitPage();
		sp.setAction(request.getRequestURI().toString());
		sp.setPageNo(pageNo);
		sp.setPageSize(pageSize);
		sp.setParams(params);
		Page<Map<String, Object>> page = cardService.findForCardPage(params, initPage(pageNo, pageSize));
		sp.setRowCnt((int) page.getTotalElements());
		model.addAttribute("list", page.getContent());
		model.addAttribute("listNavigatHtml", sp.getSysPaginHtml());
		model.addAttribute("page", sp);
		model.addAttribute("search", params);
		
		return "sys/wxcard/libCardList";
	}
	
	@RequestMapping(value="/saveCardInfo",method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity saveCardInfo(HttpServletRequest request, Model model, LibCardInfo cardInfo){
		ResponseEntity resp = new ResponseEntity();
		//cardService.save(cardInfo);如果上传成功才进行插入操作
		//创建卡券
		/**
		 *  1.调用上传LOGO接口将商户图标上传微信服务器并获取logo_url，用于创建卡券。

			2.调用门店管理接口获取门店 ID，设置卡券适用门店。
			
			3.调用获取颜色列表接口，设置卡券背景色。
			
			4.调用创建卡券接口，设置卡券相应信息，获取卡券ID，并标注可领取的库存。
		 */
		
		//firstStep 上传logo
		try {
			//step 1
			JSONObject json = MUDload.uploadMediaJson(tokenManager.getSSJAccessToken(), "image", cardInfo.getLogoUrl());
			log.info("上传图片返回json--->"+json);
			String logoUrl = json.getString("url");
			if("".equals(logoUrl)){
				resp.failure("logo上传失败");
				return resp;
			}
			
			JSONObject json2 = MUDload.uploadMediaJson(tokenManager.getSSJAccessToken(), "image", cardInfo.getBackgroundPicUrl());
			log.info("上传背景图片返回json--->"+json2);
			String backPicUrl = json2.getString("url");
			if("".equals(backPicUrl)){
				resp.failure("logo背景失败！");
				return resp;
			}
			
			//step2 门店暂时不弄
			//step3 暂时写死
			String color = "Color020";
			//step4
			CardInfo card  = new CardInfo();
			if("CASH".equals(cardInfo.getCardType())){ //代金券
				
				card.setCard_type("CASH");
				CashCard cashCard = new CashCard();
				cashCard.setLeast_cost(cardInfo.getLeastCost());
				cashCard.setReduce_cost(cardInfo.getReduceCost());
				BaseInfo info = new BaseInfo();
				info.setLogo_url(logoUrl);
				info.setCode_type("CODE_TYPE_ONLY_QRCODE");
				info.setBrand_name("私塾家家庭图书馆");
				info.setTitle("图书馆"+cardInfo.getReduceCost()/1000+"元代金券");
				info.setColor(color);
				info.setNotice("家庭图书馆借书中使用并核销");
				info.setDescription("此券在家庭图书馆功能中会自动抵消核销");
				BaseInfoSku sku = new BaseInfoSku();
				sku.setQuantity(cardInfo.getCardStore());
				info.setSku(sku);
				BaseInfoDateInfo dateInfo = new BaseInfoDateInfo();
				dateInfo.setType("DATE_TYPE_PERMANENT");
				info.setDate_info(dateInfo);
				info.setCan_give_friend(true);
				cashCard.setBase_info(info);
				card.setCash(cashCard);
				JSONObject jsonObject = CardUtil.cardCreate(tokenManager.getSSJAccessToken(), card);
				log.info("创建现金券返回json--->"+jsonObject);
				if("0".equals(jsonObject.getString("errcode"))){  //正常
					cardInfo.setCardId(jsonObject.getString("card_id"));
					cardInfo.setLogoUrl(logoUrl);
					cardInfo.setStat("1");
					cardService.save(cardInfo);
					resp.success();
				}else{
					resp.failure(jsonObject.getString("errmsg"));
				}
			}else{  //会员卡
				card.setCard_type("MEMBER_CARD");
				MemberCard memberCard = new MemberCard();
				memberCard.setAuto_activate(true);
				memberCard.setPrerogative("年费会员可以在私塾家名下家庭图书馆免费借阅");
				memberCard.setSupply_bonus(false);
				memberCard.setSupply_balance(true);
				memberCard.setBackground_pic_url(backPicUrl); //设置背景图
				BaseInfo info = new BaseInfo();
				info.setLogo_url(logoUrl);
				info.setCode_type("CODE_TYPE_ONLY_QRCODE");
				info.setBrand_name("私塾家家庭图书馆");
				info.setTitle("会员卡");
				info.setColor(color);
				info.setNotice("家庭图书馆借书中使用并核销");
				info.setDescription("此券在家庭图书馆功能中会自动抵消核销");
				BaseInfoSku sku = new BaseInfoSku();
				sku.setQuantity(cardInfo.getCardStore());
				info.setSku(sku);
				BaseInfoDateInfo dateInfo = new BaseInfoDateInfo();
				dateInfo.setType("DATE_TYPE_PERMANENT");
				info.setDate_info(dateInfo);
				info.setCan_give_friend(true);
				info.setCustom_url_name("预约");
				info.setGet_limit(1);
				String customUrl=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/mylib/initMyInfo.html";
				info.setCustom_url(customUrl);
				info.setCustom_url_sub_title("立即预约");
				String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/libVip/libListPage.html";
				info.setPromotion_url(url);
				info.setPromotion_url_name("家庭图书馆");
				info.setPromotion_url_sub_title("立即查看");
				memberCard.setBase_info(info);
				
				card.setMember_card(memberCard);
				JSONObject jsonObject = CardUtil.cardCreate(tokenManager.getSSJAccessToken(), card);
				log.info("创会员卡返回json--->"+jsonObject);
				if("0".equals(jsonObject.getString("errcode"))){  //正常
					cardService.updateCardStat("MEMBER_CARD","2");
					cardInfo.setCardId(jsonObject.getString("card_id"));
					cardInfo.setLogoUrl(logoUrl);
					cardInfo.setStat("1");
					cardService.save(cardInfo);
					resp.success();
				}else{
					resp.failure(jsonObject.getString("errmsg"));
				}
				
				
			}
			
			
		} catch (Exception e) {
			resp.failure(e.getMessage());
			e.printStackTrace();
		}
		return resp;
	}
	
	@RequestMapping("/initAddPage")
	public String initAddPage(){
		return "sys/wxcard/add";
	}
	
	 /**
	  * 生成微信菜单	    
	  * @param model
	  * @return
	  */
	 @RequestMapping("/cardTest")
    public String weixinMenu(Model model){
		  return "sys/wxcard/cardTest";
	 }
	@RequestMapping("/saveCardTest")
	@ResponseBody
	public Response saveCardTest(Model model, String menu){
		Response response = new Response();
 		try {
 			if(menu!=null){
 				JSONObject jsonObject =	CardUtil.cardTestList(tokenManager.getSSJAccessToken(), menu);
 						//MenuManager.getMenu(AccessTokenInfo.accessToken.getToken(), menu);
 				if (null != jsonObject) {  
 					if(jsonObject.getIntValue("errcode")==0){
 						response.success("提交成功");
 					}else{
 						response.failure("提交失败");
 					}
 				}else{
 					response.failure("提交失败");
 				}
 			
 			}else{
 				response.failure("提交失败");
 			}
 		} catch (Exception e) {
 			e.printStackTrace();
 			response.failure("提交失败：" + e.getMessage());
 		}
 		return response;
	}
	
	@RequestMapping(value="/updateCardInfo",method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity updateCardInfo(HttpServletRequest request, Model model,String cardId){
		ResponseEntity resp = new ResponseEntity();
		//cardService.save(cardInfo);如果上传成功才进行插入操作
		//创建卡券
		/**
		 *  1.调用上传LOGO接口将商户图标上传微信服务器并获取logo_url，用于创建卡券。

			2.调用门店管理接口获取门店 ID，设置卡券适用门店。
			
			3.调用获取颜色列表接口，设置卡券背景色。
			
			4.调用创建卡券接口，设置卡券相应信息，获取卡券ID，并标注可领取的库存。
		 */
		
		//firstStep 上传logo
		LibCardInfo cardInfo = cardService.getById(cardId);
		try {
			
			String logoUrl = cardInfo.getLogoUrl();
			
			JSONObject json2 = MUDload.uploadMediaJson(tokenManager.getSSJAccessToken(), "image", cardInfo.getBackgroundPicUrl());
			log.info("上传背景图片返回json--->"+json2);
			String backPicUrl = json2.getString("url");
			if("".equals(backPicUrl)){
				resp.failure("logo背景失败！");
				return resp;
			}
			
			//step2 门店暂时不弄
			//step3 暂时写死
			String color = "Color020";
			//step4
			CardUpdate card  = new CardUpdate();
			
				card.setCard_id(cardInfo.getCardId());
				MemberCard memberCard = new MemberCard();
				memberCard.setAuto_activate(true);
				memberCard.setPrerogative("年费会员可以在私塾家名下家庭图书馆免费借阅");
				memberCard.setSupply_bonus(false);
				memberCard.setSupply_balance(true);
				memberCard.setBackground_pic_url(backPicUrl); //设置背景图
				BaseInfo info = new BaseInfo();
				info.setLogo_url(logoUrl);
				info.setCode_type("CODE_TYPE_ONLY_QRCODE");
				//info.setBrand_name("私塾家家庭图书馆");
				info.setTitle("会员卡");
				info.setColor(color);
				info.setNotice("家庭图书馆借书中使用并核销");
				info.setDescription("此券在家庭图书馆功能中会自动抵消核销");
//				BaseInfoSku sku = new BaseInfoSku();
//				sku.setQuantity(cardInfo.getCardStore());
//				info.setSku(sku);
				//BaseInfoDateInfo dateInfo = new BaseInfoDateInfo();
				//dateInfo.setType("DATE_TYPE_PERMANENT");
				//info.setDate_info(dateInfo);
				info.setCan_give_friend(false);
				info.setCustom_url_name("预约");
				info.setGet_limit(1);
				String customUrl=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/mylib/initMyInfo.html";
				info.setCustom_url(customUrl);
				info.setCustom_url_sub_title("立即预约");
				String url=(String) SystemResourceLocator.getValue("sys_url")+"/weixin/libVip/libListPage.html";
				info.setPromotion_url(url);
				info.setPromotion_url_name("家庭图书馆");
				info.setPromotion_url_sub_title("立即查看");
				memberCard.setBase_info(info);
				
				card.setMember_card(memberCard);
				JSONObject jsonObject = CardUtil.updateMember(tokenManager.getSSJAccessToken(), card);
				log.info("创会员卡返回json--->"+jsonObject);
				resp.success();
			
			
		} catch (Exception e) {
			resp.failure(e.getMessage());
			e.printStackTrace();
		}
		return resp;
	}
	
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/getCardList")
	@ResponseBody
	public ResponseEntity getCardList(){
		ResponseEntity resp = new ResponseEntity();
		try {
			List<String> list  =new  ArrayList<String>();
			list.add("CARD_STATUS_DISPATCH");//只查询审核通过的
			JSONObject jsonObject=CardUtil.batchget(tokenManager.getSSJAccessToken(), 0, 20, list);
			if("0".equals(jsonObject.getString("errcode"))){
				list.remove("CARD_STATUS_DISPATCH");
				list =JSON.parseObject(jsonObject.getString("card_id_list"),List.class);
				for (String string : list) {
					JSONObject cardJsonObject=	CardUtil.get(tokenManager.getSSJAccessToken(), string);
					JSONObject object = JSON.parseObject(cardJsonObject.getString("card"));
					String card_type =object.getString("card_type");
					JSONObject jsonobject = JSON.parseObject(object.getString(card_type.toLowerCase()));
					BaseInfo baseInfo=JSON.parseObject(jsonobject.getString("base_info"),BaseInfo.class);
					
					LibCardInfo   libCardInfo = cardService.findByCardId(string);
					if(libCardInfo==null){
						libCardInfo= new  LibCardInfo();
					}
					libCardInfo.setCardId(string);libCardInfo.setLogoUrl(baseInfo.getLogo_url());
					libCardInfo.setCardType(card_type);
					if(baseInfo.getSku()!=null){
						libCardInfo.setCardStore(baseInfo.getSku().getQuantity());
					}
					libCardInfo.setStat("1");
					String title =baseInfo.getTitle();
					if(title.contains("作业")){
						libCardInfo.setStat("2");
					}
					libCardInfo.setTitle(title);
					libCardInfo.setJson(cardJsonObject.getString("card"));
					cardService.save(libCardInfo);
					//
				}
			}
				resp.success();
		} catch (Exception e) {
			resp.failure(e.getMessage());
			e.printStackTrace();
		}
		return resp;
	}
}
