package com.bcxin.ins.coninsweb.thrApi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.dto.Result;
import com.bcxin.ins.service.order.InsInsuranceSlipAPIService;
import com.bcxin.ins.service.product.ProductService;
import com.bcxin.ins.rest.UserSupportUtil;
import com.bcxin.ins.service.user.ClientUserService;
import com.bcxin.ins.core.base.web.BaseController;
import com.bcxin.ins.core.entity.Auth;
import com.bcxin.ins.core.service.MyTposThrUserService;
import com.bcxin.ins.spring.annotation.OperationLog;
import com.bcxin.ins.spring.util.JedisUtils;
import com.bcxin.ins.util.IdWorker;
import com.bcxin.ins.util.MD5Util;
import com.bcxin.ins.vo.BLBAPIPreservationVo;
import com.bcxin.ins.vo.ClientUserVo;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.mybatisplus.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 建筑产品相关业务逻辑处理（不包括后台产品配置）
 * @author zxf
 *
 */
@Controller
public class SAAS_API_Controller extends BaseController {

	@Autowired
	private ProductService productService;
	@Autowired
	private MyTposThrUserService myTposThrUserService;
	@Autowired
	private ClientUserService clientUserService;

	@Autowired
	private InsInsuranceSlipAPIService insInsuranceSlipAPIService;

	private static String PRODUCT_ID = "product_id";

	/**
	 * <b>第三方平台用户调用接口,token验证通过后，判断是否存在，存在：设置登录状态，不存在：新增用户并设置登录状态</b>
	 * @param token
	 * @param party 平台标识
	 * @return
	 * @author ZXF
	 * @date 2017年03月13日 下午1:40:41
	 * @注意事项 </b>
	 * <b>
	 */
	private Result checkLogin(String party, String token){
		Auth auth = myTposThrUserService.isAuth(party,token,getRequest());
		//白名单通过
		if(!auth.isSuccess()){
			return Result.fail(auth.getMsg());
		}
		JSONObject json = (JSONObject)auth.getData();
		if(!clientUserService.saveClientUserVoForTHR(party
				,json.get("login_name") != null ? String.valueOf(json.get("login_name")) : String.valueOf(json.get("user_id"))
				,String.valueOf(json.get("user_id")),getToken())){
			return Result.fail("登录失败！");
		}
		if(!party.contains(ConstProp.PSS)&&!party.contains(ConstProp.SAAS)&&!party.contains(ConstProp.PASP)){
			return Result.fail("无效来源！");
		}
		//是否有传省代码，如果有加入redis
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(userdetail != null){
			String key = ConstProp.ADDRESS_HEAD+userdetail.getOid();
			if(StringUtils.isEmpty(JedisUtils.get(key))){
				JedisUtils.set(key,String.valueOf(json.get("province")),ConstProp.ONE_HOURS_TIMEOUT_SECONDS);
			}
		}
		return Result.success("登录成功!",getToken());
	}

	/**
	 * <b>第三方平台用户调用接口返回对应订单列表页面</b>
	 * @return
	 * @author ZXF
	 * @date 2017年03月13日 下午1:40:41
	 * @注意事项 </b>
	 * <b>
	 */
	@OperationLog(source = OperationLog.SOURCETYPE.FRONT_LOGIN_THR,title ="【请求】第三方-登录")
	@RequestMapping("/api/thr/tposCheckoutToOrder")
	public ModelAndView tposCheckoutToOrder(){
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(userdetail==null){
			return new ModelAndView("forward:/synopsis/loseView");
		}
		if(userdetail.getWeb_type().contains(ConstProp.PSS)
				||userdetail.getWeb_type().contains(ConstProp.SAAS)
				||userdetail.getWeb_type().contains(ConstProp.PASP)
		){
			String type = getRequest().getParameter("businessType");

			ModelAndView view = new ModelAndView("forward:/api/order/myOrder?businessType="+type);
			setTokenByApi(view);
			return view;
		}else{
			return new ModelAndView("forward:/synopsis/loseView");
		}
	}

	/**
	 * <b>第三方平台用户调用接口返回对应理赔列表页面</b>
	 * @return
	 * @author ZXF
	 * @date 2017年03月13日 下午1:40:41
	 * @注意事项 </b>
	 * <b>
	 */
	@OperationLog(source = OperationLog.SOURCETYPE.FRONT_LOGIN_THR,title ="【请求】第三方-登录")
	@RequestMapping("/api/thr/tposCheckoutToReport")
	public ModelAndView tposCheckoutToReport(){
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(userdetail==null){
			return new ModelAndView("forward:/synopsis/loseView");
		}
		if(userdetail.getWeb_type().contains(ConstProp.PSS)
				||userdetail.getWeb_type().contains(ConstProp.SAAS)
				||userdetail.getWeb_type().contains(ConstProp.PASP)
		){
			ModelAndView view = new ModelAndView("forward:/api/report/reportList");
			setTokenByApi(view);
			return view;
		}else{
			return new ModelAndView("forward:/synopsis/loseView");
		}
	}

	/**
	 * <b>第三方平台用户调用接口返回对应订单详情页面</b>
	 * @param order_id 订单id
	 * @return
	 * @author ZXF
	 * @date 2017年03月13日 下午1:40:41
	 * @注意事项 </b>
	 * <b>
	 */
	@OperationLog(source = OperationLog.SOURCETYPE.FRONT_LOGIN_THR,title ="【请求】第三方-登录")
	@RequestMapping("/api/thr/tposCheckoutToOrderDetail")
	public ModelAndView tposCheckoutToOrderDetail(String order_id){
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(userdetail==null){
			return new ModelAndView("forward:/synopsis/loseView");
		}
		if(userdetail.getWeb_type().contains(ConstProp.PSS)
				||userdetail.getWeb_type().contains(ConstProp.SAAS)
				||userdetail.getWeb_type().contains(ConstProp.PASP)
		){
			ModelAndView view = new ModelAndView("forward:/api/order/orderDetailByOrderID/"+order_id);
			setTokenByApi(view);
			return view;
		}else{
			return new ModelAndView("forward:/synopsis/loseView");
		}
	}

	/**
	 * <b>获取当前项目访问地址头 http://localhost:8082/conins</b>
	 * 注：如果是localhost（本地访问路径）必须有项目名的路劲才能截取正确 TODO  只适应3种情况具体看代码
	 * @return
	 * @author ZXF
	 * @date 2017年03月13日 下午1:40:41
	 * @注意事项 </b>
	 * <b>
	 */
	@OperationLog(source = OperationLog.SOURCETYPE.FRONT_LOGIN_THR,title ="【请求】第三方-登录")
	@RequestMapping("/api/thr/tposCheckout")
	public ModelAndView tposCheckout(String party , String token){
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(userdetail==null){
			Result result = checkLogin(party, token);
			userdetail = UserSupportUtil.getSessionUser();
			if(Result.ERROR.equals(result.getRetType())||userdetail==null){
				return new ModelAndView("forward:/synopsis/loseView");
			}
		}

		if(userdetail.getWeb_type().contains(ConstProp.SAAS)
				||userdetail.getWeb_type().contains(ConstProp.PASP)
		){
			String key = ConstProp.ADDRESS_HEAD+getToken();
			String cacheId = JedisUtils.get(key);
			if(StringUtils.isNotEmpty(cacheId)){
				JedisUtils.del(key);
			}
			String viewName = "forward:/insurance/product/tx-product-all";
			if(StringUtils.isNotEmpty(cacheId) && cacheId.contains(BSEnum.LBBX.toString())){
				viewName = "forward:/insurance/product/dq-product-all";
			}
			ModelAndView view = new ModelAndView(viewName);
			setTokenByApi(view);
			return view;
		}else if(userdetail.getWeb_type().contains(ConstProp.PSS)){
			ModelAndView view = new ModelAndView("forward:/insurance/product/gzx-product-all");
			setTokenByApi(view);
			return view;
		}else{
			return new ModelAndView("forward:/synopsis/loseView");
		}

	}

	@RequestMapping("/api/thr/initTposUser")
	public @ResponseBody String initTposUser(String party , String token){
		getResponse().setHeader("Access-Control-Allow-Origin", "*");
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(userdetail==null){
			Result result = checkLogin(party, token);
			userdetail = UserSupportUtil.getSessionUser();
			if(Result.ERROR.equals(result.getRetType())||userdetail==null){
				return JSON.toJSONString(Result.fail("未完成用户信息注册"));
			}
			return JSON.toJSONString(result);
		}
		return JSON.toJSONString(Result.success(""));
	}

	/**
	 * <b> 第三方访问理赔（saas-app的理赔） </b>
	 * @param saasIdCardNo saas的人员id
	 * @param entranceType 访问入口（1：保单列表，2：理赔列表）
	 * @author ZXF
	 * @create 2020/06/19 0019 10:35
	 * @version
	 * @注意事项 </b>
	 */
	@OperationLog(source = OperationLog.SOURCETYPE.FRONT_LOGIN_THR,title ="【请求】第三方-登录")
	@RequestMapping("/api/thr/reportCheckout")
	public ModelAndView reportCheckout(String saasIdCardNo, String entranceType, String party, String token){
		Result result = checkLogin(party, token);
		if(Result.ERROR.equals(result.getRetType())){
			return new ModelAndView("forward:/synopsis/loseView");
		}
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(userdetail==null){
			return new ModelAndView("forward:/synopsis/loseView");
		}
		if("1".equals(entranceType)){
			ModelAndView view = new ModelAndView("forward:/app/report/orderList?saasIdCardNo="+saasIdCardNo);
			setTokenByApi(view);
			return view;
		}else if("2".equals(entranceType)){
			ModelAndView view = new ModelAndView("forward:/app/report/reportList?saasIdCardNo="+saasIdCardNo+"&status=0");
			setTokenByApi(view);
			return view;
		}else {
			return new ModelAndView("forward:/synopsis/loseView");
		}
	}

	/**
	 * <b>获取当前项目访问地址头 http://localhost:8082/conins</b>
	 * 注：如果是localhost（本地访问路径）必须有项目名的路劲才能截取正确 TODO  只适应3种情况具体看代码
	 *
	 * saas人员投保管理-批量关联保单-暂无保单业务
	 *
	 * @param revise_type
	 * @param cacheId
	 * @return
	 * @author ZXF
	 * @date 2017年03月13日 下午1:40:41
	 * @注意事项 </b>
	 * <b>
	 */
	@OperationLog(source = OperationLog.SOURCETYPE.FRONT_LOGIN_THR,title ="【请求】第三方-登录")
	@RequestMapping("/api/thr/tposCheckoutAddCache")
	public ModelAndView tposCheckoutAddCache( String revise_type , String cacheId){
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(userdetail==null){
			return new ModelAndView("forward:/synopsis/loseView");
		}
		String token = getRequest().getParameter("ACCESS_TOKEN");
		if(userdetail.getWeb_type().contains(ConstProp.PSS)
				||userdetail.getWeb_type().contains(ConstProp.SAAS)
				||userdetail.getWeb_type().contains(ConstProp.PASP)
		){
			String viewName = "forward:/insurance/product/tx-product-all";
			if(StringUtils.isNotEmpty(cacheId) && cacheId.contains(BSEnum.LBBX.toString())){
				viewName = "forward:/insurance/product/dq-product-all";
			}
			JedisUtils.set(ConstProp.ADDRESS_HEAD+token,cacheId,ConstProp.ONE_HOURS_TIMEOUT_SECONDS);
			ModelAndView view = new ModelAndView(viewName);
			setTokenByApi(view);
			return view;
		}else if(userdetail.getWeb_type().contains(ConstProp.PSS)){
			ModelAndView view = new ModelAndView("forward:/insurance/product/gzx-product-all");
			setTokenByApi(view);
			return view;
		}else{
			return new ModelAndView("forward:/synopsis/loseView");
		}
	}

	/**
	 * <b>SAAS专用,第三方平台用户调用接口返回对应订单详情页面</b>
	 * @param order_id 订单id
	 * @return
	 * @author ZXF
	 * @date 2017年03月13日 下午1:40:41
	 * @注意事项 </b>
	 * <b>
	 */
	@OperationLog(source = OperationLog.SOURCETYPE.FRONT_LOGIN_THR,title ="【请求】第三方-登录")
	@RequestMapping("/api/thr/tposDetail")
	public ModelAndView tposDetail(String order_id){
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(userdetail==null){
			return new ModelAndView("forward:/synopsis/loseView");
		}
		if(userdetail.getWeb_type().contains(ConstProp.PSS)
				||userdetail.getWeb_type().contains(ConstProp.SAAS)
				||userdetail.getWeb_type().contains(ConstProp.PASP)
		){
			ModelAndView view = new ModelAndView("forward:/api/order/orderDetailByOrderID/"+order_id);
			setTokenByApi(view);
			return view;
		}else{
			return new ModelAndView("forward:/synopsis/loseView");
		}
	}

	/**
	 * <b>获取当前项目访问地址头 http://localhost:8082/conins</b>
	 * 注：如果是localhost（本地访问路径）必须有项目名的路劲才能截取正确 TODO  只适应3种情况具体看代码
	 * @return
	 * @author ZXF
	 * @date 2017年03月13日 下午1:40:41
	 * @注意事项 </b>
	 * <b>
	 */
	@OperationLog(source = OperationLog.SOURCETYPE.FRONT_LOGIN_THR,title ="【请求】第三方-登录")
	@RequestMapping("/api/thr/tposPreservation")
	public ModelAndView tposPreservation(){
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(userdetail==null){
			return new ModelAndView("forward:/synopsis/loseView");
		}
		if(userdetail.getWeb_type().contains(ConstProp.PSS)
				||userdetail.getWeb_type().contains(ConstProp.SAAS)
				||userdetail.getWeb_type().contains(ConstProp.PASP)
		){
			ModelAndView view = new ModelAndView("forward:/api/preservation/recordList");
			setTokenByApi(view);
			return view;
		}else{
			return new ModelAndView("forward:/synopsis/loseView");
		}
	}

	@OperationLog(source = OperationLog.SOURCETYPE.FRONT_LOGIN_THR,title ="【请求】第三方-登录")
	@RequestMapping("/api/thr/tposProductAndRes")
	@ResponseBody
	public String tposProductAndRes(){
		return productService.listProductAndResponsibility();
	}

	/**
	 * <b> 手机号能查到并且为未完成绑定返回1 </b>
	 * @author ZXF
	 * @create 2024/04/07 0007 10:34
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping("/api/thr/tposIsBindAndExist")
	@ResponseBody
	public String tposIsBindAndExist(String token,String mobile){
		logger.info("tposIsBindAndExist参数：token="+token+",mobile="+mobile);
		if(!MD5Util.checkMD5BySAAS(mobile,token)){
			logger.error("tposIsBindAndExist异常：数据异常，鉴权失败！");
//			return Result.fail("数据异常，鉴权失败！");
			return "0";
		}
		if(clientUserService.checkUserExist(mobile, true)){
			return "1";
		}
		return "0";
	}

	/**
	 * <b> 手机号绑定百联保注册的用户 </b>
	 * @author ZXF
	 * @create 2024/04/07 0007 10:34
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping("/api/thr/tposBindEUser")
	@ResponseBody
	public String tposBindEUser(String token,String mobile,String id,String party,String username){
		logger.info("tposBindEUser参数：token="+token+",mobile="+mobile+",id="+id+",party="+party+",username="+username);
		if(!MD5Util.checkMD5BySAAS(mobile,token)){
			logger.error("tposBindEUser异常：数据异常，鉴权失败！");
//			return Result.fail("数据异常，鉴权失败！");
			return "0";
		}
		if(clientUserService.bindClientUser(party,mobile,username,id)){
			return "1";
		}
		return "0";
	}

	@RequestMapping("/api/thr/tposZBNum")
	@ResponseBody
	public Result tposZBNum(String token,String policyNos){
		logger.info("tposZBNum参数：token="+token+",policyNos="+policyNos);
		if(!MD5Util.checkMD5BySAAS(policyNos,token)){
			return Result.fail("数据异常，鉴权失败！");
		}
		List<Map<String,String>> list = insInsuranceSlipAPIService.findZBNumByPolicyNos(policyNos);
		return Result.success(Result.SUCCESS_MSG, list==null ? list : JSONArray.toJSONString(list));
	}

	/**
	 * <b> 投保人员暂存（跳转投保页面用） </b>
	 * @author ZXF
	 * @create 2025/02/08 0008 15:01
	 * @version
	 * @注意事项 </b>
	 */
	@RequestMapping("/api/thr/personAddCache")
	public Result personAddCache(BLBAPIPreservationVo blbVo){
		ClientUserVo userdetail = UserSupportUtil.getSessionUser();
		if(userdetail==null){
			return Result.fail("数据异常，鉴权失败！");
		}
		if(StringUtils.isEmpty(blbVo.getListStr())){
			return Result.fail("投保人员信息不存在！");
		}
		IdWorker idWorker = new IdWorker(ConstProp.INT_NUMBER_WORKERID, ConstProp.INT_NUMBER_ZERO);
		String cacheId = ConstProp.REDIS_HEAD_INS+"cacheIdForInsPerIds" + idWorker.nextId();
		JedisUtils.set(cacheId,blbVo.getListStr(),ConstProp.ONE_HOURS_TIMEOUT_SECONDS);
		return Result.success(Result.SUCCESS_MSG, cacheId);
	}

	@RequestMapping("/api/thr/tposSetSign")
	@ResponseBody
	public Result tposSetSign(String token,String policyNo,String webType){
		logger.info("tposZBNum参数：token="+token+",policyNo="+policyNo+",webType="+webType);
		if(!MD5Util.checkMD5BySAAS(policyNo+webType,token)){
			return Result.fail("数据异常，鉴权失败！");
		}
		int count = insInsuranceSlipAPIService.updateWebTypeByEx(policyNo,webType);
		if(count>0){
			return Result.success(Result.SUCCESS_MSG);
		}
		return Result.fail(Result.ERROR_MSG);
	}

}
