package com.bcxin.ins.weixin.web;

import com.alibaba.fastjson.JSON;
import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.entity.product_core.ProClauses;
import com.bcxin.ins.spring.annotation.OperationLog;
import com.bcxin.ins.util.BASE64Util;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.weixin.product.service.ProClausesService1;
import com.bcxin.ins.weixin.product.service.impl.WeiXinProductServiceImpl;
import com.bcxin.ins.weixin.util.CTLUtil;
import com.bcxin.ins.weixin.util.ZipUtils;
import com.bcxin.mybatisplus.mapper.EntityWrapper;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.lang.Console;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.Map;

@Controller
@RequestMapping("${weixin}/product")
public class WeiXinProductController extends BaseController {

	private static final String PRODUCT_LIST = getViewPath("weixin/product/product_list");
	private static final String PRODUCT_DETAIL = getViewPath("weixin/product/product_detail");
	private static final String PRODUCT_SEARCH = getViewPath("weixin/product/product_search");
	private static final String PRODUCT_SEARCH_RESULT = getViewPath("weixin/product/product_search_result");
	private static final String PAY_FINISH = getViewPath("weixin/order/zzx/zzx_pay_finish");

	@Autowired
	private WeiXinProductServiceImpl weiXinProductService;

	@Autowired
	private ProClausesService1 proClausesService;

	/** 产品列表 */
	@RequestMapping(value = "/win/list")
	public String winList(Model model, @RequestParam Map<Object,Object> params ) throws Exception {
		model.addAttribute("p",params);
		model.addAttribute("notOpen","1");
		//判断recommendCode参数（为业务支撑用户ID） 推荐码是否为存在，如果存在放入session
		if(params.get("recommendCode")!=null) {
			String recommendCode = BASE64Util.decryptBASE64((String)params.get("recommendCode"));
			getRequest().getSession().setAttribute("recommendCode", recommendCode);
		}
		return PRODUCT_LIST;
	}

	/** 产品搜索 */
	@RequestMapping(value = "/win/search")
	public String winSearch(Model model, @RequestParam Map<Object,Object> params ) {
		return PRODUCT_SEARCH;
	}

	/** 支付完成页面 要避开拦截器*/
	@RequestMapping(value = "/pay/finish/{oid}")
	public  String payFinish(Model model, @RequestParam Map<Object,Object> params,@PathVariable String oid) {
		params.put("ins_insurance_slip_id",oid);
		logger.info("调用支付完成页面>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
		model.addAttribute("p",params);
		return PAY_FINISH;
	}

	/** 产品搜索结果页 */
	@RequestMapping(value = "/win/search/result")
	public String winSearchResult(Model model, @RequestParam Map<Object,Object> params ) {
		model.addAttribute("keyword", params.get("keyword"));
		return PRODUCT_SEARCH_RESULT;
	}

	/** 产品详情 */
	@OperationLog(source = OperationLog.SOURCETYPE.FRONT_PRODUCT,title ="【请求】微信-产品详情")
	@RequestMapping(value = "/win/detail/{oid}")
	public String winDetail(Model model, @RequestParam Map<Object,Object> params ,@PathVariable String oid) {
		params.put("pro_primary_id",oid);
		model.addAttribute("p",params);
		//判断recommendCode参数（为业务支撑用户ID） 推荐码是否为存在，如果存在放入session
//		if(params.get("recommendCode")!=null) getRequest().getSession().setAttribute("recommendCode",params.get("recommendCode"));
//		getRequest().getSession().setAttribute("ywzc_activity_info",params);//保存分享链接的参数
		return PRODUCT_DETAIL;
	}

	/**
	 * 产品分销列表，oid 是产品主键ID
	 * */
	@RequestMapping(value = "/win/prolist/{oid}")
	public String winProlist(Model model, @RequestParam Map<Object,Object> params ,@PathVariable String oid) {
		params.put("activity_id",oid);
		model.addAttribute("p",params);
		model.addAttribute("type",getRequest().getSession().getAttribute("type"));
		getRequest().getSession().removeAttribute("type");//清空session的参数
		logger.info("获得的type参数是："+getRequest().getSession().getAttribute("type"));
		//发起request请求，获取参数
		String result = HttpUtil.get(String.valueOf(GlobalResources.map.get("YWZC_URL"))+"/weixin/no/getActivity?id="+oid);
		Map localParam = JSON.parseObject(result,Map.class);
		logger.info("获得的参数"+JSON.toJSONString(localParam));
		//判断recommendCode参数（为业务支撑用户ID） 推荐码是否为存在，如果存在放入session
		if(localParam.get("recommendCode")!=null) {
			getRequest().getSession().setAttribute("recommendCode", localParam.get("recommendCode"));
		}
		localParam.put("activity_id",oid);
		getRequest().getSession().setAttribute("ywzc_activity_info", localParam);//保存分享链接的参数
		getRequest().getSession().setAttribute("ywzc_pro_primary_ids", localParam.get("product_codes"));//保存产品列表全局查询条件
		logger.info(JSON.toJSONString(getRequest().getSession().getAttributeNames()));
		return PRODUCT_LIST;
	}

	/**
	 * 产品分销列表，oid 是产品主键ID
	 * */
	@RequestMapping(value = "/win/prolist/mid/{oid}")
	public String winProListMid(Model model, @RequestParam Map<Object,Object> params ,@PathVariable String oid) {
		params.put("activity_id",oid);
		getRequest().getSession().setAttribute("type",0);
		return redirectTo("/weixin/product/win/prolist/"+oid);
	}



	/** 产品详情查询*/
	@RequestMapping(value = "/detail")
	public @ResponseBody Object detail(Model model, @RequestParam Map<Object,Object> params ) {
		CTLUtil.out(weiXinProductService.queryByProductID(params),getResponse());
		return null;
	}

	/** 产品列表数据分页查询 */
	@RequestMapping(value = "/query")
	public @ResponseBody Object proListData(Model model, @RequestParam Map<Object,Object> params) {
		Map<Object,Object> p  = CTLUtil.initWX(getRequest(),params);
		logger.info("session中的参数："+getRequest().getSession().getAttribute("ywzc_pro_primary_ids"));
		if(getRequest().getSession().getAttribute("ywzc_pro_primary_ids")!=null){
			p.put("ywzc_pro_primary_ids",getRequest().getSession().getAttribute("ywzc_pro_primary_ids"));
		}
		p.put("product_code","ZZX");
		logger.info("分页查询的参数是："+JSON.toJSONString(p));
		return weiXinProductService.query(p);
	}

	/** pdf保险条款下载 */
	@RequestMapping(value = "/clause/{pro_clauses_id}")
	public @ResponseBody Object detail(Model model, @PathVariable("pro_clauses_id") String pro_clauses_id) throws Exception {
		ProClauses pc = proClausesService.selectOne(new EntityWrapper<ProClauses>().addFilter("pro_clauses_id = {0}",pro_clauses_id));
		if(pc==null) {
			return null;
		}
		String filenameEncode= URLEncoder.encode(String.valueOf(pc.getFile_name()),"utf-8");
		//一旦设置了文件名，就会编程下载
		//resp.setHeader("Content-Disposition", "attachment;filename="+filenameEncode);//设置文件名
		//resp.setContentType("application/octet-stream;");
		getResponse().setContentType("application/pdf");  //这样就可以直接打开
		getResponse().setCharacterEncoding("UTF-8");
		CTLUtil.outBlob(getResponse(),pc.getClauses_file());
		return null;
	}

	/**
	 * 传入product_codes 的数组对象，通过String转换为json获取列表，然后通过列表获取产品详情
	 * 产品编码数组 例如：1，2，3
	 * @apiNote  作者  陈堂君
	 * @since 创建于 2018/1/22 13:10
	 */
	@RequestMapping(value = "/getProDetailByProCodes")
	public @ResponseBody Object getProDetailByProCodes(Model model, @RequestParam Map<Object,Object> params) {
		Map<Object,Object> p  = CTLUtil.initWX(getRequest(),params);
		logger.info("产品编码数组："+JSON.toJSONString(p));
		return weiXinProductService.queryByProductCodes(p);
	}




}