package cn.pluss.platform.controller.home;

import cn.jiguang.common.utils.StringUtils;
import cn.pluss.platform.activityActivate.ActivityActivateService;
import cn.pluss.platform.activityConsumReturn.ActivityConsumReturnService;
import cn.pluss.platform.activityRecharge.ActivityRechargeService;
import cn.pluss.platform.activityRecommend.ActivityRecommendService;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.bestNewActivity.BestNewActivityService;
import cn.pluss.platform.constants.ServiceConstants;
import cn.pluss.platform.controller.phonecode.PhoneCodeController;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.leshua.LeshuaService;
import cn.pluss.platform.mapper.MerchantChannelStatusMapper;
import cn.pluss.platform.memberOrder.MemberOrderService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchant.MerchantRateNewService;
import cn.pluss.platform.merchantChannel.MerchantChannelService;
import cn.pluss.platform.merchantIncome.MerchantIncomeService;
import cn.pluss.platform.merchantMenber.MerchantMenberService;
import cn.pluss.platform.merchantMenberComsume.MerchantMenberComsumeService;
import cn.pluss.platform.merchantMenberRecharge.MerchantMenberRechargeService;
import cn.pluss.platform.merchantOrder.MerchantOrderService;
import cn.pluss.platform.merchantStore.MerchantStoreService;
import cn.pluss.platform.phoneValidateCode.PhoneValidateCodeService;
import cn.pluss.platform.systemConfig.SystemConfigService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.*;
import cn.pluss.platform.wap.HttpUrlConnection;
import cn.pluss.platform.wap.PayUnitedRequest;
import cn.pluss.platform.wap.WechantInfoVO;
import cn.pluss.platform.wap.XmlUtil;
import cn.pluss.platform.wechat.*;
import cn.pluss.platform.wx.WxAccessTokenRequest;
import cn.pluss.platform.wx.WxCommonService;
import cn.pluss.platform.wx.WxUserInfoResponse;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author yuchen
 *
 * @Description (会员出示付款码给商家扫码 ， 从会员余额里面扣款)
 */
@Controller
@RequestMapping("vip")
public class VIPController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @Autowired
    private MerchantMenberService merchantMenberService;

    @Autowired
    private ActivityActivateService activityActivateService;

    @Autowired
    private ActivityConsumReturnService activityConsumReturnService;

    @Autowired
    private ActivityRechargeService activityRechargeService;

    @Autowired
    private MerchantMenberComsumeService merchantMenberComsumeService;

    @Autowired
    private MerchantMenberRechargeService merchantMenberRechargeService;

    @Autowired
    private MemberOrderService memberOrderService;

    @Autowired
    private MerchantStoreService merchantStoreService;

    @Autowired
    private PhoneValidateCodeService phoneValidateCodeService;

    @Autowired
    private ActivityRecommendService activityRecommendService;

    @Autowired
    private BestNewActivityService bestNewActivityService;

    @Autowired
    private PhoneCodeController phoneCodeController;

    @Autowired
    private MerchantBaseInfoService merchantBaseInfoService;

    @Autowired
    private MerchantIncomeService merchantIncomeService;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private UserAppService userAppService;

    @Autowired
    private LeshuaService leshuaService;

    @Autowired
    private MerchantOrderService merchantOrderService;

    @Autowired
    private MerchantChannelStatusMapper merchantChannelStatusMapper;

    @Autowired
    private MerchantChannelService merchantChannelService;


    @Resource
    private MerchantRateNewService merchantRateNewService;

    @Resource
    private WxCommonService wxCommonService;





    private Integer PAGE_SIZE = 10;

    /**
     * bestNewActivity:(最新活动). <br/>
     *
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @GetMapping("/bestNewActivity")
    public ModelAndView bestNewActivity() {
        ModelAndView modelAndView = new ModelAndView("vip/bestNewActivity");
        List<BestNewActivity> bestNewActivityList = bestNewActivityService.queryBestNewActivityList(null);
        Integer i = 0;
        List<BestNewActivity> b = new ArrayList<BestNewActivity>();
        for (BestNewActivity bestNewActivity : bestNewActivityList) {
            if (i == 4) {
                break;
            }
            b.add(bestNewActivity);
            i++;
        }
        modelAndView.addObject("bestNewActivityList", b);
        return modelAndView;
    }

    /**
     * myVIPCard:(我的会员卡). <br/>
     *
     * @return
     * @throws IOException
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @RequestMapping(value = "/myVIPCard", method = RequestMethod.GET)
    public ModelAndView myVIPCard(String storeId, String code, String phone, String nickName, String birthdayDt,
                                  String checkCode) throws IOException {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("error", "请使用微信扫码");
        modelAndView.setViewName("merchant/errorInfo");
        return modelAndView;
    }

    public void getMemberInfo(WeixinOauth2Token wot, MerchantMenber merchantMenber) {
        logger.info("========开始获取头像=======");
        String accessToken = wot.getAccessToken();// token
        String openId = wot.getOpenId();// openId
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
        url = url.replace("ACCESS_TOKEN",accessToken).replace("OPENID",openId);
        try {
            String userInfo = HttpUtil.GET(url);
            logger.info("====-=userInfo========" + JSONObject.toJSONString(userInfo));
            WechantInfoVO wechantInfoVO = WechantInfoVO.convert(userInfo);
            logger.info("===微信返回的参数   用户信息======" + JSONObject.toJSONString(wechantInfoVO));
            merchantMenber.setMemberName(wechantInfoVO.getNickName());
            merchantMenber.setLogo(wechantInfoVO.getHeadimgurl());
            merchantMenber.setSex(wechantInfoVO.getSex());
            merchantMenber.setProvinces(
                    wechantInfoVO.getProvince() + "-" + wechantInfoVO.getCity() + "-" + wechantInfoVO.getCountry());
            merchantMenber.setOpenid(openId);
            logger.info("======存储的merchantMenber========" + JSONObject.toJSONString(merchantMenber));
            merchantMenberService.updateMerchantMenber(merchantMenber);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * vipOpenCard:(会员开卡). <br/>
     *
     * @param storeId
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @GetMapping("/vipOpenCard")
    public ModelAndView vipOpenCard(String storeId, String openid) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("vip/vipOpenCard");
        modelAndView.addObject("storeId", storeId);
        modelAndView.addObject("openid", openid);
        return modelAndView;
    }

    /**
     * openCardSuccess:(点击确认开卡的按钮). <br/>
     *
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @PostMapping("/openCardSuccess")
    @ResponseBody
    public Map<String, Object> openCardSuccess(MerchantMenber merchantMenber, String phoneverify) {
        Map<String, Object> result = new HashMap<>(16);

        if (StringUtils.isEmpty(merchantMenber.getPhone())) {
            result.put("code", 400);
            result.put("msg", "请输入手机号");
            return result;
        }

        if (StringUtils.isEmpty(phoneverify)) {
            result.put("code", 400);
            result.put("msg", "请输入验证码");
            return result;
        }

        if (StringUtils.isEmpty(merchantMenber.getNickName())) {
            result.put("code", 400);
            result.put("msg", "请输入会员名");
            return result;
        }

        if (StringUtils.isEmpty(merchantMenber.getBirthdayDt())) {
            result.put("code", 400);
            result.put("msg", "请输入生日");
            return result;
        }

        PhoneValidateCode phoneValidateCode = new PhoneValidateCode();
        phoneValidateCode.setCode(phoneverify);
        phoneValidateCode.setPhone(merchantMenber.getPhone());
        phoneValidateCode = phoneValidateCodeService.queryPhoneValidateCode(phoneValidateCode);
        if (phoneValidateCode == null) {// 验证码有问题
            result.put("code", "0");
            return result;
        }
        WxAccessTokenRequest tokenRequest = WxAccessTokenRequest.buidWxToken(ParametersUtil.APPID,ParametersUtil.APPSECRET,null, WxConstants.WX_USER_INFO_URL);
        WxUserInfoResponse wxUserInfo = wxCommonService.getWxUserInfo(tokenRequest, merchantMenber.getOpenid());
        wxUserInfo.buildMember(merchantMenber,null);
//        WechatUtils.getWxUserInfo(merchantMenber, merchantMenber.getOpenid());
        try {
            MerchantStore merchantStore = new MerchantStore();
            if (StringUtil.isEmpty(merchantMenber.getStoreId()) || StringUtil.isEmpty(merchantMenber.getOpenid())) {
                result.put("code", "3");
                return result;
            }
            ActivityActivate activityActivate = new ActivityActivate();
            merchantStore.setStoreId(merchantMenber.getStoreId());
            List<MerchantStore> queryMerchantStoreList = merchantStoreService.queryMerchantStoreList(merchantStore);
            if (queryMerchantStoreList != null && queryMerchantStoreList.size() > 0) {
                merchantStore = queryMerchantStoreList.get(0);
                merchantMenber.setMerchantCode(merchantStore.getMerchantCode());
                merchantMenber.setMerchantName(merchantStore.getMerchantName());
                merchantMenber.setStoreName(merchantStore.getStoreName());
                activityActivate.setStoreId(merchantStore.getStoreId());
                activityActivate.setMerchantCode(merchantStore.getMerchantCode());
                // 查询门店的激活送
                List<ActivityActivate> queryActivityActivateList = activityActivateService
                        .queryActivityActivateList(activityActivate);
                if (queryActivityActivateList != null && queryActivityActivateList.size() > 0) {
                    activityActivate = queryActivityActivateList.get(0);
                    Double giveMoney = activityActivate.getGiveMoney();// 赠送金额
                    merchantMenber.setUsableGiveFee(giveMoney);
                    merchantMenber.setTotalGiveFee(giveMoney);
                }
            }
            String number = StringUtil.getBillno();
            merchantMenber.setMemberCode("VIP" + number);
            merchantMenber.setCardNo("VIP" + number);
            merchantMenberService.saveMerchantMenber(merchantMenber);
            phoneValidateCodeService.deletePhoneValidateCode(phoneValidateCode);
            result.put("code", "1");// 正常
        } catch (Exception e) {
            result.put("code", "2");// 系统有误
            e.printStackTrace();
        }
        return result;
    }

    /**
     * vipActivity:(会员活动). <br/>
     *
     * @return
     * @throws IOException
     * @throws ServletException
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @GetMapping("/vipActivity")
    public ModelAndView vipActivity() throws IOException {
        ModelAndView modelAndView = new ModelAndView("vip/vipActivity");
        MerchantMenber merchantMenber = getSessionMerchantMenber();
        if (merchantMenber == null) {
            response.sendRedirect("myVIPCard");
            return null;
        }
        String storeId = merchantMenber.getStoreId();
        // storeId 并获得门店的活动
        ActivityActivate activityActivate = new ActivityActivate();
        activityActivate.setStoreId(storeId);
        // 激活送活动信息
        List<ActivityActivate> activityActivateList = activityActivateService
                .queryActivityActivateList(activityActivate);
        if (activityActivateList != null && activityActivateList.size() > 0) {
            activityActivate = activityActivateList.get(0);
        } else {
            activityActivate = null;
        }
        ActivityConsumReturn activityConsumReturn = new ActivityConsumReturn();
        activityConsumReturn.setStoreId(storeId);
        // 消费返活动信息
        List<ActivityConsumReturn> activityConsumReturnList = activityConsumReturnService
                .queryActivityConsumReturnList(activityConsumReturn);
        if (activityConsumReturnList != null && activityConsumReturnList.size() > 0) {
            activityConsumReturn = activityConsumReturnList.get(0);
        } else {
            activityConsumReturn = null;
        }
        ActivityRecharge activityRecharge = new ActivityRecharge();
        activityRecharge.setStoreId(storeId);
        // 充值活动信息
        List<ActivityRecharge> activityRechargeList = activityRechargeService
                .queryActivityRechargeList(activityRecharge);
        if (activityRechargeList != null && activityRechargeList.size() > 0) {
            activityRecharge = activityRechargeList.get(0);
        } else {
            activityRecharge = null;
        }
        // 推荐送
        ActivityRecommend activityRecommend = new ActivityRecommend();
        activityRecommend.setStoreId(storeId);
        List<ActivityRecommend> queryActivityRecommendList = activityRecommendService
                .queryActivityRecommendList(activityRecommend);
        if (queryActivityRecommendList != null && queryActivityRecommendList.size() > 0) {
            activityRecommend = queryActivityRecommendList.get(0);
        } else {
            activityRecommend = null;
        }
        Map<String, Object> result = new HashMap<String, Object>(16);
        result.put("activityActivate", activityActivate);
        result.put("activityConsumReturn", activityConsumReturn);
        result.put("activityRecharge", activityRecharge);
        result.put("activityRecommend", activityRecommend);
        modelAndView.addAllObjects(result);
        return modelAndView;
    }

    /**
     * storeChoose:(门店选择). <br/>
     *
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @GetMapping("/storeChoose")
    public ModelAndView storeChoose(String membercode) {
        MerchantMenber merchantMenber = (MerchantMenber) request.getSession().getAttribute("sessionMerchantMenber");
        MerchantMenber m = new MerchantMenber();
        m.setOpenid(merchantMenber.getOpenid());
        List<MerchantMenber> merchantMenberList = merchantMenberService.queryMerchantMenberList(m);
        for (MerchantMenber member : merchantMenberList) {
            MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
            merchantBaseInfo.setMerchantCode(member.getMerchantCode());
            merchantBaseInfo = merchantBaseInfoService.queryMerchantBaseInfo(merchantBaseInfo);
            member.setStoreName(merchantBaseInfo.getAlias());
        }
        ModelAndView modelAndView = new ModelAndView("vip/storeChoose");
        Map<String, Object> result = new HashMap<String, Object>(16);
        result.put("merchantMenberList", merchantMenberList);
        modelAndView.addAllObjects(result);
        return modelAndView;
    }

    /**
     * goPay:(去充值). <br/>
     *
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
//    @GetMapping("/goPay")
//    public ModelAndView goPay() {
//        ModelAndView modelAndView = new ModelAndView();
//        MerchantMenber merchantMenber = (MerchantMenber) request.getSession().getAttribute("sessionMerchantMenber");
//        logger.debug(merchantMenber + "");
//        Map<String, Object> result = new HashMap<>(16);
//        modelAndView.setViewName("vip/goPay");
//        result.put("merchantMenber", merchantMenber);
//        String storeId = merchantMenber.getStoreId();
//        String merchantCode = merchantMenber.getMerchantCode();
//        ActivityRecharge activityRecharge = new ActivityRecharge();
//        activityRecharge.setMerchantCode(merchantCode);
//        activityRecharge.setStoreId(storeId);
//        List<ActivityRecharge> queryActivityRechargeList = activityRechargeService
//                .queryActivityRechargeList(activityRecharge);
//        if (queryActivityRechargeList != null && queryActivityRechargeList.size() > 0) {
//            result.put("activityRechargeList", queryActivityRechargeList);
//        }
//        modelAndView.addAllObjects(result);
//        return modelAndView;
//    }

    /**
     * wechatPay:(点击充值按钮进入的方法). <br/>
     *
     * @param rechargeMoney
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @PostMapping("/wechatPay")
    @ResponseBody
    public Map<String, Object> wechatPay(String rechargeMoney) {
        throw new MsgException("暂时不支持该接口");
//        Map<String, Object> map = new HashMap<String, Object>(16);
//        String orderNumber = "CZ700" + StringUtil.getBillno();
//        String openid = (String) request.getSession().getAttribute("SessionOpenid");// 获取openId
//        String unionId = (String) request.getSession().getAttribute("SessionUnionId");// 获取unionId
//        MerchantMenber merchantMenber = (MerchantMenber) request.getSession().getAttribute("sessionMerchantMenber");
//        String merchantCode = merchantMenber.getMerchantCode();
//        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
//        merchantBaseInfo.setMerchantCode(merchantCode);
//        List<MerchantBaseInfo> queryMerchantBaseInfoList = merchantBaseInfoService
//                .queryMerchantBaseInfoList(merchantBaseInfo);
//        if (queryMerchantBaseInfoList != null && queryMerchantBaseInfoList.size() > 0) {
//            merchantBaseInfo = queryMerchantBaseInfoList.get(0);
//        }
//        String userId = merchantBaseInfo.getUserId();
//        logger.info("wechatPay方法=====openid:" + openid + "=========");
//        logger.info("wechatPay方法=====merchantMenber:" + JSONObject.toJSONString(merchantMenber) + "");
//        String appId = ParametersUtil.APPID;
//        PayInfo payInfo = new PayInfo();
//        payInfo.setAppId(appId);
//        if (StringUtil.isNotEmpty(merchantMenber.getStoreName())) {
//            payInfo.setGoodsName(merchantMenber.getStoreName());
//        } else {
//            payInfo.setGoodsName("payment");
//        }
//        payInfo.setOrderNumber(orderNumber);
//        payInfo.setOpenId(openid);
//        payInfo.setOrderPrice(Double.valueOf(rechargeMoney));
//        payInfo.setTransSeq(orderNumber);
//        payInfo.setSubMchId(merchantBaseInfo.getSubMchId());
//        PayUnitedResponse payUnitedResponse;
//        try {
//            // 订单表
//            MemberOrder memberOrder = new MemberOrder();
//            memberOrder.setOrderFee(rechargeMoney);
//            memberOrder.setMemberCode(merchantMenber.getMemberCode());
//            memberOrder.setMerchantCode(merchantMenber.getMerchantCode());
//            memberOrder.setMerchantName(merchantMenber.getMerchantName());
//            memberOrder.setStoreId(merchantMenber.getStoreId());
//            memberOrder.setStoreName(merchantMenber.getStoreName());
//            memberOrder.setCreateDt(new Date());
//            memberOrder.setNickName(merchantMenber.getNickName());
//            memberOrder.setOrderStatus("0");
//            memberOrder.setOrderType("1");
//            memberOrder.setRechargeType("0");
//            memberOrder.setOrderNumber(orderNumber);
//            logger.info("=======wechatPay:fangfa" + JSONObject.toJSONString(memberOrder) + "");
//            memberOrderService.saveMemberOrder(memberOrder);
//            UserApp userApp = new UserApp();
//            userApp.setUserId(Long.valueOf(userId));
//            userApp = userAppService.queryUserApp(userApp);
//            String aisleSwitch = systemConfigService.querySystemConfigValue("aisleSwitch");
//            String payTypeCode = "";
//            String payTypeName = "";
//            map.put("aisleSwitch",aisleSwitch);
//            if ("0".equals(aisleSwitch)) {
//                payTypeCode = "wechatPay";
//                payTypeName = "微信";
//                payUnitedResponse = buildPrePayment(payInfo, request);
//                WechatPayment wechatPayment = toPay(payUnitedResponse);
//                logger.info("===================wechatPayment===============" + JSONObject.toJSONString(wechatPayment));
//                map.put("code", "1");
//                map.put("data", wechatPayment);
//            } else if ("1".equals(aisleSwitch)) {
//                Map<String, String> reqMap = new HashMap<String, String>(16);
//                reqMap.put("service", "get_tdcode");
//                reqMap.put("pay_way", "WXZF");
//                reqMap.put("amount", Double.valueOf(rechargeMoney) * 100 + "");
//                reqMap.put("merchant_id", userApp.getLeshuaMchId());
//                reqMap.put("third_order_id", orderNumber);
//                reqMap.put("jspay_flag", "2");
//                reqMap.put("notify_url", URLEncoder.encode(ParametersUtil.domain + "/wap/merchant/memberPayBack", "utf-8"));
//                reqMap.put("jump_url", URLEncoder.encode(ParametersUtil.domain + "/wap/vip/jumpUrl?storeId="+merchantMenber.getStoreId()+"&leshuaMchId=" + userApp.getLeshuaMchId() + "&orderNumber=" + orderNumber, "utf-8"));
//                reqMap.put("client_ip", getIpAddress(request));
//                if (StringUtil.isNotEmpty(merchantMenber.getStoreName())) {
//                    reqMap.put("body", merchantMenber.getStoreName());
//                } else if (StringUtil.isNotEmpty(merchantMenber.getMerchantName())) {
//                    reqMap.put("body", merchantMenber.getMerchantName());
//                } else {
//                    reqMap.put("body", "leshuaPay");
//                }
//                reqMap.put("nonce_str", StringUtil.genRandomNum(32));
//                payTypeCode = "leshuaPay1";
//                payTypeName = "乐刷微信支付";
//                String apKey = "60E3F31EDEC8061C33721737B36FA86D";
//                System.out.println("reqMap===========================" + JSONObject.toJSONString(reqMap));
//                String requestPay = leshuaService.requestPay(reqMap, apKey, true);
//                System.out.println("requestPay===========================" + requestPay);
//                map = XmlUtil.toMapLeshua(requestPay);
//                map.put("code", "2");
//            }else if("2".equals(aisleSwitch)){
//                payTypeCode = "sxfPay1";
//                payTypeName = "随行微信支付";
//                MerchantStore store = new MerchantStore();
//                store.setStoreId(merchantMenber.getStoreId());
//                store.setStoreName(merchantMenber.getStoreName());
//                QueryWrapper<MerchantChannel> channelQueryWrapper = new QueryWrapper<MerchantChannel>().eq("channelCode","SXF");
//                MerchantChannel channel = merchantChannelService.getOne(channelQueryWrapper);
//                if(channel == null){
//                    map.put("code", "1");
//                    map.put("msg", "未获取到当前通道配置信息！");
//                    return map;
//                }
//                if(!"1".equals(channel.getStatus())){
//                    map.put("code", "0");
//                    map.put("msg", "通道已经关闭！");
//                    return map;
//                }
//                QueryWrapper<MerchantChannelStatus> statusQueryWrapper = new QueryWrapper<MerchantChannelStatus>().eq("channel",channel.getId())
//                        .eq("merchantCode",merchantCode);
//                MerchantChannelStatus channelStatus = merchantChannelStatusMapper.selectOne(statusQueryWrapper);
//                if(channelStatus == null){
//                    map.put("code", "0");
//                    map.put("msg", "当前交易商户还未进件！");
//                    return map;
//                }
//                if(!channelStatus.isPayment()){
//                    map.put("code", "0");
//                    map.put("msg", "当前交易商户进件还未成功！");
//                    return map;
//                }
//                Map<String,String> params = new HashMap<>();
//                params.put("comsumeMoney",rechargeMoney);
//                params.put("payWay","WXZF");
//                params.put("openid",merchantMenber.getOpenid());
//                //Map<String, Object> resultMap = sxfPayService.tradePay(params, request, store, orderNumber, channelStatus);
//                Map<String, Object> resultMap = new HashMap<>();
//                if(!"1".equals(resultMap.get("code"))){
//                    map.put("code", "0");
//                    map.put("msg", resultMap.get("msg"));
//                    return map;
//                }
//                Map<String,Object> result = (Map<String, Object>) resultMap.get("data");
//                map.put("code", "2");
//                map.put("data",result);
//            }else{
//                map.put("code", "0");
//                map.put("data", null);
//                map.put("msg", "暂不支持其他通道！");
//            }
//            MerchantOrder merchantOrder = new MerchantOrder();
//            merchantOrder.setMerchantCode(merchantCode);
//            merchantOrder.setStoreId(merchantMenber.getStoreId());
//            merchantOrder.setStoreName(merchantMenber.getStoreName());
//            merchantOrder.setMerchantName(merchantMenber.getMerchantName());
//            merchantOrder.setOrderNumber(orderNumber);
//            merchantOrder.setStaffCode(merchantMenber.getStoreId());
//            merchantOrder.setStaffName(merchantMenber.getStoreName());
//            merchantOrder.setPayTypeCode(payTypeCode);
//            merchantOrder.setPayTypeName(payTypeName);
//            merchantOrder.setConsumeFee(Double.valueOf(rechargeMoney));
//            merchantOrder.setUserImg(merchantMenber.getLogo());
//            merchantOrder.setNickName(merchantMenber.getNickName());
//
//            BigDecimal rate = merchantRateNewService.getMchRate(merchantBaseInfo.getMerchantCode(),merchantOrder.getPayTypeCode(), merchantOrder.getConsumeFee());
//
//            BigDecimal calcRate = rate.divide(new BigDecimal(10000));
//
//            merchantOrder.setEnterFee(StringUtil.bigDecimal(
//                    Double.parseDouble(rechargeMoney) - Double.parseDouble(rechargeMoney) * calcRate.doubleValue()));
//            Date date = new Date();
//            merchantOrder.setCreateDt(date);
//            merchantOrder.setUpdateTime(date);
//            merchantOrder.setStatus("5");
//            merchantOrder.setAisleSwitch(aisleSwitch);
//            merchantOrder.setOrderType("3");
//            merchantOrderService.save(merchantOrder);
//        } catch (Exception e) {
//            map.put("code", "0");
//            e.printStackTrace();
//        }
//        return map;
    }

    /**
     * jumpUrl:(乐刷支付完成后的跳转地址). <br/>
     *
     * @param orderNumber
     * @param leshuaMchId
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @GetMapping("/jumpUrl")
    public ModelAndView jumpUrl(String orderNumber, String leshuaMchId,String storeId) {
        logger.info("====订单号====" + orderNumber);
        if (orderNumber.contains("?")) {
            String str[] = orderNumber.split("[?]");
            orderNumber = str[0];
        }
        logger.info("=========当前商户乐刷商户id==========" + leshuaMchId);
        ModelAndView modelAndView = new ModelAndView();
        Map<String, String> reqMap = new HashMap<>(16);
        Map<String, Object> mapLeshua;
        try {
            reqMap.put("service", "query_status");
            reqMap.put("merchant_id", leshuaMchId);
            reqMap.put("third_order_id", orderNumber);
            reqMap.put("nonce_str", StringUtil.getBillno());
            String requestPay = leshuaService.requestPay(reqMap, "60E3F31EDEC8061C33721737B36FA86D", true);
            mapLeshua = XmlUtil.toMapLeshua(requestPay);
            String resp_code = (String) mapLeshua.get("resp_code");
            if ("0".equals(resp_code)) {
                String result_code = (String) mapLeshua.get("result_code");
                if ("0".equals(result_code)) {
                    String status = (String) mapLeshua.get("status");
                    if ("2".equals(status)) {
                        modelAndView.setViewName("vip/paySuccess");
                    } else {
                        modelAndView.setViewName("vip/payFail");
                    }
                } else {
                    modelAndView.addObject("message", "支付结果查询错误");
                    modelAndView.setViewName("merchant/error");
                }
            } else {
                modelAndView.addObject("message", "支付结果查询错误");
                modelAndView.setViewName("merchant/error");
            }
        } catch (Exception e) {
            e.printStackTrace();
            modelAndView.addObject("message", "支付结果查询错误");
            modelAndView.setViewName("merchant/error");
        }
        modelAndView.addObject("url",ParametersUtil.getRequestPrefix(request));
        modelAndView.addObject("storeId",storeId);
        return modelAndView;
    }

    public static Set<String> resExcludedSignParams() {
        Set<String> exludedSignParams = new HashSet<>(2);
        exludedSignParams.add("sign");
        exludedSignParams.add("error_code");
        return exludedSignParams;
    }

    /**
     * rechargeSuccess:(充值成功页面). <br/>
     *
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @GetMapping("/rechargeSuccess")
    public ModelAndView rechargeSuccess() {
        MerchantMenber merchantMenber = (MerchantMenber) request.getSession().getAttribute("sessionMerchantMenber");
        ModelAndView modelAndView = new ModelAndView("vip/paySuccess");
        modelAndView.addObject("url", ParametersUtil.getRequestPrefix(request));
        modelAndView.addObject("storeId", merchantMenber.getStoreId());
        return modelAndView;
    }

    /**
     * rechargeFail:(充值失败页面). <br/>
     *
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @GetMapping("/rechargeFail")
    public ModelAndView rechargeFail() {
        MerchantMenber merchantMenber = (MerchantMenber) request.getSession().getAttribute("sessionMerchantMenber");
        ModelAndView modelAndView = new ModelAndView("vip/payFail");
        modelAndView.addObject("storeId", merchantMenber.getStoreId());
        modelAndView.addObject("url",ParametersUtil.getRequestPrefix(request));
        return modelAndView;
    }

    /**
     * goPayment:(去支付). <br/>
     *
     * @return
     * @throws IOException
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @GetMapping("/goPayment")
    public ModelAndView goPayment() {
        ModelAndView modelAndView = new ModelAndView("vip/goPayment");
        Map<String, Object> result = new HashMap<String, Object>(16);
        MerchantMenber merchantMenber = getSessionMerchantMenber();
        result.put("website", merchantMenber.getCardNo());
        modelAndView.addAllObjects(result);
        return modelAndView;
    }

//	/**
//	 * 
//	 * inputComsumeMoney:(输入消费金额跳转). <br/> 
//	 *
//	 * @author Administrator 
//	 * @param cardNo
//	 * @param storeId
//	 * @return 
//	 * @since JDK 1.8
//	 */
//	@GetMapping("/inputComsumeMoney")
//	public ModelAndView inputComsumeMoney(String cardNo,String storeId) {
//		ModelAndView modelAndView=new ModelAndView("vip/inputComsumeMoney");
//		modelAndView.addObject("cardNo", cardNo);
//		modelAndView.addObject("storeId", storeId);
//		return modelAndView;
//	}

    /**
     *
     * paySuccessOrFail:(支付成功or支付失败). <br/>
     *
     *
     * @author Administrator
     * @return
     * @since JDK 1.8
     * @params comsumeMoney(消费金额)
     */
//	@GetMapping("/paySuccessOrFail")
//	public ModelAndView paySuccessOrFail(MerchantMenber merchantMenber,String comsumeMoney) {
//		ModelAndView modelAndView=new ModelAndView();
//		try {
//			List<MerchantMenber> queryMerchantMenberList = merchantMenberService.queryMerchantMenberList(merchantMenber);
//			if(queryMerchantMenberList!=null&&queryMerchantMenberList.size()>0) {
//				merchantMenber = queryMerchantMenberList.get(0);
//			}else {
//				modelAndView.setViewName("vip/payFail");
//				return modelAndView;
//			}
//			//充值金额
//			Double usableRechargeFee = merchantMenber.getUsableRechargeFee();
//			if(usableRechargeFee==null) {
//				usableRechargeFee=0.0d;
//			}
//			//赠送金额
//			Double usableGiveFee = merchantMenber.getUsableGiveFee();
//			if(usableGiveFee==null) {
//				usableGiveFee=0.0d;
//			}
//			//账户余额
//			Double count=usableRechargeFee+usableGiveFee;
//			if(StringUtil.isNotEmpty(comsumeMoney)) {
//				Double comsume=Double.valueOf(comsumeMoney);
//				if(comsume>count) {
//					//支付失败跳转的页面
//					modelAndView.setViewName("vip/payFail");
//					return modelAndView;
//				}else {
//					Double giveFee=0.0d;
//					//赠送余额大于等于消费金额
//					if(usableGiveFee>=comsume) {
//						giveFee=usableGiveFee-comsume;
//						merchantMenber.setUsableGiveFee(giveFee);
//						merchantMenberService.updateMerchantMenber(merchantMenber);
//						//赠送余额小于消费金额
//					}else {
//						Double recharge=usableRechargeFee-comsume-usableGiveFee;
//						merchantMenber.setUsableGiveFee(giveFee);
//						merchantMenber.setUsableRechargeFee(recharge);
//						merchantMenberService.updateMerchantMenber(merchantMenber);
//					}
//				}
//				//支付成功跳转的页面
//				modelAndView.setViewName("vip/paySuccess");
//			}
//		} catch (NumberFormatException e) {
//			modelAndView.setViewName("vip/payFail");
//			e.printStackTrace();
//		}
//		return modelAndView;
//	}

    /**
     * consumeLog:(消费记录跳转). <br/>
     *
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @GetMapping("/consumeLog")
    public ModelAndView consumeLog() {
        ModelAndView modelAndView = new ModelAndView("vip/consumeLog");
        Map<String, Object> result = new HashMap<String, Object>(16);
        MerchantMenber merchantMenber = getSessionMerchantMenber();
        result.put("memberCode", merchantMenber.getMemberCode());
        result.put("storeId", merchantMenber.getStoreId());
        modelAndView.addAllObjects(result);
        return modelAndView;
    }

    /**
     * goConsumeLog:(消费记录). <br/>
     *
     * @param currPage
     * @param memberCode
     * @param storeId
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @PostMapping("/goConsumeLog")
    @ResponseBody
    public Map<String, Object> goConsumeLog(@RequestParam(defaultValue = "1") Integer currPage, String memberCode,
                                            String storeId) {
        Map<String, Object> map = new HashMap<String, Object>(16);
        if (StringUtil.isNotEmpty(memberCode)) {
            map.put("memberCode", memberCode);
        }
        if (StringUtil.isNotEmpty(storeId)) {
            map.put("storeId", storeId);
        }
        map.put("orderStatus", "1");
        map.put("pageSize", PAGE_SIZE);
        map.put("offset", (currPage - 1) * PAGE_SIZE);
        Map<String, Object> result = new HashMap<>(16);
        List<MerchantMenberComsume> merchantMenberComsumeList = merchantMenberComsumeService
                .queryMerchantMenberComsumePage(map);
        Integer count = merchantMenberComsumeService.queryMerchantMenberComsumePageCount(map);
        result.put("merchantMenberComsumeList", merchantMenberComsumeList);
        result.put("count", count);
        result.put("pageCount", StringUtil.getPageCount(count, PAGE_SIZE));
        result.put("currPage", currPage);
        return result;
    }

    /**
     * rechargeLog:(充值记录跳转). <br/>
     *
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @GetMapping("/rechargeLog")
    public ModelAndView rechargeLog() {
        ModelAndView modelAndView = new ModelAndView("vip/rechargeLog");
        Map<String, Object> result = new HashMap<String, Object>(16);
        MerchantMenber merchantMenber = getSessionMerchantMenber();
        result.put("memberCode", merchantMenber.getMemberCode());
        result.put("storeId", merchantMenber.getStoreId());
        modelAndView.addAllObjects(result);
        return modelAndView;
    }

    /**
     * goRechargeLog:(充值记录). <br/>
     *
     * @param currPage
     * @param memberCode
     * @param storeId
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @PostMapping("/goRechargeLog")
    @ResponseBody
    public Map<String, Object> goRechargeLog(@RequestParam(defaultValue = "1") Integer currPage, String memberCode,
                                             String storeId) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (StringUtil.isNotEmpty(memberCode)) {
            map.put("memberCode", memberCode);
        }
        if (StringUtil.isNotEmpty(storeId)) {
            map.put("storeId", storeId);
        }
        map.put("orderStatus", "1");
        map.put("pageSize", PAGE_SIZE);
        map.put("offset", (currPage - 1) * PAGE_SIZE);
        List<MerchantMenberRecharge> merchantMenberRechargeList = merchantMenberRechargeService
                .queryMerchantMenberRechargePage(map);
        Integer count = merchantMenberRechargeService.queryMerchantMenberRechargePageCount(map);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("merchantMenberRechargeList", merchantMenberRechargeList);
        result.put("count", count);
        result.put("pageCount", StringUtil.getPageCount(count, PAGE_SIZE));
        result.put("currPage", currPage);
        return result;
    }

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

    /**
     * getUserCode:(授权). <br/>
     *
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     *
     * @author Administrator
     * @since JDK 1.8
     */
    @GetMapping("/auth")
    public ModelAndView getUserCode(HttpServletResponse response, String storeId, String phone, String nickName,
                                    String birthdayDt) throws UnsupportedEncodingException {
        ModelAndView modelAndView = new ModelAndView("vip/auth");
        Map<String, Object> result = new HashMap<String, Object>(16);
        String APPID = ParametersUtil.APPID;
        result.put("appId", APPID);
        if (!StringUtil.isEmpty(nickName)) {
            nickName = URLDecoder.decode(nickName, "UTF-8");
        }
        logger.error("======auth  fangfa=============" + nickName);
        logger.debug("=======appId==" + APPID + "==appId===========");
        result.put("appSecret", ParametersUtil.APPSECRET);
        logger.debug("=======appSecret==" + APPID + "==appSecret===========");
        modelAndView.addAllObjects(result);
        // 判断是微信，跳转微信授权
        String ua = request.getHeader("user-agent").toLowerCase();
        String redirectUri = "";
        if (StringUtil.isNotEmpty(phone)) {
            MerchantMenber merchantMenber = new MerchantMenber();
            MerchantStore merchantStore = new MerchantStore();
            merchantStore.setStoreId(storeId);
            merchantStore = merchantStoreService.queryMerchantStore(merchantStore);
            merchantMenber.setStoreId(storeId);
            if (StringUtil.isNotEmpty(nickName)) {
                merchantMenber.setNickName(nickName);
            }
            merchantMenber.setPhone(phone);
            List<MerchantMenber> queryMerchantMenberList = merchantMenberService
                    .queryMerchantMenberList(merchantMenber);
            merchantMenber.setMerchantCode(merchantStore.getMerchantCode());
            String memberCode = "VIP" + StringUtil.getBillno();
            merchantMenber.setMemberCode(memberCode);
            merchantMenber.setCardNo(memberCode);
            merchantMenber.setMerchantName(merchantStore.getMerchantName());
            merchantMenber.setStoreName(merchantStore.getStoreName());
            merchantMenber.setBirthdayDt(birthdayDt);
            ActivityActivate activityActivate = new ActivityActivate();
            if (StringUtil.isNotEmpty(storeId)) {
                redirectUri = "/vip/myVIPCard?storeId=" + storeId + "&phone=" + phone;// 回调地址
                activityActivate.setStoreId(storeId);
                List<ActivityActivate> queryActivityActivateList = activityActivateService
                        .queryActivityActivateList(activityActivate);// 查询门店的激活送
                if (queryActivityActivateList != null && queryActivityActivateList.size() > 0) {
                    activityActivate = queryActivityActivateList.get(0);
                    Double giveMoney = activityActivate.getGiveMoney();// 赠送金额
                    merchantMenber.setUsableGiveFee(giveMoney);
                    merchantMenber.setTotalGiveFee(giveMoney);
                }
            } else {
                redirectUri = "/vip/myVIPCard";
            }
            if (queryMerchantMenberList == null || queryMerchantMenberList.size() == 0) {
                saveMemberOrderSS(merchantMenber, activityActivate);
                merchantMenberService.saveMerchantMenber(merchantMenber);
            }
            request.getSession().setAttribute("sessionMerchantMenber", merchantMenber);
        } else {
            if (StringUtil.isNotEmpty(storeId)) {
                redirectUri = ParametersUtil.getRequestPrefix(request)+ "/vip/myVIPCard?storeId=" + storeId;
            } else {
                redirectUri = ParametersUtil.getRequestPrefix(request) + "/vip/myVIPCard";
            }
        }
        logger.debug("=======回调地址" + redirectUri + "回调地址===========");
        request.setAttribute("url", redirectUri);
        logger.debug("=======判断是否是微信" + ua + "判断是否是微信===========");
        logger.debug("=======判断是否是微信" + ua.contains("micromessenger") + "判断是否是微信===========");
        if (ua.contains("micromessenger")) {
            try {
                redirectUri = java.net.URLEncoder.encode(redirectUri, "utf-8");
                logger.debug("=======回调地址" + redirectUri + "回调地址===========");
                response.sendRedirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APPID
                        + "&redirect_uri=" + redirectUri
                        + "&response_type=code&scope=snsapi_base&storeId=123#wechat_redirect");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        return modelAndView;
    }


    /**
     * getUserOpenId:(通过code获取openId). <br/>
     *
     * @param code
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
//    private WeixinOauth2Token getUserOpenId(String code) {
//        String appId = ParametersUtil.APPID;
//        String appSecret = ParametersUtil.APPSECRET;
//        WeixinOauth2Token wot = null;
//        System.out.println("=====getUserOpenId: appId=" + appId + ",appSecret=" + appSecret);
//        if (!"authdeny".equals(code)) {
//            if (code != null) {
//                wot = Oauth2Util.getOauth2AccessToken(appId, appSecret, code);
//                System.out.println("wot-------------------------" + JSONObject.toJSONString(wot));
//                request.getSession().setAttribute("SessionOpenid", wot.getOpenId());
//                request.getSession().setAttribute("SessionUnionId", wot.getOpenId());
//            }
////            MerchantMenber merchantMenber = new MerchantMenber();
////            merchantMenber.setOpenid(wot.getOpenId());
////            System.out.println("wot-------------------------" + JSONObject.toJSONString(merchantMenber));
////            System.out.println("=====getUserOpenId: openid=" + wot.getOpenId());
//        }
//        return wot;
//    }

    /**
     * buildPrePayment:(创建预支付信息). <br/>
     *
     * @param payInfo
     * @return
     * @throws Exception
     *
     * @author Administrator
     * @since JDK 1.8
     */
    private PayUnitedResponse buildPrePayment(PayInfo payInfo, HttpServletRequest request) throws Exception {
        logger.debug("buildPrePayment 创建预支付信息====" + payInfo);
        String appId = ParametersUtil.APPID;
        String pId = ParametersUtil.PID;
        String pKey = ParametersUtil.KEY;
        payInfo.setPid(pId);
        payInfo.setPkey(pKey);
        payInfo.setAppId(appId);
        // 创建请求对象
        PayUnitedRequest payUnitedRequest = new PayUnitedRequest();
        String notify_url = ParametersUtil.getSelfRedirectUrl(request, "/vip/wechatCallback");
        Map<String, String> result = payUnitedRequest.getMap(payInfo, notify_url, getIpAddress(request));
        String xml = result.get("xml");
        String response = HttpUrlConnection.httpXML(ServiceConstants.WEIXIN_PAY_UNIFIED_URL, xml);
        PayUnitedResponse payUnitedResponse = WeiXinUtil.xmlToPayUnitedResponse(response);
        logger.info("=buildPrePayment==================fanhuijieguo" + response);
        // 发起支付请求
        return payUnitedResponse;
    }

    /**
     * 微信支付回调
     *
     * @throws IOException
     */
    @PostMapping("/wechatCallback")
    @ResponseBody
    public void wechatCallback() throws IOException {
        try {
            String xml = readRequestMsg(request);
            System.out.println("======================callback parameters info====================：" + xml);
            // 解析报文
            PayNotify payNotify = WeiXinUtil.xmlToPayNotify(xml);
            if ("SUCCESS".equals(payNotify.getReturn_code())) {
                String orderNumber = payNotify.getOut_trade_no();
                UpdateOrder(orderNumber, payNotify);
                UpdateMerchantOrder(orderNumber, payNotify);
            }
        } catch (Exception e) {
            System.out.println("微信支付后台回调处理异常！===" + e);
        }
        response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
    }

    private void UpdateMerchantOrder(String orderNumber, PayNotify payNotify) throws Exception {
        String transaction_id = payNotify.getTransaction_id();
        String time_end = payNotify.getTime_end();
        MerchantOrder merchantOrder = new MerchantOrder();
        merchantOrder.setOrderNumber(orderNumber);
        List<MerchantOrder> queryMerchantOrderList = merchantOrderService.list(new QueryWrapper<>(merchantOrder));
        if (queryMerchantOrderList != null && queryMerchantOrderList.size() > 0) {
            merchantOrder = queryMerchantOrderList.get(0);
            if ("1".equals(merchantOrder.getStatus())) {
                return;
            }
            MerchantOrder m = new MerchantOrder();
            m.setThirdTransNo(transaction_id);
            m.setStatus("1");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm:ss");
            m.setTransDt(sdf.parse(time_end));
            m.setId(merchantOrder.getId());
            merchantOrderService.updateById(m);
        }

    }

    /**
     * toPay:(支付). <br/>
     *
     * @param payUnitedResponse
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    private WechatPayment toPay(PayUnitedResponse payUnitedResponse) {
        logger.info("==================payUnitedResponse======================="
                + JSONObject.toJSONString(payUnitedResponse));
        String appId = ParametersUtil.APPID;
        String appSecret = ParametersUtil.APPSECRET;
        String pKey = ParametersUtil.KEY;
        WechatPayment wechatPayment = new WechatPayment();
        String nonceStr = UUID.randomUUID().toString();
        wechatPayment.setAppId(appId);
        wechatPayment.setNonceStr(nonceStr);
        String timeStamp = System.currentTimeMillis() + "";
        String packageMsg = "prepay_id=" + payUnitedResponse.getPrepay_id();
        wechatPayment.setPackageMsg(packageMsg);
        String signType = "MD5";
        String paySgin = paySign(pKey, packageMsg, appId, timeStamp, appSecret, nonceStr, signType).toUpperCase();

        wechatPayment.setSignType(signType);
        wechatPayment.setPaySgin(paySgin);
        wechatPayment.setTimeStamp(timeStamp);
        return wechatPayment;
    }

    /**
     * paySign:(获取Sign). <br/>
     *
     * @param paternerKey
     * @param packageMsg
     * @param appId
     * @param timeStamp
     * @param appkey
     * @param nonceStr
     * @param signType
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    private String paySign(String paternerKey, String packageMsg, String appId, String timeStamp, String appkey,
                           String nonceStr, String signType) {

        Map<String, String> param = new HashMap<String, String>();
        param.put("appId", appId);
        param.put("timeStamp", timeStamp);
        param.put("nonceStr", nonceStr);
        param.put("package", packageMsg);
        param.put("signType", signType);
        // 去除空串
        Map<String, String> array = MicroPayCore.paraFilter(param);
        String sign = MicroPayCore.buildMysign(array, paternerKey);// 排序

        return sign;
    }

    /**
     * merchantIncome:(添加收益记录). <br/>
     *
     *
     * @author Administrator
     * @since JDK 1.8
     */
    private void merchantIncome(MemberOrder memberOrder, String payTypeCode) {
        MerchantIncome merchantIncome = new MerchantIncome();
        merchantIncome.setMerchantCode(memberOrder.getMerchantCode());
        merchantIncome.setMerchantName(memberOrder.getMerchantName());
        merchantIncome.setStoreId(memberOrder.getStoreId());
        merchantIncome.setStoreName(memberOrder.getStoreName());
        merchantIncome.setDealFee(Double.valueOf(memberOrder.getOrderFee()));
        merchantIncome.setIncomeFee(Double.valueOf(memberOrder.getOrderFee()));
        merchantIncome.setPayTypeCode(payTypeCode);
        merchantIncome.setPayTypeName("会员充值");
        merchantIncome.setCreateTime(memberOrder.getCreateDt());
        merchantIncomeService.saveMerchantIncome(merchantIncome);
    }

    /**
     * 修改订单状态
     *
     * @param orderNumber
     * @param payNotify
     */
    private void UpdateOrder(String orderNumber, PayNotify payNotify) {
        // 支付商返回的支付订单号 暂时没有字段
        String transaction_id = payNotify.getTransaction_id();
        String openid = payNotify.getOpenid();
        logger.error("进入修改订单方法==========" + transaction_id);
        // 订单表
        MemberOrder memberOrder = new MemberOrder();
        memberOrder.setOrderNumber(orderNumber);
        memberOrder = memberOrderService.queryMemberOrder(memberOrder);
        if ("1".equals(memberOrder.getOrderStatus())) {
            return;
        }
        memberOrder.setOrderStatus("1");
        memberOrder.setWeChatTransNo(transaction_id);
        memberOrderService.updateMemberOrder(memberOrder);
        MerchantMenber merchantMenber = new MerchantMenber();// 会员表
        merchantMenber.setOpenid(openid);// 会员openId
        merchantMenber.setMemberCode(memberOrder.getMemberCode());// 会员编码
        List<MerchantMenber> queryMerchantMenberList = merchantMenberService.queryMerchantMenberList(merchantMenber);
        if (queryMerchantMenberList != null && queryMerchantMenberList.size() > 0) {
            merchantMenber = queryMerchantMenberList.get(0);
            merchantIncome(memberOrder, "2");
        }
        logger.error("===============merchantMenber=====" + JSONObject.toJSONString(merchantMenber));
        if (StringUtil.isNotEmpty(memberOrder.getOrderFee())) {
            logger.error("进入修改订单方法===OrderFee=======" + memberOrder.getOrderFee());
            MerchantMenberRecharge merchantMenberRecharge = new MerchantMenberRecharge();
            Double usableRechargeFee = merchantMenber.getUsableRechargeFee() == null ? new Double(0)
                    : merchantMenber.getUsableRechargeFee();
            logger.error("usableRechargeFee==qian==" + usableRechargeFee);
            merchantMenber.setUsableRechargeFee(
                    StringUtil.bigDecimal(usableRechargeFee + Double.parseDouble(memberOrder.getOrderFee())));
            logger.error("usableRechargeFee==hou==" + merchantMenber.getUsableRechargeFee());
            // 在存会员充值表之前查一下当前店铺的充值
            // 当前充值的店铺id
            String storeId = merchantMenber.getStoreId();
            ActivityRecharge activityRecharge = new ActivityRecharge();
            activityRecharge.setStoreId(storeId);
            List<ActivityRecharge> queryActivityRechargeList = activityRechargeService
                    .queryActivityRechargeList(activityRecharge);// 根据店铺id查询店铺的充值活动
            logger.error("queryActivityRechargeList======前======" + queryActivityRechargeList);
            Double orderFee = Double.valueOf(memberOrder.getOrderFee());// 充值的金额
            if (queryActivityRechargeList != null && queryActivityRechargeList.size() > 0) {
                logger.error("chongzhijine========" + orderFee);
                queryActivityRechargeList = rechargeMoneyByDesc(queryActivityRechargeList);
                logger.error("queryActivityRechargeList======后======" + queryActivityRechargeList);
                for (ActivityRecharge a : queryActivityRechargeList) {
                    if (1 == a.getTimeType()) {
                        if (null == a.getStartDt() || null == a.getEndDt()) {
                            continue;
                        }
                        boolean bol = isBoolean(a.getStartDt(), a.getEndDt());
                        if (!bol) {
                            activityRechargeService.deleteActivityRecharge(a);
                            continue;
                        }
                    }
                    if (null != a.getRechargeMoney()) {
                        if (orderFee >= a.getRechargeMoney()) {
                            merchantMenberRecharge.setGiveMoney(a.getGiveMoney());
                            Double totalGiveFee = merchantMenber.getTotalGiveFee() == null ? Double.valueOf(0)
                                    : merchantMenber.getTotalGiveFee();// 当前充值总额
                            merchantMenber.setTotalGiveFee(StringUtil.bigDecimal(totalGiveFee + a.getGiveMoney()));
                            Double usableGiveFee = merchantMenber.getUsableGiveFee() == null ? Double.valueOf(0)
                                    : merchantMenber.getUsableGiveFee();
                            merchantMenber.setUsableGiveFee(StringUtil.bigDecimal(usableGiveFee + a.getGiveMoney()));
                            break;
                        }
                    }
                }
            }
            merchantMenberRecharge.setRechargeMoney(StringUtil.bigDecimal(Double.valueOf(memberOrder.getOrderFee())));
            merchantMenberRecharge.setMemberCode(merchantMenber.getMemberCode());
            merchantMenberRecharge.setMerchantCode(merchantMenber.getMerchantCode());
            merchantMenberRecharge.setMerchantName(merchantMenber.getMerchantName());
            merchantMenberRecharge.setStoreId(merchantMenber.getStoreId());
            merchantMenberRecharge.setStoreName(merchantMenber.getStoreName());
            merchantMenberRecharge.setCreateDt(new Date());
            merchantMenberRecharge.setLogo(merchantMenber.getLogo());
            merchantMenberRecharge.setNickName(merchantMenber.getNickName());
            merchantMenberRecharge.setPhone(merchantMenber.getPhone());
            merchantMenberRecharge.setPayType(1);
            merchantMenberRecharge.setOrderNumber(orderNumber);
            logger.error("进入修改订单方法===OrderFee==merchantMenberRecharge====="
                    + JSONObject.toJSONString(merchantMenberRecharge));
            merchantMenberRechargeService.saveMerchantMenberRecharge(merchantMenberRecharge);
        }
        Double totalRechargeFee = merchantMenber.getTotalRechargeFee() == null ? new Double(0)
                : merchantMenber.getTotalRechargeFee();
        merchantMenber.setTotalRechargeFee(
                StringUtil.bigDecimal(totalRechargeFee + Double.parseDouble(memberOrder.getOrderFee())));
        logger.error("进入修改订单方法===OrderFee==merchantMenber=====" + JSONObject.toJSONString(merchantMenber));

        merchantMenberService.updateMerchantMenber(merchantMenber);
    }

    @PostMapping("/getPhoneCode")
    @ResponseBody
    public Map<String, Object> getPhoneCode(String phone,String validateCode,HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>(16);
        try {
            ValidateCodeUtil.checkVerifyCode(request, validateCode);
            String sevice = (String) phoneCodeController.sevice(phone);
            if ("{\"SUCCESS\":\"发送成功\"}".equals(sevice)) {
                result.put("code", "1");
            } else if ("{\"FAIL\":\"手机号已注册\"}".equals(sevice)) {
                result.put("code", "3");
            } else {
                result.put("code", "0");
            }
        } catch (ClientException e) {
            result.put("code", "2");
            e.printStackTrace();
        }catch (MsgException e){
            result.put("code", -1);
            result.put("msg", e.getMessage());
        }
        return result;
    }

    @PostMapping("/getPhoneCodeVIP")
    @ResponseBody
    public Map<String, Object> getPhoneCodeVIP(String phone, String storeId) {
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            String sevice = (String) phoneCodeController.seviceVIP(phone, storeId);
            if ("{\"SUCCESS\":\"发送成功\"}".equals(sevice)) {
                result.put("code", "1");
            } else if ("{\"FAIL\":\"该门店已注册会员\"}".equals(sevice)) {
                result.put("code", "3");
            } else {
                result.put("code", "0");
            }
        } catch (ClientException e) {
            result.put("code", "2");
            e.printStackTrace();
        }
        return result;
    }

    private MerchantMenber getSessionMerchantMenber() {
        MerchantMenber merchantMenber = (MerchantMenber) request.getSession().getAttribute("sessionMerchantMenber");
        return merchantMenber;

    }

    /**
     * orderByDesc:(充值金额从大到小排列). <br/>
     *
     * @param list
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    public List<ActivityRecharge> rechargeMoneyByDesc(List<ActivityRecharge> list) {
        Collections.sort(list, new Comparator<ActivityRecharge>() {
            @Override
            public int compare(ActivityRecharge o1, ActivityRecharge o2) {
                int desc = (int) (o2.getRechargeMoney() - o1.getRechargeMoney());
                return desc;
            }
        });
        return list;
    }

    /**
     * isBoolean:(当前时间大于活动开始时间，并且当前时间小于活动结束时间). <br/>
     *
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    public boolean isBoolean(Date startTime, Date endTime) {
        boolean flag = false;
        boolean start = System.currentTimeMillis() >= startTime.getTime();
        boolean end = System.currentTimeMillis() <= endTime.getTime();
        if (start && end) {
            flag = true;
        }
        return flag;
    }

    /**
     * 从request中获取请求方IP
     *
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            // 若以上方式均为获取到ip则证明获得客户端并没有采用反向代理直接使用getRemoteAddr()获取客户端的ip地址
            ip = request.getRemoteAddr();
        }
        // 多个路由时，取第一个非unknown的ip
        final String[] arr = ip.split(",");
        for (final String str : arr) {
            if (!"unknown".equalsIgnoreCase(str)) {
                ip = str;
                break;
            }
        }
        return ip;
    }

    private void saveMemberOrderSS(MerchantMenber merchantMenber, ActivityActivate activityActivate) {
        String memberCode = merchantMenber.getMemberCode();
        MerchantMenber merchantMenber2 = new MerchantMenber();
        merchantMenber2.setMemberCode(memberCode);
        MerchantMenber queryMerchantMenber = merchantMenberService.queryMerchantMenber(merchantMenber2);
        if (null != queryMerchantMenber) {
            MemberOrder memberOrder = new MemberOrder();
            memberOrder.setMerchantCode(queryMerchantMenber.getMerchantCode());
            memberOrder.setMerchantName(queryMerchantMenber.getMerchantName());
            memberOrder.setStoreId(queryMerchantMenber.getStoreId());
            memberOrder.setStoreName(queryMerchantMenber.getStoreName());
            String billno = StringUtil.getBillno();
            memberOrder.setOrderNumber(billno);
            memberOrder.setMemberCode(memberCode);
            memberOrder.setNickName(queryMerchantMenber.getNickName());
            Date date = new Date();
            memberOrder.setCreateDt(date);
            memberOrder.setOrderType("1");
            memberOrder.setOrderFee(activityActivate.getGiveMoney() + "");
            memberOrder.setOrderStatus("1");
            memberOrder.setRechargeType("0");
            MerchantMenberRecharge menberRecharge = new MerchantMenberRecharge();
            menberRecharge.setMerchantCode(queryMerchantMenber.getMerchantCode());
            menberRecharge.setMerchantName(queryMerchantMenber.getMerchantName());
            menberRecharge.setStoreId(queryMerchantMenber.getStoreId());
            menberRecharge.setStoreName(queryMerchantMenber.getStoreName());
            menberRecharge.setOrderNumber(billno);
            menberRecharge.setCreateDt(date);
            menberRecharge.setLogo(queryMerchantMenber.getLogo());
            menberRecharge.setMemberCode(memberCode);
            menberRecharge.setNickName(queryMerchantMenber.getNickName());
            menberRecharge.setPhone(queryMerchantMenber.getPhone());
            menberRecharge.setRechargeMoney(0d);
            menberRecharge.setGiveMoney(activityActivate.getGiveMoney());
            merchantMenberRechargeService.saveMerchantMenberRecharge(menberRecharge);
            memberOrderService.saveMemberOrder(memberOrder);
        }

    }

    /**
     * 会员开卡

     * @return
     */
    @RequestMapping(value = "/api/card/open",method = RequestMethod.POST)
    @ResponseBody
    public Result<JSONObject> vipOpenCard(@RequestBody JSONObject json) {
        logger.info("============>会员开卡接口请求，请求参数:{}<============",json);
        return merchantMenberService.vipOpenCard(json);
    }

    @RequestMapping(value = "/api/card/open/new",method = RequestMethod.POST)
    @ResponseBody
    public Result<JSONObject> vipOpenCardNew(@RequestBody JSONObject json) {
        logger.info("============>会员开卡接口请求，请求参数:{}<============",json);
        return merchantMenberService.vipOpenCard(json);
    }

    /**
     *
     * 获取会员信息接口
     */
    @RequestMapping(value = "/api/member/info",method = RequestMethod.POST)
    @ResponseBody
    public Result<JSONObject> getMenberInfo(@RequestBody JSONObject json){
        JSONObject result = new JSONObject();
        String appOpenId = json.getString("appOpenId");
        if(StringUtil.isEmpty(appOpenId)){
            return ResultGenerator.genFailResult("appOpenId不能为空！");
        }
        String unionId = json.getString("unionId");
        String storeId = json.getString("storeId");
        if(StringUtil.isEmpty(storeId) || "undefined".equals(storeId)){
            return ResultGenerator.genFailResult("店铺ID不能为空！");
        }
        MerchantStore store = new MerchantStore();
        store.setId(Integer.valueOf(storeId));
        MerchantStore info = merchantStoreService.queryMerchantStore(store);
        if(info == null){
            return ResultGenerator.genFailResult("店铺信息异常！");
        }
        List<Map<String,Object>> lists = activityActivateService.getNewestActivityJoin(info.getStoreId());
        List<String> titleTips = merchantMenberService.getTitleTips(lists);
        result.put("title",titleTips);
        QueryWrapper<MerchantMenber> queryWrapper = new QueryWrapper<MerchantMenber>().eq("appOpenId",appOpenId)
                .eq("storeId",info.getStoreId());
        MerchantMenber one = merchantMenberService.getOne(queryWrapper);
        if(one == null){
            if(StringUtil.isNotEmpty(unionId)){
                QueryWrapper<MerchantMenber> qw = new QueryWrapper<MerchantMenber>().eq("storeId",info.getStoreId()).eq("unionId",unionId);
                one = merchantMenberService.getOne(qw);
                if(one != null){
                    MerchantMenber update = new MerchantMenber();
                    update.setId(one.getId());
                    update.setAppOpenId(appOpenId);
                    merchantMenberService.updateById(update);
                }
            }
        }else{
            if(StringUtil.isEmpty(one.getUnionId()) && StringUtil.isNotEmpty(unionId)){
                MerchantMenber update = new MerchantMenber();
                update.setId(one.getId());
                update.setUnionId(unionId);
                merchantMenberService.updateById(update);
            }
        }
        logger.info("=========>【查询出的会员卡】查询结果：{}<==========",JSONObject.toJSONString(one));
        if(one == null){
            result.put("isFlag",0);
        }else{
            result.put("isFlag",1);
            Double useRechFee = one.getUsableRechargeFee() == null ? new Double(0) : one.getUsableRechargeFee();
            Double useGiveFee = one.getUsableGiveFee() == null ? new Double(0) : one.getUsableGiveFee();
            BigDecimal useAmt = new BigDecimal(String.valueOf(useRechFee)).add(new BigDecimal(String.valueOf(useGiveFee))).setScale(2, RoundingMode.HALF_UP);
            result.put("useAmt",useAmt);
            result.put("cardNo",one.getCardNo());
            result.put("phone",one.getPhone());
            result.put("avater",one.getLogo());
            result.put("nickName",EmojiUtil.emojiRecovery2(one.getNickName()));
        }
        logger.info("=========>【返回的会员卡信息】信息为：{}<==========",JSONObject.toJSONString(result));
        return ResultGenerator.genSuccessResult("获取成功!",result);
    }


    /**
     *
     * 获取会员卡信息列表
     */
    @RequestMapping(value = "/api/card/list",method = RequestMethod.POST)
    @ResponseBody
    public Result<JSONObject> getCardList(@RequestBody JSONObject json){
        JSONObject result = new JSONObject();
        String appOpenId = json.getString("appOpenId");
        if(StringUtil.isEmpty(appOpenId)){
            return ResultGenerator.genFailResult("appOpenId不能为空！");
        }
        String unionid = json.getString("unionid");
        Integer pageNum = json.getInteger("pageNum") == null ? Integer.valueOf(0) : json.getInteger("pageNum");
        Integer pageSize = json.getInteger("pageSize") == null ? Integer.valueOf(10): json.getInteger("pageSize");

        Page<MerchantMenber> page = new Page<>();
        page.setCurrent(pageNum);
        page.setSize(pageSize == 0 ? 10 : pageSize);
        MerchantMenber menber = new MerchantMenber();
        menber.setAppOpenId(appOpenId);
        menber.setUnionId(unionid);
        page = merchantMenberService.pageJoinData(page,menber);
        result.put("cardList",page.getRecords());
        result.put("count",page.getTotal());
        return ResultGenerator.genSuccessResult("获取成功!",result);
    }

    /**
     *
     * 获取会员账单信息分页数据
     */
    @RequestMapping(value = "/api/member/bill",method = RequestMethod.POST)
    @ResponseBody
    public Result<JSONObject> getMenberBill(@RequestBody JSONObject json){
        JSONObject result = new JSONObject();
        String appOpenId = json.getString("appOpenId");
        if(StringUtil.isEmpty(appOpenId)){
            return ResultGenerator.genFailResult("appOpenId不能为空！");
        }
        Integer storeId = json.getInteger("storeId");
        if(StringUtil.isEmpty(storeId)){
            return ResultGenerator.genFailResult("店铺ID不能为空！");
        }
        MerchantStore store = new MerchantStore();
        store.setId(storeId);
        MerchantStore info = merchantStoreService.queryMerchantStore(store);
        if(info == null){
            return ResultGenerator.genFailResult("店铺信息异常！");
        }
        QueryWrapper<MerchantMenber> queryWrapper = new QueryWrapper<MerchantMenber>().eq("storeId",info.getStoreId()).eq("appOpenId",appOpenId);
        MerchantMenber menber = merchantMenberService.getOne(queryWrapper);
        if(menber == null){
            return ResultGenerator.genFailResult("用户不是该门店的会员！");
        }
        int currPage = json.getInteger("currPage") == null ? 1 : json.getInteger("currPage");

        Map<String,Object> params = new HashMap<>();
        params.put("pageSize", PAGE_SIZE);
        params.put("offset", (currPage - 1) * PAGE_SIZE);
        params.put("storeId",info.getStoreId());
        params.put("memberCode",menber.getMemberCode());

        List<MerchantMenberRecharge> rechargeList = merchantMenberRechargeService.queryMerchantMenberRechargePage(params);
        List<MerchantMenberComsume> comsumeList = merchantMenberComsumeService.queryMerchantMenberComsumePage(params);
        result.put("rechargeList",rechargeList);
        result.put("comsumeList",comsumeList);
        result.put("totalGiveFee",menber.getTotalGiveFee() == null ? new Double(0) : menber.getTotalGiveFee());
        Double rechargeFee = menber.getUsableRechargeFee() == null ? new Double(0) : menber.getUsableRechargeFee();
        Double giveFee = menber.getUsableGiveFee() == null ? new Double(0) : menber.getUsableGiveFee();
        result.put("useAmt",StringUtil.bigDecimal(rechargeFee + giveFee));
        return ResultGenerator.genSuccessResult("获取成功!",result);
    }


    /**
     * 创建会员卡接口 pY6Es6TELPLwuzi6hzBelewOtVhU
     * @param
     * @return
     */
    @RequestMapping(value = "/api/card/open",method = RequestMethod.GET)
    public ModelAndView getMenberInfo(String storeId,String openId,HttpServletRequest request){
        ModelAndView view = new ModelAndView("vip/card");
        String appid = "wx20403c16079b1b59";
        String key = "bca9c306d375840f4c5d7bfea22d5f74";
        String cardId = "pY6Es6TELPLwuzi6hzBelewOtVhU";
        String token = "43_Egb6xoDokwxQZFd2gkeznYyZ7MB_ykr8L-KroIgquIEpbDe8FO-IhgNQyhxl69c6BSImhJPPvVBEdYfj999JtX7czGK8fhX3FQY8IStnBSMp9IK8sQP5hqtjczVZOW84jeOxdbaguYED7jvFUHYdAIAFSJ";
        String jsapi_ticket = "O3SMpm8bG7kJnF36aXbe8-RgUX3L9LUK8DbkzsSQfdxJp7Bx4zguzn3OJgSHpWxbEQdP5CT7SOYB06XmEHyJSQ";
//        String token = Oauth2Util.getAccessToken4User(appid, key);
//        System.out.println("=======================>token============>"+token);
//        String jsapi_ticket = Oauth2Util.getJsapiTicket(token);
//        System.out.println("=======================>jsapiTicket============>"+jsapi_ticket);
        StringBuffer url = request.getRequestURL();
        if(StringUtil.isNotEmpty(request.getQueryString())){
            url.append("?"+request.getQueryString());
        }
        System.out.println("=======================>url================>"+url.toString());
        String noncestr = UUID.randomUUID().toString().replace("-","").substring(0,16);
        String timestamp = String.valueOf(System.currentTimeMillis());
        JSONObject obj = new JSONObject();
        obj.put("noncestr",noncestr);
        obj.put("url",url.toString());
        obj.put("timestamp",timestamp);
        obj.put("jsapi_ticket",jsapi_ticket);
        String signContent = SignUtils.getSignContent(obj);
        String signature = SignUtils.sha1Encrypt(signContent);


        String openid = "oY6Es6Y52jNTArOpt-CTDP4ScKqs";
        String code = "1324567778978";
        String nonce_str = UUID.randomUUID().toString().replace("-","").substring(0,16);
        String timestamps = String.valueOf(new Date().getTime());


        //String apiTicket = Oauth2Util.getApiTicket(appid,key);
        String apiTicket = "kqxRwT0lF4G-mWsgBWkeIroojoScOkHH3OpnWuEYNQ_u2oZeZp_Y8eYgmBG1U0RJURSf1-SIFwWal_tW6ogaTA";
        System.out.println("====================apiTicket=====================>"+apiTicket);


        List<String> list = new ArrayList<>();
        list.add(nonce_str);
//        list.add(code);
        list.add(timestamps);
        list.add(apiTicket);
        list.add(cardId);
//        list.add(openid);
        Collections.sort(list);

        StringBuffer signStr = new StringBuffer();
        for (String s:list) {
            signStr.append(s);
        }
        System.out.println("====================带签名字符串=====================>"+signStr.toString());
        String sign = SignUtils.sha1Encrypt(signStr.toString());
        System.out.println("====================签名结果=====================>"+sign);

        JSONObject cardExt = new JSONObject();
        cardExt.put("nonce_str",nonce_str);
//        cardExt.put("code",code);
        cardExt.put("timestamp",timestamps);
//        cardExt.put("openid",openid);
        cardExt.put("apiTicket",apiTicket);
        cardExt.put("card_id",cardId);
        cardExt.put("signature",sign);

        view.addObject("cardId",cardId);
        view.addObject("appid",appid);
        view.addObject("noncestr",noncestr);
        view.addObject("timestamp",timestamp);
        view.addObject("signature",signature);

        view.addObject("nonce_str",nonce_str);
        view.addObject("timestamps",timestamps);
        view.addObject("api_ticket",apiTicket);
        //view.addObject("card_id",card_id);
        view.addObject("signatures",sign);
        //view.addObject("cardExt",cardExt.toJSONString());
        System.out.println("============================>cardExt===========================>"+cardExt);
        return view;
    }

    @RequestMapping(value = "/api/check/token",method = RequestMethod.GET)
    @ResponseBody
    public String checkToken(@RequestParam Map<String,String> params){
        return params.get("echostr");
    }

    @RequestMapping(value = "/api/create/card",method = RequestMethod.GET)
    @ResponseBody
    public Result createCard(@RequestParam Map<String,String> params){

        String token = "43_av9Kgf3nnplHXLniPnbX16Qb7L30G8iZwS0GLBQazysmqNidr5cdta3s1Co-FvJC1sfC1Vg02_Qx9gOP49npQkTE8v9eKTPCnr5onQbCEDY312-O3zAKjWW5pcQ2JvoJ2xHoHWX6I75BqsrdFLXeABAJPB";
        // String url = "https://api.weixin.qq.com/card/create?access_token="+token;

        // JSONObject jsonObject = new JSONObject();

        JSONObject card = new JSONObject();

        card.put("card_type","MEMBER_CARD");

        JSONObject memberCard = new JSONObject();

        memberCard.put("background_pic_url","http://mmbiz.qpic.cn/mmbiz/p98FjXy8LacgHxp3sJ3vn97bGLz0ib0Sfz1bjiaoOYA027iasqSG0sjpiby4vce3AtaPu6cIhBHkt6IjlkY9YnDsfw/0");

        JSONObject baseInfo = new JSONObject();

        baseInfo.put("logo_url","http://mmbiz.qpic.cn/mmbiz/p98FjXy8LacgHxp3sJ3vn97bGLz0ib0Sfz1bjiaoOYA027iasqSG0sjpiby4vce3AtaPu6cIhBHkt6IjlkY9YnDsfw/0");

        baseInfo.put("brand_name","收银呗");
        baseInfo.put("code_type","CODE_TYPE_TEXT");
        baseInfo.put("title","白金尊贵会员卡");
        baseInfo.put("color","Color010");
        baseInfo.put("notice","使用时向服务员出示此券");
        baseInfo.put("service_phone","020-88888888");
        baseInfo.put("description","不可与其他优惠同享");

        JSONObject type = new JSONObject();
        type.put("type","DATE_TYPE_PERMANENT");
        baseInfo.put("date_info",type);
        JSONObject sku = new JSONObject();
        type.put("quantity","10000000");
        baseInfo.put("sku",sku);

        baseInfo.put("get_limit",1);
        baseInfo.put("use_custom_code",false);
        baseInfo.put("can_give_friend",true);

        return null;
    }

//    @RequestMapping(value = "/api/card/sign",method = RequestMethod.GET)
//    @ResponseBody
//    public Result getCardSign(@RequestParam Map<String,String> params){
//        return params.get("echostr");
//    }

    @GetMapping("/**.txt")
    @ResponseBody
    public String aKfAirN1hO() {

        return "3cdbacb2d4ceefa36ef1c43d0c562fb9";
    }

    /**
     * 读取request数据
     *
     * @param request
     * @return
     */
    public String readRequestMsg(HttpServletRequest request) {
        java.io.BufferedReader bis = null;
        String line = null;
        String result = "";
        try {
            bis = new java.io.BufferedReader(new java.io.InputStreamReader(
                    request.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            while ((line = bis.readLine()) != null) {
                sb.append(line).append("\r\n");
            }
            result = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return result;
    }
}
