package cn.pluss.platform.controller;

import cn.pluss.platform.IdCardService;
import cn.pluss.platform.annotation.OpLog;
import cn.pluss.platform.api.PageInfo;
import cn.pluss.platform.api.Result;
import cn.pluss.platform.api.ResultCode;
import cn.pluss.platform.api.ResultGenerator;
import cn.pluss.platform.constants.ProjectConstant;
import cn.pluss.platform.deviceStock.DeviceStockService;
import cn.pluss.platform.dto.*;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.MerchantChannelStatusMapper;
import cn.pluss.platform.mapper.MerchantOrderVOMapper;
import cn.pluss.platform.memberOrder.MemberOrderService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantIncome.MerchantIncomeService;
import cn.pluss.platform.merchantMenber.MerchantMenberService;
import cn.pluss.platform.merchantMenberRecharge.MerchantMenberRechargeService;
import cn.pluss.platform.merchantOrder.MerchantOrderService;
import cn.pluss.platform.notice.NoticeService;
import cn.pluss.platform.pay.PayService;
import cn.pluss.platform.ryx.pay.RyxPayService;
import cn.pluss.platform.sxf.pay.SxfPayService;
import cn.pluss.platform.user.impl.GeneralPushUtil;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.util.StringUtil;
import cn.pluss.platform.util.TokenUtil;
import cn.pluss.platform.vo.MemberScanVO;
import cn.pluss.platform.vo.MerchantOrderVO;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/merchantOrder")
@Api(value = "MerchantOrder控制类", tags = {"MerchantOrder接口"})
public class MerchantOrderController {

    @Autowired
    private GeneralPushUtil generalPushUtil;
    private final MerchantOrderVOMapper merchantOrderVOMapper;
    private final MerchantOrderService merchantOrderService;
    private final MerchantBaseInfoService merchantBaseInfoService;
    private final UserAppService userAppService;
    private final MemberOrderService memberOrderService;
    private final MerchantIncomeService merchantIncomeService;
    private final NoticeService noticeService;
    private final MerchantMenberService merchantMenberService;
    private final MerchantMenberRechargeService merchantMenberRechargeService;
    private final SxfPayService sxfPayService;
    private final RyxPayService ryxPayService;
    private final MerchantChannelStatusMapper merchantChannelStatusMapper;
    @Autowired
    private DeviceStockService deviceStockService;

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private IdCardService idCardService;

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

    // 微信支付无法确认支付结果状态
    private String[] wechatPayNotSureResult = new String[]{"SYSTEMERROR", "USERPAYING", "BANKERROR"};


    @GetMapping("/plugin/order/page")
    @ApiOperation(value = "获取插件分页订单信息", notes = "返回分页过后的数据", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "查询页码", paramType = "query", dataType = "Integer", defaultValue = "0"),
            @ApiImplicitParam(name = "size", value = "每页数据量", paramType = "query", dataType = "Integer", defaultValue = "0")})
    public Result<Object> pluginOrderPage(@RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer size,MerchantOrder query) {
        UserApp app = userAppService.queryUserAppByToken();
        Page<MerchantOrder> pageInfo = new Page<>();
        pageInfo.setCurrent(page);
        pageInfo.setSize(size);
        query.setUserId(Integer.parseInt(String.valueOf(app.getUserId())));
        query.setOrderType("99");
        pageInfo = merchantOrderService.pageInfo(pageInfo, query);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

    /**
     * 获取插件账单
     * @param page
     * @param size
     * @return
     */
    @GetMapping
    @ApiOperation(value = "获取全部", notes = "返回分页过后的数据", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "查询页码", paramType = "query", dataType = "Integer", defaultValue = "0"),
            @ApiImplicitParam(name = "size", value = "每页数据量", paramType = "query", dataType = "Integer", defaultValue = "0")})
    public Result<PageInfo<MerchantOrder>> list(@RequestParam(defaultValue = "1") Integer page,
                                                @RequestParam(defaultValue = "10") Integer size) {

        Map<String, Object> map = new HashMap<>();
        map.put("pageSize", size);
        map.put("offset", (page - 1) * size);
        List<MerchantOrder> merchantOrderList = merchantOrderService.queryMerchantOrderPage(map);
        for (MerchantOrder o : merchantOrderList) {
            MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
            merchantBaseInfo.setMerchantCode(o.getMerchantCode());
            merchantBaseInfo = merchantBaseInfoService.queryMerchantBaseInfo(merchantBaseInfo);
            o.setAlias(merchantBaseInfo.getAlias());

        }
        Integer count = merchantOrderService.queryMerchantOrderPageCount(map);
        // 返回参数
        PageInfo<MerchantOrder> pager = new PageInfo<>(count.longValue(), (long) StringUtil.getPageCount(count,size), page.longValue(), size.longValue(),
                merchantOrderList);
        return ResultGenerator.genSuccessResult(pager);
    }

    // 添加数据
    @PostMapping
    @ApiOperation(value = "添加数据", notes = "添加新的数据", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MerchantOrder", value = "待添加的MerchantOrder实例", paramType = "body", dataType = "MerchantOrder", required = true)})
    public Result add(@RequestBody MerchantOrder merchantOrder) {
        merchantOrderService.save(merchantOrder);
        return ResultGenerator.genSuccessResult();
    }

    // 查询商家订单的统计数据
    @PostMapping("/queryMerchantOrderCensusData")
    @ApiOperation(value = "查询商家订单的统计数据", notes = "查询商家订单的统计数据", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MerchantOrder", value = "待添加的MerchantOrder实例", paramType = "body", dataType = "MerchantOrder", required = true)})
    public Result queryMerchantOrderCensusData(@RequestBody MerchantOrder merchantOrder) {
        UserApp tokenUa = userAppService.queryUserAppByToken();
        merchantOrder.setMerchantCode(tokenUa.getMerchantCode());

        if (StringUtil.isEmpty(merchantOrder.getMerchantCode())) {
            return ResultGenerator.genFailResult("无商家编码");
        }
        Map<String, Object> queryMap = new HashMap<String, Object>(16);
        Calendar startCalendar = Calendar.getInstance();
        try {
            startCalendar.setTime(merchantOrder.getStartTime());// 设置查询的开始时间
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        queryMap.put("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startCalendar.getTime()));
        Calendar endCalendar = Calendar.getInstance();
        try {
            endCalendar.setTime(merchantOrder.getEndTime());// 设置查询的结束时间
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        endCalendar.set(Calendar.HOUR_OF_DAY, 23);
        endCalendar.set(Calendar.MINUTE, 59);
        endCalendar.set(Calendar.SECOND, 59);
        queryMap.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endCalendar.getTime()));
        queryMap.put("merchantCode", merchantOrder.getMerchantCode());
        // 获取指定时间段内的交易数量
        Integer orderCount = merchantOrderService.queryMerchantOrderPageCountByTime(queryMap);
        // 获取指定时间内的交易金额
        Double totalOrderFee = merchantOrderService.queryMerchantOrderFeeByTime(queryMap);
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("orderCount", orderCount.toString());
        resultMap.put("totalOrderFee", totalOrderFee.toString());
        return ResultGenerator.genSuccessResult(resultMap);
    }

    // 查询商家订单集合
    @PostMapping("/queryMerchantOrderList")
    @ApiOperation(tags = {"页面-账单_账单", "页面-日账单", "页面-周账单", "页面-月账单"}, value = "查询商家订单集合", notes = "查询商家订单集合", httpMethod = "POST")
    public Result<Map<String, Object>> queryMerchantOrderList(@Valid @RequestBody MerchantOrder merchantOrder) {
        UserApp tokenUa = userAppService.queryUserAppByToken();
        merchantOrder.setMerchantCode(tokenUa.getMerchantCode());
        Map<String, Object> resultMap = merchantOrderService.billCollect(merchantOrder);
        return ResultGenerator.genSuccessResult(resultMap);
    }

    // 查询首页统计数据
    @PostMapping("/queryHomePageData")
    @ApiOperation(tags = {"页面-首页"}, value = "查询首页统计数据", notes = "查询首页统计数据", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "UserApp", value = "待查询的UserApp实例", paramType = "body", dataType = "UserApp", required = true)})
    public Result<Map<String, Object>> queryHomePageData(@RequestBody UserApp userApp) {
        Map<String, Object> resultMap = merchantOrderService.queryHomePageData(userApp);
        return ResultGenerator.genSuccessResult(resultMap);
    }

    // 查询商家订单集合（按天分组）
    @PostMapping("/queryMerchantOrderListGroupByDay")
    @ApiOperation(value = "查询商家订单集合（按天分组）", notes = "查询商家订单集合（按天分组）", httpMethod = "POST")
    public Result queryMerchantOrderListGroupByDay(@RequestBody MerchantOrder merchantOrder) {
        UserApp tokenUa = userAppService.queryUserAppByToken();
        merchantOrder.setMerchantCode(tokenUa.getMerchantCode());

        if (StringUtil.isEmpty(merchantOrder.getMerchantCode())) {
            return ResultGenerator.genFailResult("无商家编码");
        }
        Map<String, Object> queryMap = new HashMap<String, Object>(16);
        if (StringUtil.isNotEmpty(merchantOrder.getStartTime())) {
            queryMap.put("startTime", merchantOrder.getStartTime());
        }
        if (StringUtil.isNotEmpty(merchantOrder.getEndTime())) {
            queryMap.put("endTime", merchantOrder.getEndTime());
        }
        queryMap.put("merchantCode", merchantOrder.getMerchantCode());
        if (merchantOrder.getSize() == null || merchantOrder.getSize() == 0) {
            merchantOrder.setSize(ProjectConstant.PAGE_SIZE);
        }
        if (merchantOrder.getPage() == null || merchantOrder.getPage() == 0) {
            merchantOrder.setPage(1);
        }
        queryMap.put("pageSize", merchantOrder.getSize());
        queryMap.put("offset", (merchantOrder.getPage() - 1) * merchantOrder.getSize());
        if (StringUtil.isNotEmpty(merchantOrder.getPayTypeCode())) {// 确定查询条件
            String[] payTypeCode = merchantOrder.getPayTypeName().split(",");
            List<String> payTypeCodeList = new ArrayList<>(Arrays.asList(payTypeCode));
            List<String> p = new ArrayList<String>();
            if (payTypeCodeList.contains("wechatPay")) {
                p.add("wechatPay");
                p.add("leshuaPay1");
                p.add("leshuaPay-1");
                p.add("leshuaPay");
            }
            if (payTypeCodeList.contains("aliPay")) {
                p.add("aliPay");
                p.add("leshuaPay0");
                p.add("leshuaPay-0");
                p.add("leshuaPay");
            }
            if (payTypeCodeList.contains("bank")) {
                p.add("leshuaPay2");
                p.add("bank");
            }
            queryMap.put("payTypeCodeList", p);
        }
        if (merchantOrder.getStatus() != null && !StringUtil.isEmpty(merchantOrder.getStatus())) {
            queryMap.put("status", merchantOrder.getStatus());
        }
        if (merchantOrder.getStoreId() != null && StringUtil.isEmpty(merchantOrder.getStoreId())) {
            String[] storeId = merchantOrder.getStoreId().split(",");
            List<String> storeIdList = new ArrayList<>(Arrays.asList(storeId));
            queryMap.put("storeId", storeIdList);
        }
        if (merchantOrder.getStaffCode() != null && !StringUtil.isEmpty(merchantOrder.getStaffCode())) {
            String[] staffCode = merchantOrder.getStaffCode().split(",");
            List<String> staffCodeList = new ArrayList<>(Arrays.asList(staffCode));
            queryMap.put("staffCode", staffCodeList);
        }
        List<MerchantOrder> merchantOrders = merchantOrderService.queryMerchantOrderPageByTime(queryMap);
        Map<String, Object> resultMap = new HashMap<>();
        if (merchantOrders != null) {
            List<String> timeStringList = new ArrayList<String>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            for (MerchantOrder merchantOrder2 : merchantOrders) {
                // 获取当前交易的时间
                String time = sdf.format(merchantOrder2.getCreateDt());
                if (!timeStringList.contains(time)) {
                    timeStringList.add(time);
                    resultMap.put(time, new ArrayList<MerchantOrder>());
                }
                ((List<MerchantOrder>) resultMap.get(time)).add(merchantOrder2);// 将查询到的数据按天进行分组
            }
        }
        Integer count = merchantOrderService.queryMerchantOrderPageCountByTime(queryMap);
        PageInfo<MerchantOrder> pager = new PageInfo<MerchantOrder>(count.longValue(),
                (long) StringUtil.getPageCount(count, merchantOrder.getSize()), merchantOrder.getPage().longValue(),
                merchantOrder.getSize().longValue(), merchantOrders);// 返回参数
        resultMap.put("pager", pager);
        return ResultGenerator.genSuccessResult(resultMap);
    }

    // 查询商家对账数据
    @PostMapping("/queryCheckOrderData")
    @ApiOperation(value = "查询商家对账数据", notes = "查询商家对账数据", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MerchantOrder", value = "待添加的MerchantOrder实例", paramType = "body", dataType = "MerchantOrder", required = true)})
    public Result queryCheckOrderData(@RequestBody MerchantOrder merchantOrder) {
        Map<String, Object> resultMap = merchantOrderService.queryCheckOrderData(merchantOrder);
        return ResultGenerator.genSuccessResult(resultMap);
    }

    // 删除数据
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除数据", notes = "根据id删除数据", httpMethod = "DELETE")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "查询的id实例", paramType = "path", dataType = "Integer", required = true)})
    public Result delete(@PathVariable Integer id) {
        MerchantOrder merchantOrder = new MerchantOrder();
        merchantOrder.setId(id.longValue());
        merchantOrderService.removeById(merchantOrder.getId());
        return ResultGenerator.genSuccessResult();
    }

    // 更新数据
    @PutMapping
    @ApiOperation(value = "更新数据", notes = "根据内容更新数据", httpMethod = "PUT")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MerchantOrder", value = "更新的MerchantOrder实例", paramType = "body", dataType = "MerchantOrder", required = true)})
    public Result update(@RequestBody MerchantOrder merchantOrder) {
        merchantOrderService.updateById(merchantOrder);
        return ResultGenerator.genSuccessResult();
    }

    // 获取单个值
    @GetMapping("/{orderNumber}")
    @ApiOperation(value = "获取单个值", notes = "查看单个项目的内容", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNumber", value = "查询的orderNumber", paramType = "orderNumber", required = true, dataType = "String")})
    public Result<MerchantOrder> detail(@PathVariable String orderNumber) {
        if (StringUtil.isEmpty(orderNumber)) {
            return ResultGenerator.genFailResult("无订单号");
        }
        MerchantOrderVO merchantOrderVO = new MerchantOrderVO();
        merchantOrderVO.setOrderNumber(orderNumber);
        merchantOrderVO.setStatus("1");
        List<MerchantOrderVO> result = merchantOrderVOMapper.selectList(new QueryWrapper<>(merchantOrderVO));
        if (result != null && result.size() > 0) {
            merchantOrderVO = result.get(0);
            MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
            merchantBaseInfo.setMerchantCode(merchantOrderVO.getMerchantCode());
            merchantBaseInfo = merchantBaseInfoService.queryMerchantBaseInfo(merchantBaseInfo);
            merchantOrderVO.setAlias(merchantBaseInfo.getAlias());
            merchantOrderVO.setMerchantName(merchantBaseInfo.getAlias());
            if (!"1".equals(merchantOrderVO.getOrderType())) {
                // 除开主扫可以存在店员，其他的收银员均为老板
                merchantOrderVO.setStaffName(merchantBaseInfo.getContactName());
            }

            Integer userId = merchantOrderVO.getUserId();
            IdCard idCard = new IdCard().setUserId(userId + "");
            idCard = idCardService.getOne(new QueryWrapper<>(idCard));
            MerchantOrder.updateStaffName(merchantOrderVO, merchantOrderVO.getMerchantCode(), idCard);
            MerchantOrder.updateOrderTypeDesc(merchantOrderVO);
        }
        return ResultGenerator.genSuccessResult(merchantOrderVO);
    }


    /**
     * belongCalendar:(判断在不在营业时间范围内). <br/>
     *
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    private static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);
        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);
        Calendar end = Calendar.getInstance();
        end.setTime(endTime);
        if (date.after(begin) && date.before(end)) {
            return true;
        } else if (nowTime.compareTo(beginTime) == 0 || nowTime.compareTo(endTime) == 0) {
            return true;
        } else {
            return false;
        }
    }

    @PostMapping("/memberRecharge")
    @ApiOperation(value = "会员充值", notes = "APP扫码-会员充值", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MemberRechargeDTO", value = "MemberRechargeDTO", paramType = "MemberRechargeDTO", dataType = "MemberRechargeDTO", required = true)})
    public Result<Map<String, Object>> memberRecharge(@RequestBody MemberRechargeDTO memberRechargeDTO) {

        try {
            UserApp userApp = userAppService.queryUserAppByToken();
            if(userApp == null) {
                MsgException.throwException("登陆信息异常！");
            }
            memberRechargeDTO.setMerchantCode(userApp.getMerchantCode());
            memberRechargeDTO.setUserId(String.valueOf(userApp.getUserId()));
            memberRechargeDTO.setUserName(userApp.getUserName());
            return merchantOrderService.toMemberRecharge(memberRechargeDTO);
        }catch (Exception e){
            e.printStackTrace();
            MsgException.throwException(e.getMessage());
        }
        return ResultGenerator.genFailResult("支付失败");
    }


    /**
     * 扫用户付款ma进行收款
     * @param merchantOrderDTO
     * @return
     */
    @OpLog(opCode = "APP_SCAN_PAY", opDetail = "app主扫收款", opName = "APP主扫收款")
    @PostMapping("/scanPay")
    @ApiOperation(tags = {"页面-收款"}, value = "扫码支付", notes = "扫码支付", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MerchantOrderVo", value = "扫码支付需要传递的参数实例", paramType = "body", dataType = "MerchantOrderVo", required = true)})
    public Result<Object> scanPay(@RequestBody MerChantOrderDTO merchantOrderDTO) {
        UserApp tokenUa = userAppService.queryUserAppByToken();
        merchantOrderDTO.setMerchantCode(tokenUa.getMerchantCode());
        //校验金额
        if (!StringUtil.isMoney(String.valueOf(merchantOrderDTO.getConsumeFee()))){
            MsgException.throwException("金额异常");
        }
        try {
            return merchantOrderService.toActivePay(merchantOrderDTO);
        } catch (Exception e){
            e.printStackTrace();
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }
    /**
     * 博实结pos机反扫支付
     * @param merchantOrderDTO
     * @return
     */
    @PostMapping("/posScanPay")
    public Result<Object> posScanPay(@RequestBody MerChantOrderDTO merchantOrderDTO) {
        //首先验签
        Map<String, String> token = TokenUtil.getToken(merchantOrderDTO.getTimestamp(), merchantOrderDTO.getRequestId());
        boolean sign = token.get("TOKEN").equals(merchantOrderDTO.getToken());
        System.out.println(token);
        MsgException.check(!sign,"签名错误");
        //通过后查询商户信息
        DeviceStock deviceStock = deviceStockService.checkBind(merchantOrderDTO.getSn());
        MerchantBaseInfo merchantBaseInfoById = merchantBaseInfoService.getMerchantBaseInfoById(Integer.valueOf(deviceStock.getActMercId()));
        MsgException.checkNull(merchantBaseInfoById, "找不到商户");
        merchantOrderDTO.setMerchantCode(merchantBaseInfoById.getMerchantCode());
        //校验金额
        if (!StringUtil.isMoney(String.valueOf(merchantOrderDTO.getConsumeFee()))){
            MsgException.throwException("金额异常");
        }
        //进行支付操作
        try {
            return merchantOrderService.toActivePay(merchantOrderDTO);
        } catch (Exception e){
            e.printStackTrace();
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }


    /**
     * 主扫会员支付
     * @param memberScanPayDTO
     * @return
     */
    @PostMapping("/memberScanPay")
    @ApiOperation(tags = {"页面-收款"}, value = "扫会员码支付", notes = "扫会员码支付", httpMethod = "POST")
    public Result<MemberScanVO> memberScanPay(@RequestBody MemberScanPayDTO memberScanPayDTO) {
        log.error("=========参数===============" + JSONObject.toJSONString(memberScanPayDTO));
        UserApp tokenUa = userAppService.queryUserAppByToken();
        memberScanPayDTO.setMerchantCode(tokenUa.getMerchantCode());
        try{
            return merchantOrderService.toMemberScanPay(memberScanPayDTO);
        }catch (Exception e){
            e.printStackTrace();
            return ResultGenerator.genFailResult(e.getMessage());
        }
    }

    /**
     * merchantIncome:(添加收益记录). <br/>
     *
     *
     * @author Administrator
     * @since JDK 1.8
     */
    private void merchantIncome(MerchantOrder merchantOrder, String payTypeCode) {
        MerchantIncome merchantIncome = new MerchantIncome();
        if ("1".equals(payTypeCode)) {
            merchantIncome.setMerchantCode(merchantOrder.getMerchantCode());
            merchantIncome.setMerchantName(merchantOrder.getMerchantName());
            merchantIncome.setStoreId(merchantOrder.getStoreId());
            merchantIncome.setStoreName(merchantOrder.getStoreName());
            merchantIncome.setDealFee(merchantOrder.getConsumeFee());
            merchantIncome.setIncomeFee(merchantOrder.getEnterFee());
            merchantIncome.setPayTypeCode(payTypeCode);
            merchantIncome.setPayTypeName("微信");
            merchantIncome.setCreateTime(merchantOrder.getTransDt());
            merchantIncomeService.saveMerchantIncome(merchantIncome);
        } else if ("0".equals(payTypeCode)) {
            merchantIncome.setMerchantCode(merchantOrder.getMerchantCode());
            merchantIncome.setMerchantName(merchantOrder.getMerchantName());
            merchantIncome.setStoreId(merchantOrder.getStoreId());
            merchantIncome.setStoreName(merchantOrder.getStoreName());
            merchantIncome.setDealFee(merchantOrder.getConsumeFee());
            merchantIncome.setIncomeFee(merchantOrder.getEnterFee());
            merchantIncome.setPayTypeCode(payTypeCode);
            merchantIncome.setPayTypeName("支付宝");
            merchantIncome.setCreateTime(merchantOrder.getTransDt());
            merchantIncomeService.saveMerchantIncome(merchantIncome);
        }
    }

    /**
     * LeshuaPay:(乐刷支付). <br/>
     *
     * @param merchantOrderDTO
     * @return
     *
     * @author Administrator
     * @since JDK 1.8
     */
    private Result<Map<String, Object>> LeshuaPay(MerChantOrderDTO merchantOrderDTO, MerchantOrder order,
                                                  MerchantBaseInfo queryMerchantBaseInfo) {
        throw new MsgException("不支持的方法");
//        UserApp userApp = new UserApp();
//        userApp.setMerchantCode(queryMerchantBaseInfo.getMerchantCode());
//        userApp.setUserType("promoter");
//        userApp = userAppService.queryUserApp(userApp);
//        Map<String, Object> resultMap = new HashMap<>(16);
//        Map<String, String> reqMap = new HashMap<>(16);
//        reqMap.put("service", "upload_authcode");
//        reqMap.put("merchant_id", userApp.getLeshuaMchId());
//        reqMap.put("auth_code", merchantOrderDTO.getAuthCode());
//        reqMap.put("third_order_id", order.getOrderNumber());
//        reqMap.put("amount", merchantOrderDTO.getConsumeFee() * 100 + "");
//        reqMap.put("notify_url", ParametersUtil.domain + "/wap/merchant/appScanPayLeshuaCallBack");
//        reqMap.put("nonce_str", StringUtil.genRandomNum(32));
//        String requestPay;
//        try {
//            requestPay = leshuaService.requestPay(reqMap, ParametersUtil.leshuapaykey, true);
//            Map<String, Object> map = XmlUtil.toMapLeshua(requestPay);
//            String resp_code = (String) map.get("resp_code");
//            if ("0".equals(resp_code)) {// 0表示通信成功
//                String result_code = (String) map.get("result_code");
//                if ("0".equals(result_code)) {// 0表示业务成功
//                    String status = (String) map.get("status");// 0支付中 2支付成功 6订单关闭 8支付失败 10退款中 11退款成功 12退款失败
//                    if ("2".equals(status)) {
//                        String leshua_order_id = (String) map.get("leshua_order_id");
//                        String payTime = (String) map.get("pay_time");
//                        SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                        order.setTransDt(sFormat.parse(payTime));
//                        merchantOrderService.saveMerchantOrderStatus(leshua_order_id, order);
//                        resultMap.put("data", order);
//                        resultMap.put("message", "交易成功");
//                        String pay_way = (String) map.get("pay_way");
//                        if ("WXZF".equals(pay_way)) {
//                            merchantIncome(order, "1");
//                        } else if ("ZFBZF".equals(pay_way)) {
//                            merchantIncome(order, "0");
//                        }
//                        UserApp userApp2 = new UserApp();
//                        if (StringUtil.isNotEmpty(userApp.getParentId())) {
//                            userApp2.setUserId(userApp.getParentId());// 当前商户的上级
//                            userApp2 = userAppService.queryUserApp(userApp2);
//                            double extendProfit = userApp2.getExtendProfit() == null ? 0d : userApp2.getExtendProfit();// 现在的推广分润
//                            extendProfit = extendProfit + Double.parseDouble(order.getShareMoney());// 添加之后的推广分润
//                            double tradeMoney = userApp2.getTradeMoney() == null ? 0d : userApp2.getTradeMoney();
//                            userApp2.setTradeMoney(tradeMoney + order.getConsumeFee());// 交易额
//                            userApp2.setExtendProfit(extendProfit);
//                            userAppService.updateUserApp(userApp2);
//                        }
//                        return ResultGenerator.genSuccessResult(resultMap);
//                    } else {
//                        resultMap.put("data", order);
//                        return ResultGenerator.genTransunKonwResult("交易未知", resultMap);
//                    }
//                } else {
//                    resultMap.put("data", order);
//                    return ResultGenerator.genFailResult("支付失败", resultMap);
//                }
//            } else {
//                resultMap.put("data", order);
//                return ResultGenerator.genFailResult("支付失败", resultMap);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            resultMap.put("data", order);
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return ResultGenerator.genFailResult("支付失败", resultMap);
//        }
    }

    // 查询微信订单支付状态
    @PostMapping("/queryWechatOrderResult")
    @ApiOperation(value = "查询微信订单支付状态", notes = "查询微信订单支付状态", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "queryOrderDTO", value = "扫码支付需要传递的参数实例", paramType = "body", dataType = "queryOrderDTO", required = true)})
    public Result queryWechatOrderResult(@RequestBody QueryOrderDTO queryOrderDTO) throws Exception {
        throw new MsgException("暂不支持该接口");
//        if (StringUtil.isEmpty(queryOrderDTO.getMerchantCode())) {// 校验参数是否完整
//            return ResultGenerator.genFailResult("没有商家编码");
//        }
//        if (StringUtil.isEmpty(queryOrderDTO.getOrderNumber())) {
//            return ResultGenerator.genFailResult("没有订单编号");
//        }
//        MerchantBaseInfo merchantBaseInfo = new MerchantBaseInfo();
//        merchantBaseInfo.setMerchantCode(queryOrderDTO.getMerchantCode());
//        List<MerchantBaseInfo> queryMerchantBaseInfoList = merchantBaseInfoService
//                .queryMerchantBaseInfoList(merchantBaseInfo);
//        if (queryMerchantBaseInfoList == null || queryMerchantBaseInfoList.size() == 0) {
//            return ResultGenerator.genFailResult("无商家信息");
//        }
//        merchantBaseInfo = queryMerchantBaseInfoList.get(0);
//        Map<String, String> requestMap = new HashMap<String, String>(16);
//        requestMap.put("appid", "wxed824282c345b7a0");
//        requestMap.put("mch_id", "1551169371");
//        requestMap.put("sub_mch_id", merchantBaseInfo.getSubMchId());
//        requestMap.put("out_trade_no", queryOrderDTO.getOrderNumber());
//        requestMap.put("nonce_str", StringUtil.genRandomNum(10));
//        requestMap.put("sign_type", "HMAC-SHA256");
//        requestMap.put("sign", WechatSignUtil.sha256Sign(requestMap, "7F05NZBTJ3XNDK5HLSDC3H25ZXOQKDHT"));
//        String requestResult = WXPayHttpUtil.WXHttpPostXMLWithoutCert("https://api.mch.weixin.qq.com/pay/orderquery",
//                requestMap);
//        Map<String, String> map = WXPayXmlUtil.parseXMLToMap(requestResult);
//        Map<String, Object> resultMap = new HashMap<>();
//        MerchantOrder order = queryOrderDTO.convertMerchantOrder();
//        if ("SUCCESS".equalsIgnoreCase(map.get("return_code"))) {
//            if ("SUCCESS".equalsIgnoreCase(map.get("result_code"))
//                    && "SUCCESS".equalsIgnoreCase(map.get("trade_state"))) {
//                String transaction_id = map.get("transaction_id");
//                String time_end = map.get("time_end");
//                SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                order.setTransDt(sFormat.parse(time_end));
//                order = merchantOrderService.saveMerchantOrderStatus(transaction_id, order);// 更新订单的支付状态
//                resultMap.put("merchantOrder", order);
//                merchantIncome(order, "1");
//                return ResultGenerator.genSuccessResult(resultMap);
//            } else {
//                boolean isNeedQuery = Arrays.asList(wechatPayNotSureResult).contains(map.get("trade_state"));// 判断是否需要条用查询接口
//                if (isNeedQuery) {
//                    resultMap.put("merchantOrder", order);
//                    return ResultGenerator.genTransunKonwResult("交易未知", resultMap);
//                } else {
//                    return ResultGenerator.genFailResult("交易失败");
//                }
//            }
//        }
//        return ResultGenerator.genFailResult("交易失败");
    }

    @PostMapping("/leshuaPayQuery")
    @ApiOperation(value = "乐刷交易结果查询", notes = "乐刷交易结果查询", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "QueryOrderDTO", value = "QueryOrderDTO实体类", paramType = "QueryOrderDTO", dataType = "QueryOrderDTO"),})
    public Result<Object> leshuaPayQuery(@RequestBody QueryOrderDTO queryOrderDTO) throws Exception {
        // 校验参数是否完整
        MsgException.throwException("当前接口不可用，请升级APP后再使用！");
        return null;
//        if (StringUtil.isEmpty(queryOrderDTO.getMerchantCode())) {
//            return ResultGenerator.genFailResult("没有商家编码");
//        }
//        if (StringUtil.isEmpty(queryOrderDTO.getOrderNumber())) {
//            return ResultGenerator.genFailResult("没有订单编号");
//        }
//        MerchantBaseInfo queryMerchantBaseInfo = new MerchantBaseInfo();
//        queryMerchantBaseInfo.setMerchantCode(queryOrderDTO.getMerchantCode());
//        queryMerchantBaseInfo = merchantBaseInfoService.queryMerchantBaseInfo(queryMerchantBaseInfo);
//        if (queryMerchantBaseInfo == null) {
//            return ResultGenerator.genFailResult("无商家信息");
//        }
//        Map<String, Object> resultMap = new HashMap<String, Object>(16);
//        Map<String, String> reqMap = new HashMap<String, String>(16);
//        reqMap.put("service", "query_status");
//        reqMap.put("merchant_id", queryOrderDTO.getLeshuaMchId());
//        reqMap.put("third_order_id", queryOrderDTO.getOrderNumber());
//        reqMap.put("nonce_str", StringUtil.genRandomNum(32));
//        String requestPay = leshuaService.requestPay(reqMap, "60E3F31EDEC8061C33721737B36FA86D", true);
//        log.info("======支付结果====" + requestPay);
//        Map<String, Object> map = XmlUtil.toMapLeshua(requestPay);
//        String resp_code = (String) map.get("resp_code");
//        if ("0".equals(resp_code)) {// 0表示通信成功
//            String result_code = (String) map.get("result_code");
//            MerchantOrder order = queryOrderDTO.convertMerchantOrder();// 0表示业务成功
//            if ("0".equals(result_code)) {
//                // 0支付中 2支付成功 6订单关闭 8支付失败 10退款中 11退款成功 12退款失败
//                String status = (String) map.get("status");
//                if ("2".equals(status)) {
//                    String leshua_order_id = (String) map.get("leshua_order_id");
//                    String payTime = (String) map.get("pay_time");
//                    String pay_way = (String) map.get("pay_way");
//                    SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                    order.setTransDt(sFormat.parse(payTime));
//                    order = merchantOrderService.saveMerchantOrderStatus(leshua_order_id, order);
//                    if ("WXZF".equals(pay_way)) {
//                        merchantIncome(order, "1");
//                    } else if ("ZFBZF".equals(pay_way)) {
//                        merchantIncome(order, "0");
//                    }
//                    return ResultGenerator.genSuccessResult(order);
//                } else if ("8".equals(status)) {
//                    return ResultGenerator.genFailResult("交易失败");
//                } else if ("0".equals(status)) {
//                    return ResultGenerator.genTransunKonwResult("支付中", order);
//                } else if ("6".equals(status)) {
//                    return ResultGenerator.genFailResult("订单关闭");
//                } else if ("10".equals(status)) {
//                    return ResultGenerator.genFailResult("退款中");
//                } else if ("11".equals(status)) {
//                    return ResultGenerator.genFailResult("退款成功");
//                } else if ("12".equals(status)) {
//                    return ResultGenerator.genFailResult("退款失败");
//                }
//                log.info("=== resultMap === \n{}", JSON.toJSONString(resultMap));
//            } else {
//                return ResultGenerator.genFailResult("查询失败");
//            }
//        } else {
//            return ResultGenerator.genFailResult("查询失败");
//        }
//        return ResultGenerator.genFailResult("交易失败");
    }

    @GetMapping("/tradeQuery/{orderNumber}")
    @ApiOperation(value = "交易订单支付结果查询", notes = "交易订单支付结果查询", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNumber", value = "查询的orderNumber", paramType = "orderNumber", required = true, dataType = "String")})
    public Result<Object> tradeQuery(@PathVariable String orderNumber) throws Exception {
        // 校验参数是否完整
        if (StringUtil.isEmpty(orderNumber)) {
            return ResultGenerator.genFailResult("无订单号");
        }
        QueryWrapper<MerchantOrder> queryWrapper = new QueryWrapper<MerchantOrder>()
                .eq("orderNumber",orderNumber);
        MerchantOrder order = merchantOrderService.getOne(queryWrapper);
        if(order == null){
            return ResultGenerator.genFailResult("订单数据异常");
        }
        //支付成功
        if("1".equals(order.getStatus())){
            return ResultGenerator.genSuccessResult("获取成功",order);
        }
        String aisleSwitch = order.getAisleSwitch();
        MerchantChannelStatus channel = null;
        switch (aisleSwitch){
            case "2":
                channel = merchantChannelStatusMapper.getByMerchantCode(order.getMerchantCode(),1);
                break;
            default:
                channel = merchantChannelStatusMapper.getByMerchantCode(order.getMerchantCode(),Integer.valueOf(aisleSwitch));
                break;
        }
        if(channel != null){
            JSONObject result = null;
            switch (channel.getChannel()){
                case 1:
                    result = sxfPayService.tradeQuery(order,channel.getMerchantId());
                    break;
                case 3:
                    result = ryxPayService.tradeQuery(order,channel.getMerchantId());
                    break;
                case 4:
                    result = ysPayOldService.tradeQuery(order,channel.getMerchantId());
                    break;
            }

            if(result != null){
                merchantOrderService.updateOrderStatus(result,order);
                String status = result.getString("payStatus");
                if("1".equals(status)){
                    order.setStatus("1");
                }
            }
        }
        return ResultGenerator.genSuccessResult("获取成功",order);
    }

    @GetMapping("/closeOrder")
    @ApiOperation(value = "订单关闭", notes = "订单关闭", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNumber", value = "订单号", paramType = "orderNumber", dataType = "orderNumber"),})
    public Result<?> closeOrder(@RequestParam String orderNumber)
            throws Exception {
        if(StringUtil.isEmpty(orderNumber)){
            return ResultGenerator.genFailResult("订单号不能为空！");
        }
        QueryWrapper<MerchantOrder> queryWrapper = new QueryWrapper<MerchantOrder>().eq("orderNumber",orderNumber);
        MerchantOrder order = merchantOrderService.getOne(queryWrapper);
        if(order == null){
            return ResultGenerator.genFailResult("订单不存在！！");
        }
        QueryWrapper<MerchantChannelStatus> channelStatusQueryWrapper = new QueryWrapper<>();
        channelStatusQueryWrapper.eq("merchantCode",order.getMerchantCode())
            .in("channel", 1, 3);
        MerchantChannelStatus channelStatus = merchantChannelStatusMapper.selectOne(channelStatusQueryWrapper);
        if(channelStatus == null){
            return ResultGenerator.genFailResult("当前商户通道未配置！！");
        }
        Map<String, Object> reuslt = null;
        try {
            if("1".equals(order.getAisleSwitch())){
                return ResultGenerator.genFailResult("通道已关闭");
            }else if("2".equals(order.getAisleSwitch())){
                reuslt = sxfPayService.closeOrder(orderNumber, channelStatus.getMerchantId());
            }else if("3".equals(order.getAisleSwitch())){
                reuslt = ryxPayService.closeOrder(orderNumber, channelStatus.getMerchantId());
            }else if("4".equals(order.getAisleSwitch())){
                log.info("<================银盛暂无订单关闭接口===========>");
                return ResultGenerator.genSuccessResult("成功",null);
            }else{
                return ResultGenerator.genFailResult("未查询到其他通道");
            }
        }catch (Exception e){
            return ResultGenerator.genFailResult(e.getMessage());
        }
        if((Integer) reuslt.get("code") == ResultCode.FAIL.code()){
            return ResultGenerator.genFailResult(reuslt.get("msg"));
        }
        return ResultGenerator.genSuccessResult("关闭成功",reuslt);
    }

    /*@GetMapping("/leshuaCloseOrder")
    @ApiOperation(value = "乐刷订单关闭", notes = "乐刷订单关闭", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "leshuaMchId", value = "乐刷商户号", paramType = "leshuaMchId", dataType = "leshuaMchId"),
            @ApiImplicitParam(name = "orderNumber", value = "订单号", paramType = "orderNumber", dataType = "orderNumber"),})
    public Result<?> leshuaCloseOrder(@RequestParam String leshuaMchId, @RequestParam String orderNumber)
            throws Exception {
        Map<String, String> reqMap = new HashMap<>(16);
        reqMap.put("service", "close_order");
        reqMap.put("merchant_id", leshuaMchId);
        reqMap.put("third_order_id", orderNumber);
        reqMap.put("nonce_str", StringUtil.genRandomNum(32));
        String requestPay = leshuaService.requestPay(reqMap, "60E3F31EDEC8061C33721737B36FA86D", true);
        Map<String, Object> map = XmlUtil.toMapLeshua(requestPay);
        String resp_code = (String) map.get("resp_code");
        String result_code = (String) map.get("result_code");
        if ("0".equals(resp_code) && "0".equals(result_code)) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("关闭失败");
        }
    }*/

    // 查询商家账户余额
    @PostMapping("/queryMerchantOrderFee")
    @ApiOperation(value = "查询商家账户余额", notes = "查询商家账户余额", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MerchantOrder", value = "查询的商家编码", paramType = "body", dataType = "MerchantOrder", required = true)})
    public Result queryMerchantOrderFee(@RequestBody MerchantOrder merchantOrder) {
        // 校验参数是否完整
        if (StringUtil.isEmpty(merchantOrder.getMerchantCode())) {
            return ResultGenerator.genFailResult("没有商家编码");
        }
        Map<String, Object> queryMap = new HashMap<String, Object>();
        // 设置查询的开始时间
        Calendar startCalendar = Calendar.getInstance();
        try {
            startCalendar.setTime(new SimpleDateFormat("yyyy-MM-dd").parse("2019-09-23"));
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        queryMap.put("startTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(startCalendar.getTime()));
        // 设置查询的结束时间
        Calendar endCalendar = Calendar.getInstance();
        try {
            endCalendar.setTime(merchantOrder.getEndTime());
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        endCalendar.set(Calendar.HOUR_OF_DAY, 23);
        endCalendar.set(Calendar.MINUTE, 59);
        endCalendar.set(Calendar.SECOND, 59);
        queryMap.put("endTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(endCalendar.getTime()));
        queryMap.put("merchantCode", merchantOrder.getMerchantCode());
        if (merchantOrder.getSize() == null || merchantOrder.getSize() == 0) {
            merchantOrder.setSize(ProjectConstant.PAGE_SIZE);
        }
        if (merchantOrder.getPage() == null || merchantOrder.getPage() == 0) {
            merchantOrder.setPage(1);
        }
        queryMap.put("pageSize", merchantOrder.getSize());
        queryMap.put("offset", (merchantOrder.getPage() - 1) * merchantOrder.getSize());
        queryMap.put("status", 1);
        Double enterFee = merchantOrderService.queryMerchantOrderFeeByTime(queryMap);// 查询交易成功的交易费用
        queryMap.put("orderType", 1);
        Double totalRechargeFee = memberOrderService.queryMemberOrderTotalOrderFeeByTime(queryMap);// 查询会员充值的金额
        List<MerchantOrder> merchantOrders = merchantOrderService.queryMerchantOrderPageByTime(queryMap);
        // List<MemberOrder> memberOrderList =
        // memberOrderService.queryMemberOrderPage(queryMap);
        Map<String, Object> resultMap = new HashMap<>(16);
        Integer count = merchantOrderService.queryMerchantOrderPageCountByTime(queryMap);
        // 返回参数
        PageInfo<MerchantOrder> pager = new PageInfo<>(count.longValue(),
                (long) StringUtil.getPageCount(count, merchantOrder.getSize()), merchantOrder.getPage().longValue(),
                merchantOrder.getSize().longValue(), merchantOrders);
        resultMap.put("pager", pager);
        resultMap.put("merchantOrders", merchantOrders);
        return ResultGenerator.genSuccessResult(resultMap);
    }

    @GetMapping("/returnOrder")
    @ApiOperation(value = "商家退款", notes = "商家给用户交易退款", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNumber", value = "待退款的订单编号", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "noticeCode", value = "退款通知的编号", paramType = "query", dataType = "String")})
    public Result<Object> returnOrder(@RequestParam String orderNumber, @RequestParam String noticeCode) {
        merchantOrderService.returnOrder(orderNumber,null,"app", noticeCode);
        return ResultGenerator.genSuccessResult("退款成功",null);
    }

    @GetMapping("/returnOrderV2")
    @ApiOperation(value = "商家退款", notes = "商家给用户交易退款", httpMethod = "GET")
    public Result<Object> returnOrder(@RequestParam String orderNumber, @RequestParam String noticeCode, String payPassword) {
        merchantOrderService.apiReturnOrderV2(orderNumber,null,"app", noticeCode, payPassword);
        return ResultGenerator.genSuccessResult("退款成功",null);
    }

    /**
     * leshuaReturn:(乐刷退款). <br/>
     *
     *
     * @author Administrator
     * @since JDK 1.8
     */
    /*private Result<Object> leshuaReturn(MerchantOrder queryMerchantOrder, String leshuaMchId) {
        Map<String, String> reqMap = new HashMap<>(16);
        String merchant_refund_id = StringUtil.getBillno();
        reqMap.put("service", "unified_refund");
        reqMap.put("merchant_id", leshuaMchId);
        reqMap.put("third_order_id", queryMerchantOrder.getOrderNumber());
        reqMap.put("refund_amount", queryMerchantOrder.getConsumeFee() * 100 + "");
        reqMap.put("merchant_refund_id", merchant_refund_id);// 退款随机字符 在查询退款的时候需要用到
        reqMap.put("nonce_str", StringUtil.genRandomNum(32));
        reqMap.put("notify_url", systemConfigService.querySystemConfigValue("LeshuaRefundBack"));

        String requestPay;
        try {
            requestPay = leshuaService.requestPay(reqMap, "60E3F31EDEC8061C33721737B36FA86D", true);
            Map<String, Object> map = XmlUtil.toMapLeshua(requestPay);
            String resp_code = (String) map.get("resp_code");
            if ("0".equals(resp_code)) {
                // 0表示通信成功
                String result_code = (String) map.get("result_code");
                if ("0".equals(result_code)) {
                    // 0表示业务成功
                    getProfit(queryMerchantOrder);
                    Date refundTime = DateUtils.parse(map.get("refund_time").toString(), "yyyy-MM-dd HH:mm:ss");
                    queryMerchantOrder.setUpdateTime(refundTime);
                    queryMerchantOrder.setStatus("2");
                    return ResultGenerator.genSuccessResult("退款成功");
                } else {
                    queryMerchantOrder.setStatus("3");
                    String error_msg = (String) map.get("error_msg");
                    return ResultGenerator.genFailResult(error_msg);
                }
            } else {
                // 0表示业务成功
                queryMerchantOrder.setStatus("3");
                return ResultGenerator.genFailResult("退款失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            queryMerchantOrder.setStatus("3");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultGenerator.genFailResult("退款失败");
        } finally {
            queryMerchantOrder.setId(null);
            queryMerchantOrder.setLeshuaMerchantRefundId(merchant_refund_id);
            queryMerchantOrder.setUpdateTime(new Date());
            merchantOrderService.saveMerchantOrder(queryMerchantOrder);
        }
    }*/

    // 微信退款方法
    private Boolean wechatReturnOrder(MerchantOrder merchantOrder) {
        // 查询商家的subMchId
//        MerchantBaseInfo queryMerchantBaseInfo = new MerchantBaseInfo();
//        queryMerchantBaseInfo.setMerchantCode(merchantOrder.getMerchantCode());
//        queryMerchantBaseInfo = merchantBaseInfoService.queryMerchantBaseInfo(queryMerchantBaseInfo);
//        Map<String, String> wechatMap = new HashMap<>();
//        wechatMap.put("appid", "wxed824282c345b7a0");
//        wechatMap.put("mch_id", "1551169371");
//        wechatMap.put("sub_mch_id", queryMerchantBaseInfo.getSubMchId());
//        wechatMap.put("nonce_str", StringUtil.genRandomNum(10));
//        wechatMap.put("sign_type", "HMAC-SHA256");
//        wechatMap.put("out_trade_no", merchantOrder.getOrderNumber());
//        wechatMap.put("out_refund_no", StringUtil.genRandomNum(10));
//        wechatMap.put("total_fee", ((int) (merchantOrder.getConsumeFee() * 100)) + "");
//        wechatMap.put("refund_fee", ((int) (merchantOrder.getConsumeFee() * 100)) + "");
//        wechatMap.put("sign", WechatSignUtil.sha256Sign(wechatMap, "7F05NZBTJ3XNDK5HLSDC3H25ZXOQKDHT"));
//        String resultString = WXPayHttpUtil.WXHttpPostXMLWithCert("https://api.mch.weixin.qq.com/secapi/pay/refund", wechatMap, "/home/syb/resources/wechatCert/apiclient_cert.p12");
//        Map<String, String> resultMap = WXPayXmlUtil.parseXMLToMap(resultString);
//        if ("SUCCESS".equalsIgnoreCase(resultMap.get("return_code"))) {
//            if ("SUCCESS".equalsIgnoreCase(resultMap.get("result_code"))) {
//                return true;
//            } else if ("FAIL".equalsIgnoreCase(resultMap.get("result_code"))) {
//
//            }
//        }
        return false;
    }

    private Boolean aliReturnOrder(MerchantOrder order) {
        return false;
//        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
//        request.setBizContent("{" + "\"out_trade_no\":\"" + order.getOrderNumber() + "\"," + "\"refund_amount\":"
//                + order.getConsumeFee() + "" + "}");
//        // 获取对应商户的授权信息
//        UserApp queryUserApp = new UserApp();
//        queryUserApp.setMerchantCode(order.getMerchantCode());
//        queryUserApp.setUserType("promoter");
//        List<UserApp> queryUserAppList = userAppService.queryUserAppList(queryUserApp);
//        if (queryUserAppList == null || queryUserAppList.size() == 0) {
//            return false;
//        }
//        queryUserApp = queryUserAppList.get(0);
//        if (StringUtil.isEmpty(queryUserApp.getAppAuthToken())) {
//            return false;
//        }
//        request.putOtherTextParam("app_auth_token", queryUserApp.getAppAuthToken());
//        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
//                AliPayParam.getAppId(), AliPayParam.getPri(), "json", "GBK", AliPayParam.getPub(), "RSA2");
//        AlipayTradeRefundResponse response = null;
//        try {
//            response = alipayClient.execute(request);
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//        }
//        if (response != null && response.isSuccess()) {
//            return true;
//        }
//        return false;
    }

    // 店员退款发给商家的通知
    @GetMapping("/returnOrderSend")
    @ApiOperation(value = "商家退款通知", notes = "店员退款发给商家的通知", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNumber", value = "待退款的订单编号", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "userId", value = "发起退款的人员id", paramType = "query", dataType = "Integer", required = true)})
    public Result returnOrderSend(@RequestParam String orderNumber, @RequestParam Long userId) {
        if (StringUtil.isEmpty(orderNumber)) {
            return ResultGenerator.genFailResult("无订单编号");
        }
        if (StringUtil.isEmpty(userId)) {
            return ResultGenerator.genFailResult("无发起人员信息！");
        }
        // 查询退款发起人信息
        UserApp startUserApp = new UserApp();
        startUserApp.setUserId(userId);
        List<UserApp> queryUserAppList2 = userAppService.queryUserAppList(startUserApp);
        if (queryUserAppList2 == null || queryUserAppList2.size() == 0) {
            return ResultGenerator.genFailResult("发起人信息不正确！");
        } else {
            startUserApp = queryUserAppList2.get(0);
        }
        MerchantOrder queryMerchantOrder = new MerchantOrder();
        queryMerchantOrder.setOrderNumber(orderNumber);
        List<MerchantOrder> queryMerchantOrderList = merchantOrderService.list(new QueryWrapper<>(queryMerchantOrder));
        if (queryMerchantOrderList == null || queryMerchantOrderList.size() == 0) {
            return ResultGenerator.genFailResult("该订单不存在");
        } else {
            queryMerchantOrder = queryMerchantOrderList.get(0);
        }

        UserApp queryUserApp = new UserApp();
        queryUserApp.setMerchantCode(queryMerchantOrder.getMerchantCode());
        queryUserApp.setUserType("promoter");
        List<UserApp> queryUserAppList = userAppService.queryUserAppList(queryUserApp);// 查询当前商户的用户信息
        if (queryUserAppList == null || queryUserAppList.size() == 0) {
            return ResultGenerator.genFailResult("无商户信息");
        } else {
            queryUserApp = queryUserAppList.get(0);
        }

        MerchantBaseInfo info = new MerchantBaseInfo();
        info.setMerchantCode(queryMerchantOrder.getMerchantCode());
        info = merchantBaseInfoService.queryMerchantBaseInfo(info);

        // 生成退款通知
        Notice notice = new Notice(1, 2, queryUserApp);
        notice.setOrderNumber(orderNumber);
        List<String> alias = new ArrayList<String>();
        alias.add(queryUserApp.getUserId().toString());

        String notificationContent = info.getAlias() + "店" + startUserApp.getUserName() + "店员发起"
                + queryMerchantOrder.getPayTypeName() + "退款 ￥" + queryMerchantOrder.getConsumeFee() + "，请及时审核。";
        generalPushUtil.sendAllPlatByAlias(alias, "店员退款审核通知", notificationContent, "1");
        // 插入通知信息
        notice.setConrtent(info.getAlias() + "店" + startUserApp.getUserName() + "店员发起");
        noticeService.saveNotice(notice);
        return ResultGenerator.genSuccessResult();
    }

    // 拒绝店员退款接口
    @GetMapping("/confuseStaffReturnOrder")
    @ApiOperation(value = "商户拒绝员工退款", notes = "商户拒绝员工退款", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "noticeCode", value = "退款通知的编号", paramType = "query", dataType = "String", required = true)})
    public Result confuseStaffReturnOrder(@RequestParam String noticeCode) {
        if (StringUtil.isEmpty(noticeCode)) {
            return ResultGenerator.genFailResult("无通知编号");
        }
        // 更新通知的处理状态
        Notice queryNotice = new Notice();
        queryNotice.setNoticeCode(noticeCode);
        List<Notice> queryNoticeList = noticeService.queryNoticeList(queryNotice);
        if (queryNoticeList != null && queryNoticeList.size() > 0) {
            queryNotice = queryNoticeList.get(0);
            queryNotice.setIsDeal(1);
            queryNotice.setIsApply(0);
            noticeService.updateNotice(queryNotice);
        }
        return ResultGenerator.genSuccessResult();
    }

    @PostMapping("/memberRechargeQuery")
    @ApiOperation(value = "轮循会员充值订单", notes = "轮循会员充值订单", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "MemberOrderDTO", value = "MemberOrderDTO", paramType = "MemberOrderDTO", dataType = "MemberOrderDTO", required = true)})
    public Result memberRechargeQuery(@RequestBody MemberOrderDTO memberOrderDTO) {
        String aisle = memberOrderDTO.getAisle();
        MemberOrder memberOrder = memberOrderDTO.convertMemberOrder();
        Map<String, Object> map = new HashMap<String, Object>(16);
        map.put("aisle", aisle);
        map.put("orderNumber", memberOrderDTO.getOrderNumber());
        map.put("authCode", memberOrderDTO.getAuthCode());
        MerchantMenber merchantMenber = new MerchantMenber();
        merchantMenber.setMemberCode(memberOrderDTO.getMemberCode());
        merchantMenber = merchantMenberService.queryMerchantMenber(merchantMenber);
        MerchantMenberRecharge merchantMenberRecharge = memberOrderDTO.convertMerchantMenberRecharge(merchantMenber);
        try {
//			Result<Map<String, Object>> transQuery = transQueryService.TransQuery(map);
            MerchantOrder merchantOrder = new MerchantOrder();
            merchantOrder.setOrderNumber(memberOrder.getOrderNumber());
            merchantOrder = merchantOrderService.queryMerchantOrder(merchantOrder);


            if ("5".equals(merchantOrder.getStatus())) {
                return ResultGenerator.genTransunKonwResult("交易未知", memberOrderDTO);
            }
            if ("0".equals(merchantOrder.getStatus())) {
                return ResultGenerator.genFailResult("交易失败");
            }
            if ("1".equals(merchantOrder.getStatus())) {
//				Map<String, Object> data = transQuery.getData();
//				String tradeNo = (String) data.get("tradeNo");
//				String payTime = (String) data.get("payTime");
                SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                memberOrder.setOrderStatus("1");
                memberOrder.setCreateDt(new Date());
                merchantMenberRecharge.setCreateDt(new Date());
//				MerchantOrder merchantOrder=new MerchantOrder();
//				merchantOrder.setOrderNumber(memberOrderDTO.getOrderNumber());
//				merchantOrder = merchantOrderService.queryMerchantOrder(merchantOrder);
                merchantOrder.setTransDt(new Date());
                merchantOrder.setStatus("1");
                if ("0".equals(aisle)) {
//					memberOrder.setAliPayTransNo(tradeNo);
                    merchantMenberRecharge.setPayType(0);
//					merchantOrder.setAliPayTransNo(tradeNo);
                    memberOrderService.saveMemberOrder(memberOrder);
                } else if ("1".equals(aisle)) {
//					memberOrder.setWeChatTransNo(tradeNo);
                    merchantMenberRecharge.setPayType(1);
//					merchantOrder.setWeChatTransNo(tradeNo);
                    memberOrderService.saveMemberOrder(memberOrder);
                } else if ("2".equals(aisle)) {
//					memberOrder.setLeshuaTransNo(tradeNo);
                    merchantMenberRecharge.setPayType(2);
                    memberOrder.setOrderStatus("1");
//					merchantOrder.setLeshuaTransNo(tradeNo);
                    memberOrderService.updateMemberOrder(memberOrder);
                }
//				merchantOrderService.updateMerchantOrder(merchantOrder);
                merchantMenberRechargeService.saveMerchantMenberRecharge(merchantMenberRecharge);
//				merchantMenberService.saveMerchantMenber(merchantMenber);
                Double totalRechargeFee = merchantMenber.getTotalRechargeFee() == null ? new Double(0)
                        : merchantMenber.getTotalRechargeFee();
                Double usableRechargeFee = merchantMenber.getUsableRechargeFee() == null ? new Double(0)
                        : merchantMenber.getUsableRechargeFee();
                Double totalGiveFee = merchantMenber.getTotalGiveFee() == null ? new Double(0) : merchantMenber.getTotalGiveFee();
                Double usableGiveFee = merchantMenber.getUsableGiveFee() == null ? new Double(0)
                        : merchantMenber.getUsableGiveFee();
                totalRechargeFee = totalRechargeFee + Double.parseDouble(memberOrderDTO.getOrderFee());
                usableRechargeFee = usableRechargeFee + Double.parseDouble(memberOrderDTO.getOrderFee());
                if (StringUtil.isNotEmpty(memberOrderDTO.getGiveMoney())) {
                    totalGiveFee = totalGiveFee + Double.parseDouble(memberOrderDTO.getGiveMoney());
                    usableGiveFee = usableGiveFee + Double.parseDouble(memberOrderDTO.getGiveMoney());
                }
                merchantMenber.setTotalRechargeFee(totalRechargeFee);
                merchantMenber.setUsableRechargeFee(usableRechargeFee);
                merchantMenber.setTotalGiveFee(totalGiveFee);
                merchantMenber.setUsableGiveFee(usableGiveFee);
                merchantMenberService.updateMerchantMenber(merchantMenber);
                merchantIncome(memberOrder);
                return ResultGenerator.genSuccessResult();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultGenerator.genFailResult("交易失败");
        }
        return ResultGenerator.genFailResult("交易失败");
    }

    /**
     * merchantIncome:(添加收益). <br/>
     *
     * @param memberOrder
     *
     * @author Administrator
     * @since JDK 1.8
     */
    private void merchantIncome(MemberOrder memberOrder) {
        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("2");
        merchantIncome.setPayTypeName("会员充值");
        merchantIncome.setCreateTime(memberOrder.getCreateDt());
        merchantIncomeService.saveMerchantIncome(merchantIncome);
    }

    @GetMapping("/couponList/{orderNumber}")
    public Result<List<Map<String, Object>>> getCouponListByOrderNumber(@PathVariable("orderNumber") String orderNumber) {
        List<Map<String, Object>> couponList = merchantOrderService.getCouponList(orderNumber);
        return ResultGenerator.genSuccessResult(couponList);
    }
}
