package cn.pluss.platform.controller.home;

import cn.pluss.platform.IdCardService;
import cn.pluss.platform.activityActivate.ActivityActivateService;
import cn.pluss.platform.activityConsumReturn.ActivityConsumReturnService;
import cn.pluss.platform.activityRecharge.ActivityRechargeService;
import cn.pluss.platform.annotation.NoRepeatSubmit;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultCode;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.deviceStock.DeviceStockService;
import cn.pluss.platform.dto.AccountDTO;
import cn.pluss.platform.dto.RealFansDTO;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.exception.PayRiskException;
import cn.pluss.platform.guideLabel.GuideLabelService;
import cn.pluss.platform.jfShop.JfShopHandler;
import cn.pluss.platform.jft.JftMercBaseInfoService;
import cn.pluss.platform.jft.JftReceiptInfoService;
import cn.pluss.platform.jty.JtyDeviceHandler;
import cn.pluss.platform.jty.constant.JtyConstant;
import cn.pluss.platform.leshua.LeshuaService;
import cn.pluss.platform.leshua.LeshuaSignature;
import cn.pluss.platform.mapper.JftReceiptInfoMapper;
import cn.pluss.platform.mapper.JftReceiptOrderMapper;
import cn.pluss.platform.mapper.UserInfoMapper;
import cn.pluss.platform.memberOrder.MemberOrderService;
import cn.pluss.platform.merchant.*;
import cn.pluss.platform.merchant.move.MerchantMoveRecordsService;
import cn.pluss.platform.merchant.move.MerchantMoveSettingService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantChannel.MerchantChannelService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.merchantComplaintImage.MerchantComplaintImageService;
import cn.pluss.platform.merchantComplaintRecord.MerchantComplaintRecordService;
import cn.pluss.platform.merchantGuide.MerchantGuideService;
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.merchantProfit.MerchantProfitService;
import cn.pluss.platform.merchantQrcode.MerchantQrcodeService;
import cn.pluss.platform.merchantRejectDesc.MerchantRejectDescService;
import cn.pluss.platform.merchantStore.MerchantStoreService;
import cn.pluss.platform.mswitch.CommonSwitchService;
import cn.pluss.platform.notify.NotifyMessageService;
import cn.pluss.platform.pay.PayService;
import cn.pluss.platform.phoneValidateCode.PhoneValidateCodeService;
import cn.pluss.platform.ryx.pay.RyxPayService;
import cn.pluss.platform.sxf.pay.SxfPayService;
import cn.pluss.platform.systemConfig.SystemConfigService;
import cn.pluss.platform.user.UserIpRecordService;
import cn.pluss.platform.user.impl.GeneralPushUtil;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.util.*;
import cn.pluss.platform.vo.StoreSummaryVO;
import cn.pluss.platform.vo.UserInfoVO;
import cn.pluss.platform.wap.MD5Util;
import cn.pluss.platform.wap.PayUnitedRequest;
import cn.pluss.platform.wap.XmlUtil;
import cn.pluss.platform.wap.*;
import cn.pluss.platform.wechat.*;
import cn.pluss.platform.wx.WxAccessTokenRequest;
import cn.pluss.platform.wx.WxCommonService;
import cn.pluss.platform.wx.WxOauth2AccessTokenResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeCreateRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayTradeCreateResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.RedirectView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author yuchen
 * @Description (会员扫商户二维码 ， 走正常的扣款流程 ， 微信扫的话调微信支付接口 ， 支付宝扫调支付宝支付接口)
 */
@Controller
@Slf4j
@RequiredArgsConstructor
@RequestMapping("merchant")
public class MerchantController {

    private final MerchantService merchantService;
    private final LeshuaService leshuaService;
    private final HttpServletRequest request;
    private final HttpServletResponse response;
    private final MerchantOrderService merchantOrderService;
    private final SystemConfigService systemConfigService;
    private final MerchantBaseInfoService merchantBaseInfoService;
    private final MerchantStoreService merchantStoreService;
    private final UserAppService userAppService;
    private final PhoneValidateCodeService phoneValidateCodeService;
    private final UserInfoService userInfoService;
    private final MerchantMenberService merchantMenberService;
    private final MerchantMenberRechargeService menberRechargeService;
    private final MerchantIncomeService merchantIncomeService;
    private final ActivityActivateService activityActivateService;
    private final ActivityConsumReturnService activityConsumReturnService;
    private final ActivityRechargeService activityRechargeService;
    private final MerchantMenberComsumeService merchantMenberComsumeService;
    private final MemberOrderService memberOrderService;
    private final UserInfoMapper userInfoMapper;
    private final CommonSwitchService commonSwitchService;
    private final SxfPayService sxfPayService;
    private final GuideLabelService guideLabelService;
    private final MerchantGuideService merchantGuideService;
    private final MerchantQrcodeService merchantQrcodeService;
    private final MerchantChannelStatusService merchantChannelStatusService;
    private final IdCardService idCardService;
    private final MerchantRejectDescService merchantRejectDescService;
    private final MerchantPluginService merchantPluginService;
    private final MerchantChannelService merchantChannelService;
    private final NotifyMessageService notifyMessageService;

    private final AccountService accountService;

    private final MerchantMoveRecordsService merchantMoveRecordsService;

    private final MerchantMoveSettingService merchantMoveSettingService;

    private final MerchantProfitService merchantProfitService;

    private final MerchantComplaintRecordService merchantComplaintRecordService;

    private final MerchantComplaintImageService merchantComplaintImageService;

    private final MerchantStaffConnService merchantStaffConnService;

    @Setter(onMethod_ = {@Autowired})
    private DeviceStockService deviceStockService;

    @Setter(onMethod_ = {@Autowired, @Qualifier("ysPayOldService")})
    private PayService ysPayOldService;

    @Setter(onMethod_ = {@Autowired})
    private RyxPayService ryxPayService;

    @Autowired
    private UserIpRecordService ipRecordService;

    @Resource
    private WxCommonService wxCommonService;

    @Autowired
    private GeneralPushUtil generalPushUtil;


    @Setter(onMethod_ = {@Autowired})
    private JtyDeviceHandler jtyDeviceHandler;

    @Resource
    private JfShopHandler jfShopHandler;

    @Resource
    private JftMercBaseInfoService jftMercBaseInfoService;

    @Resource
    private JftReceiptInfoMapper jftReceiptInfoMapper;

    @Resource
    private JftReceiptOrderMapper jftReceiptOrderMapper;

    /*@GetMapping("/auth/aKfAirN1hO.txt")
    @ResponseBody
    public String aKfAirN1hO() {
        return "3cdbacb2d4ceefa36ef1c43d0c562fb9";
    }*/

    @GetMapping("/auth/ODzUwrTrcr.txt")
    @ResponseBody
    public String aKfAirN1hO() {
        return "68eb6c8f59bf143e3165aa5198c6905f";
    }

    @GetMapping("/account/auth")
    public String accountAuth(HttpServletResponse response, HttpServletRequest request) {
        String url = "/merchant/account/bind";
        String domain_wap = ParametersUtil.domain + "/wap";
        try {
            String jump = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + ParametersUtil.SJ_APPID
                    + "&redirect_uri=" + java.net.URLEncoder.encode(domain_wap + url, "utf-8")
                    + "&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
            response.sendRedirect(jump);
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "授权出错！");
            return "merchant/errorInfo2";
        }
    }

    @GetMapping("/pay/test")
    public String payTest(HttpServletResponse response, HttpServletRequest request) {
        return "th_pay_test";
    }

    @RequestMapping("/jumpUrlTest")
    public ModelAndView jumpUrlTest() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("merchant/paySuccess");
        return modelAndView;
    }

    @PostMapping("/tradePayTest")
    @ResponseBody
    public Result<?> tradePayTest(String comsumeMoney) {
        if (StringUtil.isEmpty(comsumeMoney)) {
            return ResultGenerator.genFailResult("订单金额为空！");
        }
        DeviceStock stock = new DeviceStock();
        stock.setDeviceNo(JtyConstant.TEST_DEVICE_NUM);
        String data = jtyDeviceHandler.sendNotice(Double.parseDouble(comsumeMoney), "pay", stock);
        return ResultGenerator.genSuccessResult("支付成功！", "【佳天亿】支付成功消息推送响应参数:" + data);
    }

    @GetMapping("/cancelPayTest/{comsumeMoney}")
    @ResponseBody
    public Result cancelPayTest(@PathVariable("comsumeMoney") String comsumeMoney) {
        try {
            DeviceStock stock = new DeviceStock();
            stock.setDeviceNo(JtyConstant.TEST_DEVICE_NUM);
            String data = jtyDeviceHandler.sendNotice(Double.parseDouble(comsumeMoney), "cancel", stock);
            return ResultGenerator.genSuccessResult("操作成功", "【佳天亿】取消支付消息推送响应参数:" + data);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    @RequestMapping("/account/bind")
    public String accountBind(String code, String openId, HttpServletResponse response) {
        if (StringUtil.isNotEmpty(code)) {
            WxAccessTokenRequest tokenRequest = WxAccessTokenRequest.buidWxToken(ParametersUtil.SJ_APPID, ParametersUtil.SJ_APPSECRET, code, WxConstants.OAUTH2_ACCESS_TOKEN_URL);
            WxOauth2AccessTokenResponse result = wxCommonService.getOauth2Info(tokenRequest);
            if (result == null) {
                request.setAttribute("error", "授权出错，请重新扫码!");
                return "merchant/errorInfo2";
            }
            openId = result.getOpenid();
        }
        request.setAttribute("openid", openId);
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>().eq("openid", openId);
        List<UserInfo> lists = userInfoMapper.selectList(queryWrapper);
        if (lists.isEmpty()) {
            return "th_account_bind";
        } else {
            UserInfo userInfo = lists.get(0);
            String url = ParametersUtil.domain + "/wap/merchant/account/list/" + userInfo.getId();
            try {
                response.sendRedirect(url);
                return null;
            } catch (IOException e) {
                e.printStackTrace();
                request.setAttribute("error", "跳转异常");
                return "merchant/errorInfo2";
            }
        }
    }

    @GetMapping("/account/list/{userAppId}")
    public String accountList(@PathVariable("userAppId") String userAppId) {
        UserApp userApp = userAppService.queryUserApp(new UserApp().setUserId(Long.parseLong(userAppId)));
        if (userApp == null) {
            request.setAttribute("error", "参数有误！");
            return "merchant/errorInfo2";
        }
        UserInfo userInfo = userInfoMapper.selectById(userAppId);
        if (userInfo == null) {
            request.setAttribute("error", "用户信息异常！");
            return "merchant/errorInfo2";
        }
        if (StringUtil.isEmpty(userInfo.getOpenId())) {
            request.setAttribute("error", "未获取到绑定信息，请重新扫码！");
            return "merchant/errorInfo2";
        }
        if ("promoter".equals(userApp.getUserType())) {
            List<UserInfoVO> listVo = userInfoMapper.selectMainUserInfoList(userAppId);
            request.setAttribute("list", listVo);
        } else if ("staff".equals(userApp.getUserType())) {
            List<MerchantBaseInfo> list = merchantStaffConnService.getMercInfoByStaffId(userAppId);
            request.setAttribute("list", list);
        } else {
            request.setAttribute("error", "当前角色不支持该操作！");
            return "merchant/errorInfo2";
        }
        request.setAttribute("userAppId", userAppId);
        return "th_account_list";
    }

    @PostMapping("/account/toBind")
    @ResponseBody
    public Result<?> toBind(String loginName, String password, String openid) {
        if (StringUtil.isEmpty(loginName)) {
            return ResultGenerator.genFailResult("账号不能为空！");
        }
        if (StringUtil.isEmpty(password)) {
            return ResultGenerator.genFailResult("密码不能为空！");
        }
        if (StringUtil.isEmpty(openid)) {
            return ResultGenerator.genFailResult("缺失参数！");
        }
        String pwd = MD5Util.MD5Encode(password);
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<UserInfo>().eq("loginName", loginName).eq("password", pwd);
        UserInfo info = userInfoMapper.selectOne(queryWrapper);
        if (info == null) {
            return ResultGenerator.genFailResult("账号或密码不正确！");
        }
        info.setOpenId(openid);
        userInfoMapper.updateById(info);
        return ResultGenerator.genSuccessResult("绑定成功！", info.getId());
    }

    @RequestMapping("/account/unBind/{userAppId}")
    @ResponseBody
    public Result<?> unBind(@PathVariable("userAppId") String userAppId) {
        if (StringUtil.isEmpty(userAppId)) {
            return ResultGenerator.genFailResult("缺失参数！");
        }
        UserInfo info = userInfoMapper.selectById(userAppId);
        if (info == null) {
            return ResultGenerator.genFailResult("用户数据异常！");
        }
        String openid = info.getOpenId();
        info.setOpenId(null);
        userInfoMapper.updateById(info);
        return ResultGenerator.genSuccessResult("解绑成功！", openid);
    }

    @RequestMapping("/account/unBindSend")
    @ResponseBody
    public Result<?> unBindSend(@RequestParam String userAppId, @RequestParam String merchantCode, @RequestParam String isPushWxMessage) {
        UserApp userApp = userAppService.queryUserApp(new UserApp().setUserId(Long.parseLong(userAppId)));
        if (userApp == null) {
            return ResultGenerator.genFailResult("设置失败，用户异常！");
        }
        if ("promoter".equals(userApp.getUserType())) {
            UpdateWrapper<MerchantBaseInfo> updateWrapper = new UpdateWrapper<MerchantBaseInfo>()
                    .set("isPushWxMessage", isPushWxMessage).eq("merchantCode", merchantCode);
            merchantBaseInfoService.update(updateWrapper);
            return ResultGenerator.genSuccessResult("设置成功！", null);
        } else if ("staff".equals(userApp.getUserType())) {
            UpdateWrapper<MerchantStaffConn> updateWrapper = new UpdateWrapper<MerchantStaffConn>()
                    .set("isPushWxMessage", isPushWxMessage).eq("userId", userAppId).eq("merchantCode", merchantCode);
            merchantStaffConnService.update(updateWrapper);
            return ResultGenerator.genSuccessResult("设置成功！", null);
        } else {
            return ResultGenerator.genFailResult("当前用户暂不支持！");
        }
    }

    @GetMapping(value = "/complaint/{token}")
    public String toComplaint(@PathVariable("token") String token) {
        QueryWrapper<MerchantMoveRecords> queryWrapper = new QueryWrapper<MerchantMoveRecords>().eq("token", token);
        MerchantMoveRecords record = merchantMoveRecordsService.getOne(queryWrapper);
        if (record == null) {
            JftReceiptInfo byToken = jftReceiptInfoMapper.getByToken(token);
            if (byToken == null) {
                request.setAttribute("error", "参数有误！");
                return "merchant/errorInfo2";
            }
            JftMercBaseInfo merchant = jftMercBaseInfoService.getMercBaseInfo(byToken.getUserId());
            List<JftReceiptOrder> lists = jftReceiptOrderMapper.listByReceiptId(byToken.getId(), JftReceiptOrder.PAY_STATUS_YES);
            request.setAttribute("mercName", merchant.getMerchantName());
            if (!lists.isEmpty()) {
                request.setAttribute("orderNumber", lists.get(0).getOrderNumber());
            }
            request.setAttribute("merchantCode", merchant.getMerchantCode());
            return "merchant/complaint";
        }
        MerchantBaseInfo baseInfo = merchantBaseInfoService.getMerchantBaseInfoByMerchantCode(record.getMerchantCode());
        request.setAttribute("mercName", baseInfo.getAlias());
        request.setAttribute("mercPhone", baseInfo.getContactMobile());
        request.setAttribute("orderNumber", record.getOrderNumber());
        request.setAttribute("merchantCode", record.getMerchantCode());
        return "merchant/complaint";
    }

    @PostMapping(value = "/complaint/save")
    @ResponseBody
    @NoRepeatSubmit
    public Result<?> complaintSave(MerchantComplaintRecord record) {
        try {
            if (record.getImageList() == null || record.getImageList().size() <= 0) {
                return ResultGenerator.genFailResult("请上传交易截图和被骗经过截图！");
            }
            if (record.getImageList().size() > 8) {
                return ResultGenerator.genFailResult("最多可上传8张截图！");
            }
            QueryWrapper<MerchantComplaintRecord> queryWrapper = new QueryWrapper<MerchantComplaintRecord>().eq("merchantCode", record.getMerchantCode())
                    .eq("complaintPhone", record.getComplaintPhone());
            MerchantComplaintRecord info = merchantComplaintRecordService.getOne(queryWrapper);
            if (info != null) {
                return ResultGenerator.genFailResult("您已提交过投诉，请耐心等待官方回复！");
            }
            merchantComplaintRecordService.save(record);
            List<MerchantComplaintImage> list = new ArrayList<>();
            for (String s : record.getImageList()) {
                MerchantComplaintImage image = new MerchantComplaintImage();
                image.setComplaintId(record.getId());
                byte[] imgBase64 = Base64.getDecoder().decode(s);
                ByteArrayInputStream bis = new ByteArrayInputStream(imgBase64);
                String picUrl = OssOperatUtil.upload(bis, UUID.randomUUID().toString(), "jpeg");
                image.setPicUrl(picUrl);
                list.add(image);
            }
            if (!list.isEmpty()) {
                merchantComplaintImageService.saveBatch(list);
            }
            return ResultGenerator.genSuccessResult("提交投诉成功，请耐心等待官方回复！", null);
        } catch (Exception e) {
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    /**
     * @param params:
     * @param request:
     * @return cn.pluss.platform.api.Result<java.lang.Object>
     * @description:动态码支付接口
     * @date: 2021/8/23 14:57
     */
    @PostMapping("/moveTradePay")
    @ResponseBody
    public Result<Object> moveTradePay(@RequestParam Map<String, Object> params, HttpServletRequest request) {
        try {
            params.put("ip", IpUtils.getIpAddr(request));
            return merchantService.moveTradePay(params);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    /**
     * 动态码授权回调接口
     *
     * @param code
     * @param auth_code
     * @param userAuthCode
     * @param p
     * @param request
     * @return
     */
    @GetMapping("/toMovePay")
    public ModelAndView toMovePay(String code,
                                  String auth_code,
                                  String userAuthCode,
                                  String p,
                                  String token,
                                  String merchantCode,
                                  HttpServletRequest request,
                                  HttpServletResponse response,
                                  ModelAndView view) {
        view.setViewName("merchant/errorInfo2");
        if (StringUtil.isEmpty(p)) {
            view.addObject("error", "缺失参数!");
            return view;
        }
        if (StringUtil.isEmpty(merchantCode)) {
            view.addObject("error", "缺失商编参数!");
            return view;
        }
        if (StringUtil.isEmpty(token)) {
            view.addObject("error", "缺失token参数!");
            return view;
        }
        MerchantMoveSetting setting = merchantMoveSettingService.getOne(new QueryWrapper<MerchantMoveSetting>().eq("merchantCode", merchantCode));
        if (setting == null) {
            view.addObject("error", "当前商户未开启动态码功能！");
            return view;
        }
        if (setting.getStatus() != 1) {
            view.addObject("error", "当前商户动态码功能已被关闭，请联系客服！");
            return view;
        }
        view.addObject("merchantCode", merchantCode);
        view.addObject("token", token);
        MerchantBaseInfo baseInfo = new MerchantBaseInfo();
        baseInfo.setMerchantCode(merchantCode);
        baseInfo = merchantBaseInfoService.queryMerchantBaseInfo(baseInfo);
        view.addObject("storeName", baseInfo.getAlias());

        AccountDTO realAccount = accountService.getRealAccount(baseInfo.getUserId());
        view.addObject("accountName", StringUtil.hideSecret(realAccount.getBankCard().getBankHolder()));
        view.addObject("accountPhone", StringUtil.hideSecret(realAccount.getBankCard().getPhone()));

        if (StringUtil.isEmpty(code) && StringUtil.isEmpty(auth_code) && StringUtil.isEmpty(userAuthCode)) {
            view.addObject("p", p);
            view.setViewName("th_index");
            return view;
        } else {
            String userId = "";
            String payType = "";
            if (StringUtil.isNotEmpty(code)) {
                WxAccessTokenRequest tokenRequest = WxAccessTokenRequest.buidWxToken(ParametersUtil.APPID, ParametersUtil.APPSECRET, code, WxConstants.OAUTH2_ACCESS_TOKEN_URL);
                WxOauth2AccessTokenResponse result = wxCommonService.getOauth2Info(tokenRequest);
                String openid = result.getOpenid();
                userId = openid;
                payType = "WXZF";
            } else if (StringUtil.isNotEmpty(auth_code)) {
                //支付宝取消主动授权 采用静默授权方式，无法获取用户信息
                AlipaySystemOauthTokenResponse tokenResponse = AliUtil.getAliUserIdV2(auth_code, ParametersUtil.ZY_PRI, ParametersUtil.ZY_PUB, ParametersUtil.ZY_ALI_APP_ID);
                payType = "ZFBZF";
                userId = tokenResponse.getUserId();
            } else if (StringUtil.isNotEmpty(userAuthCode)) {
                MerchantChannelStatus channel = merchantChannelStatusService.getValidData(merchantCode);
                String ua = request.getHeader("User-Agent");
                log.info("===================>【银联】标识，获取请求头部信息:{},==============", ua);
                int begin = ua.indexOf("UnionPay");
                String payMentApp = ua.substring(begin);
                if (payMentApp.length() > 30) {
                    payMentApp = payMentApp.substring(0, 30);
                }
                try {
                    Map<String, Object> unionInfo = new HashMap<>(3);
                    //随行付
                    if (channel.getChannel() == 1) {
                        unionInfo = sxfPayService.getUnionInfo(userAuthCode, payMentApp, null);
                    } else if (channel.getChannel() == 2) {
                        view.addObject("error", "当前通道已关闭,请联系客户切换");
                        return view;
                    } else if (channel.getChannel() == 3) {
                        unionInfo = ryxPayService.getUnionInfo(userAuthCode, payMentApp, channel.getMerchantId());
                    } else if (channel.getChannel() == 4) {
                        unionInfo = ysPayOldService.getUnionInfo(userAuthCode, payMentApp, null);
                    } else {
                        view.addObject("error", "未知通道类型");
                        return view;
                    }
                    payType = "UNIONPAY";
                    log.info("===================>【银联】获取用户标识结果参数:{}==============", unionInfo);
                    if ("1".equals(unionInfo.get("code"))) {
                        Object userIdData = unionInfo.get("data");
                        if (userIdData instanceof Map) {
                            Map<String, String> data = (Map<String, String>) userIdData;
                            userId = data.get("data");
                        } else {
                            userId = userIdData.toString();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("===================>【银联】获取用户标识出错，==============", ua);
                }
            } else {
                view.addObject("error", "不支持当前扫码方式，请使用微信、支付宝、云闪付或京东金融扫码支付");
                return view;
            }
            Integer overTime = 5;
            if (setting.getPayOverTime() != null) {
                overTime = setting.getPayOverTime();
            }
            if (StringUtil.isNotEmpty(userId)) {
                String cokusName = "cokus_" + payType;
                String cokusId = Base64.getEncoder().encodeToString(userId.getBytes(StandardCharsets.UTF_8));
                Cookie cookie = new Cookie(cokusName, cokusId);
                cookie.setMaxAge(-1);
                response.addCookie(cookie);
            }
            Long endTime = DateUtils.add(Calendar.MINUTE, DateUtils.currentDate(), overTime).getTime();
            String params = "cokus=" + userId + "&payType=" + payType + "&time=" + endTime;
            try {
                String pa = AESEncrypt.encryptEcbToString(params.getBytes(StandardCharsets.UTF_8), setting.getAesKey().getBytes(StandardCharsets.UTF_8), null);
                String pk = new String(Base64.getEncoder().encode(pa.getBytes(StandardCharsets.UTF_8)), "UTF-8");
                view.addObject("p", pk);
            } catch (Exception e) {
                e.printStackTrace();
                view.addObject("error", "系统异常，数据处理失败！");
                return view;
            }
        }
        view.setViewName("th_index");
        return view;
    }

    /**
     * @param token:
     * @param view:
     * @param ipAddr:
     * @return com.alibaba.fastjson.JSONObject
     * @description:动态码参数校验
     * @date: 2021/8/23 14:58
     */
    public JSONObject checkMovePayParams(String token, ModelAndView view, String ipAddr) {
        view.addObject("token", token);
        if (StringUtil.isEmpty(token)) {
            view.addObject("error", "缺失参数!");
            return ResultGenerator.genFailJsonResult("缺失参数");
        }
        Date now = DateUtils.currentDate();
        QueryWrapper<MerchantMoveRecords> queryWrapper = new QueryWrapper<MerchantMoveRecords>()
                .orderByDesc("createTime").eq("token", token);
        List<MerchantMoveRecords> list = merchantMoveRecordsService.list(queryWrapper);
        if (list.isEmpty()) {
            view.addObject("error", "付款码已过期");
            return ResultGenerator.genFailJsonResult("付款码已过期!");
        }
        MerchantMoveRecords record = list.get(0);
        if (now.compareTo(record.getStartTime()) < 0 || now.compareTo(record.getEndTime()) > 0) {
            view.addObject("error", "付款码已过期!");
            return ResultGenerator.genFailJsonResult("付款码已过期");
        }
        if (StringUtil.isNotEmpty(record.getIp()) && !ipAddr.equals(record.getIp())) {
            view.addObject("error", "当前付款码已被其他用户使用，请重新生成!");
            return ResultGenerator.genFailJsonResult("当前付款码已被其他用户使用，请重新生成!");
        }
        MerchantMoveSetting setting = merchantMoveSettingService.getOne(new QueryWrapper<MerchantMoveSetting>().eq("merchantCode", record.getMerchantCode()).eq("status", "1"));
        if (setting == null) {
            view.addObject("error", "当前商户未开启动态码功能！");
            return ResultGenerator.genFailJsonResult("当前商户未开启动态码功能!");
        }
        if (setting.getStatus() != 1) {
            view.addObject("error", "当前商户动态码功能已被关闭，请联系客服开通！");
            return ResultGenerator.genFailJsonResult("当前商户动态码功能已被关闭，请联系客服开通!");
        }
        if (StringUtil.isEmpty(record.getIp())) {
            record.setIp(ipAddr);
            merchantMoveRecordsService.updateById(record);
        }
        JSONObject result = new JSONObject(2);
        result.put("record", record);
        result.put("setting", setting);
        return ResultGenerator.genSuccessJsonResult(result);
    }

    /**
     * @param token:
     * @return cn.pluss.platform.api.Result<java.lang.Object>
     * @description: 动态码授权接口
     * @date: 2021/7/30 16:29
     */
    @GetMapping("/moveAuth")
    public ModelAndView moveAuth(String token, HttpServletRequest request, ModelAndView view, HttpServletResponse response) {
        view.setViewName("merchant/errorInfo2");
        String ipAddr = IpUtils.getIpAddr(request);
        JSONObject result = checkMovePayParams(token, view, ipAddr);
        if (ResultCode.FAIL.code() == result.getInteger("code")) {
            return view;
        }
        MerchantMoveRecords record = result.getJSONObject("data").getObject("record", MerchantMoveRecords.class);
        MerchantMoveSetting setting = result.getJSONObject("data").getObject("setting", MerchantMoveSetting.class);
        String ua = request.getHeader("user-agent").toLowerCase();
        String payType = "";
        if (ua.contains("micromessenger")) {
            payType = "WXZF";
        } else if (ua.contains("alipay")) {
            payType = "ZFBZF";
        } else {
            payType = "UNIONPAY";
        }
        Cookie[] cookies = request.getCookies();
        String cokus = "";
        String cokusName = "cokus_" + payType;
        if (cookies != null && cookies.length > 0) {
            for (Cookie c : cookies) {
                if (cokusName.equals(c.getName())) {
                    String cValue = c.getValue();
                    if (StringUtil.isNotEmpty(cValue)) {
                        //TODO 解决银联用户标识转码后特殊字符异常
                        if ("UNIONPAY".equals(payType)) {
                            cValue = cValue.replace(" ", "+");
                        }
                        byte[] decode = Base64.getDecoder().decode(cValue.getBytes(StandardCharsets.UTF_8));
                        cokus = new String(decode, 0, 0, decode.length);
                        break;
                    }
                }
            }
        }
        String domain_wap = ParametersUtil.domain + "/wap";
        String APP_ID = ParametersUtil.APPID;
        String ali_appid = ParametersUtil.ZY_ALI_APP_ID;

        String url = "/merchant/toMovePay?merchantCode=" + record.getMerchantCode() + "&token=" + token;
        //付款时间10分钟
        Integer overTime = 10;
        if (setting.getPayOverTime() != null) {
            overTime = setting.getPayOverTime();
        }
        Long endTime = DateUtils.add(Calendar.MINUTE, DateUtils.currentDate(), overTime).getTime();
        if (StringUtil.isNotEmpty(cokus)) {
            String params = "cokus=" + cokus + "&payType=" + payType + "&time=" + endTime;
            try {
                String p = AESEncrypt.encryptEcbToString(params.getBytes(StandardCharsets.UTF_8), setting.getAesKey().getBytes(StandardCharsets.UTF_8), null);
                url = url + "&p=" + new String(Base64.getEncoder().encode(p.getBytes(StandardCharsets.UTF_8)), "UTF-8");
                response.sendRedirect(domain_wap + url);
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                view.addObject("error", "系统异常！");
                return view;
            }
        } else {
            String params = "time=" + endTime;
            try {
                String p = AESEncrypt.encryptEcbToString(params.getBytes(StandardCharsets.UTF_8), setting.getAesKey().getBytes(StandardCharsets.UTF_8), null);
                url = url + "&p=" + p;
                if (ua.contains("micromessenger")) {
                    String jump = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APP_ID
                            + "&redirect_uri=" + java.net.URLEncoder.encode(domain_wap + url, "utf-8")
                            + "&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
                    response.sendRedirect(jump);
                    return null;
                } else if (ua.contains("alipay")) {
                    String urlString = domain_wap + url;
                    String rurl = java.net.URLEncoder.encode(urlString, "utf-8");
                    String jmp = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=" + ali_appid + "&scope=auth_base&redirect_uri=" + rurl;
                    response.sendRedirect(jmp);
                    return null;
                } else {
                    String urlString = domain_wap + url;
                    String rurl = java.net.URLEncoder.encode(urlString, "utf-8");
                    String jmp = "https://qr.95516.com/qrcGtwWeb-web/api/userAuth?version=1.0.0&redirectUrl=" + rurl;
                    response.sendRedirect(jmp);
                    return null;
                }
            } catch (UnsupportedEncodingException e) {
                view.addObject("error", "url转码异常!");
                return view;
            } catch (IOException e) {
                view.addObject("error", "response跳转异常!");
                return view;
            } catch (Exception e) {
                view.addObject("error", "系统异常!");
                return view;
            }
        }
    }


    @GetMapping("/audit")
    @ResponseBody
    public Result<Object> audit(String userId) {
        if (StringUtil.isEmpty(userId)) {
            return ResultGenerator.genFailResult("缺失参数！");
        }
        QueryWrapper<UserApp> userAppQueryWrapper = new QueryWrapper<UserApp>().eq("userId", userId);
        UserApp app = userAppService.getOne(userAppQueryWrapper);
        if (app == null) {
            return ResultGenerator.genFailResult("用户数据异常！");
        }
        MerchantChannelStatus byMerchantCode = merchantChannelStatusService.getByMerchantCode(app.getMerchantCode());
        if (byMerchantCode == null) {
            return ResultGenerator.genFailResult("进件数据不存在！");
        }
        if (!(MerchantChannelStatus.AUDIT_STATUS_EXAMINING.equals(byMerchantCode.getStatus()) && MerchantChannelStatus.AUDIT_THIRD_STATUS_WAITING.equals(byMerchantCode.getThirdStatus()))) {
            return ResultGenerator.genFailResult("当前商户已处理，请勿重复操作！");
        }
        JSONObject object = new JSONObject();
        object.put("userId", userId);
        try {
            userAppService.merchantAudit(object, "1");
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("操作失败！");
        }
        return ResultGenerator.genSuccessResult("操作成功！");
    }

    @GetMapping("/reject")
    @ResponseBody
    public Result<Object> reject(String userId, String remark) {
        if (StringUtil.isEmpty(userId)) {
            return ResultGenerator.genFailResult("用户id不能为空！");
        }
        if (StringUtil.isEmpty(remark)) {
            return ResultGenerator.genFailResult("驳回原因不能为空！");
        }
        QueryWrapper<UserApp> userAppQueryWrapper = new QueryWrapper<UserApp>().eq("userId", userId);
        UserApp app = userAppService.getOne(userAppQueryWrapper);
        if (app == null) {
            return ResultGenerator.genFailResult("用户数据异常！");
        }
        merchantChannelStatusService.rejectAudit(app.getMerchantCode(), remark);
        return ResultGenerator.genSuccessResult("操作成功！");
    }

    @GetMapping("/toAudit")
    public ModelAndView toAudit(String userId) {
        ModelAndView view = new ModelAndView();
        if (StringUtil.isEmpty(userId)) {
            view.addObject("error", "无效的参数");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        QueryWrapper<UserApp> appWrapper = new QueryWrapper<UserApp>().eq("userId", userId);
        UserApp app = userAppService.getOne(appWrapper);
        if (app == null) {
            view.addObject("error", "无效的参数");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        //查询当前商户已经进件的通道
        QueryWrapper<MerchantChannelStatus> queryUseChannel = new QueryWrapper<MerchantChannelStatus>()
                .eq("merchantCode", app.getMerchantCode())
                .ne("status", MerchantChannelStatus.AUDIT_STATUS_EXAMINING)
                .ne("thirdStatus", MerchantChannelStatus.AUDIT_THIRD_STATUS_WAITING);

        List<MerchantChannelStatus> useChannelList = merchantChannelStatusService.list(queryUseChannel);
        List<Integer> useList = new ArrayList<>(10);
        if (!useChannelList.isEmpty()) {
            for (MerchantChannelStatus channelStatus : useChannelList) {
                useList.add(channelStatus.getChannel());
            }
        }
        QueryWrapper<MerchantChannelStatus> query = new QueryWrapper<MerchantChannelStatus>()
                .eq("merchantCode", app.getMerchantCode())
                .eq("status", MerchantChannelStatus.AUDIT_STATUS_EXAMINING)
                .eq("thirdStatus", MerchantChannelStatus.AUDIT_THIRD_STATUS_WAITING);
        MerchantChannelStatus channel = merchantChannelStatusService.getOne(query);
        if (channel == null) {
            view.addObject("error", "未获取到等待进件的数据！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        QueryWrapper<MerchantPlugin> queryWrapper = new QueryWrapper<MerchantPlugin>().eq("userId", app.getUserId());
        List<MerchantPlugin> list = merchantPluginService.list(queryWrapper);
        if (list.isEmpty()) {
            view.addObject("importType", "1");
        } else {
            view.addObject("importType", "2");
        }
        StoreSummaryVO storeSummaryVO = accountService.getReckoner(userId, "-1");
        List<MerchantRejectDesc> rejectList = merchantRejectDescService.list(new QueryWrapper<MerchantRejectDesc>().orderByDesc("sort"));

        IdCard cert = idCardService.getCertIdCard(userId);

        AccountDTO account = accountService.getRealAccount(userId);
        //获取上次驳回原因

        UserApp userApp = userAppService.queryUserAppJoinById(Long.parseLong(userId));
        view.addObject("userApp", userApp);
        view.addObject("settleType", account.getSettleType());
        view.addObject("cert", cert);
        view.addObject("merchant", storeSummaryVO.getMerchantBaseInfo());
        view.addObject("settleType", storeSummaryVO.getSettleType());
        view.addObject("card", storeSummaryVO.getReckonerInfo());
        view.addObject("bank", storeSummaryVO.getReckonerBankInfo());
        UserInfo info = userInfoService.getById(userId);

        //查询目前的启动的通道列表
        QueryWrapper<MerchantChannel> channelWrapper = new QueryWrapper<MerchantChannel>().eq("status", "1");
        List<MerchantChannel> channelList = merchantChannelService.list(channelWrapper);
        List useChannelNameList = new ArrayList();
        for (MerchantChannel c : channelList) {
            if (useList.size() == 0) {
                c.setUseFlag(false);
            } else {
                if (useList.contains(c.getId())) {
                    c.setUseFlag(true);
                    useChannelNameList.add(c.getChannelName());
                } else {
                    c.setUseFlag(false);
                }
            }
        }
        view.addObject("info", info);
        view.addObject("channelList", channelList);
        view.addObject("app", app);
        view.addObject("userId", userId);
        view.addObject("rejectList", rejectList);
        view.addObject("channelFlag", useList.size() == 0 ? false : true);
        view.addObject("useChannelName", StringUtils.join(useChannelNameList, ","));

        view.setViewName("merchant/audit");
        return view;
    }

    /**
     * @param userAppId: 1257
     * @param userId:    2088502904759300
     * @param openId:
     * @param qrNo:
     * @param view:
     * @return org.springframework.web.servlet.ModelAndView
     * @description:支付测试
     * @date: 2021/8/23 15:00
     */
    @GetMapping("/test/pay")
    @ResponseBody
    public ModelAndView testH5pay(String userAppId, String userId, String openId, String qrNo, ModelAndView view) {
        view.setViewName("merchant/errorInfo2");
        //oY6Es6YJKxaFRoGUlM9Yr6L4LbMo
        if (StringUtil.isEmpty(userAppId)) {
            view.addObject("error", "用户ID不能为空!");
            return view;
        }
        Cookie[] cookies = request.getCookies();
        String cokus = "2088502904759300";
        if (cookies != null && cookies.length > 0) {
            for (Cookie c : cookies) {
                if ("cokus".equals(c.getName())) {
                    String cValue = c.getValue();
                    if (StringUtil.isNotEmpty(cValue)) {
                        byte[] decode = Base64.getDecoder().decode(cValue.getBytes(StandardCharsets.UTF_8));
                        cokus = new String(decode, 0, 0, decode.length);
                        break;
                    }
                }
            }
        }
        String domain_wap = ParametersUtil.domain + "/wap";
        String ua = request.getHeader("user-agent").toLowerCase();
        if (StringUtil.isNotEmpty(cokus)) {
            String payType = "";
            if (ua.contains("micromessenger")) {
                payType = "WXZF";
            } else if (ua.contains("alipay")) {
                payType = "ZFBZF";
            } else {
                payType = "UNIONPAY";
            }
            String url = "/merchant/testH5pay?userAppId=" + userAppId + "&cokus=" + cokus + "&payType=" + payType;
            if (StringUtil.isNotEmpty(qrNo)) {
                url = url + "&qrNo=" + qrNo;
            }
            try {
                response.sendRedirect(domain_wap + url);
                return null;
            } catch (IOException e) {
                log.info("=================>【response跳转异常】异常信息:{}<==============", e.getMessage());
                e.printStackTrace();
            }
            return null;
        } else {
            String url = "/merchant/testH5pay?userAppId=" + userAppId;
            if (StringUtil.isNotEmpty(qrNo)) {
                url = url + "&qrNo=" + qrNo;
            }
            if (StringUtil.isNotEmpty(userId)) {
                url = url + "&userId=" + userId;
            }
            if (StringUtil.isNotEmpty(openId)) {
                url = url + "&openId=" + openId;
            }
            String jmp = domain_wap + url;
            try {
                response.sendRedirect(jmp);
                return null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * @param model:
     * @param userAppId:
     * @param userId:
     * @param openId:
     * @param cokus:
     * @param payType:
     * @param qrNo:
     * @param request:
     * @param response:
     * @param view:
     * @return org.springframework.web.servlet.ModelAndView
     * @description:支付测试回调
     * @date: 2021/8/23 15:01
     */
    @GetMapping("/testH5pay")
    public ModelAndView toTestH5pay(Model model,
                                    String userAppId,
                                    String userId,
                                    String openId,
                                    String cokus,
                                    String payType,
                                    String qrNo,
                                    HttpServletRequest request,
                                    HttpServletResponse response,
                                    ModelAndView view) {
        view.setViewName("merchant/errorInfo2");
        if (StringUtil.isEmpty(userAppId)) {
            model.addAttribute("error", "用户ID不能为空!");
            return view;
        }
        QueryWrapper<UserApp> query = new QueryWrapper<UserApp>().eq("userId", userAppId);
        UserApp userApp = userAppService.getOne(query);
        if (userApp == null) {
            model.addAttribute("error", "用户ID不存在！");
            return view;
        }
        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
        merchantBaseInfo.setMerchantCode(userApp.getMerchantCode());
        List<MerchantBaseInfo> queryMerchantBaseInfoList = merchantBaseInfoService
                .queryMerchantBaseInfoList(merchantBaseInfo);
        if (queryMerchantBaseInfoList.isEmpty()) {
            model.addAttribute("error", "无此商家！");
            return view;
        }
        MerchantStore store = new MerchantStore();
        store.setMerchantCode(merchantBaseInfo.getMerchantCode());
        List<MerchantStore> storeList = merchantStoreService.queryMerchantStoreList(store);
        if (storeList.isEmpty()) {
            model.addAttribute("error", "无此店铺！");
            return view;
        }
        MerchantStore storeInfo = storeList.get(0);
        if ("2".equals(storeInfo.getStatus())) {
            model.addAttribute("error", "店铺已被禁用！");
            return view;
        }
        MerchantBaseInfo baseInfo = queryMerchantBaseInfoList.get(0);
        // 全局电子围栏和单商户电子围栏判定
        //TODO 先暂时可以异地支付
//        if (!commonSwitchService.allowEcdemicPay() && !storeInfo.allowEcdemicPay()) {
//            // 不允许异地支付的时候需要校验ip和商户所在城市
//            try {
//                merchantService.checkPayLocation(request, baseInfo);
//            } catch (PayRiskException e) {
//                model.addAttribute("error", e.getMessage());
//                return view;
//            }
//        }
        model.addAttribute("merchantCode", baseInfo.getMerchantCode());
        model.addAttribute("userAppId", userApp.getUserId());
        model.addAttribute("storeId", storeInfo.getStoreId());
        if (StringUtil.isNotEmpty(cokus)) {
            model.addAttribute("payType", payType);
            model.addAttribute("openid", cokus);
        } else {
            String cookUid = "";
            if (StringUtil.isNotEmpty(openId)) {
                model.addAttribute("payType", "WXZF");
                model.addAttribute("openid", openId);
                cookUid = openId;
            } else if (StringUtil.isNotEmpty(userId)) {
                model.addAttribute("payType", "ZFBZF");
                model.addAttribute("userid", userId);
                cookUid = userId;
            } else {
                model.addAttribute("error", "未获取到有效的支付方式");
                return view;
            }
            if (StringUtil.isNotEmpty(cookUid)) {
                String cokusId = Base64.getEncoder().encodeToString(cookUid.getBytes(StandardCharsets.UTF_8));
                Cookie cookie = new Cookie("cokus", cokusId);
                cookie.setMaxAge(-1);
                response.addCookie(cookie);
            }
        }
        model.addAttribute("storeName", baseInfo.getAlias());
        if (StringUtil.isNotEmpty(qrNo)) {
            model.addAttribute("qrNo", qrNo);
        }
        view.setViewName("th_pay");
        return view;
    }

    /**
     * @param token:
     * @param view:
     * @param request:
     * @return java.lang.String
     * @description:校验token
     * @date: 2021/8/23 15:01
     */
    private String chenkToken(String token, ModelAndView view, HttpServletRequest request) {
        if (StringUtil.isEmpty(token)) {
            view.addObject("error", "无效的token");
            view.setViewName("merchant/errorInfo");
            return null;
        }
        Object code = request.getSession().getAttribute(token);
        String merchantCode = "";
        if (code == null) {
            QueryWrapper<UserApp> queryAppWrapper = new QueryWrapper<UserApp>();
            queryAppWrapper.eq("token", token);
            UserApp app = userAppService.getOne(queryAppWrapper);
            if (app == null) {
                view.addObject("error", "无效的token");
                view.setViewName("merchant/errorInfo");
                return null;
            }
            request.getSession().setAttribute(token, app.getMerchantCode());
            merchantCode = app.getMerchantCode();
        } else {
            merchantCode = code.toString();
        }
        return merchantCode;
    }

    /**
     * @param view:
     * @param token:
     * @param request:
     * @return org.springframework.web.servlet.ModelAndView
     * @description:用户自定义设置
     * @date: 2021/8/23 15:01
     */
    @GetMapping("/customer/set")
    public ModelAndView customerSet(ModelAndView view, String token, HttpServletRequest request) {
        String merchantCode = chenkToken(token, view, request);
        if (StringUtil.isEmpty(merchantCode)) {
            return view;
        }
        view.setViewName("customer/customerSet");
        QueryWrapper<GuideLabel> queryWrapper = new QueryWrapper<GuideLabel>().orderByAsc("id");
        List<GuideLabel> guideLabel = guideLabelService.list(queryWrapper);
        QueryWrapper<MerchantGuide> queryMgWrapper = new QueryWrapper<MerchantGuide>().eq("merchantCode", merchantCode).
                orderByDesc("createTime").isNull("guideId");
        List<MerchantGuide> mGlist = merchantGuideService.list(queryMgWrapper);

        QueryWrapper<MerchantGuide> wrapper = new QueryWrapper<MerchantGuide>().eq("merchantCode", merchantCode)
                .eq("status", "1")
                .isNotNull("guideId");
        List<MerchantGuide> notNullGlist = merchantGuideService.list(wrapper);
        if (!notNullGlist.isEmpty()) {
            view.addObject("checkCommonId", notNullGlist.get(0).getGuideId());
        } else {
            if (!mGlist.isEmpty()) {
                boolean flag = false;
                for (MerchantGuide g : mGlist) {
                    if ("1".equals(g.getStatus())) {
                        flag = true;
                        break;
                    }
                }
                if (flag) {
                    for (GuideLabel l : guideLabel) {
                        l.setStatus("0");
                    }
                }
            }
        }
        view.addObject("token", token);
        view.addObject("guideLabel", guideLabel);
        view.addObject("mGlist", mGlist);
        Map<String, String> uploadParam = OssOperatUtil.getUploadParam();
        view.addObject("upload", JSONObject.toJSONString(uploadParam));
        QueryWrapper<MerchantQrcode> qrcodeQueryWrapper = new QueryWrapper<MerchantQrcode>().eq("merchantCode", merchantCode);
        MerchantQrcode qrCode = merchantQrcodeService.getOne(qrcodeQueryWrapper);
        if (qrCode != null) {
            view.addObject("qrCodeUrl", qrCode.getQrCodeUrl());
            view.addObject("wechat", qrCode.getWechat());
            view.addObject("id", qrCode.getId());
        }
        return view;
    }

    @RequestMapping("/guide/save")
    @ResponseBody
    public Result<JSONObject> guideSave(ModelAndView view, String token, Integer id, String type, HttpServletRequest request) {
        String merchantCode = chenkToken(token, view, request);
        if (StringUtil.isEmpty(merchantCode)) {
            return ResultGenerator.genFailResult("未检查到有效的token");
        }
        if (StringUtil.isEmpty(id)) {
            return ResultGenerator.genFailResult("标签id不能为空！");
        }
        if (StringUtil.isEmpty(type)) {
            return ResultGenerator.genFailResult("标签type不能为空！");
        }
        QueryWrapper<MerchantBaseInfo> queryWrapper = new QueryWrapper<MerchantBaseInfo>().eq("merchantCode", merchantCode);
        MerchantBaseInfo one = merchantBaseInfoService.getOne(queryWrapper);
        if (one == null) {
            return ResultGenerator.genFailResult("操作失败");
        }
        MerchantGuide guide = new MerchantGuide();
        if ("common".equals(type)) {
            UpdateWrapper<MerchantGuide> updateWapper = new UpdateWrapper<MerchantGuide>().eq("merchantCode", merchantCode)
                    .isNull("guideId").set("status", "0");
            merchantGuideService.update(updateWapper);
            QueryWrapper<MerchantGuide> guideQueryWrapper = new QueryWrapper<MerchantGuide>().eq("merchantCode", merchantCode)
                    .eq("guideId", id);
            List<MerchantGuide> list = merchantGuideService.list(guideQueryWrapper);
            if (list.isEmpty()) {
                QueryWrapper<MerchantGuide> removeWapper = new QueryWrapper<MerchantGuide>().eq("merchantCode", merchantCode)
                        .isNotNull("guideId");
                merchantGuideService.remove(removeWapper);
                guide.setCreateTime(new Date());
                guide.setMerchantCode(merchantCode);
                guide.setMerchantName(one.getAlias());
                guide.setStatus("1");
                guide.setGuideId(id);
                merchantGuideService.save(guide);
            } else if (list.size() == 1) {
                MerchantGuide g = list.get(0);
                if ("0".equals(g.getStatus())) {
                    g.setStatus("1");
                    merchantGuideService.saveOrUpdate(g);
                }
            } else {
                List<Integer> ids = new ArrayList<>();
                for (MerchantGuide g : list) {
                    ids.add(g.getId());
                }
                merchantGuideService.removeByIds(ids);
                guide.setCreateTime(new Date());
                guide.setMerchantCode(merchantCode);
                guide.setMerchantName(one.getAlias());
                guide.setStatus("1");
                guide.setGuideId(id);
                merchantGuideService.save(guide);
            }
        } else {
            UpdateWrapper<MerchantGuide> updateWapper = new UpdateWrapper<MerchantGuide>().eq("merchantCode", merchantCode)
                    .isNotNull("guideId").set("status", "0");
            merchantGuideService.update(updateWapper);
            guide.setId(id);
            guide.setStatus("1");
            merchantGuideService.updateById(guide);
        }
        return ResultGenerator.genSuccessResult("操作成功！", null);
    }

    @NoRepeatSubmit
    @RequestMapping("/guide/add")
    @ResponseBody
    public Result<MerchantGuide> getGuide(ModelAndView view, String token, String name, HttpServletRequest request) {
        String merchantCode = chenkToken(token, view, request);
        if (StringUtil.isEmpty(merchantCode)) {
            return ResultGenerator.genFailResult("未检查到有效的token");
        }
        if (StringUtil.isEmpty(name)) {
            return ResultGenerator.genFailResult("标签名称不能为空！");
        }
        if (name.contains("花呗") || name.contains("信用") || name.contains("套现")) {
            return ResultGenerator.genFailResult("标签名称不能包含敏感字符！");
        }
        QueryWrapper<MerchantBaseInfo> queryWrapper = new QueryWrapper<MerchantBaseInfo>().eq("merchantCode", merchantCode);
        MerchantBaseInfo one = merchantBaseInfoService.getOne(queryWrapper);
        if (one == null) {
            return ResultGenerator.genFailResult("操作失败");
        }
        MerchantGuide guide = new MerchantGuide();
        guide.setCreateTime(new Date());
        guide.setMerchantCode(merchantCode);
        guide.setName(name);
        guide.setMerchantName(one.getAlias());
        guide.setStatus("0");
        merchantGuideService.save(guide);
        return ResultGenerator.genSuccessResult("操作成功！", guide);
    }

    @RequestMapping("/wechat/clear")
    @ResponseBody
    public Result<Object> clearWechat(ModelAndView view, String token, HttpServletRequest request) {
        String merchantCode = chenkToken(token, view, request);
        if (StringUtil.isEmpty(merchantCode)) {
            return ResultGenerator.genFailResult("未检查到有效的token");
        }

        MerchantQrcode merchantQrcode = new MerchantQrcode().setMerchantCode(merchantCode);
        QueryWrapper<MerchantQrcode> queryWrapper = new QueryWrapper<>(merchantQrcode);
        merchantQrcodeService.remove(queryWrapper);

        return ResultGenerator.genSuccessResult();
    }

    @RequestMapping("/wechat/add")
    @ResponseBody
    public Result<MerchantQrcode> addWechat(ModelAndView view, String token, String wechat, Integer id, HttpServletRequest request) {
        String merchantCode = chenkToken(token, view, request);
        if (StringUtil.isEmpty(merchantCode)) {
            return ResultGenerator.genFailResult("未检查到有效的token");
        }
        if (StringUtil.isEmpty(wechat)) {
            return ResultGenerator.genFailResult("微信号不能为空！");
        }
        boolean b = wechat.matches("^[^\\u4e00-\\u9fa5]+$");
        if (!b) {
            return ResultGenerator.genFailResult("微信号不能包含中文字符！");
        }
        if (StringUtil.isEmpty(id)) {
            return ResultGenerator.genFailResult("id不能为空！");
        }
        MerchantQrcode qrcode = new MerchantQrcode();
        qrcode.setWechat(wechat);
        qrcode.setId(id);
        qrcode.setUpdateTime(new Date());
        merchantQrcodeService.updateById(qrcode);
        return ResultGenerator.genSuccessResult("操作成功！", qrcode);
    }

    @RequestMapping("/guide/remove")
    @ResponseBody
    public Result<JSONObject> guideRemove(ModelAndView view, String token, Integer id, HttpServletRequest request) {
        String merchantCode = chenkToken(token, view, request);
        if (StringUtil.isEmpty(merchantCode)) {
            return ResultGenerator.genFailResult("未检查到有效的token");
        }
        if (StringUtil.isEmpty(id)) {
            return ResultGenerator.genFailResult("标签ID不能为空！");
        }
        merchantGuideService.removeById(id);
        return ResultGenerator.genSuccessResult("操作成功！", null);
    }

    @RequestMapping("/qrCode1/upload")
    public ModelAndView qrCodeUpload(@RequestParam("file") MultipartFile file, ModelAndView view, HttpServletRequest request) {
        System.out.println("file:" + file);
        view.setViewName("customer/customerSet");
        return view;
    }

    @RequestMapping("/qrCode/upload")
    @ResponseBody
    public Result<Object> qrCodeUpload(ModelAndView view, String token, String photoUrl, HttpServletRequest request) {
        String merchantCode = chenkToken(token, view, request);
        if (StringUtil.isEmpty(merchantCode)) {
            return ResultGenerator.genFailResult("未检查到有效的token");
        }
        if (StringUtil.isEmpty(photoUrl)) {
            return ResultGenerator.genFailResult("图片地址不能为空！");
        }
        QueryWrapper<MerchantBaseInfo> queryWrapper = new QueryWrapper<MerchantBaseInfo>().eq("merchantCode", merchantCode);
        MerchantBaseInfo one = merchantBaseInfoService.getOne(queryWrapper);
        if (one == null) {
            return ResultGenerator.genFailResult("上传失败");
        }
        QueryWrapper<MerchantQrcode> removeWrapper = new QueryWrapper<MerchantQrcode>().eq("merchantCode", merchantCode);
        merchantQrcodeService.remove(removeWrapper);
        MerchantQrcode qrcode = new MerchantQrcode();
        qrcode.setCreateTime(new Date());
        qrcode.setMerchantCode(merchantCode);
        qrcode.setMerchantName(one.getAlias());
        qrcode.setQrCodeUrl(photoUrl);
        merchantQrcodeService.save(qrcode);
        return ResultGenerator.genSuccessResult("操作成功！", qrcode);
    }

    @GetMapping("/store/{qrNo}")
    @ResponseBody
    public Result<Map<String, Object>> getStoreQrNo(@PathVariable(value = "qrNo") String qrNo) {
        Map<String, Object> result = new HashMap<>(2);
        if (StringUtil.isEmpty(qrNo)) {
            return ResultGenerator.genFailResult("二维码编号不能为空！");
        }

        DeviceStock deviceStock = new DeviceStock().setSnNo(qrNo);
        deviceStock = deviceStockService.getOne(new QueryWrapper<>(deviceStock));
        if (deviceStock == null) {
            return ResultGenerator.genFailResult("未获取到当前二维码信息！");
        }
        if (!"3".equals(deviceStock.getStatus())) {
            return ResultGenerator.genFailResult("当前二维码暂未激活！");
        }
        MerchantBaseInfo merchantInfo = merchantBaseInfoService.getById(deviceStock.getActMercId());
        if (merchantInfo == null) {
            return ResultGenerator.genFailResult("未获取到商户信息！");
        }
        MerchantStore store = new MerchantStore();
        store.setMerchantCode(merchantInfo.getMerchantCode());
        List<MerchantStore> storeList = merchantStoreService.queryMerchantStoreList(store);
        if (storeList.isEmpty()) {
            return ResultGenerator.genFailResult("未获取到店铺信息！");
        }
        result.put("storeId", storeList.get(0));
        return ResultGenerator.genSuccessResult("获取成功！", result);
    }

    @RequestMapping("/store/userApp/{userAppId}")
    @ResponseBody
    public Result<Map<String, Object>> getStoreByUserAppId(@PathVariable(value = "userAppId") String userAppId) {
        Map<String, Object> result = new HashMap<>(2);
        if (StringUtil.isEmpty(userAppId)) {
            return ResultGenerator.genFailResult("用户ID不能为空！");
        }
        QueryWrapper<UserApp> userAppQueryWrapper = new QueryWrapper<UserApp>().eq("userId", userAppId);
        UserApp app = userAppService.getOne(userAppQueryWrapper);
        if (app == null) {
            return ResultGenerator.genFailResult("用户不存在！");
        }
        MerchantStore store = new MerchantStore();
        store.setMerchantCode(app.getMerchantCode());
        List<MerchantStore> storeList = merchantStoreService.queryMerchantStoreList(store);
        if (storeList.isEmpty()) {
            return ResultGenerator.genFailResult("未获取到店铺信息！");
        }
        result.put("storeId", storeList.get(0));
        return ResultGenerator.genSuccessResult("获取成功！", result);
    }

    /**
     * 更具id获取店铺ID
     */
    @RequestMapping(value = "/store/getInfoId", method = RequestMethod.POST)
    @ResponseBody
    public Result<JSONObject> getStoreId(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        String userAppId = json.getString("userAppId");
        if (StringUtil.isEmpty(userAppId)) {
            return ResultGenerator.genFailResult("用户ID不能为空！");
        }
        QueryWrapper<UserApp> userAppQueryWrapper = new QueryWrapper<UserApp>().eq("userId", userAppId);
        UserApp app = userAppService.getOne(userAppQueryWrapper);
        if (app == null) {
            return ResultGenerator.genFailResult("用户不存在！");
        }
        MerchantStore store = new MerchantStore();
        store.setMerchantCode(app.getMerchantCode());
        List<MerchantStore> storeList = merchantStoreService.queryMerchantStoreList(store);
        if (storeList.isEmpty()) {
            return ResultGenerator.genFailResult("未获取到店铺信息！");
        }
        result.put("storeId", storeList.get(0));
        return ResultGenerator.genSuccessResult("获取成功!", result);
    }

    /**
     * 添加h5 页面转发接口
     *
     * @param request
     * @param userAppId
     * @return
     */
    @RequestMapping(value = "/h5/pay", method = RequestMethod.GET)
    public ModelAndView toH5Pay(HttpServletRequest request, String userAppId) {
        ModelAndView modelAndView = new ModelAndView();
        JSONObject result = new JSONObject();
        if (StringUtil.isEmpty(userAppId)) {
            result.put("message", "用户ID不能为空！");
            modelAndView.addAllObjects(result);
            modelAndView.setViewName("merchant/error");
            return modelAndView;
        }
        if (!"7249".equals(userAppId)) {
            result.put("message", "当前商户暂不支持！");
            modelAndView.addAllObjects(result);
            modelAndView.setViewName("merchant/error");
            return modelAndView;
        }
        String domain_wap = ParametersUtil.domain + "/wap";
        String jump = "/merchant/auth?userAppId=" + userAppId;
        try {
            response.sendRedirect(domain_wap + jump);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 新版授权
     *
     * @param userAppId
     * @param request
     * @param view
     * @param response
     * @return
     */
    @GetMapping("/authPay")
    public ModelAndView authPay(String userAppId, Integer channel, String qrNo, HttpServletRequest request, ModelAndView view, HttpServletResponse response) {
        if (StringUtil.isEmpty(userAppId)) {
            view.setViewName("merchant/errorInfo2");
            view.addObject("error", "用户ID不能为空!");
            return view;
        }
        String ua = request.getHeader("user-agent").toLowerCase();
        String payType = "";
        if (ua.contains("micromessenger")) {
            payType = "WXZF";
        } else if (ua.contains("alipay")) {
            payType = "ZFBZF";
        } else {
            payType = "UNIONPAY";
        }
        String cokusName = "cokus_" + payType;
        Cookie[] cookies = request.getCookies();
        String cokus = "";
        if (cookies != null && cookies.length > 0) {
            for (Cookie c : cookies) {
                if (cokusName.equals(c.getName())) {
                    String cValue = c.getValue();
                    if (StringUtil.isNotEmpty(cValue)) {
                        //TODO 解决银联用户标识转码后特殊字符异常
                        if ("UNIONPAY".equals(payType)) {
                            cValue = cValue.replace(" ", "+");
                        }
                        byte[] decode = Base64.getDecoder().decode(cValue.getBytes(StandardCharsets.UTF_8));
                        cokus = new String(decode, 0, 0, decode.length);
                        break;
                    }
                }
            }
        }
        String domain_wap = ParametersUtil.domain + "/wap";

        log.info("跳转域名", domain_wap);

        String APP_ID = ParametersUtil.APPID;
        String ali_appid = ParametersUtil.ZY_ALI_APP_ID;
        String url = "/merchant/h5pay?userAppId=" + userAppId;
        if (StringUtil.isNotEmpty(qrNo)) {
            url = url + "&qrNo=" + qrNo;
        }
        if (StringUtil.isNotEmpty(channel)) {
            url = url + "&channel=" + channel;
        }
        if (StringUtil.isNotEmpty(cokus)) {
            url = url + "&cokus=" + cokus + "&payType=" + payType;
            try {
                response.sendRedirect(domain_wap + url);
                return null;
            } catch (IOException e) {
                log.info("=================>【response跳转异常】异常信息:{}<==============", e.getMessage());
                e.printStackTrace();
            }
            return null;
        } else {
            try {
                if (ua.contains("micromessenger")) {
                    String jump = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APP_ID
                            + "&redirect_uri=" + java.net.URLEncoder.encode(domain_wap + url, "utf-8")
                            + "&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
                    response.sendRedirect(jump);
                    return null;
                } else if (ua.contains("alipay")) {
                    String urlString = domain_wap + url;
                    String rurl = java.net.URLEncoder.encode(urlString, "utf-8");
                    String jmp = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=" + ali_appid + "&scope=auth_base&redirect_uri=" + rurl;
                    response.sendRedirect(jmp);
                    return null;
                } else {
                    String urlString = domain_wap + url;
                    String rurl = java.net.URLEncoder.encode(urlString, "utf-8");
                    String jmp = "https://qr.95516.com/qrcGtwWeb-web/api/userAuth?version=1.0.0&redirectUrl=" + rurl;
                    response.sendRedirect(jmp);
                    return null;
                }
            } catch (UnsupportedEncodingException e) {
                view.setViewName("merchant/errorInfo2");
                view.addObject("error", "url转码异常!");
                return view;
            } catch (IOException e) {
                view.setViewName("merchant/errorInfo2");
                view.addObject("error", "response跳转异常!");
                return view;
            }
        }
    }

    /**
     * 新版授权回调页面
     *
     * @param model
     * @param code
     * @param auth_code
     * @param userAuthCode
     * @param userAppId
     * @param request
     * @return
     */
    @GetMapping("/h5pay")
    public ModelAndView html(Model model,
                             String code,
                             String auth_code,
                             String userAuthCode,
                             String userAppId,
                             String cokus,
                             String payType,
                             String qrNo,
                             Integer channelVal,
                             HttpServletRequest request,
                             HttpServletResponse response,
                             ModelAndView view, String province) {
        view.setViewName("merchant/errorInfo2");
        if (StringUtil.isEmpty(userAppId)) {
            model.addAttribute("error", "用户ID不能为空!");
            return view;
        }
        QueryWrapper<UserApp> query = new QueryWrapper<UserApp>().eq("userId", userAppId);
        UserApp userApp = userAppService.getOne(query);
        if (userApp == null) {
            model.addAttribute("error", "用户ID不存在！");
            return view;
        }
        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
        merchantBaseInfo.setMerchantCode(userApp.getMerchantCode());
        List<MerchantBaseInfo> queryMerchantBaseInfoList = merchantBaseInfoService
                .queryMerchantBaseInfoList(merchantBaseInfo);
        if (queryMerchantBaseInfoList.isEmpty()) {
            model.addAttribute("error", "无此商家！");
            return view;
        }
        MerchantStore store = new MerchantStore();
        store.setMerchantCode(merchantBaseInfo.getMerchantCode());
        List<MerchantStore> storeList = merchantStoreService.queryMerchantStoreList(store);
        if (storeList.isEmpty()) {
            model.addAttribute("error", "无此店铺！");
            return view;
        }
        MerchantStore storeInfo = storeList.get(0);
        if ("2".equals(storeInfo.getStatus())) {
            model.addAttribute("error", "店铺已被禁用！");
            return view;
        }
        Map<String, Object> params = new HashMap<>(16);
        params.put("code", code);
        params.put("auth_code", auth_code);
        params.put("userAuthCode", userAuthCode);
        params.put("merchantCode", merchantBaseInfo.getMerchantCode());
        params.put("userAppId", userAppId);
        params.put("qrNo", qrNo);
        params.put("payType", payType);
        params.put("cokus", cokus);
        params.put("province", province);
        MerchantBaseInfo baseInfo = queryMerchantBaseInfoList.get(0);
        // 全局电子围栏和单商户电子围栏判定
        if (!commonSwitchService.allowEcdemicPay() && !storeInfo.allowEcdemicPay()) {
            // 不允许异地支付的时候需要校验ip和商户所在城市
            try {
                String ip = IpUtils.getIpAddr(request);
                merchantService.checkPayLocation(ip, baseInfo, province);
            } catch (PayRiskException e) {
                view.addObject("error", e.getMessage());
                view.setViewName("/merchant/locationError");
                view.addAllObjects(params);
                return view;
            }
        }
        model.addAttribute("merchantCode", baseInfo.getMerchantCode());
        model.addAttribute("userAppId", userApp.getUserId());
        model.addAttribute("storeId", storeInfo.getStoreId());
        model.addAttribute("channelVal", channelVal);
        if (StringUtil.isNotEmpty(cokus)) {
            model.addAttribute("payType", payType);
            model.addAttribute("openid", cokus);
        } else {
            String cookUid = "";
            String pType = "";
            if (StringUtil.isNotEmpty(code)) {
                pType = "WXZF";
                WxAccessTokenRequest tokenRequest = WxAccessTokenRequest.buidWxToken(ParametersUtil.APPID, ParametersUtil.APPSECRET, code, WxConstants.OAUTH2_ACCESS_TOKEN_URL);
                WxOauth2AccessTokenResponse result = wxCommonService.getOauth2Info(tokenRequest);
                String openid = result.getOpenid();
                model.addAttribute("openid", openid);
                model.addAttribute("unionId", result.getUnionid());
                cookUid = openid;
            } else if (StringUtil.isNotEmpty(auth_code)) {
                pType = "ZFBZF";
                AlipaySystemOauthTokenResponse tokenResponse = AliUtil.getAliUserIdV2(auth_code, ParametersUtil.ZY_PRI, ParametersUtil.ZY_PUB, ParametersUtil.ZY_ALI_APP_ID);
                model.addAttribute("userid", tokenResponse.getUserId());
                cookUid = tokenResponse.getUserId();
            } else if (StringUtil.isNotEmpty(userAuthCode)) {
                pType = "UNIONPAY";
                MerchantChannelStatus channel = merchantChannelStatusService.getValidData(baseInfo.getMerchantCode());
                String ua = request.getHeader("User-Agent");
                log.info("===================>【银联】标识，获取请求头部信息:{},==============", ua);
                int begin = ua.indexOf("UnionPay");
                String payMentApp = ua.substring(begin);
                if (payMentApp.length() > 30) {
                    payMentApp = payMentApp.substring(0, 30);
                }
                try {
                    Map<String, Object> unionInfo = null;
                    //随行付
                    if (channel.getChannel() == 1) {
                        unionInfo = sxfPayService.getUnionInfo(userAuthCode, payMentApp, null);
                    } else if (channel.getChannel() == 2) {
                        view.addObject("error", "当前通道已关闭,请联系客户切换");
                        return view;
                    } else if (channel.getChannel() == 3) {
                        unionInfo = ryxPayService.getUnionInfo(userAuthCode, payMentApp, channel.getMerchantId());
                    } else if (channel.getChannel() == 4) {
                        unionInfo = ysPayOldService.getUnionInfo(userAuthCode, payMentApp, null);
                    } else {
                        view.addObject("error", "未知通道类型");
                        return view;
                    }
                    log.info("===================>【银联】获取用户标识结果参数:{}==============", unionInfo);
                    if ("1".equals(unionInfo.get("code"))) {
                        Object userIdData = unionInfo.get("data");
                        String userId = "";
                        if (userIdData instanceof Map) {
                            Map<String, String> data = (Map<String, String>) userIdData;
                            userId = data.get("data");
                        } else {
                            userId = userIdData.toString();
                        }
                        cookUid = userId;
                        model.addAttribute("userid", userId);
                    }
                } catch (Exception e) {
                    model.addAttribute("error", "银联用户标识解析出错！");
                    return view;
                }
            } else {
                model.addAttribute("error", "未获取到有效的支付方式");
                return view;
            }
            model.addAttribute("payType", pType);
            if (StringUtil.isNotEmpty(cookUid)) {
                String cokusName = "cokus_" + pType;
                String cokusId = Base64.getEncoder().encodeToString(cookUid.getBytes(StandardCharsets.UTF_8));
                Cookie cookie = new Cookie(cokusName, cokusId);
                cookie.setMaxAge(-1);
                response.addCookie(cookie);
            }
        }
        model.addAttribute("storeName", baseInfo.getAlias());
        if (StringUtil.isNotEmpty(qrNo)) {
            model.addAttribute("qrNo", qrNo);
        }
        view.setViewName("th_pay");
        return view;
    }

    /**
     * 扫码设备支付授权页面
     *
     * @param request:
     * @return org.springframework.web.servlet.ModelAndView
     * @date: 2021/12/28 13:53
     */
    @GetMapping("/scanPayAuth")
    public ModelAndView scanPayAuth(HttpServletRequest request, HttpServletResponse response, String tk) {
        return merchantService.scanPayAuth(request, response, tk);
    }


    /**
     * 扫码支付页面
     *
     * @param request:
     * @return org.springframework.web.servlet.ModelAndView
     * @date: 2021/12/28 13:53
     */
    @GetMapping("/scanPay")
    public ModelAndView scanPay(HttpServletRequest request, HttpServletResponse response, String tk,
                                String code,
                                String auth_code,
                                String userAuthCode,
                                String userId,
                                String payType) {
        return merchantService.scanPay(request, response, tk, code, auth_code, userAuthCode, userId, payType);
    }

    @GetMapping("/auth")
    public ModelAndView auth(HttpServletRequest request, String userAppId, String qrNo) throws IOException {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("merchant/errorInfo2");
        if (StringUtil.isEmpty(userAppId)) {
            modelAndView.addObject("error", "用户ID不能为空！");
            return modelAndView;
        }
        //TODO 喜客定制需求
        if ("7044".equals(userAppId)) {
            modelAndView.addObject("error", "本店不支持支付宝，请使用微信扫码支付！");
            return modelAndView;
        }
        //支付宝更换支付页面
        String jump = ParametersUtil.domain + "/wap/merchant/authPay?userAppId=" + userAppId + "&qrNo=" + qrNo;
        response.sendRedirect(jump);
        return null;
    }

    @ApiOperation(value = "商户码牌链接", notes = "商户码牌链接", httpMethod = "GET")
    @GetMapping("/auth/{qrNo}")
    public ModelAndView customQrCode(@ApiParam @PathVariable String qrNo, RedirectAttributes attrs) throws IOException {
        ModelAndView view = new ModelAndView();
        if (StringUtil.isEmpty(qrNo)) {
            view.setViewName("merchant/errorInfo");
            request.setAttribute("error", "请扫描正确的二维码！");
            return view;
        }
        String actMercId = null;
        DeviceStock deviceStock = new DeviceStock().setSnNo(qrNo);
        List<DeviceStock> deviceStockList = deviceStockService.list(new QueryWrapper<>(deviceStock));
        if (deviceStockList == null || deviceStockList.isEmpty()) {
            view.setViewName("merchant/errorInfo");
            request.setAttribute("error", "很抱歉，该收款码暂未激活！");
            return view;
        }
        deviceStock = deviceStockList.get(0);
        if ("1".equals(deviceStock.getStatus())) {
            request.setAttribute("error", "很抱歉，该设备暂未激活！");
            view.setViewName("merchant/errorInfo");
            return view;
        }

        if (StringUtils.isEmpty(deviceStock.getActMercId())) {
            request.setAttribute("error", "很抱歉，该设备暂未激活！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        actMercId = deviceStock.getActMercId();
        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo().setId(Long.parseLong(actMercId));
        merchantBaseInfo = merchantBaseInfoService.queryMerchantBaseInfo(merchantBaseInfo);

        String merchantCode = merchantBaseInfo.getMerchantCode();
        UserApp userApp = new UserApp().setMerchantCode(merchantCode).setUserType("promoter");
        userApp = userAppService.queryUserApp(userApp);
        MerchantStore merchantStore = new MerchantStore().setMerchantCode(merchantCode);
        merchantStore = merchantStoreService.queryMerchantStore(merchantStore);

        // 通过各种检测即重定向到付款页
        attrs.addAttribute("merchantCode", merchantCode);
        attrs.addAttribute("storeId", merchantStore.getStoreId());
        attrs.addAttribute("userAppId", userApp.getUserId());
        attrs.addAttribute("qrNo", qrNo);
        //view.setViewName("redirect:/merchant/auth");
        view.setView(new RedirectView("/merchant/auth?merchantCode" + merchantCode + "&storeId" + merchantStore.getStoreId() + "&userAppId=" + userApp.getUserId() + "&qrNo=" + qrNo, true, false));
        return view;
    }

    /**
     * index:(授权回调页面). <br/>
     *
     * @param code
     * @param auth_code
     * @return
     * @author Administrator
     * @since JDK 1.8
     */
    @GetMapping("/index")
    public ModelAndView index(String code, String auth_code, String userAuthCode, String merchantCode, String storeId, String userAppId,
                              String aisleSwitch, String qrNo, HttpServletRequest request, String province) {
        ModelAndView modelAndView = new ModelAndView("merchant/index");
        MerchantStore merchantStore = new MerchantStore().setMerchantCode(merchantCode);
        List<MerchantStore> merchantStoreList = merchantStoreService.queryMerchantStoreList(merchantStore);
        if (merchantStoreList == null || merchantStoreList.size() == 0) {
            modelAndView.setViewName("/merchant/errorInfo");
            modelAndView.addObject("error", "无法获取商户信息");
            return modelAndView;
        } else {
            merchantStore = merchantStoreList.get(0);
            if ("2".equals(merchantStore.getStatus())) {
                modelAndView.setViewName("/merchant/errorInfo");
                modelAndView.addObject("error", "该店铺已被冻结");
                return modelAndView;
            }
        }
        Map<String, Object> result = new HashMap<>(16);
        result.put("code", code);
        result.put("auth_code", auth_code);
        result.put("userAuthCode", userAuthCode);
        result.put("merchantCode", merchantCode);
        result.put("storeId", storeId);
        result.put("userAppId", userAppId);
        result.put("aisleSwitch", aisleSwitch);
        result.put("qrNo", qrNo);
        result.put("province", province);
        //电子围栏
        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
        merchantBaseInfo.setMerchantCode(merchantCode);
        merchantBaseInfo = merchantBaseInfoService.queryMerchantBaseInfo(merchantBaseInfo);
        // 全局电子围栏和单商户电子围栏判定
        if (!commonSwitchService.allowEcdemicPay() && !merchantStore.allowEcdemicPay()) {
            // 不允许异地支付的时候需要校验ip和商户所在城市
            try {
                String ip = IpUtils.getIpAddr(request);
                merchantService.checkPayLocation(ip, merchantBaseInfo, province);
            } catch (PayRiskException e) {
                modelAndView.addObject("error", e.getMessage());
                modelAndView.setViewName("/merchant/locationError");
                modelAndView.addAllObjects(result);
                return modelAndView;
            }
        }
        String userImg = "";// 用户头像
        String nickName = "";// 用户昵称
        if (StringUtil.isNotEmpty(code)) {
            result.put("payType", "wx");
            WxAccessTokenRequest tokenRequest = WxAccessTokenRequest.buidWxToken(ParametersUtil.APPID, ParametersUtil.APPSECRET, code, WxConstants.OAUTH2_ACCESS_TOKEN_URL);
            WxOauth2AccessTokenResponse params = wxCommonService.getOauth2Info(tokenRequest);
            result.put("openid", params.getOpenid());
            result.put("unionId", params.getUnionid());
        } else if (StringUtil.isNotEmpty(auth_code)) {
            //支付宝取消主动授权 采用静默授权方式，无法获取用户信息
            AlipaySystemOauthTokenResponse tokenResponse = AliUtil.getAliUserIdV2(auth_code, ParametersUtil.ZY_PRI, ParametersUtil.ZY_PUB, ParametersUtil.ZY_ALI_APP_ID);
            result.put("payType", "alipay");
            result.put("userid", tokenResponse.getUserId());
        } else if (StringUtil.isNotEmpty(userAuthCode)) {
            MerchantChannelStatus channel = merchantChannelStatusService.getValidData(merchantCode);
            String ua = request.getHeader("User-Agent");
            log.info("===================>【银联】标识，获取请求头部信息:{},==============", ua);
            int begin = ua.indexOf("UnionPay");
            String payMentApp = ua.substring(begin);
            if (payMentApp.length() > 30) {
                payMentApp = payMentApp.substring(0, 30);
            }
            try {
                Map<String, Object> unionInfo = new HashMap<>(3);
                //随行付
                if (channel.getChannel() == 1) {
                    unionInfo = sxfPayService.getUnionInfo(userAuthCode, payMentApp, null);
                } else if (channel.getChannel() == 2) {
                    modelAndView.addObject("error", "当前通道已关闭,请联系客户切换");
                    modelAndView.setViewName("/merchant/errorInfo2");
                    return modelAndView;
                } else if (channel.getChannel() == 3) {
                    modelAndView.addObject("error", "当前商户类型不支持扫码，请使用反扫功能或切换实时到账通道");
                    modelAndView.setViewName("/merchant/errorInfo2");
                    return modelAndView;
                } else if (channel.getChannel() == 4) {
                    unionInfo = ysPayOldService.getUnionInfo(userAuthCode, payMentApp, null);
                } else {
                    modelAndView.addObject("error", "未知通道类型");
                    modelAndView.setViewName("/merchant/errorInfo2");
                    return modelAndView;
                }
                log.info("===================>【银联】获取用户标识结果参数:{}==============", unionInfo);
                if ("1".equals(unionInfo.get("code"))) {
                    Object userIdData = unionInfo.get("data");
                    String userId = "";
                    if (userIdData instanceof Map) {
                        Map<String, String> data = (Map<String, String>) userIdData;
                        userId = data.get("data");
                    } else {
                        userId = userIdData.toString();
                    }
                    result.put("userid", userId);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("===================>【银联】获取用户标识出错:{}==============", ua);
            }
        } else {
            modelAndView.addObject("error", "不支持当前扫码方式，请使用微信、支付宝、云闪付或京东金融扫码支付");
            modelAndView.setViewName("/merchant/errorInfo2");
            return modelAndView;
        }
        //TODO 测试
//        result.put("payType", "wx");
//        result.put("openid", "oY6Es6Y52jNTArOpt-CTDP4ScKqs");
//        result.put("payType", "alipay");
//        result.put("userid", "2088502904759300");

        result.put("userImg", userImg);
        result.put("nickName", nickName);
        String storeName = "收银呗商家";
        UserApp userApp = new UserApp();
        userApp.setUserId(Long.parseLong(userAppId));
        userApp = userAppService.queryUserApp(userApp);
        if (StringUtil.isNotEmpty(userApp.getMerchantName())) {
            storeName = userApp.getMerchantName();
        }
        if (StringUtil.isNotEmpty(merchantBaseInfo.getAlias())) {
            storeName = merchantBaseInfo.getAlias();
        }
        result.put("storeName", storeName);
        modelAndView.addAllObjects(result);
        return modelAndView;
    }

//    public WeixinOauth2Token getWeChatUserOpenId(String code) {
//        log.info(code);
//        String appId = ParametersUtil.APPID;
//        String appSecret = ParametersUtil.APPSECRET;
//        log.info("====appId===" + appId);
//        log.info("===appSecret===" + appSecret);
//        String openid = "";
//        WeixinOauth2Token wot = null;
//        if (!"authdeny".equals(code)) {
//            if (code != null) {
//                wot = Oauth2Util.getOauth2AccessToken(appId, appSecret, code);
//            }
//        }
//        log.info(openid);
//        return wot;
//    }

//    public WeixinOauth2Token getWeChatUserOpenId(String code) {
//        log.info(code);
//        String appId = ParametersUtil.APPID;
//        String appSecret = ParametersUtil.APPSECRET;
//        log.info("====appId===" + appId);
//        log.info("===appSecret===" + appSecret);
//        String openid = "";
//        Object oauthInfo = request.getSession().getAttribute(code);
//        log.info("获取SESSION中微信授权信息:{}",oauthInfo);
//        if(oauthInfo != null){
//            return (WeixinOauth2Token) oauthInfo;
//        }else{
//            WeixinOauth2Token wot = null;
//            if (!"authdeny".equals(code)) {
//                if (code != null) {
//                    wot = Oauth2Util.getOauth2AccessToken(appId, appSecret, code);
//                    if(wot != null){
//                        request.getSession().setAttribute(code,wot);
//                    }
//                }
//            }
//            log.info(openid);
//            return wot;
//        }
//    }

    /**
     * wechatPay:(微信支付). <br/>
     *
     * @return
     * @author Administrator
     * @since JDK 1.8
     */
    @PostMapping("/wechatPay")
    @ResponseBody
    public Map<String, Object> wechatPay(MerchantWechatPayDTO merchantWechatPayDTO) {
        return null;
//        String jsonString = JSONObject.toJSONString(merchantWechatPayDTO);
//        log.error("==================merchantWechatPayDTO QIAN===================" + jsonString);
////		log.info("===========nickName==========="+nickName);
////		merchantWechatPayDTO.setOpenid(openid);
////		merchantWechatPayDTO.setComsumeMoney(comsumeMoney);
////		merchantWechatPayDTO.setMerchantCode(merchantCode);
////		merchantWechatPayDTO.setUserAppId(userAppId);
////		merchantWechatPayDTO.setUserImg(userImg);
////		merchantWechatPayDTO.setNickName(nickName);
//        Map<String, Object> result = new HashMap<String, Object>(16);
//        // 通过UserApp-userId 查商户号
//        UserApp userApp = new UserApp();
//        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
//        if (StringUtil.isNotEmpty(merchantWechatPayDTO.getMerchantCode())) {
//            merchantBaseInfo.setMerchantCode(merchantWechatPayDTO.getMerchantCode());
//            merchantBaseInfo = merchantBaseInfoService.queryMerchantBaseInfo(merchantBaseInfo);
//        }
//        if (StringUtil.isNotEmpty(merchantWechatPayDTO.getUserAppId())) {
//            userApp.setUserId(Long.valueOf(merchantWechatPayDTO.getUserAppId()));
//            userApp = userAppService.queryUserApp(userApp);
//        }
//        if (StringUtil.isEmpty(merchantBaseInfo.getSubMchId()) && StringUtil.isEmpty(userApp.getSubMchId())) {
//            result.put("code", "0");
//            return result;
//        }
//        log.info("方法名wechatPay  userApp" + merchantWechatPayDTO.getUserAppId() + "====");
//        // APPID
//        String APPID = ParametersUtil.APPID;
//        log.error("===APPID===" + APPID);
//        String pid = ParametersUtil.PID;
//        log.error("===APPID===" + pid);
//        String subAppid = "";
//        if (StringUtil.isNotEmpty(userApp.getSubMchId())) {
//            subAppid = userApp.getSubMchId();
//        } else if (StringUtil.isNotEmpty(merchantBaseInfo.getSubMchId())) {
//            subAppid = merchantBaseInfo.getSubMchId();
//        }
//        log.error("===subAppid===" + subAppid);
//        String wechatCallback = ParametersUtil.wechatCallback + "/wap/merchant/wechatCallback";// 支付成功后的回调地址
//        merchantWechatPayDTO.setAppid(APPID);
//        merchantWechatPayDTO.setNotifyUrl(wechatCallback);
//        merchantWechatPayDTO.setMchId(pid);
//        merchantWechatPayDTO.setSubMchId(subAppid);
//        log.error("===merchantWechatPayDTO HOU===" + JSONObject.toJSONString(merchantWechatPayDTO));
//        PayUnitedResponse payUnitedResponse = wechantMerchantOrderCreate(merchantWechatPayDTO, request);
//        WechatPayment wechatPayment = toPay(payUnitedResponse);
//        result.put("data", wechatPayment);
//        log.info("===result==" + JSONObject.toJSONString(result));
//        return result;
    }

    public WechatPayment toPay(PayUnitedResponse 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);
        System.out.println("pkey-------" + pKey + "---   wechatPayment=" + JSONObject.toJSONString(wechatPayment));
        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;
    }

    /**
     * wechantMerchantOrderCreate:(微信生成订单). <br/>
     *
     * @author Administrator
     * @since JDK 1.8
     */
    private PayUnitedResponse wechantMerchantOrderCreate(MerchantWechatPayDTO merchantWechatPayDTO,
                                                         HttpServletRequest request) {
        MerchantStore merchantInfo = merchantStoreService.getMerchantInfo(merchantWechatPayDTO.getMerchantCode(),
                merchantWechatPayDTO.getStoreId());
        String orderSn = "W" + StringUtil.getBillno();
        MerchantOrder merchantOrder = new MerchantOrder();
        merchantOrder.setOrderType("2");
        merchantOrder.setUserImg(merchantWechatPayDTO.getUserImg());
        merchantOrder.setNickName(merchantWechatPayDTO.getNickName());
        merchantOrder.setConsumeFee(Double.valueOf(merchantWechatPayDTO.getComsumeMoney()));
        merchantOrder.setMerchantCode(merchantWechatPayDTO.getMerchantCode());
        merchantOrder.setStoreId(merchantWechatPayDTO.getStoreId());
        merchantOrder.setOrderNumber(orderSn);
        String storeId = merchantWechatPayDTO.getStoreId();
        MerchantStore merchantStore = new MerchantStore();
        merchantStore.setStoreId(storeId);
        merchantStore = merchantStoreService.queryMerchantStore(merchantStore);
        if (null != merchantStore) {
            String storeName = merchantStore.getStoreName();
            merchantOrder.setStaffName(storeName);
        }
        merchantOrder.setStaffCode(merchantWechatPayDTO.getStoreId());
        if (StringUtil.isNotEmpty(merchantInfo.getMerchantName())) {
            merchantOrder.setMerchantName(merchantInfo.getMerchantName());
        }
        merchantOrder.setPayTypeCode("wechatPay");
        merchantOrder.setPayTypeName("微信");
        Date date = new Date();
        merchantOrder.setCreateDt(date);
        merchantOrder.setUpdateTime(date);
        merchantOrder.setStatus("5");
        merchantOrderService.save(merchantOrder);
        PayUnitedRequest payUnitedRequest = new PayUnitedRequest();
        merchantWechatPayDTO.setIp(IpUtils.getIpAddr(request));
        merchantWechatPayDTO.setOrderSn(orderSn);
        String WX_PAY_KEY = ParametersUtil.KEY;
        Map<String, String> result = payUnitedRequest.getMerchantMap(merchantWechatPayDTO, merchantOrder.getStoreName(),
                WX_PAY_KEY);
        String xml = result.get("xml");
        System.out.println(xml);
        String response = HttpUrlConnection.httpXML("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
        System.out.println(response);
        PayUnitedResponse payUnitedResponse = WeiXinUtil.xmlToPayUnitedResponse(response);
        return payUnitedResponse;
    }

    /**
     * wechatCallback:(微信回调地址). <br/>
     *
     * @return
     * @author Administrator
     * @since JDK 1.8
     */
    @RequestMapping("/wechatCallback")
    @ResponseBody
    public Map<String, Object> wechatCallback() {
        RealFansDTO realFansDTO = new RealFansDTO();
        InputStream is = null;
        try {
            is = request.getInputStream();// 获取请求的流信息(这里是微信发的xml格式所有只能使用流来读)
            String xml = XmlUtil.toUTF8(is);
            log.info(xml);
            Map<String, Object> notifyMap = XmlUtil.toMap(xml);// 将微信发的xml转map
            log.info("===notifyMap====" + notifyMap);
            if ("SUCCESS".equals(notifyMap.get("result_code"))) {
                String ordersSn = (String) notifyMap.get("out_trade_no");// 商户订单号
                String transaction_id = (String) notifyMap.get("transaction_id");
                String amountpaid = (String) notifyMap.get("total_fee");// 实际支付的订单金额:单位 分
                String openid = (String) notifyMap.get("openid");// 用户openid
                String time_end = (String) notifyMap.get("time_end");// 支付完成时间
                BigDecimal amountPay = (new BigDecimal(amountpaid).divide(new BigDecimal("100"))).setScale(2);// 将分转换成元-实际支付金额:元
                // 消费金额
                String amount = amountPay + "";
                MerchantOrder merchantOrder = new MerchantOrder();
                merchantOrder.setOrderNumber(ordersSn);
                List<MerchantOrder> queryMerchantOrderList = merchantOrderService.list(new QueryWrapper<>(merchantOrder));
                if (queryMerchantOrderList != null && queryMerchantOrderList.size() > 0) {
                    merchantOrder = queryMerchantOrderList.get(0);
                    if ("1".equals(merchantOrder.getStatus())) {
                        response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
                        return null;
                    }
                    Map<String, Object> map = new HashMap<>(16);
                    realFansDTO.setConSumMoney(amount);
                    realFansDTO.setConsumTime(time_end);
                    realFansDTO.setLogo(merchantOrder.getUserImg());
                    realFansDTO.setNickName(merchantOrder.getNickName());
                    realFansDTO.setMerchantCode(merchantOrder.getMerchantCode());
                    realFansDTO.setOrderNumber(ordersSn);
                    realFansDTO.setTradeNumber(transaction_id);
                    realFansDTO.setSoleId(openid);
                    realFansDTO.setPayWay("1");
                    merchantOrder.setTransNo(transaction_id);
                    merchantOrder.setTransDt(new Date());
                    merchantOrder.setStatus("1");
                    merchantOrder.setMercUserId(openid);
                    merchantOrder.setThirdTransNo(transaction_id);
                    merchantOrderService.updateOrderAndCreateProfit(merchantOrder);
                }
            } else {
                log.info("回调失败");
            }
            // 告诉微信服务器收到信息了，不要在调用回调action了========这里很重要回复微信服务器信息用流发送一个xml即可
            response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * aliPay:(支付宝支付). <br/>
     *
     * @return
     * @throws AlipayApiException
     * @author Administrator
     * @since JDK 1.8
     */
    @PostMapping("/aliPay")
    @ResponseBody
    public Map<String, Object> aliPay(MerchantAliPayDTO merchantAliPayDTO) {
        Map<String, Object> result = new HashMap<>(16);
        merchantAliPayDTO = getAppAuthToken(merchantAliPayDTO);
        MerchantStore merchantStore = merchantStoreService.getMerchantInfo(merchantAliPayDTO.getMerchantCode(),
                merchantAliPayDTO.getStoreId());
        merchantAliPayDTO = alipayMerchantOrderCreate(merchantAliPayDTO, merchantStore);
        if (StringUtil.isEmpty(merchantAliPayDTO.getAliPayTransNo())) {
            result.put("code", "0");
            return result;
        } else {
            // 组装订单类
            MerchantOrder merchantOrder = merchantAliPayDTO.getMerchantOrder();
            merchantOrder.setMerchantName(merchantStore.getMerchantName());
            merchantOrder.setStoreName(merchantStore.getStoreName());
            merchantOrder.setStaffCode(merchantStore.getStoreId());
            merchantOrder.setStaffName(merchantStore.getStoreId());
            // end
            merchantOrderService.save(merchantOrder);
            result.put("code", "1");
            result.put("transNo", merchantOrder.getThirdTransNo());
        }
        return result;
    }

    /**
     * getappAuthToken:(根据userId查询数据库里的商户appAuthToken). <br/>
     *
     * @param merchantAliPayDTO
     * @author Administrator
     * @since JDK 1.8
     */
    private MerchantAliPayDTO getAppAuthToken(MerchantAliPayDTO merchantAliPayDTO) {
        UserApp userApp = new UserApp();
        userApp.setUserId(Long.valueOf(merchantAliPayDTO.getUserAppId()));
        userApp = userAppService.queryUserApp(userApp);
//        merchantAliPayDTO.setAppAuthToken(userApp.getAppAuthToken());
        return merchantAliPayDTO;
    }

    /**
     * alipayMerchantOrderCreate:(支付宝创建订单). <br/>
     *
     * @throws AlipayApiException
     * @author Administrator
     * @since JDK 1.8
     */
    private MerchantAliPayDTO alipayMerchantOrderCreate(MerchantAliPayDTO merchantAliPayDTO,
                                                        MerchantStore merchantStore) {
        String appId = ParametersUtil.ZY_ALI_APP_ID;
        String pri = ParametersUtil.ZY_PRI;
        String pub = ParametersUtil.ZY_PUB;
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", appId, pri, "json",
                "GBK", pub, "RSA2");
        AlipayTradeCreateRequest request = new AlipayTradeCreateRequest();
        System.out.println(ParametersUtil.domain + "/wap/merchant/aliCallBack");
        request.setNotifyUrl(ParametersUtil.domain + "/wap/merchant/aliCallBack");
        request.putOtherTextParam("app_auth_token", merchantAliPayDTO.getAppAuthToken());
        request.setBizContent("{" + "\"out_trade_no\":\"" + merchantAliPayDTO.getOrderNumber() + "\","
                + "\"buyer_id\":\"" + merchantAliPayDTO.getUserid() + "\"," + "\"total_amount\":"
                + merchantAliPayDTO.getComsumeMoney() + "," + "\"subject\":\"" + merchantStore.getStoreName() + "\","
                + "\"body\":\"" + merchantStore.getStoreName() + "\"" + "}");
        AlipayTradeCreateResponse response;
        try {
            response = alipayClient.execute(request);
            if (response.isSuccess()) {
                String aliPayTransNo = response.getTradeNo();
                merchantAliPayDTO.setAliPayTransNo(aliPayTransNo);
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return merchantAliPayDTO;
    }


    /**
     * getaliCallBack:(支付宝回调通知). <br/>
     *
     * @return
     * @throws Exception
     * @author Administrator
     * @since JDK 1.8
     */
    @RequestMapping("/aliCallBack")
    @ResponseBody
    public String getaliCallBack() throws Exception {
        RealFansDTO realFansDTO = new RealFansDTO();
        // 必须返回success才会停止通知，若不返回则继续通知 本地无法测试该回调 必须要在服务器上测试
        log.debug("===========================================================" + request
                + "============================================================================================================");
        String code = null;
        Map<String, Object> params = HttpUrlConnection.convertRequestParamsToMap(this.request);
        log.info("===params====" + params);
        String paramsJson = JSON.toJSONString(params);
        log.info("zhifubaohuidiao，{}", paramsJson);
        try {
            // boolean signVerified =
            // AlipaySignature.rsaCheckV1(params,systemConfigService.querySystemConfigValue("PUB"),"GBK","RSA2");
            // log.info("==signVerified===" + signVerified);
            // if (signVerified) {
            String tradeStatus = (String) params.get("trade_status");
            log.info("=====tradeStatus=====" + tradeStatus);
            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                String buyer_id = (String) params.get("buyer_id");// 支付宝唯一识别用户码
                String tradeNumber = (String) params.get("trade_no");
                String orderNumber = (String) params.get("out_trade_no");// 商家订单号
                MerchantOrder merchantOrder = new MerchantOrder();
                merchantOrder.setOrderNumber(orderNumber);
                ;// 支付宝订单号
                merchantOrder = merchantOrderService.queryMerchantOrder(merchantOrder);
                if ("1".equals(merchantOrder.getStatus())) {
                    code = "success";
                    return code;
                }
                String amountPay = (String) params.get("total_amount");// 拿到消费金额
                String consumTime = (String) params.get("gmt_payment");// 交易付款时间
                merchantOrder.setTransNo(tradeNumber);
                merchantOrder.setTransDt(new Date());
                merchantOrder.setStatus("1");
                merchantOrder.setMercUserId(buyer_id);
                merchantOrder.setThirdTransNo(tradeNumber);
                merchantOrderService.updateOrderAndCreateProfit(merchantOrder);
            }
            code = "success";
//			} else {
//				log.info("支付宝回调签名认证失败，signVerified=false, paramsJson:{}", paramsJson);
//				return "failure";
//			}
        } catch (Exception e) {
            code = "failure";
            e.printStackTrace();
        }
        return code;
    }

    /**
     * toUpDateMerchantOrder:(修改订单状态[支付宝发起的] 有bug 必须在用户支付完成之后点右上角的完成才会触发 这里照样保留该方法
     * 在上面的getaliCallBack()方法也会进行这个修改订单的处理). <br/>
     *
     * @param aliPayTransNo
     * @return
     * @author Administrator
     * @since JDK 1.8
     */
    @GetMapping("/toUpDateMerchantOrder")
    public void toUpDateMerchantOrder(String aliPayTransNo) {
        MerchantOrder merchantOrder = new MerchantOrder();
        merchantOrder.setThirdTransNo(aliPayTransNo);
        merchantOrder = merchantOrderService.queryMerchantOrder(merchantOrder);
        merchantOrder.setStatus("1");
        Date date = new Date();
        merchantOrder.setUpdateTime(date);
        merchantOrder.setCreateDt(date);
        merchantOrderService.updateById(merchantOrder);
    }

    @GetMapping("/paySuccess")
    public ModelAndView paySuccess() {
        return new ModelAndView("merchant/paySuccess");
    }

    /**
     * register:(分享注册). <br/>
     *
     * @return
     * @author Administrator
     * @since JDK 1.8
     */
    @GetMapping("/register")
    public ModelAndView register() {
        ModelAndView modelAndView = new ModelAndView("merchant/share");
        Map<String, String> result = new HashMap<>(16);
        String inviteNum = request.getParameter("inviteNum");// 推广码
        String phone = "";
        String userName = "";
        if (StringUtil.isNotEmpty(inviteNum)) {
            UserApp appInfo = userAppService.queryUserAppByInviteNum(inviteNum);
            if (appInfo != null) {
                phone = appInfo.getPhone();
                userName = appInfo.getUserName();
            }
        }
        String enPhone = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");// 中间隐藏4位数的号码
        if (StringUtil.isNotEmpty(userName)) {
            String reg = ".{1}";
            StringBuffer sb = new StringBuffer();
            Pattern p = Pattern.compile(reg);
            Matcher m = p.matcher(userName);
            int i = 0;
            while (m.find()) {
                i++;
                if (i == 1) {
                    continue;
                }
                m.appendReplacement(sb, "*");
            }
            m.appendTail(sb);
            result.put("userName", sb.toString());
        }
        result.put("enPhone", enPhone);
        result.put("inviteNum", inviteNum);
        modelAndView.addAllObjects(result);
        return modelAndView;
    }


    /**
     * goRegister:(去注册). <br/>
     *
     * @return
     * @author Administrator
     * @since JDK 1.8
     */
    @NoRepeatSubmit
    @PostMapping("/goRegister")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public Result<?> goRegister(String inviteNum, String phoneverify, String phone, String password) {
        if (StringUtil.isEmpty(inviteNum)) {
            return ResultGenerator.genFailResult("推荐人不能为空");
        }
        UserApp condition = new UserApp().setInviteNum(inviteNum);
        UserApp appInfo = userAppService.getOne(new QueryWrapper<>(condition));
        if (appInfo == null) {
            return ResultGenerator.genFailResult("推荐人不存在！");
        }

        UserApp parentInfo;
        if ("agent_staff".equals(appInfo.getUserType())) {
            QueryWrapper<UserApp> queryWrapper = new QueryWrapper<UserApp>().eq("userId", appInfo.getParentId());
            parentInfo = userAppService.getOne(queryWrapper);
        } else {
            parentInfo = appInfo;
        }

        if (!Objects.equals(parentInfo.getStatus(), 3) || !Objects.equals(parentInfo.getBankStatus(), 3)) {
            throw new MsgException("邀请码无效，当前推广服务商未完成实名");
        }

        UserInfo ui = userInfoService.getById(parentInfo.getUserId());
        if (Objects.equals(ui.getStatus(), UserInfo.STATUS_NO_SPREAD)) {
            throw new MsgException("当前推广服务商存在违规行为, 已被关闭推广权限, 请联系收银呗客服申诉");
        }

        if (!"1".equals(parentInfo.getSpreadFlag())) {
            throw new MsgException("该服务商已注册多个账户，该推广码无效");
        }

        UserInfo queryUserInfo = new UserInfo().setLoginName(phone);
        List<UserInfo> existUserInfoList = userInfoMapper.queryUserInfoList(queryUserInfo);
        if (existUserInfoList != null && !existUserInfoList.isEmpty()) {
            return ResultGenerator.genFailResult("当前手机号已被注册！");
        }
        PhoneValidateCode phoneValidateCode = new PhoneValidateCode();
        phoneValidateCode.setCode(phoneverify);
        List<PhoneValidateCode> queryPhoneValidateCodeList = phoneValidateCodeService
                .queryPhoneValidateCodeList(phoneValidateCode);
        if (queryPhoneValidateCodeList != null && queryPhoneValidateCodeList.size() > 0) {
            phoneValidateCode = queryPhoneValidateCodeList.get(0);
            if (phoneverify.equals(phoneValidateCode.getCode())) {
                password = MD5Util.MD5Encode(password);
                UserInfo userInfo = new UserInfo();
                userInfo.setLoginName(phone);
                userInfo.setTrueName(phone);
                userInfo.setPhone(phone);
                userInfo.setPassword(password);
                userInfo.setCreateTime(new Date());
                userInfoService.saveUserInfo(userInfo);
                UserApp userApp = new UserApp();
                userApp.setUserId(userInfo.getId());

                //判断推广员是否是业务员
                if ("agent_staff".equals(appInfo.getUserType())) {
                    userApp.setAgentStaffId(appInfo.getUserId());
                }

                userApp.setParentId(parentInfo.getUserId());
                UserApp.setSort(parentInfo, userApp);
                UserApp.setRoleInfo(parentInfo, userApp, null);

                userApp.setUserName(phone);
                userApp.setUserType("promoter");
                userApp.setLevel(1);
                userApp.setStatus(0);

                userApp.setCreateDt(new Date());
                userApp.setInviteNum(StringUtil.genRandomNum(5));
                userAppService.save(userApp);
                ipRecordService.saveRegIp(userInfo.getId() + "", userInfo.getId() + "");
                PhoneValidateCode phoneValidate = new PhoneValidateCode();
                if (StringUtil.isNotEmpty(phone)) {
                    phoneValidate.setPhone(phone);
                    phoneValidateCodeService.deletePhoneValidateCode(phoneValidate);
                }
                // TODO 同步用户到积分商城系统这边
                jfShopHandler.syncJfShopUser(userApp, userInfo);
                return ResultGenerator.genSuccessResult("注册成功!", null);
            }
        }
        return ResultGenerator.genFailResult("验证码输入有误!");
    }

    /**
     * registerSuccess:(分享注册成功). <br/>
     *
     * @return
     * @author Administrator
     * @since JDK 1.8
     */
    @GetMapping("/registerSuccess")
    public ModelAndView registerSuccess() {
        ModelAndView modelAndView = new ModelAndView("merchant/registerSuccess");
        return modelAndView;
    }

    /**
     * 统一支付下单接口<br/>
     *
     * @return
     * @throws Exception
     * @author Administrator
     * @since JDK 1.8
     */
    @PostMapping("/tradePay")
    @ResponseBody
    public Result<Map<String, Object>> tradePay(@RequestParam Map<String, Object> params, HttpServletRequest request) {

        try {
            params.put("ip", IpUtils.getIpAddr(request));
            return merchantService.tradePay(params);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    /**
     * 取消支付播报
     *
     * @param orderNumber
     * @return
     */
    @GetMapping("/cancelPay/{orderNumber}")
    @ResponseBody
    public Result cancelPay(@PathVariable("orderNumber") String orderNumber) {
        try {
            if (StringUtil.isEmpty(orderNumber)) {
                return ResultGenerator.genFailResult("缺失参数", null);
            }
            QueryWrapper<MerchantOrder> orderWrapper = new QueryWrapper<MerchantOrder>().eq("orderNumber", orderNumber);
            MerchantOrder order = merchantOrderService.getOne(orderWrapper);
            if (order == null) {
                return ResultGenerator.genFailResult("订单号异常", null);
            }
            QueryWrapper<MerchantBaseInfo> queryWrapper = new QueryWrapper<MerchantBaseInfo>().eq("merchantCode", order.getMerchantCode());
            List<MerchantBaseInfo> list = merchantBaseInfoService.list(queryWrapper);
            if (!list.isEmpty()) {
                JSONObject params = new JSONObject();
                params.put("mercId", list.get(0).getId());
                params.put("order", order);
                params.put("userId", list.get(0).getUserId());
                notifyMessageService.sendCancelPayMessage(params);
                return ResultGenerator.genSuccessResult("请求成功", null);
            }
            return ResultGenerator.genFailResult("商户数据不存在", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    /**
     * jumpUrl:(支付完成后的跳转地址). <br/>
     *
     * @param orderNumber
     * @param
     * @return
     * @author Administrator
     * @since JDK 1.8
     */
    @RequestMapping("/jumpUrl")
    public ModelAndView jumpUrl(String orderNumber) {
        log.info("====订单号====" + orderNumber);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("merchant/errorInfo2");
        if (StringUtil.isEmpty(orderNumber)) {
            modelAndView.addObject("error", "参数不能为空");
            return modelAndView;
        }
        QueryWrapper<MerchantOrder> queryWrapper = new QueryWrapper<MerchantOrder>().eq("orderNumber", orderNumber);
        List<MerchantOrder> listOrder = merchantOrderService.list(queryWrapper);
        if (listOrder.isEmpty()) {
            modelAndView.addObject("error", "参数有误");
            return modelAndView;
        }
        MerchantOrder order = listOrder.get(0);
        String status = order.getStatus();
        if ("1".equals(status)) {
            modelAndView.setViewName("merchant/paySuccess");
        } else if ("5".equals(status)) {
            try {
                merchantOrderService.suppleOrder(order.getId().intValue());
                modelAndView.setViewName("merchant/paySuccess");
            } catch (RuntimeException e) {
                e.printStackTrace();
                modelAndView.setViewName("merchant/payFail");
            }
        } else {
            modelAndView.setViewName("merchant/payFail");
        }
        return modelAndView;
    }

    /**
     * leshuaCallBack:(乐刷支付回调地址). <br/>
     *
     * @return
     * @author Administrator
     * @since JDK 1.8
     */
    @RequestMapping("/leshuaCallBack")
    @ResponseBody
    public String leshuaCallBack(HttpServletRequest request) {
        log.info("=========================jinruleshua huidiao =====================");
        String respString = "";
        InputStream is = null;
        Map<String, Object> notifyMap = null;
        try {
            RealFansDTO realFansDTO = new RealFansDTO();
            is = request.getInputStream();
            String xml = XmlUtil.toUTF8(is);
            log.info("=========fanhui     canshu=============" + xml);
            notifyMap = XmlUtil.toMapLeshua(xml);
            log.info("==================fanhuicanshu    Map   jihe=====" + notifyMap + "");
            if (notifyMap.containsKey("sign")) {
                if (!LeshuaSignature.checkIsSignValidFromResponseString(xml, LeshuaSignature.resExcludedSignParams(), "75C27ABB12F78A747DCB4368EEBCB542")) {
                    log.info("============================qianming butongguo======================");
                    respString = "error";
                } else {
                    String status = (String) notifyMap.get("status");
                    if ("2".equals(status)) {
                        // 此处可以再添加相关处理业务，校验通知参数中的商户订单号third_order_id和金额amount是否和商户业务系统的单号和金额是否一致，一致后方可更新数据可表中的数据
                        log.info("============huidiao SUCCESS============");
                        respString = "000000";
                        // 乐刷商户id
                        // String merchant_id = (String) notifyMap.get("merchant_id");
                        String ordersSn = (String) notifyMap.get("third_order_id");// 商户订单号
                        String amountpaid = (String) notifyMap.get("amount");// 订单金额
                        String pay_way = (String) notifyMap.get("pay_way");// 支付类型
                        String openid = (String) notifyMap.get("openid");// 微信openid
                        String sub_openid = (String) notifyMap.get("sub_openid");//支付宝
                        String transaction_id = (String) notifyMap.get("out_transaction_id");
                        String leshua_order_id = (String) notifyMap.get("leshua_order_id");
                        String pay_time = (String) notifyMap.get("pay_time");
                        BigDecimal amountPay = (new BigDecimal(amountpaid).divide(new BigDecimal("100"))).setScale(2);// 将分转换成元-实际支付金额:元
                        String amount = amountPay + "";// 消费金额
                        MerchantOrder merchantOrder = new MerchantOrder();
                        merchantOrder.setOrderNumber(ordersSn);
                        List<MerchantOrder> queryMerchantOrderList = merchantOrderService.list(new QueryWrapper<>(merchantOrder));
                        if (StringUtil.isNotEmpty(ordersSn) && queryMerchantOrderList != null && queryMerchantOrderList.size() > 0) {
                            merchantOrder = queryMerchantOrderList.get(0);
                            if ("1".equals(merchantOrder.getStatus())) {
                                respString = "000000";
                                return null;
                            }
                            Map<String, Object> map = new HashMap<>(16);
                            realFansDTO.setConSumMoney(amount);
                            realFansDTO.setConsumTime(pay_time);
                            realFansDTO.setLogo(merchantOrder.getUserImg());
                            realFansDTO.setNickName(merchantOrder.getNickName());
                            realFansDTO.setMerchantCode(merchantOrder.getMerchantCode());
                            realFansDTO.setOrderNumber(ordersSn);
                            realFansDTO.setTradeNumber(leshua_order_id);
                            String userId = "";
                            if ("ZFBZF".equals(pay_way)) {
                                userId = sub_openid;
                            } else if ("WXZF".equals(pay_way)) {
                                userId = openid;
                            }
                            map.put("realFansDTO", realFansDTO);
                            log.info("=============realFansDTO================" + JSONObject.toJSONString(realFansDTO));
                            merchantOrder.setTransNo(leshua_order_id);
                            merchantOrder.setTransDt(new Date());
                            merchantOrder.setStatus("1");
                            merchantOrder.setMercUserId(userId);
//                            merchantOrderService.updateOrderAndCreateProfit(merchantOrder,leshua_order_id);

                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return respString;
    }


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

    @PostMapping(value = "/posCallBack")
    public String posCallBack(HttpServletRequest request) {
//        InputStream is = null;
//        Map<String, Object> notifyMap = null;
//        String respString = "";
//        try {
//            is = request.getInputStream();
//            String xml = XmlUtil.toUTF8(is);
//            log.info("=========pos=========== fanhui     canshu=============" + xml);
//            notifyMap = XmlUtil.toMapLeshua(xml);
//            if (notifyMap.containsKey("sign")) {
//                if (!LeshuaSignature.checkIsSignValidFromResponseString(xml, resExcludedSignParams(), "75C27ABB12F78A747DCB4368EEBCB542")) {
//                    log.info("============================qianming butongguo======================");
//                    respString = "error";
//                } else {
//                    respString = "000000";
//                    String merchant_id = (String) notifyMap.get("merchant_id");//商户号
//                    log.debug("=========merchant_id===============" + merchant_id);
//                    String leshua_order_id = (String) notifyMap.get("leshua_order_id");//乐刷订单号
//                    log.debug("=========leshua_order_id===============" + leshua_order_id);
//                    String third_order_id = (String) notifyMap.get("third_order_id");//商户订单号
//                    String flow_id = (String) notifyMap.get("flow_id");//凭证号
//                    log.debug("=========third_order_id===============" + third_order_id);
//                    String refund_amount = (String) notifyMap.get("refund_amount");//退款金额
//                    log.debug("=========refund_amount===============" + refund_amount);
//                    String status = (String) notifyMap.get("status");//订单状态
//                    log.debug("=========status===============" + status);
//                    String pay_time = (String) notifyMap.get("pay_time");//交易时间
//                    log.debug("=========pay_time===============" + pay_time);
//                    String refund_time = (String) notifyMap.get("refund_time");//退款时间
//                    log.debug("=========refund_time===============" + refund_time);
//                    String failure_reason = (String) notifyMap.get("failure_reason");//失败原因
//                    log.debug("=========failure_reason===============" + failure_reason);
//                    String leshua_refund_id = (String) notifyMap.get("leshua_refund_id");//失败原因
//                    String pay_way = (String) notifyMap.get("pay_way");//支付类型
//
//                    UserApp userApp = new UserApp();
//                    userApp.setLeshuaMchId(merchant_id);
//                    List<UserApp> queryUserAppList = userAppService.queryUserAppList(userApp);
//                    log.error("========queryUserAppList============" + JSONObject.toJSONString(queryUserAppList));
//                    if (queryUserAppList != null && queryUserAppList.size() > 0) {
//                        userApp = queryUserAppList.get(0);
//                        String merchantCode = userApp.getMerchantCode();//商家Code;
//                        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
//                        merchantBaseInfo.setMerchantCode(merchantCode);
//                        List<MerchantBaseInfo> queryMerchantBaseInfoList = merchantBaseInfoService.queryMerchantBaseInfoList(merchantBaseInfo);
//                        if (queryMerchantBaseInfoList != null && queryMerchantBaseInfoList.size() > 0) {
//                            merchantBaseInfo = queryMerchantBaseInfoList.get(0);
//                            String merchantName = merchantBaseInfo.getMerchantName();
//                            String alias = merchantBaseInfo.getAlias();
//                            if (StringUtil.isEmpty(merchantName)) {
//                                merchantName = alias;
//                            }
//                            MerchantOrder merchantOrder = new MerchantOrder();
//                            merchantOrder.setLeshuaTransNo(leshua_order_id);
//                            List<MerchantOrder> queryMerchantOrderList = merchantOrderService.list(new QueryWrapper<>(merchantOrder));
//                            if (queryMerchantOrderList != null && queryMerchantOrderList.size() > 0) {
//                                merchantOrder = queryMerchantOrderList.get(0);
//                                log.info("===========merchantOrder==============" + JSONObject.toJSONString(merchantOrder));
//                                Double consumeFee = merchantOrder.getConsumeFee();
//                                if ("5".equals(merchantOrder.getStatus())) {//待付款
//                                    merchantOrder.setStatus("1");
//                                    String userId = merchantBaseInfo.getUserId();
//                                    if (StringUtil.isNotEmpty(userId)) {
//                                        String amountpaid = (String) notifyMap.get("amount");//订单金额
//                                        BigDecimal amountPay = (new BigDecimal(amountpaid).divide(new BigDecimal("100"))).setScale(2);// 将分转换成元-实际支付金额:元
//                                        Double amount = Double.valueOf(amountPay + "");
//                                        log.debug("=================ji guang tuisong===========================================");
//                                        List<String> aliass = userAppService.storeMemberList(merchantCode);
//                                        log.info("=========推送人userId======" + JSON.toJSONString(aliass) + "=========金额=======" + amount);
//                                        aliass.add(userId);
//
//                                        GeneralPushUtil.sendAllPlatByAlias(aliass, "收银呗到账通知", "收银呗到账" + amount + "元", "3");
//                                        log.debug("===============================收银呗到账" + amount + "元");
//                                    }
//                                    SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                                    merchantOrder.setTransDt(sFormat.parse(pay_time));
//                                    merchantOrder.setLeshuaMerchantRefundId(leshua_refund_id);
//                                    merchantOrder.setLeshuaTransNo(leshua_order_id);
//                                    log.info("===========merchantOrder==============" + JSONObject.toJSONString(merchantOrder));
//                                    merchantOrderService.updateById(merchantOrder);
//                                } else if ("1".equals(merchantOrder.getStatus())) {//付款成功
//                                    if (StringUtil.isNotEmpty(refund_amount)) {
//                                        Double refund = Double.valueOf(refund_amount) * 100;
//                                        if ("11".equals(status) || "32".equals(status)) {
//                                            if (consumeFee > refund) {
//                                                merchantOrder.setStatus("6");
//                                            } else {
//                                                merchantOrder.setStatus("2");
//                                            }
//                                        }
//                                    }
//                                    SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                                    merchantOrder.setTransDt(sFormat.parse(pay_time));
//                                    merchantOrder.setLeshuaMerchantRefundId(leshua_refund_id);
//                                    merchantOrder.setLeshuaTransNo(leshua_order_id);
//                                    log.info("===========merchantOrder==============" + JSONObject.toJSONString(merchantOrder));
//                                    merchantOrderService.updateById(merchantOrder);
//                                }
//                            } else {
//                                SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                                merchantOrder.setTransDt(sFormat.parse(pay_time));
//                                String amountpaid = (String) notifyMap.get("amount");//订单金额
//                                log.debug("=========amountpaid===============" + amountpaid);
//                                BigDecimal amountPay = (new BigDecimal(amountpaid).divide(new BigDecimal("100"))).setScale(2);// 将分转换成元-实际支付金额:元
//                                Double amount = Double.valueOf(amountPay + "");// 消费金额
//                                log.debug("=========amount===============" + amount);
//                                merchantOrder.setConsumeFee(amount);
//                                merchantOrder.setMerchantCode(merchantCode);
//                                merchantOrder.setMerchantName(merchantName);
//
//                                Date date = new Date();
//                                merchantOrder.setCreateDt(date);
//                                merchantOrder.setUpdateTime(date);
//                                merchantOrder.setStoreId(merchantCode);
//                                merchantOrder.setStoreName(merchantName);
//                                merchantOrder.setStaffCode(merchantCode);
//                                merchantOrder.setStaffName(merchantName);
//
//                                Double rate = 0.0038d;
//                                List<MerchantRate> myRateList = merchantRateMapper.selectList(new QueryWrapper<MerchantRate>().eq("userId", userApp.getUserId()));
//                                if(!myRateList.isEmpty()){
//                                    rate = new BigDecimal(myRateList.get(0).getCurrentRate()).divide(new BigDecimal(10000)).doubleValue();
//                                }
//                                //rate = merchantOrderService.getCurrentFee(userApp, "current", rate, userApp.getUserId());
//
//                                merchantOrder.setEnterFee(StringUtil.bigDecimal(amount - amount * rate));
//                                merchantOrder.setOrderType("1");
//                                merchantOrder.setAisleSwitch("1");
//                                if ("2".equals(status)) {
//                                    if ("WXZF".equals(pay_way)) {
//                                        merchantOrder.setPayTypeCode("leshuaPay1");
//                                        merchantOrder.setPayTypeName("乐刷微信支付");
//                                    } else if ("ZFBZF".equals(pay_way)) {
//                                        merchantOrder.setPayTypeCode("leshuaPay0");
//                                        merchantOrder.setPayTypeName("乐刷支付宝支付");
//                                    }
//                                    merchantOrder.setOrderNumber(third_order_id);
//                                } else if ("30".equals(status)) {
//                                    merchantOrder.setOrderNumber(flow_id);
//                                    merchantOrder.setPayTypeCode("leshuaPay2");
//                                    merchantOrder.setPayTypeName("乐刷刷卡支付");
//                                    merchantOrder.setIsPos("isPos");
//                                }
//                                if ("2".equals(status) || "30".equals(status)) {
//                                    merchantOrder.setStatus("1");
//                                } else if ("8".equals(status)) {
//                                    merchantOrder.setStatus("0");
//                                }
//                                merchantOrder.setOrderType("4");
////                                merchantOrder.setRate(new BigDecimal(String.valueOf(rate)).multiply(new BigDecimal(10000)).intValue());
//                                merchantOrderService.save(merchantOrder);
//                                String userId = merchantBaseInfo.getUserId();
//                                if (StringUtil.isNotEmpty(userId)) {
//                                    log.debug("=================ji guang tuisong===========================================");
//                                    List<String> aliass = userAppService.storeMemberList(merchantCode);
//
//                                    GeneralPushUtil.sendAllPlatByAlias(aliass, "收银呗到账通知", "收银呗到账" + amount + "元", "3");
//                                    log.debug("===============================收银呗到账" + amount + "元");
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        return null;
    }


    @PostMapping(value = "/appScanPayLeshuaCallBack")
    public String appLeshuaCallBack(HttpServletRequest request) {
        InputStream is = null;
        Map<String, Object> notifyMap = null;
        String respString = "";
        try {
            is = request.getInputStream();
            String xml = XmlUtil.toUTF8(is);
            log.info("=========appScanPayLeshuaCallBack=========== fanhui     canshu=============" + xml);
            notifyMap = XmlUtil.toMapLeshua(xml);
            if (notifyMap.containsKey("sign")) {
                if (!LeshuaSignature.checkIsSignValidFromResponseString(xml, resExcludedSignParams(), "75C27ABB12F78A747DCB4368EEBCB542")) {
                    log.info("============================qianming butongguo======================");
                    respString = "error";
                } else {
                    respString = "000000";
                    String merchant_id = (String) notifyMap.get("merchant_id");//商户号
                    log.debug("=========merchant_id===============" + merchant_id);
                    String leshua_order_id = (String) notifyMap.get("leshua_order_id");//乐刷订单号
                    log.debug("=========leshua_order_id===============" + leshua_order_id);
                    String third_order_id = (String) notifyMap.get("third_order_id");//商户订单号
                    log.debug("=========third_order_id===============" + third_order_id);
                    String refund_amount = (String) notifyMap.get("refund_amount");//退款金额
                    log.debug("=========refund_amount===============" + refund_amount);
                    String status = (String) notifyMap.get("status");//订单状态
                    log.debug("=========status===============" + status);
                    String pay_time = (String) notifyMap.get("pay_time");//交易时间
                    log.debug("=========pay_time===============" + pay_time);
                    String refund_time = (String) notifyMap.get("refund_time");//退款时间
                    log.debug("=========refund_time===============" + refund_time);
                    String failure_reason = (String) notifyMap.get("failure_reason");//失败原因
                    log.debug("=========failure_reason===============" + failure_reason);
                    String leshua_refund_id = (String) notifyMap.get("leshua_refund_id");//失败原因
                    String pay_way = (String) notifyMap.get("pay_way");//支付类型
                    MerchantOrder merchantOrder = new MerchantOrder();
                    merchantOrder.setOrderNumber(third_order_id);
                    List<MerchantOrder> queryMerchantOrderList = merchantOrderService.list(new QueryWrapper<>(merchantOrder));
                    if (queryMerchantOrderList != null && queryMerchantOrderList.size() > 0) {
                        merchantOrder = queryMerchantOrderList.get(0);
                        if ("5".equals(merchantOrder.getStatus())) {
                            merchantOrder.setThirdTransNo(leshua_order_id);
                            SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            merchantOrder.setTransDt(sFormat.parse(pay_time));
                            merchantOrder.setStatus("1");
                            merchantOrderService.updateById(merchantOrder);
                        }
                        respString = "000000";
                        System.out.println("======支付成功========" + respString);
                        return respString;
                    }
                }
            }
        } catch (Exception e) {
//			respString = "error";

            e.printStackTrace();
            respString = "error";
            return respString;
        }

        respString = "000000";
        return respString;
    }

    @PostMapping(value = "/rechargeCallBack")
    public String rechargeCallBack(HttpServletRequest request) {
        InputStream is = null;
        Map<String, Object> notifyMap = null;
        String respString = "";
        try {
            is = request.getInputStream();
            String xml = XmlUtil.toUTF8(is);
            log.info("=========rechargeCallBack=========== fanhui     canshu=============" + xml);
            notifyMap = XmlUtil.toMapLeshua(xml);
            if (notifyMap.containsKey("sign")) {
                if (!LeshuaSignature.checkIsSignValidFromResponseString(xml, resExcludedSignParams(), "75C27ABB12F78A747DCB4368EEBCB542")) {
                    log.info("============================qianming butongguo======================");
                    respString = "error";
                } else {
                    respString = "000000";
                    String merchant_id = (String) notifyMap.get("merchant_id");//商户号
                    log.debug("=========merchant_id===============" + merchant_id);
                    String leshua_order_id = (String) notifyMap.get("leshua_order_id");//乐刷订单号
                    log.debug("=========leshua_order_id===============" + leshua_order_id);
                    String third_order_id = (String) notifyMap.get("third_order_id");//商户订单号
                    log.debug("=========third_order_id===============" + third_order_id);
                    String refund_amount = (String) notifyMap.get("refund_amount");//退款金额
                    log.debug("=========refund_amount===============" + refund_amount);
                    String status = (String) notifyMap.get("status");//订单状态
                    log.debug("=========status===============" + status);
                    String pay_time = (String) notifyMap.get("pay_time");//交易时间
                    log.debug("=========pay_time===============" + pay_time);
                    String refund_time = (String) notifyMap.get("refund_time");//退款时间
                    log.debug("=========refund_time===============" + refund_time);
                    String failure_reason = (String) notifyMap.get("failure_reason");//失败原因
                    log.debug("=========failure_reason===============" + failure_reason);
                    String leshua_refund_id = (String) notifyMap.get("leshua_refund_id");//失败原因
                    String pay_way = (String) notifyMap.get("pay_way");//支付类型
                    MerchantOrder merchantOrder = new MerchantOrder();
                    merchantOrder.setOrderNumber(third_order_id);
                    List<MerchantOrder> queryMerchantOrderList = merchantOrderService.list(new QueryWrapper<>(merchantOrder));
                    if (queryMerchantOrderList != null && queryMerchantOrderList.size() > 0) {
                        merchantOrder = queryMerchantOrderList.get(0);
                        if ("1".equals(merchantOrder.getStatus())) {
                            respString = "000000";
                            return respString;
                        }
                        merchantOrder.setThirdTransNo(leshua_order_id);
                        SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        merchantOrder.setTransDt(sFormat.parse(pay_time));
                        merchantOrder.setStatus("1");
                        merchantOrderService.updateById(merchantOrder);
                    }
                }
            }
        } catch (Exception e) {
            respString = "error";
            e.printStackTrace();
            respString = "error";
            return respString;
        }

        respString = "000000";
        return respString;
    }

    /**
     * goMemberPay:(去充值页面). <br/>
     *
     * @param
     * @param merchantCode
     * @param storeId
     * @return
     * @author Administrator
     * @since JDK 1.8
     */
    @GetMapping(value = "/goMemberPay")
    public ModelAndView goMemberPay(String openid, String merchantCode, String storeId) {
        ModelAndView modelAndView = new ModelAndView("/merchant/goMemberPay");
        Map<String, Object> result = new HashMap<String, Object>(16);
        MerchantMenber merchantMenber = new MerchantMenber();
        merchantMenber.setStoreId(storeId);
        merchantMenber.setMerchantCode(merchantCode);
        merchantMenber.setOpenid(openid);
        List<MerchantMenber> queryMerchantMenberList = merchantMenberService.queryMerchantMenberList(merchantMenber);
        if (queryMerchantMenberList != null && queryMerchantMenberList.size() > 0) {
            merchantMenber = queryMerchantMenberList.get(0);
            result.put("merchantMenber", merchantMenber);
        }
        getMerchantStoreActity(result, merchantMenber);
        modelAndView.addAllObjects(result);
        return modelAndView;
    }


    /**
     * getMerchantStoreActity:(获取门店活动). <br/>
     *
     * @param result
     * @param merchantMenber
     * @return
     * @author Administrator
     * @since JDK 1.8
     */
    public Map<String, Object> getMerchantStoreActity(Map<String, Object> result, MerchantMenber merchantMenber) {
        if (StringUtil.isNotEmpty(merchantMenber.getStoreId())) {
            ActivityActivate activityActivate = new ActivityActivate();// storeId 并获得门店的活动
            activityActivate.setStoreId(merchantMenber.getStoreId());
            List<ActivityActivate> activityActivateList = activityActivateService.queryActivityActivateList(activityActivate);// 激活送活动信息
            ActivityConsumReturn activityConsumReturn = new ActivityConsumReturn();
            activityConsumReturn.setStoreId(merchantMenber.getStoreId());
            List<ActivityConsumReturn> activityConsumReturnList = activityConsumReturnService
                    .queryActivityConsumReturnList(activityConsumReturn);// 消费返活动信息
            ActivityRecharge activityRecharge = new ActivityRecharge();
            activityRecharge.setStoreId(merchantMenber.getStoreId());
            List<ActivityRecharge> activityRechargeList = activityRechargeService.queryActivityRechargeList(activityRecharge);// 充值活动信息
            result.put("merchantMenber", merchantMenber);
            result.put("activityActivateList", activityActivateList);
            result.put("activityConsumReturnList", activityConsumReturnList);
            result.put("activityRechargeList", activityRechargeList);
        }
        return result;
    }


    /**
     * memberPay:(会员充值). <br/>
     *
     * @param merchantCode
     * @param storeId
     * @param consumeMoney
     * @return
     * @author Administrator
     * @since JDK 1.8
     */
    @PostMapping(value = "/memberPay")
    @ResponseBody
    public Map<String, Object> memberPay(String merchantCode, String storeId, String openId, String consumeMoney) {
//        MerchantMenber merchantMenber = new MerchantMenber();
//        merchantMenber.setMerchantCode(merchantCode);
//        merchantMenber.setStoreId(storeId);
//        merchantMenber.setOpenid(openId);
//        merchantMenber = merchantMenberService.queryMerchantMenber(merchantMenber);// 当前会员信息
//        String orderNumber = "CZ700" + StringUtil.getBillno();
//        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
//        merchantBaseInfo.setMerchantCode(merchantCode);
//        merchantBaseInfo = merchantBaseInfoService.queryMerchantBaseInfo(merchantBaseInfo);
//        String userId = merchantBaseInfo.getUserId();
//        MemberOrder memberOrder = new MemberOrder();
//        memberOrder.setOrderFee(consumeMoney);
//        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);
//        log.info("=======wechatPay:fangfa" + JSONObject.toJSONString(memberOrder) + "");
//        memberOrderService.saveMemberOrder(memberOrder);
//        Map<String, String> reqMap = new HashMap<>(16);
//        reqMap.put("service", "get_tdcode");
//        reqMap.put("pay_way", "WXZF");
//        reqMap.put("amount", Double.parseDouble(consumeMoney) * 100 + "");
//        UserApp userApp = new UserApp();
//        userApp.setUserId(Long.valueOf(userId));
//        userApp = userAppService.queryUserApp(userApp);
//        reqMap.put("merchant_id", userApp.getLeshuaMchId());
//        reqMap.put("third_order_id", orderNumber);
//        reqMap.put("jspay_flag", "2");
//        Map<String, Object> mapLeshua = new HashMap<String, Object>(16);
//        try {
//            reqMap.put("notify_url", URLEncoder.encode(ParametersUtil.domain + "/wap/merchant/memberPayBack", "utf-8"));
//            reqMap.put("jump_url", URLEncoder.encode(ParametersUtil.domain + "/wap/merchant/jpUrl?leshuaMchId=" + userApp.getLeshuaMchId() + "&orderNumber=" + orderNumber, "utf-8"));
//            reqMap.put("client_ip", IpUtils.getIpAddr(request));
//            MerchantStore merchantInfo = merchantStoreService.getMerchantInfo(merchantCode, storeId);
//            if (StringUtil.isNotEmpty(merchantInfo.getStoreName())) {
//                reqMap.put("body", merchantInfo.getStoreName());
//            } else if (StringUtil.isNotEmpty(merchantInfo.getMerchantName())) {
//                reqMap.put("body", merchantInfo.getMerchantName());
//            } else {
//                reqMap.put("body", "leshuaPay");
//            }
//            reqMap.put("nonce_str", StringUtil.genRandomNum(32));
//            String apKey = "60E3F31EDEC8061C33721737B36FA86D";
//            System.out.println("reqMap===========================" + JSONObject.toJSONString(reqMap));
//            String requestPay = leshuaService.requestPay(reqMap, apKey, true);
//            System.out.println("requestPay===========================" + requestPay);
//            mapLeshua = XmlUtil.toMapLeshua(requestPay);
//            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.getStoreId());
//            merchantOrder.setPayTypeCode("leshuaPay1");
//            merchantOrder.setPayTypeName("乐刷微信支付");
//            merchantOrder.setConsumeFee(Double.valueOf(consumeMoney));
//
//            double rate = merchantRateNewService.getRate(userId,merchantOrder.getPayTypeCode(),merchantOrder.getConsumeFee());
//            merchantOrder.setRate(new BigDecimal(String.valueOf(rate)));
//            //rate = merchantOrderService.getCurrentFee(userApp, "current", rate, userApp.getUserId());
////            merchantOrder.setEnterFee(StringUtil.bigDecimal(Double.parseDouble(consumeMoney) - Double.parseDouble(consumeMoney) * rate));
//            Date date = new Date();
//            merchantOrder.setCreateDt(date);
//            merchantOrder.setUpdateTime(date);
//            merchantOrder.setStatus("5");
//            merchantOrder.setOrderType("3");
////				merchantOrder.setOrderType("3");
////            merchantOrder.setRate(new BigDecimal(String.valueOf(rate)).multiply(new BigDecimal(10000)).intValue());
//            merchantOrderService.save(merchantOrder);
//            mapLeshua.put("code", "1");
//        } catch (Exception e) {
//            e.printStackTrace();
//            mapLeshua.put("code", "0");
//            mapLeshua.put("msg", "充值失败");
//        }
//        return mapLeshua;
        return null;
    }


    @GetMapping("/jpUrl")
    public ModelAndView jpUrl(String orderNumber, String leshuaMchId) {
        log.info("====订单号====" + orderNumber);
        if (orderNumber.contains("?")) {
            String str[] = orderNumber.split("[?]");
            orderNumber = str[0];
        }
        log.info("=========当前商户乐刷商户id==========" + leshuaMchId);
        ModelAndView modelAndView = new ModelAndView();
        Map<String, String> reqMap = new HashMap<String, String>(16);
        Map<String, Object> mapLeshua = new HashMap<String, Object>(16);
        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));
        return modelAndView;
    }

    @PostMapping("/memberPayBack")
    @ResponseBody
    public String memberPayBack(HttpServletRequest request) {
        log.info("=========================jinruleshua huidiao =====================");
        String respString = "";
        InputStream is = null;
        Map<String, Object> notifyMap = null;
        try {
            is = request.getInputStream();
            String xml = XmlUtil.toUTF8(is);
            log.info("=========fanhui     canshu=============" + xml);
            notifyMap = XmlUtil.toMapLeshua(xml);
            log.info("==================fanhuicanshu    Map   jihe=====" + notifyMap + "");
            if (notifyMap.containsKey("sign")) {
                if (!LeshuaSignature.checkIsSignValidFromResponseString(xml, resExcludedSignParams(), "75C27ABB12F78A747DCB4368EEBCB542")) {
                    log.info("============================qianming butongguo======================");
                    respString = "error";
                } else {
                    String status = (String) notifyMap.get("status");
                    if (status != null && "2".equals(status)) {
                        respString = "000000";
                        updateLeshuaOrder(notifyMap);
                        updateLeshuaMerchantOrder(notifyMap);
                        //TODO 添加推广分润
                        String ordersSn = (String) notifyMap.get("third_order_id");// 商户订单号
                        MerchantOrder merchantOrder = new MerchantOrder();
                        merchantOrder.setOrderNumber(ordersSn);
                        MerchantOrder order = merchantOrderService.queryMerchantOrder(merchantOrder);
                        if (order != null) {
                            merchantProfitService.createOrderProfitV2(order, "1");
                        } else {
                            log.error("===================添加推广分润失败，当前订单号：{}不存在<==============", ordersSn);
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return respString;
    }

    private void updateLeshuaOrder(Map<String, Object> notifyMap) {
        String ordersSn = (String) notifyMap.get("third_order_id");// 商户订单号
        String amountpaid = (String) notifyMap.get("amount");// 订单金额
        String pay_way = (String) notifyMap.get("pay_way");// 支付类型
        String openid = (String) notifyMap.get("openid");// 微信openid
        String sub_openid = (String) notifyMap.get("sub_openid");//支付宝
        String transaction_id = (String) notifyMap.get("out_transaction_id");
        String leshua_order_id = (String) notifyMap.get("leshua_order_id");
        String pay_time = (String) notifyMap.get("pay_time");
        BigDecimal amountPay = (new BigDecimal(amountpaid).divide(new BigDecimal("100"))).setScale(2);// 将分转换成元-实际支付金额:元
        String amount = amountPay + "";// 消费金额
        log.error("进入修改订单方法==========" + transaction_id);
        // 订单表
        MemberOrder memberOrder = new MemberOrder();
        memberOrder.setOrderNumber(ordersSn);
        memberOrder = memberOrderService.queryMemberOrder(memberOrder);
        if ("1".equals(memberOrder.getOrderStatus())) {
            return;
        }
        memberOrder.setOrderStatus("1");
        memberOrder.setLeshuaTransNo(leshua_order_id);
        memberOrderService.updateMemberOrder(memberOrder);
        MerchantMenber merchantMenber = new MerchantMenber();// 会员表
        merchantMenber.setMemberCode(memberOrder.getMemberCode());//会员编码
        List<MerchantMenber> queryMerchantMenberList = merchantMenberService.queryMerchantMenberList(merchantMenber);
        if (queryMerchantMenberList != null && queryMerchantMenberList.size() > 0) {
            merchantMenber = queryMerchantMenberList.get(0);
            merchantIncome(memberOrder, "2");
        }
        log.error("===============merchantMenber=====" + JSONObject.toJSONString(merchantMenber));
        if (StringUtil.isNotEmpty(memberOrder.getOrderFee())) {
            log.error("进入修改订单方法===OrderFee=======" + memberOrder.getOrderFee());
            MerchantMenberRecharge merchantMenberRecharge = new MerchantMenberRecharge();
            Double usableRechargeFee = merchantMenber.getUsableRechargeFee() == null ? 0d : merchantMenber.getUsableRechargeFee();
            log.error("usableRechargeFee==qian==" + usableRechargeFee);
            merchantMenber.setUsableRechargeFee(StringUtil.bigDecimal(usableRechargeFee + Double.valueOf(memberOrder.getOrderFee())));
            log.error("usableRechargeFee==hou==" + merchantMenber.getUsableRechargeFee());
            //在存会员充值表之前查一下当前店铺的充值
            // 当前充值的店铺id
            String storeId = merchantMenber.getStoreId();
            ActivityRecharge activityRecharge = new ActivityRecharge();
            activityRecharge.setMerchantCode(merchantMenber.getMerchantCode());
            activityRecharge.setStoreId(storeId);
            List<ActivityRecharge> queryActivityRechargeList = activityRechargeService.queryActivityRechargeList(activityRecharge);//根据店铺id查询店铺的充值活动
            log.error("queryActivityRechargeList======前======" + queryActivityRechargeList);
            Double orderFee = Double.valueOf(memberOrder.getOrderFee());//充值的金额
            if (queryActivityRechargeList != null && queryActivityRechargeList.size() > 0) {
                log.error("chongzhijine========" + orderFee);
                queryActivityRechargeList = rechargeMoneyByDesc(queryActivityRechargeList);
                log.error("queryActivityRechargeList======后======" + queryActivityRechargeList);
                for (ActivityRecharge a : queryActivityRechargeList) {
                    if (1 == a.getTimeType()) {
                        if (null == a.getStartDt() || null == a.getEndDt()) {
                            continue;
                        }
                        boolean bol = DateUtils.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 ? 0d : merchantMenber.getTotalGiveFee();//当前充值总额
                            merchantMenber.setTotalGiveFee(StringUtil.bigDecimal(totalGiveFee + a.getGiveMoney()));
                            Double usableGiveFee = merchantMenber.getUsableGiveFee() == null ? 0d : 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(ordersSn);
            log.error("进入修改订单方法===OrderFee==merchantMenberRecharge=====" + JSONObject.toJSONString(merchantMenberRecharge));
            menberRechargeService.saveMerchantMenberRecharge(merchantMenberRecharge);
        }
        Double totalRechargeFee = merchantMenber.getTotalRechargeFee() == null ? 0d : merchantMenber.getTotalRechargeFee();
        merchantMenber.setTotalRechargeFee(StringUtil.bigDecimal(totalRechargeFee + Double.valueOf(memberOrder.getOrderFee())));
        log.error("进入修改订单方法===OrderFee==merchantMenber=====" + JSONObject.toJSONString(merchantMenber));
        merchantMenberService.updateMerchantMenber(merchantMenber);

        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
        merchantBaseInfo.setMerchantCode(memberOrder.getMerchantCode());
        List<MerchantBaseInfo> queryMerchantBaseInfoList = merchantBaseInfoService.queryMerchantBaseInfoList(merchantBaseInfo);
        if (queryMerchantBaseInfoList != null && queryMerchantBaseInfoList.size() > 0) {
            merchantBaseInfo = queryMerchantBaseInfoList.get(0);
            if (StringUtil.isNotEmpty(merchantBaseInfo.getUserId())) {
                List<String> alias = userAppService.storeMemberList(merchantBaseInfo.getMerchantCode());
                log.info("=========推送人userId======" + JSON.toJSONString(alias) + "=========金额=======" + memberOrder.getOrderFee());

                generalPushUtil.sendAllPlatByAlias(alias, "会员充值通知", "会员充值" + memberOrder.getOrderFee() + "元", "3");
//                JpushClientUtil.sendToRegistrationId2(alias, "会员充值通知", "会员充值通知",
//                        "会员充值" + memberOrder.getOrderFee() + "元", "3",
//                        DateUtils.currentYourDate("yyyy-MM-dd HH:mm:ss"));
            }
        }

    }

    private void updateLeshuaMerchantOrder(Map<String, Object> notifyMap) throws ParseException {
        String ordersSn = (String) notifyMap.get("third_order_id");// 商户订单号
        String amountpaid = (String) notifyMap.get("amount");// 订单金额
        String pay_way = (String) notifyMap.get("pay_way");// 支付类型
        String openid = (String) notifyMap.get("openid");// 微信openid
        String sub_openid = (String) notifyMap.get("sub_openid");//支付宝
        String transaction_id = (String) notifyMap.get("out_transaction_id");
        String leshua_order_id = (String) notifyMap.get("leshua_order_id");
        String pay_time = (String) notifyMap.get("pay_time");
        BigDecimal amountPay = (new BigDecimal(amountpaid).divide(new BigDecimal("100"))).setScale(2);// 将分转换成元-实际支付金额:元
        String amount = amountPay + "";// 消费金额
        MerchantOrder merchantOrder = new MerchantOrder();
        merchantOrder.setOrderNumber(ordersSn);
        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.setId(merchantOrder.getId());
            m.setStatus("1");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            m.setTransDt(sdf.parse(pay_time));
            m.setThirdTransNo(leshua_order_id);
            merchantOrderService.updateById(m);
        }

    }


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

    }

    /**
     * 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);
    }

    /**
     * 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;
    }


    /**
     * leshuaCallBack:(乐刷退款回调地址). <br/>
     *
     * @return
     * @author Administrator
     * @since JDK 1.8
     */
    @RequestMapping("/leshuaRefundCallBack")
    @ResponseBody
    public String leshuaRefundCallBack(HttpServletRequest request) {
        return merchantService.appRefundCallback(request);
    }

    @PostMapping("/appMemberScanPayLeshuaCallBack")
    @ResponseBody
    public String appMemberScanPayLeshuaCallBack(HttpServletRequest request) {
        String respString = "";
        InputStream is = null;
        Map<String, Object> notifyMap = null;
        try {
            is = request.getInputStream();
            String xml = XmlUtil.toUTF8(is);
            notifyMap = XmlUtil.toMapLeshua(xml);
            if (notifyMap.containsKey("sign")) {
                if (!LeshuaSignature.checkIsSignValidFromResponseString(xml, resExcludedSignParams(), "75C27ABB12F78A747DCB4368EEBCB542")) {
                    log.info("============================签名不通过======================");
                    respString = "error";
                } else {
                    String status = (String) notifyMap.get("status");
                    log.info("============订单状态 status============" + status);
                    respString = "000000";
                    String orderNumber = (String) notifyMap.get("third_order_id");// 商户订单号
                    MemberOrder memberOrder = new MemberOrder();
                    memberOrder.setOrderNumber(orderNumber);
                    List<MemberOrder> queryMemberOrderList = memberOrderService.queryMemberOrderList(memberOrder);
                    System.out.println("======查询订单=====order=" + JSONObject.toJSONString(queryMemberOrderList));
                    if (StringUtil.isNotEmpty(orderNumber) && queryMemberOrderList != null && queryMemberOrderList.size() > 0) {
                        System.out.println("======订单状态=====order=" + JSONObject.toJSONString(queryMemberOrderList));
                        memberOrder = queryMemberOrderList.get(0);
                        if ("1".equals(memberOrder.getOrderStatus())) {
                            return respString;
                        }
                        if ("2".equals(status)) {//交易成功
                            memberOrder.setOrderStatus("1");
                        }
                        memberOrderService.updateMemberOrder(memberOrder);
                        String memberCode = memberOrder.getMemberCode();//会员编码
                        MerchantMenber menber = new MerchantMenber();
                        menber.setMemberCode(memberCode);
                        menber = merchantMenberService.queryMerchantMenber(menber);
                        MerchantMenberComsume merchantMenberComsume = new MerchantMenberComsume();
                        merchantMenberComsume.setComsumeMoney(Double.valueOf(memberOrder.getOrderFee()));
                        merchantMenberComsume.setLogo(menber.getLogo());
                        merchantMenberComsume.setMerchantCode(menber.getMerchantCode());
                        merchantMenberComsume.setMerchantName(menber.getMerchantName());
                        merchantMenberComsume.setStoreId(menber.getStoreId());
                        merchantMenberComsume.setStoreName(menber.getStoreName());
                        merchantMenberComsume.setOrderNumber(orderNumber);
                        merchantMenberComsume.setPayType(1);
                        merchantMenberComsume.setCreateDt(new Date());
                        merchantMenberComsume.setLogo(menber.getLogo());
                        merchantMenberComsume.setMemberCode(memberCode);
                        merchantMenberComsume.setNickName(menber.getNickName());
                        merchantMenberComsume.setPhone(menber.getPhone());
                        merchantMenberComsumeService.saveMerchantMenberComsume(merchantMenberComsume);
                        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
                        merchantBaseInfo.setMerchantCode(menber.getMerchantCode());
                        List<MerchantBaseInfo> queryMerchantBaseInfoList = merchantBaseInfoService.queryMerchantBaseInfoList(merchantBaseInfo);
                        if (queryMerchantBaseInfoList != null && queryMerchantBaseInfoList.size() > 0) {
                            merchantBaseInfo = queryMerchantBaseInfoList.get(0);
                            log.info("=========推送人userId======" + merchantBaseInfo.getUserId() + "=========金额=======" + memberOrder.getOrderFee());
                            if (StringUtil.isNotEmpty(merchantBaseInfo.getUserId())) {
                                List<String> alias = userAppService.storeMemberList(merchantBaseInfo.getMerchantCode());

                                generalPushUtil.sendAllPlatByAlias(alias, "会员消费通知", "会员消费" + memberOrder.getOrderFee() + "元", "3");
                            }
                        }
                    }
                    return respString;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 升级页面
     */
    @GetMapping(value = "/toUpGradeAuth")
    public ModelAndView toUpGradeAuth(String userAppId,
                                      HttpServletRequest request, ModelAndView view) {

        String url = "/merchant/goUpgradePage?userAppId=" + userAppId;
        String APP_ID = ParametersUtil.APPID;
        String ali_appid = ParametersUtil.ZY_ALI_APP_ID;
        this.request.setAttribute("appId", APP_ID);
        this.request.setAttribute("ali_appid", ali_appid);
        String domain_wap = ParametersUtil.domain + "/wap";
        request.setAttribute("domain_wap", domain_wap);
        try {
            String ua = request.getHeader("user-agent").toLowerCase();
            if (ua.contains("micromessenger")) {
                String jump = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APP_ID
                        + "&redirect_uri=" + java.net.URLEncoder.encode(domain_wap + url, "utf-8")
                        + "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
                response.sendRedirect(jump);
                return null;
            } else if (ua.contains("alipay")) {
                String urlString = domain_wap + url;
                log.info(urlString);
                String rurl = java.net.URLEncoder.encode(urlString, "utf-8");
                String jmp = "https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=" + ali_appid + "&scope=auth_base&redirect_uri=" + rurl;
                log.info(jmp);
                response.sendRedirect(jmp);
                return null;
            } else {
                String urlString = domain_wap + url;
                log.info(urlString);
                String rurl = java.net.URLEncoder.encode(urlString, "utf-8");
                String jmp = "https://qr.95516.com/qrcGtwWeb-web/api/userAuth?version=1.0.0&redirectUrl=" + rurl;
                log.info(jmp);
                response.sendRedirect(jmp);
                return null;
            }
        } catch (Exception e) {
            view.setViewName("merchant/errorInfo");
            request.setAttribute("error", "授权异常！");
            return view;
        }
    }

    /**
     * goUpgradePage:(跳转到升级页面). <br/>
     *
     * @param userAppId
     * @param code
     * @param auth_code
     * @param userAuthCode
     * @param request
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
//    @GetMapping(value = "/goUpgradePage")
//    public ModelAndView goUpgradePage(String userAppId, String code, String auth_code, String userAuthCode,
//                                      HttpServletRequest request) {
//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.setViewName("merchant/goUpgradePage");
//        setUpVipAmtResult(modelAndView, "twoUpVipAmount", 2);
//        setUpVipAmtResult(modelAndView, "threeUpVipAmount", 3);
//        modelAndView.addObject("userAppId", userAppId);
//        UserApp userApp = new UserApp();
//        userApp.setUserId(Long.valueOf(userAppId));
//        userApp = userAppService.queryUserApp(userApp);
//        if (null != userApp) {
//            modelAndView.addObject("level", userApp.getLevel());
//        }
//        if (StringUtil.isNotEmpty(code)) {
//            modelAndView.addObject("payType", "WXZF");
//            WeixinOauth2Token wot = getWeChatUserOpenId(code);
//            String openid = wot.getOpenId();
//            log.info("openid  = " + openid);
//            log.info("unionid  = " + wot.getUnionId());
//            modelAndView.addObject("openid", openid);
//        } else if (StringUtil.isNotEmpty(auth_code)) {
//            modelAndView.addObject("payType", "ZFBZF");
//            Map<String, Object> aliMap = AliUtil.getAliUserId(auth_code,ParametersUtil.ZY_PRI,ParametersUtil.ZY_PUB,ParametersUtil.ZY_ALI_APP_ID);
//            //支付宝取消主动授权 采用静默授权方式，无法获取用户信息
//           /* String accessToken = (String) aliMap.get("accessToken");
//            AliUserInfoVO aliUserInfo = getAliUserInfo(accessToken);*/
//            log.info("============aliUserInfo============" + JSONObject.toJSONString(aliMap));
//            modelAndView.addObject("userid", aliMap.get("aliUserId"));
//        } else if (StringUtil.isNotEmpty(userAuthCode)) {
//            modelAndView.addObject("payType", "UNIONPAY");
//            String ua = request.getHeader("User-Agent");
//            log.info("===================>【银联】标识，获取请求头部信息:{},==============", ua);
//            int begin = ua.indexOf("UnionPay");
//            String payMentApp = ua.substring(begin);
//            if(payMentApp.length() > 30){
//                payMentApp = payMentApp.substring(0,30);
//            }
//            try {
//                Map<String, Object> unionInfo = sxfPayService.getUnionInfo(userAuthCode, payMentApp);
//                log.info("===================>【银联】获取用户标识结果参数，==============", unionInfo);
//                if ("1".equals(unionInfo.get("code"))) {
//                    Map<String, String> data = (Map<String, String>) unionInfo.get("data");
//                    modelAndView.addObject("userid", data.get("data"));
//                }
//            } catch (Exception e) {
//                log.error("===================>【银联】获取用户标识出错:{}==============", ua);
//            }
//        } else {
//            modelAndView.setViewName("merchant/errorInfo");
//            request.setAttribute("error", "请使用，支付宝、微信、云闪付扫码支付！");
//            return modelAndView;
//        }
//        return modelAndView;
//    }

//    public void setUpVipAmtResult(ModelAndView modelAndView, String propertyKey, int level) {
//        String configValue = systemConfigService.querySystemConfigValue(propertyKey);
//        if (StringUtil.isNotEmpty(configValue)) {
//            if (configValue.contains("-")) {
//                modelAndView.addObject(propertyKey, configValue.split("-")[0]);
//                //modelAndView.addObject(shapeKey, propertyValue.split("-")[1]);
//            }
//        } else {
//            if (level == 2) {
//                modelAndView.addObject(propertyKey, 999);
//                //modelAndView.addObject(shapeKey, 500);
//            } else {
//                modelAndView.addObject(propertyKey, 9999);
//                //modelAndView.addObject(shapeKey, 5000);
//            }
//        }
//    }

//    @PostMapping("/upGradePay")
//    @ResponseBody
//    public Map<String, Object> upGradePay(LevelDTO levelDTO, HttpServletRequest request) {
//        Map<String, Object> result = new HashMap<>(16);
//        if (StringUtil.isEmpty(levelDTO.getUserAppId())) {
//            result.put("code", "0");
//            result.put("msg", "页面已超时，请稍后再试");
//            return result;
//        }
//        try {
//            return merchantService.tradePay(levelDTO, request);
//        } catch (Exception e) {
//            result.put("code", "0");
//            result.put("msg", "支付异常！");
//            return result;
//        }
//    }

    /**
     * 获取商户支付成功页面的信息 二维码 和提示信息
     *
     * @return
     */
    @RequestMapping(value = "/pay/success/page/info", method = RequestMethod.POST)
    @ResponseBody
    public Result<JSONObject> getSuccessPageInfo(@RequestBody JSONObject json) {
        JSONObject result = new JSONObject();
        Integer storeId = json.getInteger("storeId");
        if (StringUtil.isEmpty(storeId)) {
            return ResultGenerator.genFailResult("店铺ID不能为空");
        }
        MerchantStore store = new MerchantStore();
        store.setId(storeId);
        MerchantStore storeInfo = merchantStoreService.queryMerchantStore(store);
        if (storeInfo == null) {
            return ResultGenerator.genFailResult("店铺信息异常!");
        }
        QueryWrapper<MerchantQrcode> qrcodeQueryWrapper = new QueryWrapper<MerchantQrcode>().eq("merchantCode", storeInfo.getMerchantCode());
        MerchantQrcode one = merchantQrcodeService.getOne(qrcodeQueryWrapper);
        if (one == null) {
            result.put("qrCodeUrl", "");
        } else {
            result.put("qrCodeUrl", one.getQrCodeUrl());
            result.put("wechat", one.getWechat());
        }
        QueryWrapper<MerchantGuide> guideQueryWrapper = new QueryWrapper<MerchantGuide>().eq("status", "1")
                .eq("merchantCode", storeInfo.getMerchantCode());
        List<MerchantGuide> list = merchantGuideService.list(guideQueryWrapper);
        if (list.size() == 0) {
            QueryWrapper<GuideLabel> labelQueryWrapper = new QueryWrapper<GuideLabel>().eq("status", "1")
                    .orderByDesc("createTime");
            List<GuideLabel> g = guideLabelService.list(labelQueryWrapper);
            if (!g.isEmpty()) {
                result.put("guideLabel", g.get(0).getName());
            } else {
                result.put("guideLabel", "");
            }
        } else {
            MerchantGuide guide = list.get(0);
            if (StringUtil.isNotEmpty(guide.getGuideId())) {
                GuideLabel byId = guideLabelService.getById(guide.getGuideId());
                if (byId != null) {
                    result.put("guideLabel", byId.getName());
                } else {
                    result.put("guideLabel", "");
                }
            } else {
                result.put("guideLabel", guide.getName());
            }
        }
        return ResultGenerator.genSuccessResult("获取成功!", result);
    }

    /**
     * 更新会员信息接口
     *
     * @param json
     * @return
     */
    @RequestMapping(value = "/member/update", method = RequestMethod.POST)
    @ResponseBody
    public Result<JSONObject> vipOpenCard(@RequestBody JSONObject json) {
        log.info("============>更新会员信息接口请求，请求参数:{}<============", json);
        String memberName = json.getString("memberName");
        String avatar = json.getString("avatar");
        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("appOpenId", appOpenId)
                .eq("storeId", info.getStoreId());
        MerchantMenber menber = merchantMenberService.getOne(queryWrapper);
        if (menber != null) {
            menber.setMemberName(memberName);
            menber.setNickName(memberName);
            menber.setLogo(avatar);
            merchantMenberService.updateById(menber);
        }
        return ResultGenerator.genSuccessResult("操作成功!", result);
    }

    /**
     * 被扫小程序会员卡充值接口
     *
     * @param json
     * @return
     */
    @NoRepeatSubmit
    @RequestMapping(value = "/toRecharge", method = RequestMethod.POST)
    @ResponseBody
    public Result<JSONObject> memberRecharge(@RequestBody JSONObject json, HttpServletRequest request) {
        log.info("===============>小程序会员卡充值开始，请求参数:{}<===================", json);
        try {
            json.put("ip", IpUtils.getIpAddr(request));
            return merchantService.memberRecharge(json);
        } catch (Exception e) {
            e.printStackTrace();
            MsgException.throwException(e.getMessage());
        }
        return ResultGenerator.genFailResult("支付失败");
    }

    @GetMapping(value = "/recharge")
    public ModelAndView recharge(ModelAndView view, Integer storeId, String appOpenId) {
        view.setViewName("recharge/recharge");
        if (StringUtil.isEmpty(storeId)) {
            view.addObject("error", "店铺ID不能为空！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        if (StringUtil.isEmpty(appOpenId)) {
            view.addObject("error", "openId不能为空！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        MerchantStore s = new MerchantStore();
        s.setId(storeId);
        MerchantStore store = merchantStoreService.queryMerchantStore(s);
        if (store == null) {
            view.addObject("error", "店铺数据异常！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        if ("0".equals(store.getStatus())) {
            view.addObject("error", "店铺已经打烊！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        if ("2".equals(store.getStatus())) {
            view.addObject("error", "店铺已被禁用！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        QueryWrapper<MerchantMenber> queryWrapper = new QueryWrapper<MerchantMenber>().eq("storeId", store.getStoreId())
                .eq("appOpenId", appOpenId);
        MerchantMenber menber = merchantMenberService.getOne(queryWrapper);
        if (menber == null) {
            view.addObject("error", "您还不是当前门店的会员，请先开通会员！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        QueryWrapper<MerchantBaseInfo> infoQueryWrapper = new QueryWrapper<MerchantBaseInfo>()
                .eq("merchantCode", store.getMerchantCode());
        MerchantBaseInfo merchant = merchantBaseInfoService.getOne(infoQueryWrapper);
        if (merchant == null) {
            view.addObject("error", "商户信息异常！");
            view.setViewName("merchant/errorInfo");
            return view;
        }
        ActivityRecharge activityRecharge = new ActivityRecharge();
        activityRecharge.setMerchantCode(store.getMerchantCode());
        activityRecharge.setStoreId(store.getStoreId());
        List<String> amt = new ArrayList<String>() {{
            add("100");
            add("200");
            add("300");
            add("400");
            add("500");
            add("1000");
        }};
        int p = amt.size();
        List<ActivityRecharge> rechargeList = activityRechargeService
                .queryUsableActivityRechageList(activityRecharge);
        if (!rechargeList.isEmpty()) {
            view.addObject("list", rechargeList);
            if (!"TQTDMS".equals(store.getStoreId())) {
                if (rechargeList.size() < 6) {
                    for (ActivityRecharge r : rechargeList) {
                        String d = r.getRechargeMoney().intValue() + "";
                        amt.remove(d);
                    }
                    int a = rechargeList.size();
                    List<String> useAmtList = new ArrayList<>();
                    for (int i = 0; i < p - a; i++) {
                        useAmtList.add(amt.get(i));
                    }
                    amt = useAmtList;
                } else if (rechargeList.size() >= 6 && rechargeList.size() <= 9) {
                    amt.clear();
                } else {
                    List<ActivityRecharge> rList = new ArrayList<>();
                    for (int i = 0; i < 9; i++) {
                        rList.add(rechargeList.get(i));
                    }
                    view.addObject("list", rList);
                }
            } else {
                amt.clear();
            }
        }
        if (StringUtil.isNotEmpty(menber.getMemberName())) {
            menber.setMemberName(EmojiUtil.emojiRecovery2(menber.getMemberName()));
        }
        if (StringUtil.isNotEmpty(menber.getNickName())) {
            menber.setMemberName(EmojiUtil.emojiRecovery2(menber.getNickName()));
        }
        view.addObject("store", store);
        view.addObject("amt", amt);
        view.addObject("menber", menber);
        Double rechargeFee = menber.getUsableRechargeFee() == null ? 0.00d : menber.getUsableRechargeFee();
        Double giveFee = menber.getUsableGiveFee() == null ? 0.00d : menber.getUsableGiveFee();
        double balance = StringUtil.bigDecimal(rechargeFee + giveFee);
        view.addObject("balance", balance);
        view.addObject("appOpenId", appOpenId);
        view.addObject("merchant", merchant);
        return view;
    }

    @GetMapping(value = "/wxLocation")
    public ModelAndView wxLocation(ModelAndView view, HttpServletRequest request, String storeId, String appOpenId) {
        String appId = ParametersUtil.APPID;
        String noncestr = StringUtil.generateMixStr(10);
        Long timestamp = System.currentTimeMillis() / 1000;
        StringBuffer requestURL = request.getRequestURL();
        if (StringUtil.isNotEmpty(request.getQueryString())) {
            requestURL.append("?" + request.getQueryString());
        }
        WxAccessTokenRequest tokenRequest = WxAccessTokenRequest.buidWxToken(appId, ParametersUtil.APPSECRET, null, WxConstants.ACCESS_TOKEN_URL);
        String jsapiTicket = wxCommonService.getJsapiTicket(tokenRequest, "jsapi");
        String signStr = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + requestURL.toString();
        String sign = SignUtils.sha1Encrypt(signStr);

        view.addObject("appId", appId);
        view.addObject("noncestr", noncestr);
        view.addObject("timestamp", timestamp);
        view.addObject("sign", sign);

        view.addObject("storeId", storeId);
        view.addObject("appOpenId", appOpenId);
        view.setViewName("merchant/wxLocation");
        return view;
    }
}