package com.platform.yijia.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.*;
import com.alipay.api.internal.util.AlipayEncrypt;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayUserInfoAuthRequest;
import com.alipay.api.request.AlipayUserInfoShareRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserInfoAuthResponse;
import com.alipay.api.response.AlipayUserInfoShareResponse;
import com.google.gson.Gson;
import com.platform.yijia.config.YiJiaRequest;
import com.platform.yijia.param.request.AppUserInfoRequest;
import com.platform.yijia.pojo.*;
import com.platform.yijia.service.*;
import com.platform.yijia.utils.CodeMsg;
import com.platform.yijia.utils.ResultData;
import com.platform.yijia.utils.redis.RedisCacheUtil;
import com.platform.yijia.utils.weixinapp.AesDecryptUtil;
import com.platform.yijia.utils.weixinapp.WeiXinUserUtil;
import com.sun.org.apache.bcel.internal.classfile.Code;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
@YiJiaRequest()
@CrossOrigin
public class AppUserInfoController {
    private static Logger logger =(Logger) LoggerFactory.getLogger(AppUserInfoController.class);
    @Autowired
    private PayOrderService payOrderService;
    @Autowired
    private AppUserInfoService appUserInfoService;
    @Resource
    private StationService stationService;
    @Resource
    private CustomerPointsService customerPointsService;
    @Resource
    private RedisCacheUtil redisCacheUtil;
    @Resource
    private ElectronicMembershipCardService electronicMembershipCardService;
    @Resource
    private LabelService labelService;

//    String appId = "wxe1135cd390b38a54";        //微信小程序appID
//    String appSecret = "0532c7d9ae876c4ad636df0b1e3b9ddb";      //微信小程序密钥

    //支付宝小程序：公钥、私钥、解密钥
    String PRIVATE_KEY ="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCBVAR3NE/UNvnpXNhmx8xX6se8euxQefbbkWLSykgA9dkP7eaNDyllMtuxjNLaQ1VB26sh2us0VrzSsNA7nmX5aPXu7ckHXH6wBzChCeCdDCHVpoHVq5doehgwMQrvh6aUEcPId+szepvoMmKaSEbFmFapZrTxrPOthI6ENR3RRgs+29vYgru+qJtg3V+tsOr1gkhocU16dX9s7zYfSQQNOmFa01aAhtwI9pDKZVYtELrqOg1dP5WY+jMyXReaDLfAP40H3X7+sVuzTCLu4oVE9CMU2rR+hxwjs6rVWbgE4z13IbM3N8FoPjwJJK0+cXYuORE3yHd4eZj3pEFKvCajAgMBAAECggEADHnAXIdtU/lhrkNIlNGdQrXhQqtQ9IpvZ8rkj5T30S/mGoVGgkD+K0b2rm/5PxjTtqCsJ33oxom/eUuZKsci6yZW4w+JHu6rQevPoxlC06OB+Awx5hzBZFCy2KNCfMzHIu17x3DZ/YNMWt/RZzSlrxX89iZ0OgQHFav9238MO02z9ejRPQEWO4tNb7YyHmi1h56fH2Y+cvLh32QWc+t16tkr5HVY6I2ktMIHYpGU4lyfYEjZ01P7QruAVol2lDNiIYVFXfyDvtwqQNWol6iCswSrDFj0LFsdTWEA1OLZUdD/mfLuBJ9nUAHoCyIh3uR+Aag87DRURcFN92hG0cex4QKBgQDwzmdUC1upAKmRTVEcKUUyDxHZxDhfjRoyhZGf6s/paPvWAVo60VGDC2lQeYqQ8sMnWbpAYWq/yFT2bGK9iPD9UoZWKwLSJuR5RAhiet5WpCfvRmEqEVHJtCaZeV0Q4Al2dPZqu/7opFsrrlY5MvdKJZuLCtL/UBdmkz4BJyFwGQKBgQCJfPoIF5EI/4iYvAQM6FNEQ/kbtb3BF9In9m5GwaMP25ho8evkdI0q5H88FI+i+PdqtdM2gKhuNCXNK/LbF8AzEAu0Qr2clwOq6wQzPU4wl0RNrmdg6H/YC1uTgoy4cr9RdTrqOwXT2UyWghP7AjrifcstZVsrdamOxQHRQ/p0GwKBgQC/uHWH8msNyRs4NkiHlUwkKN9bc+A2Iw9iffmNStQxz4YBwp3mClVNcj5s9feeo8lAgS3KqETnYEZU08JhiK/l4FhYLnJWguSQr9vFHHH8pUGuPWiKp7NoVegNdRTlpJmkGEdAf2DaNFDqHClF7Q/5lquaLgoDf+7BmiVZoZ/7sQKBgF9aw1qLZba063rqo3CETQPClOnIAYQDTmkS++as87fS2ICokK9QunuuICR+KiSgwZBL7OIXFznfhvwmZ/fWICIKFeP+id0py4xmFPKoqSsALool1GMcvVYMgoXq/EgMpW4MfUDokKEeS4TzUII9SLO/BQRGEJYys9dmAV2u5OxTAoGAb5qCQVtmmhO+A0GJG4KZ4xd3i54ZiykrRyCLralBudpI6Vr5+N6yD4R5IdqN2iJKcokt1TxtcJzrunKhUHtOXEiLK/k872iWGQhPeMV+sqWcQXQpKLtRhn4dROOP2qgeOHtdkeLoPlIcfd6TjIsGJJCksXE2hNKr6aljS/zhoKo=";
    String PUBLIC_KEY ="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsXdLLSfp79oe89Q+i1KHx7DfNQjAPWlDaBVtHnwo+jiCkVcNzkeRtz5mZsM3lBURFG6T3eY3qUu0b3FUCSUWd1Q06J4bFI1y4ID3JBCyRi0Up5pcqZzwZqa22QxK3m5/2tabd56FL9C/PPSuQj8gPgT8eUbPUZFeLcnYCLSM0VKU/ZxlXRx9G0MEOZizMxiGdKVwNCE1BxJKTybFz2X0AyakpOWlAZZNQm3JIGfJVHEsc2lgBoeEt8T8d1AJiTdlzAayRGJWpX0nymRZ+RhwQQmuKlPGPvLJDNTV87YvvMttmzlXN32lobK6203PlOoDiLmenj0lxniZfC9tPcRhgwIDAQAB";
    String ALI_APP_ID = "2021002140684377";
    String ENCRYPT_KEY ="K5F2BgcYsRYo8YpRnNSTsg==";

    //获取支付宝用户信息
    @ResponseBody
    @RequestMapping(value = "/getAliUserInfo")
    public String getAliUserInfo(@RequestParam String code){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        logger.info("获取用户信息所需code："+code);
        if(StringUtils.isNotBlank(code)){
            try {
                AlipayClient alipayClient = new DefaultAlipayClient(
                        "https://openapi.alipay.com/gateway.do",
                        ALI_APP_ID,
                        PRIVATE_KEY,
                        "json",
                        "UTF-8",
                        PUBLIC_KEY,
                        "RSA2");
                AlipaySystemOauthTokenRequest alipaySystemOauthTokenRequest = new AlipaySystemOauthTokenRequest();
                alipaySystemOauthTokenRequest.setGrantType("authorization_code");
                alipaySystemOauthTokenRequest.setCode(code);
                AlipaySystemOauthTokenResponse alipaySystemOauthTokenResponse = alipayClient.execute(alipaySystemOauthTokenRequest);
                if (alipaySystemOauthTokenResponse.isSuccess()){
                    logger.info("支付宝小程序获取access_token："+ alipaySystemOauthTokenResponse.getAccessToken());
                    //获取用户信息
                    AlipayUserInfoShareRequest alipayUserInfoShareRequest = new AlipayUserInfoShareRequest();
                    AlipayUserInfoShareResponse alipayUserInfoShareResponse = alipayClient.execute(alipayUserInfoShareRequest, alipaySystemOauthTokenResponse.getAccessToken());
                    resultData = ResultData.success(alipayUserInfoShareResponse);
                }else {
                    resultData = ResultData.success(alipaySystemOauthTokenResponse);
                }
            } catch (AlipayApiException e) {
                e.printStackTrace();
                resultData =ResultData.error(CodeMsg.REQUEST_FAIL);
            }
        }else {
            resultData =ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return gson.toJson(resultData);
    }

    //支付宝小程序用户手机号解密 encryptedData
    @ResponseBody
    @RequestMapping(value = "/alipayEncryptUserPhone", method = RequestMethod.POST, consumes = "application/json")
    public String alipayEncryptUserPhone(@RequestBody JSONObject jsonObject){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(StringUtils.isNotBlank(jsonObject.get("encryptedData").toString())){
            try {
                //解密用户手机号数据
                String encryptedData = jsonObject.get("encryptedData").toString();
                logger.info("支付宝获取手机号要解密数据: " +encryptedData);
                String aes = AlipayEncrypt.decryptContent(encryptedData, "AES", ENCRYPT_KEY, "UTF-8");
                logger.info("支付宝获取手机号解密后的数据：" +aes);
                resultData = ResultData.success(aes);
            } catch (AlipayApiException e) {
                e.printStackTrace();
                resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
            }
        }else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll);
        }
        return gson.toJson(resultData);
    }


    /*
     * 微信小程序根据code获取用户openId和sessionKey
     * @param code
     * @param stationId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getSessionKeyAndOpenID")
    public String getSessionKeyAndOpenID(@RequestParam String code, Integer stationId){
        logger.info("微信小程序获取用户openId和sessionKey入参code和stationId: "+code +"-----" +stationId);
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(stationId !=null  && StringUtils.isNotBlank(code)){
            String appId = "";        //微信小程序appID
            String appSecret = "";      //微信小程序密钥
            Map<String, String> map = stationService.getStationAppIdAndAppSecret(stationId);
            appId = map.get("appId");        //微信小程序appID
            appSecret = map.get("appSecret");      //微信小程序密钥
            logger.info("油站信息："+map.toString());
            Map<String, Object> userSessionKeyAndOpenID = WeiXinUserUtil.getUserSessionKeyAndOpenID(appId, appSecret, code);
            resultData = ResultData.success(userSessionKeyAndOpenID);
        }else {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    /*
     * 解密 encryptedData
     * @param sessionKey
     * @param encryptedData
     * @param iv
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/decryptEncryptedData", method = RequestMethod.POST, consumes = "application/json")
    public String decryptEncryptedData(@RequestBody JSONObject jsonObject){
        logger.info("解密获取手机号前台传入参数：" +jsonObject.toString());
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        String encryptedData = jsonObject.get("encryptedData").toString();
        String sessionKey = jsonObject.get("sessionKey").toString();
        String iv = jsonObject.get("iv").toString();
        if(StringUtils.isNotBlank(encryptedData) && StringUtils.isNotBlank(sessionKey) && StringUtils.isNotBlank(iv) ){
            net.sf.json.JSONObject jsonObject1 = AesDecryptUtil.decryptEncryptedData(encryptedData, sessionKey, iv, "UTF-8");
            resultData = ResultData.success(jsonObject1);
        }else {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    /*
     * JS-SDK使用权限签名算法
     * @param noncestr  随机字符串
     * @param timestamp 时间戳
     * @param url   页面访问路径
     * @param stationId 油站ID
     * @return
     */
    @RequestMapping(value = "/getSignature", method = RequestMethod.GET)
    @ResponseBody
    public String getSignature(@RequestParam String noncestr, String timestamp, String url, Integer stationId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        logger.info("JS-SDK使用权限签名算法前台传来参数: "+"油站ID："+stationId+"; noncestr: " +noncestr+"; timestamp: " +timestamp + "; url: "+url);
        Map<String, String> m = stationService.getStationAppIdAndAppSecret(stationId);
        String gzhAppId ="";
        String gzhAppSecret ="";
        String accessToken ="";
        if(m !=null && m.containsKey("gzhAppId") && m.containsKey("gzhAppSecret")){
            gzhAppId = m.get("gzhAppId");
            gzhAppSecret = m.get("gzhAppSecret");
            accessToken  = this.getTokenByRedisCache(gzhAppId, gzhAppSecret);
            //当前用户登录的公众号redis缓存中的jsapi_ticket
            String appIdTicket =gzhAppId + "-ticket";
            String jsapiTicket ="";
            if(redisCacheUtil.hasKey(appIdTicket)){
                jsapiTicket = redisCacheUtil.getCacheObject(appIdTicket);
            }else {
                //获取jsapi_ticket
                net.sf.json.JSONObject gzhJsapiTicket = WeiXinUserUtil.getGzhJsapiTicket(accessToken);
                if(gzhJsapiTicket.containsKey("ticket")){
                    redisCacheUtil.setCacheObject(appIdTicket, gzhJsapiTicket.get("ticket"));
                    redisCacheUtil.expire(appIdTicket, 7200, TimeUnit.SECONDS);
                    jsapiTicket = gzhJsapiTicket.get("ticket").toString();
                }
            }
            String string1 = "jsapi_ticket="+jsapiTicket + "&noncestr=" +noncestr +"&timestamp=" +timestamp +"&url=" +url;
            logger.info("签名参数拼接："+ string1);
            //sha1加密
            String signature = DigestUtils.sha1Hex(string1);
            logger.info("JS-SDK签名参数sha1加密后："+ signature);
            resultData = ResultData.success(signature);
        }
        return gson.toJson(resultData);
    }

    /*
     * 判断使用小程序支付的用户是否关注公众号
     * @param unionId
     * @param stationId
     * @return
     */
    @RequestMapping(value = "/whetherFollowGzh", method = RequestMethod.GET)
    @ResponseBody
    public String whetherFollowGzh(@RequestParam String unionId, Integer stationId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if (unionId !=null){
            Map<String, String> param = new HashMap<>();
            param.put("unionId", unionId);
            param.put("userType", "1");
            param.put("stationId", stationId.toString());
            String openId = appUserInfoService.whetherFollowGzh(param);
            if(openId !=null){
                Map<String, String> m = stationService.getStationAppIdAndAppSecret(stationId);
                String gzhAppId ="";
                String gzhAppSecret ="";
                String accessToken ="";
                if(m !=null && m.containsKey("gzhAppId") && m.containsKey("gzhAppSecret")){
                    gzhAppId = m.get("gzhAppId");
                    gzhAppSecret = m.get("gzhAppSecret");
                    accessToken  = this.getTokenByRedisCache(gzhAppId, gzhAppSecret);
                    net.sf.json.JSONObject unionIdInfo = WeiXinUserUtil.getUnionIdInfo(accessToken, openId);
                    logger.info("用户公众号信息：" + unionIdInfo);
                    if(unionIdInfo.containsKey("subscribe") && unionIdInfo.get("subscribe").equals(1)){
                        resultData = ResultData.success(CodeMsg.SUCCESS);
                    }else {
                        resultData = ResultData.error(CodeMsg.NO_FollowGzh);
                    }
                }else {
                    resultData = ResultData.error(CodeMsg.SEARCH_APPID_FAIL);
                }
            }else {
                resultData = ResultData.error(CodeMsg.USERGZHINFO_EXSIST);
            }
        }
        return gson.toJson(resultData);
    }

    /*
     * 获取公众号授权后的信息
     * @param code
     * @param stationId
     * @return
     */
    @RequestMapping(value = "/getGzhAuthorizeInfo", method = RequestMethod.GET)
    @ResponseBody
    public String getGzhAuthorizeInfo(@RequestParam String code, Integer stationId){
        logger.info("获取公众号授权后的信息前端传递参数：code："+ code );
        logger.info("获取公众号授权后的信息前端传递参数：stationId：" +stationId);
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(code != null && stationId !=null){
            String gzhAppId ="";
            String gzhAppSecret ="";
            Map<String, String> m = stationService.getStationAppIdAndAppSecret(stationId);
            if(m !=null && m.containsKey("gzhAppId") && m.containsKey("gzhAppSecret")){
                gzhAppId = m.get("gzhAppId");
                gzhAppSecret = m.get("gzhAppSecret");
                net.sf.json.JSONObject gzhAuthorizeInfo = WeiXinUserUtil.getGzhAuthorizeInfo(gzhAppId, gzhAppSecret, code);
                logger.info("授权获取到信息：" + gzhAuthorizeInfo.toString());
                resultData = ResultData.success(gzhAuthorizeInfo);
            }else {
                resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
            }
        }else {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }


    /*
     * 测试用来
     * 获取公众号授权后的信息测试
     * @param code
     * @param stationId
     * @return
     */
    @RequestMapping(value = "/getGzhAuthorizeInfoNew", method = RequestMethod.GET)
    @ResponseBody
    public String getGzhAuthorizeInfoNew(@RequestParam String code, Integer stationId){
        logger.info("获取公众号授权后的信息前端传递参数：code："+ code );
        logger.info("获取公众号授权后的信息前端传递参数：stationId：" +stationId);
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(code != null && stationId !=null){
            String gzhAppId ="";
            String gzhAppSecret ="";
            Map<String, String> m = stationService.getStationAppIdAndAppSecret(stationId);
            if(m !=null && m.containsKey("gzhAppId") && m.containsKey("gzhAppSecret")){
                gzhAppId = m.get("gzhAppId");
                gzhAppSecret = m.get("gzhAppSecret");
                net.sf.json.JSONObject gzhAuthorizeInfo = WeiXinUserUtil.getGzhAuthorizeInfo(gzhAppId, gzhAppSecret, code);
                logger.info("授权获取到信息：" + gzhAuthorizeInfo.toString());
                if(gzhAuthorizeInfo.containsKey("openid")){
                    String openId = gzhAuthorizeInfo.get("openid").toString();
                    String accessToken  = this.getTokenByRedisCache(gzhAppId, gzhAppSecret);
                    net.sf.json.JSONObject unionIdInfo = null;
                    unionIdInfo= WeiXinUserUtil.getUnionIdInfo(accessToken, openId);
                    if(unionIdInfo.containsKey("errcode")){
                        //删除原来key
                        redisCacheUtil.deleteObject(gzhAppId);
                        String token = WeiXinUserUtil.getToken(gzhAppId, gzhAppSecret).getAccessToken();
                        redisCacheUtil.setCacheObject(gzhAppId, token);
                        redisCacheUtil.expire(gzhAppId, 7200, TimeUnit.SECONDS);
                        unionIdInfo= WeiXinUserUtil.getUnionIdInfo(token, openId);
                    }
                    AppUserInfo appUserInfo = new AppUserInfo();
                    if(unionIdInfo.containsKey("openid")){
                        appUserInfo.setBlogOpenid(unionIdInfo.get("openid").toString());
                    }
                    if(unionIdInfo.containsKey("nickname")){
                        appUserInfo.setBlogNickName(unionIdInfo.get("nickname").toString());
                    }
                    if(unionIdInfo.containsKey("sex")){
                        appUserInfo.setSexFlag(unionIdInfo.get("sex").toString());
                    }
                    if(unionIdInfo.containsKey("headimgurl")){
                        appUserInfo.setBlogProfilePhoto(unionIdInfo.get("headimgurl").toString());
                    }
                    if(unionIdInfo.containsKey("unionid")){
                        appUserInfo.setUnionId(unionIdInfo.get("unionid").toString());
                    }
                    appUserInfo.setUserType("1");
                    Map<String, Object> params = new HashMap<>();
                    params.put("openId", openId);                   //注册用户openId
                    params.put("userType", appUserInfo.getUserType());  //用户类型
                    //判断该用户是否已存在
                    int count = appUserInfoService.isExistAppUser(params);
                    if(count > 0){
                        appUserInfoService.updateAppUserInfo(appUserInfo);
                    }else {
                        appUserInfoService.AddAppUserInfo(appUserInfo);
                    }
                    resultData = ResultData.success(unionIdInfo);
                }
            }else {
                resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
            }
        }else {
            resultData = ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }


    /*
     * 获取公众号信息
     * @param openId
     * @param stationId
     * @return
     */
    @RequestMapping(value = "/getGzhUserInfo", method = RequestMethod.GET)
    @ResponseBody
    public String getGzhUserInfo(@RequestParam String openId, Integer stationId){
        Gson gson =new Gson();
        //返回结果集
        ResultData resultData = null;
        if(openId !=null && stationId !=null){
            String gzhAppId ="";
            String gzhAppSecret ="";
            String accessToken ="";
            Map<String, String> m = stationService.getStationAppIdAndAppSecret(stationId);
            if(m !=null && m.containsKey("gzhAppId") && m.containsKey("gzhAppSecret")){
                gzhAppId = m.get("gzhAppId");
                gzhAppSecret = m.get("gzhAppSecret");
                accessToken  = this.getTokenByRedisCache(gzhAppId, gzhAppSecret);
                net.sf.json.JSONObject unionIdInfo = null;
                unionIdInfo= WeiXinUserUtil.getUnionIdInfo(accessToken, openId);
                if(unionIdInfo.containsKey("errcode")){
                    //删除原来key
                    redisCacheUtil.deleteObject(gzhAppId);
                    String token = WeiXinUserUtil.getToken(gzhAppId, gzhAppSecret).getAccessToken();
                    redisCacheUtil.setCacheObject(gzhAppId, token);
                    redisCacheUtil.expire(gzhAppId, 7200, TimeUnit.SECONDS);
                    unionIdInfo= WeiXinUserUtil.getUnionIdInfo(token, openId);
                }
                resultData=ResultData.success(unionIdInfo);
            }
        }else {
            resultData=ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        return gson.toJson(resultData);
    }

    /*
     * 从Redis缓存中获取 tokenCache
     * @param appId
     * @param appSecret
     * @return
     */
    public String getTokenByRedisCache(String appId, String appSecret){
        logger.info("appId参数: "+ appId+" ;appSecret参数: " +appSecret);
        if(!redisCacheUtil.hasKey(appId) || redisCacheUtil.getCacheObject(appId) ==null || redisCacheUtil.getCacheObject(appId).equals("")){
            String token = WeiXinUserUtil.getToken(appId, appSecret).getAccessToken();
            redisCacheUtil.setCacheObject(appId, token);
            redisCacheUtil.expire(appId, 7200, TimeUnit.SECONDS);
            logger.info("Redis缓存中token信息: " + token);
            return token;
        }else {
            return redisCacheUtil.getCacheObject(appId);
        }
    }

    /*
     * 添加用户信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/addAppUserInfo", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public String addAppUserInfo(@RequestBody AppUserInfoRequest request){
        Gson gson =new Gson();
        ResultData resultData=null;
        try{
            logger.info("前端传入参数：" +request.toString());
            AppUserInfo appUserInfo =new AppUserInfo();
            CustomerPoints customerPoints =  new CustomerPoints();
            CustomerElectronicCard customerElectronicCard = new CustomerElectronicCard();   //客户电子卡
            String openId = request.getOpenId();     //此参数用于查询该用户是否已注册过
            if(StringUtils.isNotBlank(request.getBlogNickName())){
                appUserInfo.setBlogNickName(request.getBlogNickName());
                customerPoints.setCustomerName(request.getBlogNickName());
                customerElectronicCard.setCustomerName(request.getBlogNickName());
            }else {
                appUserInfo.setBlogNickName(request.getOpenId());
                customerPoints.setCustomerName(request.getOpenId());
                customerElectronicCard.setCustomerName(request.getOpenId());
            }
            if(StringUtils.isNotBlank(request.getBlogProfilePhoto())){
                appUserInfo.setBlogProfilePhoto(request.getBlogProfilePhoto());
            }
            if(StringUtils.isNotBlank(request.getUnionId())){
                appUserInfo.setUnionId(request.getUnionId());
                customerPoints.setUnionId(request.getUnionId());
                customerElectronicCard.setUnionId(request.getUnionId());
            }

            customerPoints.setCreateTime(new Date());
            customerPoints.setUnionId(request.getUnionId());
            customerPoints.setPoints(0);
            customerPoints.setConsumptionPoints(0);
            customerPoints.setAccumulatePoints(0);
            customerPoints.setInvalidPoints(0);
            customerPoints.setStationId(request.getStationId());
            customerPoints.setStationName(request.getStationName());

            customerElectronicCard.setStationId(request.getStationId());
            customerElectronicCard.setStationName(request.getStationName());

            if(StringUtils.isNotBlank(request.getSexFlag())){
                appUserInfo.setSexFlag(request.getSexFlag());
            }

            if(StringUtils.isNotBlank(request.getMobilePhone())){
                appUserInfo.setMobilePhone(request.getMobilePhone());
                customerPoints.setMobilePhone(request.getMobilePhone());
                customerElectronicCard.setMobilePhone(request.getMobilePhone());
            }

            StationInfo stationInfo = new StationInfo();
            stationInfo.setStationId(request.getStationId());
            //获取油站功能信息
            StationInfo stationInfos = stationService.selectStationInfo(stationInfo);
            appUserInfo.setStationId(stationInfos.getGroupId());
            if(request.getUserType()!=null){
                String userType = request.getUserType();
                appUserInfo.setUserType(userType);
                switch (userType){
                    case "1":       //当为微信用户时
                        AppUserInfo wxInfo = new AppUserInfo();
                        wxInfo.setStationId(stationInfos.getGroupId());
//                        if(stationInfos.getCardRuleFlag().equals("1")){
//                            wxInfo.setStationId(stationInfos.getGroupId());
//                        }
                        //判断当前登录是否存在手机号
                        if(StringUtils.isNotBlank(request.getMobilePhone())){
                            appUserInfo.setMinaOpenid(openId);
                            //wxInfo.setMobilePhone(request.getMobilePhone());
                            wxInfo.setUnionId(request.getUnionId());
                            AppUserInfo wxInfoResult = appUserInfoService.getAppUserInfo(wxInfo);
                            if(wxInfoResult !=null){
                                //如果不为空，则说明存在小程序用户信息；
                                appUserInfo.setUpdateDate(new Date());
                                appUserInfoService.updateAppUserInfo(appUserInfo);
                            }else {
                                //否则，根据unionID查询用户信息
                                wxInfo.setUnionId(request.getUnionId());
                                wxInfo.setMobilePhone(null);
                                AppUserInfo appUserInfoByUnionID = appUserInfoService.getAppUserInfo(wxInfo);
                                if(appUserInfoByUnionID !=null){
                                    //如果不为空，则说明存在公众号用户信息
                                    appUserInfo.setUpdateDate(new Date());
                                    appUserInfoService.updateAppUserInfo(appUserInfo);
                                }else {
                                    //否则，新增用户信息
                                    appUserInfo.setRegisteDate(new Date());
                                    appUserInfoService.AddAppUserInfo(appUserInfo);
                                }
                            }
                        }else {
                            appUserInfo.setBlogOpenid(openId);
                            //如果没有手机号，则说明是用户公众号登录
                            wxInfo.setUnionId(request.getUnionId());
                            AppUserInfo appUserInfoNoPhone = appUserInfoService.getAppUserInfo(wxInfo);
                            if(appUserInfoNoPhone !=null){
                                appUserInfo.setUpdateDate(new Date());
                                appUserInfoService.updateAppUserInfo(appUserInfo);
                            }else {
                                appUserInfo.setRegisteDate(new Date());
                                appUserInfoService.AddAppUserInfo(appUserInfo);
                            }
                        }
                        break;
                    case "2":
                        AppUserInfo aLiInfo  =new AppUserInfo();
                        aLiInfo.setStationId(request.getStationId());
                        if(stationInfos.getCardRuleFlag().equals("1")){
                            aLiInfo.setStationId(stationInfos.getGroupId());
                        }
                        if(StringUtils.isNotBlank(request.getMobilePhone())){
                            //如果手机号不为空，则说明是支付宝小程序登录
                            aLiInfo.setMobilePhone(request.getMobilePhone());
                            AppUserInfo appUserInfos = appUserInfoService.getAppUserInfo(aLiInfo);
                            if(appUserInfos !=null){
                                //如果不为空，则说明用户存在小程序用户信息
                                appUserInfo.setUpdateDate(new Date());
                                appUserInfoService.updateAppUserInfo(appUserInfo);
                                //删除用户支付宝的公众号信息
                                //appUserInfoService.delAliInfo();
                            }else {
                                //如果为空
                                aLiInfo.setALiId(request.getALiId());
                                AppUserInfo appUserInfoByAliId = appUserInfoService.getAppUserInfo(aLiInfo);
                                if(appUserInfoByAliId !=null){
                                    //如果不为空则说明存在支付宝公众号
                                    appUserInfo.setUpdateDate(new Date());
                                    appUserInfoService.updateAppUserInfo(appUserInfo);
                                }else {
                                    appUserInfo.setRegisteDate(new Date());
                                    appUserInfoService.AddAppUserInfo(appUserInfo);
                                }
                            }
                        }else {
                            //如果手机号为空，则说明是公众号登录
                            aLiInfo.setALiId(request.getALiId());
                            AppUserInfo appUserInfoNoPhone = appUserInfoService.getAppUserInfo(aLiInfo);
                            if(appUserInfoNoPhone !=null){
                                //说明存在支付宝小程序用户信息
                                appUserInfo.setUpdateDate(new Date());
                                appUserInfoService.updateAppUserInfo(appUserInfo);
                            }else {
                                //不存在
                                appUserInfo.setRegisteDate(new Date());
                                appUserInfoService.AddAppUserInfo(appUserInfo);
                            }
                        }
                        break;
                }
            }
            if(stationInfos !=null && stationInfos.getStationName() !=null){
                customerPoints.setStationName(stationInfos.getStationName());
                customerElectronicCard.setStationName(stationInfos.getStationName());
            }
//            if(stationInfos.getCardRuleFlag().equals("1")){
//                if(stationInfos.getCardEnabledFlagGroup().equals("1")){
//                    customerPoints.setStationId(stationInfos.getGroupId());
//                    this.insertCustomerPointsInfo(customerPoints, request, stationInfos);
//                }
//            }

            //如果该站开启标签功能
//            if(stationInfos.getLabelFlag() !=null && stationInfos.getLabelFlag().equals("1")){
//                //如果前端传来labelId，则表示一签一码；
//                if(StringUtils.isNotBlank(request.getLabelId()) && StringUtils.isNotBlank(request.getMobilePhone()) && request.getStationId() !=null){
//                    LabelRule labelRule = new LabelRule();
//                    labelRule.setLabelId(Integer.valueOf(request.getLabelId()));
//                    labelRule.setStationId(Integer.valueOf(request.getStationId()));
//                    List<LabelRule> labelRuleList = labelService.getLabelRuleList(labelRule);
//                    if(labelRuleList !=null && labelRuleList.size()>0){
//                        CustomerLabel customerLabel = new CustomerLabel();
//                        customerLabel.setStationId(request.getStationId());
//                        customerLabel.setPhone(request.getMobilePhone());
//                        if(labelRuleList.get(0).getIsAddLabel() !=null && labelRuleList.get(0).getIsAddLabel().equals("1")){
//                            //获取该标签用户信息
//                            CustomerLabel c = labelService.getCustomerLabel(customerLabel);
//                            if(c !=null){
//                                customerLabel.setLabelId(request.getLabelId());
//                                customerLabel.setUpdateBy(request.getCreateBy());
//                                customerLabel.setUpdateTime(new Date());
//                                labelService.updateCustomerLabel(customerLabel);
//                            }else {
//                                customerLabel.setCreateBy(c.getCreateBy());
//                                customerLabel.setCreateTime(new Date());
//                                customerLabel.setDelFlag("0");
//                                customerLabel.setLabelId(request.getLabelId());
//                                labelService.insertCustomerLabel(customerLabel);
//                            }
//                        }
//                    }
//                }
//            }

            //是否开起积分功能
            if(stationInfos.getIntegralRuleFlagGroup().equals("1")){
                customerPoints.setStationId(stationInfos.getGroupId());
                if(stationInfos.getIntegralFlagGroup().equals("1")){
                    this.insertCustomerPointsInfo(customerPoints, request, stationInfos);
                }
            }else {
                if(stationInfos.getIntegralFlag().equals("1")){
                    customerPoints.setStationId(request.getStationId());
                    this.insertCustomerPointsInfo(customerPoints, request, stationInfos);
                }

            }
            //是否开起电子卡功能
            if(stationInfos !=null && stationInfos.getCardRuleFlagGroup().equals("1")){
                customerElectronicCard.setStationId(stationInfos.getGroupId());
                if(stationInfos.getCardEnabledFlagGroup().equals("1")){
                    this.insertCustomerElectronicCard(customerElectronicCard, request, stationInfos);
                }
            }else {
                customerElectronicCard.setStationId(request.getStationId());
                if(stationInfos.getCardEnabledFlag().equals("1")){
                    this.insertCustomerElectronicCard(customerElectronicCard, request, stationInfos);
                }
            }
            resultData = ResultData.success(CodeMsg.SUCCESS);
        }catch (Exception e){
            resultData = ResultData.error(CodeMsg.INSERT_FAIL);
            e.printStackTrace();
        }
        return gson.toJson(resultData);
    }

    //客户积分表信息操作
    public void insertCustomerPointsInfo(CustomerPoints customerPoints, AppUserInfoRequest request, StationInfo stationInfos){
        CustomerPoints customerPointsInfo = customerPointsService.getCustomerPointsInfo(customerPoints);
        if(customerPointsInfo !=null){
            CustomerPoints c = new CustomerPoints();
            c.setUnionId(customerPoints.getUnionId());
            c.setStationId(request.getStationId());
            c.setMobilePhone(request.getMobilePhone());
            c.setStationId(request.getStationId());
            customerPointsService.updateCustomerPointsInfo(c);
        }else {
            customerPointsService.insertCustomerPointsInfo(customerPoints);
        }
    }

    //客户电子会员卡表操作
    public void insertCustomerElectronicCard(CustomerElectronicCard customerElectronicCard, AppUserInfoRequest request, StationInfo stationInfos){
        CustomerCardSetting customerCardSetting = new CustomerCardSetting();
        customerCardSetting.setStationId(request.getStationId());
        if(stationInfos.getCardRuleFlagGroup().equals("1")){
            //表示共享则使用集团ID为查询条件
            customerCardSetting.setStationId(stationInfos.getGroupId());
            customerElectronicCard.setStationId(stationInfos.getGroupId());
        }
        List<CustomerCardSetting> cardRechargeSettingList = electronicMembershipCardService.getCardRechargeSettingList(customerCardSetting);
        if(cardRechargeSettingList !=null && cardRechargeSettingList.size() >0){
            String cardOilsTypeStr = cardRechargeSettingList.get(0).getCardOilsType();
            String[] split = cardOilsTypeStr.split(",");
            for(int i=0; i<split.length; i++){
                customerElectronicCard.setCardOilsType(String.valueOf(split[i]));   //卡的类型
                List<CustomerElectronicCard> electronicCardList = electronicMembershipCardService.getElectronicCardList(customerElectronicCard);
                if(electronicCardList !=null && electronicCardList.size() ==1){
                    electronicMembershipCardService.updateElectronicCardInfoByUnionId(customerElectronicCard);
                }else {
                    String currentTime = String.valueOf(System.currentTimeMillis());
                    String customerNo = request.getStationId() + currentTime;
                    customerElectronicCard.setCustomerNo(customerNo);
                    customerElectronicCard.setAmt(new BigDecimal(0));
                    customerElectronicCard.setCreateTime(new Date());
                    electronicMembershipCardService.insetElectronicCard(customerElectronicCard);
                }
            }
        }
    }

}
