package com.bcxin.ins.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bcxin.ins.core.util.HttpUtil;
import com.bcxin.ins.dto.oauth.AccessToken;
import com.bcxin.ins.entity.user.SysClientCompany;
import com.bcxin.ins.entity.user.SysClientUser;
import com.bcxin.ins.spring.listener.SessionContext;
import com.bcxin.ins.spring.util.JedisUtils;
import com.bcxin.ins.util.BASE64Util;
import com.bcxin.ins.util.Constant;
import com.bcxin.ins.util.GlobalResources;
import com.bcxin.ins.util.IpAddress;
import com.bcxin.ins.vo.ClientUserVo;
import com.bcxin.ins.vo.ConstProp;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

public class UserSupportUtil {

    private static Logger log = LoggerFactory.getLogger(UserSupportUtil.class);

//    private final static String  URL ="http://localhost:8081/";
//    private final static String URL = "http://120.76.218.179:9113/"; //测试环境

    //4.1.1.终端用户同步
    private final static String USER_SYNCHRONIZATION = "api/webUser/receiveData";

    //4.1.9  终端机构用户
    private final static String COMPANY_SYNCHRONIZATION = "api/webCompany/receiveTerminalData";


    private static final Logger logger = LoggerFactory.getLogger(UserSupportUtil.class);


    public static ClientUserVo getSessionUser() {
        // 利用request获得session
        HttpServletRequest request = null;
        if (RequestContextHolder.getRequestAttributes() == null) {
            return null;
        }
        request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String access_token = request.getParameter("ACCESS_TOKEN");
        if(StringUtils.isEmpty(access_token)){
            String referer_url = request.getHeader("Referer");
            if(StringUtils.isNotEmpty(referer_url)&&referer_url.contains("ACCESS_TOKEN=")&&!referer_url.endsWith("ACCESS_TOKEN=")){
                String x_at = referer_url.split("ACCESS_TOKEN=")[1];
                if(x_at.length()==32){
                    access_token = x_at;
                }else if(x_at.length()>32){
                    access_token = x_at.substring(0,32);
                }
            }
        }
        /**单点业务 star**/
        AccessToken accessToken = (AccessToken)JedisUtils.getObject(ConstProp.REDIS_HEAD_BLB_TOKEN+access_token);
        ClientUserVo user = null;
        if (accessToken != null) {
            user = accessToken.getUserVo();
            if (null != user) {
                //根据登录名字去获取是否登录状态。。
                return user;
            }
        }else{
            //如果能拿到token但是redis中没有的就默认用户过期
            if(StringUtils.isNotEmpty(access_token)){
                return null;
            }
        }
        /**单点业务 end**/

        HttpSession session = request.getSession();
        try{
            user = (ClientUserVo) session.getAttribute("userdetail");
        }catch (Exception e){

        }
        if (null != user) {
            //根据登录名字去获取是否登录状态。。
            return user;
        }
        //获取是否存在Ip跟session绑定的数据（针对第三方的iframe导致sessionId不断变的问题）
        String sessionId = JedisUtils.get(ConstProp.REDIS_HEAD_THR_TOKEN + request.getParameter("ACCESS_TOKEN"));
        if(StringUtils.isEmpty(sessionId)){
            return null;
        }
        //获取session
        session = SessionContext.getInstance().getSession(sessionId);
        if(session == null){
            return null;
        }
        user = (ClientUserVo) session.getAttribute("userdetail");
        if (null != user) {
            return user;
        }
        return null;
    }

    public static void setSessionUser(ClientUserVo vo) {
        HttpServletRequest request = null;
        if (RequestContextHolder.getRequestAttributes() != null) {
            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            HttpSession session = request.getSession();
            session.setAttribute("userdetail", vo);
        }
    }

    public static void setSessionWeiXinUser(ClientUserVo vo) {
        HttpServletRequest request = null;
        if (RequestContextHolder.getRequestAttributes() != null) {
            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            HttpSession session = request.getSession();
            session.setAttribute("weixinVo", vo);
        }
    }

    public static Map<String, Object> getUserSynchronization(SysClientUser user, String sys_client_company_id) {
        //需要记录请求记录信息，URL"http://120.76.218.179:9113/"; //测试环境 USER_SYNCHRONIZATION "api/webUser/receiveData"
        //url http://120.76.218.179:9113/api/webUser/receiveData
        String url = GlobalResources.map.get("YWZC_URL") + USER_SYNCHRONIZATION;
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> mapParams = new HashMap<String, Object>();

        //BLB
        mapParams.put("webType", Constant.WEB_TYPE_COINS);

        if(StringUtils.isNotEmpty(user.getWeb_type())&&!Constant.WEB_TYPE_COINS.equals(user.getWeb_type())){
            //如果类型为内部类型 不传
            mapParams.put("webTHirdType",user.getWeb_type() );
            mapParams.put("webUserName",user.getWeb_type()+user.getWeb_user_name() );
        }
        if (user.getLogin_name() != null) {
            mapParams.put("loginName", Constant.WEB_TYPE_COINS+user.getLogin_name());
        }

        if (user.getUser_name() != null) {
            mapParams.put("userName", Constant.WEB_TYPE_COINS+user.getUser_name());

        }
        if (user.getReal_name() != null) {
            mapParams.put("realName", user.getReal_name());

        }
        //性别：0.保密；1.男； 2.女
        if (user.getSex() != null) {
            mapParams.put("sex", user.getSex());
        }
        if (user.getAge() != null) {
            mapParams.put("age", user.getAge());
        }
        //pic_img
        if (user.getEmail() != null) {
            mapParams.put("email", user.getEmail());
        }
        if (user.getTelephone() != null) {
            mapParams.put("telephone", user.getTelephone());
        }
        if (user.getSys_client_user_id() != null) {
            mapParams.put("webUserId", user.getSys_client_user_id());
        }
        if (user.getBusiness_support_id() != null) {
            mapParams.put("id", user.getBusiness_support_id());
        }
        //如果是企业用户需要同步公司 0，或者1 都不传companyId 过去
        if (StringUtils.isNotEmpty(sys_client_company_id)&&!("1".equals(sys_client_company_id)||"0".equals(sys_client_company_id))) {
            mapParams.put("sysCompany.id", sys_client_company_id);
        }
        if (StringUtils.isNotEmpty(user.getId_card())) {
            mapParams.put("idNumber", user.getId_card());
        }
        if (StringUtils.isNotEmpty(user.getId_type())) {
            mapParams.put("idType", user.getId_type());
        }


        try {
            logger.debug("同步内容参数" + mapParams);
            String s = HttpUtil.doPost2(url, mapParams);
            logger.debug("同步内容结果" + s);
            JSONObject json = JSON.parseObject(s);
            if (json != null && json.get("success").toString().equals("true")) {
                map.put("status", true);
                map.put("webID", json.get("data"));
            }
        } catch (Exception ex) {
            log.error("用户同步内容",ex);
            map.put("status", false);
//            ex.printStackTrace();
        }
        return map;
    }



    public static Map<String, Object> getCompany(SysClientCompany company) {
        //需要记录请求记录信息
        Map<String, Object> map = new HashMap<>();

        String url = GlobalResources.map.get("YWZC_URL") +  COMPANY_SYNCHRONIZATION;
        Map<String, Object> mapParams = new HashMap<String, Object>();
        mapParams.put("sign", Constant.WEB_TYPE_COINS);
        mapParams.put("webType", Constant.WEB_TYPE_COINS);

        if(company.getWeb_id()!=null){
            mapParams.put("id", company.getWeb_id());
        }
        if (company.getCompany_name() != null) {
            mapParams.put("companyName", company.getCompany_name());
        }
        if (company.getCompany_ename() != null) {
            mapParams.put("companyEname", company.getCompany_ename());

        }
        if (company.getProvince() != null) {
            mapParams.put("province", company.getProvince());

        }
        if (company.getCity() != null) {
            mapParams.put("city", company.getCity());

        }
        if (company.getDistrict() != null) {
            mapParams.put("district", company.getDistrict());

        }
        if (company.getRegistered_address() != null) {
            mapParams.put("registeredAddress", company.getRegistered_address());

        }
        if (company.getBusiness_address() != null) {
            mapParams.put("businessAddress", company.getBusiness_address());

        }
        //1: 营业执照,2: 统一社会信用代码
        if(company.getOrganization_code_type()!=null&&"7".equals(company.getOrganization_code_type())){
            mapParams.put("documentType", "1");
        }
        if(company.getOrganization_code_type()!=null&&"2".equals(company.getOrganization_code_type())){
            mapParams.put("documentType", "2");
        }
        if(company.getOrganization_code_type()!=null&&"1".equals(company.getOrganization_code_type())){
            mapParams.put("documentType", "3");
        }
        if (company.getOrganization_code() != null) {
            mapParams.put("organizationCode", company.getOrganization_code());
        }

        if (company.getEnterprise_type() != null) {
            mapParams.put("enterpriseType", company.getEnterprise_type());
        }

        if (company.getManagement_nature() != null) {
            mapParams.put("natureManagement", company.getManagement_nature());

        }

        //联系人

        if (company.getLink_name() != null) {
            mapParams.put("contactsList[0].contactsType", 2);
            mapParams.put("contactsList[0].name", company.getLink_name());
        }
        if (company.getAgent_duty() != null) {
            mapParams.put("contactsList[0].contactsDuty", company.getLink_duty());
        }

        if (company.getLink_phone() != null) {
            mapParams.put("contactsList[0].contactsWay", company.getLink_phone());
        }
        if (company.getLink_email() != null) {
            mapParams.put("contactsList[0].email", company.getLink_email());
        }



        try {
            logger.info("同步机构内容" + mapParams.toString());
            String s = HttpUtil.doPost2(url, mapParams);
            logger.info("同步机构返回值" + s);
            JSONObject json = JSON.parseObject(s);
            if (json != null && json.get("success").toString().equals("true")) {
                map.put("status", true);
                map.put("webID", json.get("data"));
            }
        } catch (Exception ex) {
            map.put("status", false);
            log.error("同步机构",ex);
        }

        return map;
    }



    /**
     * 获取session中存在的推荐码（产品分享上的那个码）
     * @return
     */
    public static String getRecommendCode() {
        String r_code = JedisUtils.get(ConstProp.PRO_R_CODE+IpAddress.getIpAddress(getRequest()));
        if (StringUtils.isNotEmpty(r_code)) {
            try {
                r_code = BASE64Util.decryptBASE64(r_code);
            } catch (Exception e) {
                log.error("产品分享上的那个码",e);
            }
            return r_code;
        } else {
            return "";
        }
        // 利用request获得session
//        HttpServletRequest request = null;
//        if (RequestContextHolder.getRequestAttributes() != null) {
//            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//            HttpSession session = request.getSession();
//            String r_code = (String) session.getAttribute("r_code");
//            if (StringUtils.isNotEmpty(r_code)) {
//                try {
//                    r_code = BASE64Util.decryptBASE64(r_code);
//                } catch (Exception e) {
//                    log.error("产品分享上的那个码",e);
//
//                }
//                return r_code;
//            } else {
//                return "";
//            }
//        } else {
//            return "";
//        }
    }

    /**
     * 设置推荐码到session中（协会链过来的分享码）
     * @return
     */
    public static void setRecommendCodeXH(String rCode) {
        try {
            JedisUtils.set(ConstProp.PRO_R_CODE+IpAddress.getIpAddress(getRequest()),BASE64Util.encryptBASE64(rCode),30*60);
        } catch (Exception e) {
            log.error("UserSupportUtil-setRecommendCodeXH：产品分享码base64加密失败--",e);
        }
//        HttpServletRequest request = null;
//        if (RequestContextHolder.getRequestAttributes() != null) {
//            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//            HttpSession session = request.getSession();
//            try {
//                session.setAttribute("r_code", BASE64Util.encryptBASE64(rCode));
//            } catch (Exception e) {
//                log.error("UserSupportUtil-setRecommendCodeXH：产品分享码base64加密失败--",e);
//            }
//        }
    }

    /**
     * 设置推荐码到session中（产品分享上的那个码）
     * @return
     */
    public static void setRecommendCode(String rCode) {
        JedisUtils.set(ConstProp.PRO_R_CODE+IpAddress.getIpAddress(getRequest()),rCode,30*60);
//        HttpServletRequest request = null;
//        if (RequestContextHolder.getRequestAttributes() != null) {
//            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//            HttpSession session = request.getSession();
//            session.setAttribute("r_code", rCode);
//        }
    }

    public static void delCustomSession(String key) {
        JedisUtils.del(key + IpAddress.getIpAddress(getRequest()));
    }

    /**
     * 自定义设置session中
     * @return
     */
    public static void setCustomSession(String key,String value) {
        JedisUtils.set(key+IpAddress.getIpAddress(getRequest()),value,10 * 60);
//        HttpServletRequest request = null;
//        if (RequestContextHolder.getRequestAttributes() != null) {
//            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//            HttpSession session = request.getSession();
//            session.setAttribute(key, value);
//        }
    }

    /**
     * 获取session中存在的值
     * @return
     */
    public static String getCustomSession(String key) {
        return JedisUtils.get(key+IpAddress.getIpAddress(getRequest()));
        // 利用request获得session
//        HttpServletRequest request = null;
//        if (RequestContextHolder.getRequestAttributes() != null) {
//            request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//            HttpSession session = request.getSession();
//            String r_code = (String) session.getAttribute(key);
//            if (StringUtils.isNotEmpty(r_code)) {
//                return r_code;
//            } else {
//                return "";
//            }
//        } else {
//            return "";
//        }
    }

    public static HttpServletRequest getRequest() {
        if (RequestContextHolder.getRequestAttributes() != null) {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } else {
            return null;
        }
    }

    public static void setQrCode(String key,String value) {
        JedisUtils.set(ConstProp.PRO_QR_CODE+key,value,10 * 60);
    }

    /**
     * 获取session中存在的值
     * @return
     */
    public static String getQrCode(String key) {
        return JedisUtils.get(ConstProp.PRO_QR_CODE+key);
    }

    public static void main(String[] args) {
//        getUserSynchronization();
    }
}