package com.ym.mec.collectfee.controller;

import com.alibaba.druid.sql.visitor.functions.Now;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ym.mec.collectfee.common.sms.SmsExample;
import com.ym.mec.collectfee.common.web.BaseController;
import com.ym.mec.collectfee.entity.*;
import com.ym.mec.collectfee.service.*;
import com.ym.mec.collectfee.utils.Constants;
import com.ym.mec.collectfee.utils.GenerateNum;
import com.ym.mec.collectfee.utils.ShortUrlUtil;
import com.ym.mec.collectfee.utils.yqpay.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

//@Api("支付")
@Slf4j
@RestController
@RequestMapping("yqpay")
@EnableScheduling   // 2.开启定时任务
public class YqPayController extends BaseController {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private YqPayService yqPayService;
    @Autowired
    private YqQueryService yqQueryService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private CourseGroupInfoService CourseGroupInfoService;

    @Autowired
    private ApplyInfoService applyInfoService;

    @Autowired
    private RenewalsService renewalsService;
    @Autowired
    private SchoolService schoolService;


    /**
     * 统一下单(乐团缴费)
     *
     * @return String
     * @throws Exception
     */
//    @ApiOperation(value = "提交支付", notes = "易乾支付统一下单")
    @PostMapping("/toPay")
    @Transactional(rollbackFor = Exception.class)
    public Object toPay(@ModelAttribute @Validated Order order) throws Exception {
        BigDecimal amount = new BigDecimal("0");
        School school = schoolService.get(order.getClassId());

        //计划招生人数有更新，更新
        orderService.getSchoolDetail(school.getSchoolId());

        Order userOrder = orderService.findRegOrderByStatus(order.getUserId(), 2);
        if (userOrder != null) {
            return failed("您已支付成功，请勿重复支付");
        }

        //判断用户是否已存在订单
        userOrder = orderService.findRegOrderByStatus(order.getUserId(), 1);
        if (userOrder != null) {
            return failed(HttpStatus.CONTINUE, "您有待支付的订单");
        }

        if (!school.getStatus().equals(2)) {
            return failed("乐团不在缴费状态！");
        }

        //1、判断已报名人数
        CourseGroupInfo courseGroupInfo = CourseGroupInfoService.get(order.getCourseId());
        if (courseGroupInfo.getRegNum().compareTo(courseGroupInfo.getPlanNum()) >= 0) {
            Integer nums = orderService.getPayingOrderNums(order.getCourseId());
            if (nums != null && nums > 0) {
                return failed(HttpStatus.FORBIDDEN, "当前排队人数" + nums + "人，请您耐心等待");
            } else {
                return succeed("招生人数已满！");
            }
        }

        //课程组价格
        BigDecimal courseFee = courseGroupInfo.getFeeAmount();
        amount = amount.add(courseFee);

        //获取乐器的价格
        ClassPathResource classPathResource = new ClassPathResource("instruments.json"); //解析乐器数据

        BigDecimal instrumentPrice = new BigDecimal("0");//乐器价格
        String instrumentName = "";//乐器名称

        String instrumentId = order.getInstrument();
        String jsonString = IOUtils.toString(new InputStreamReader(classPathResource.getInputStream(), "UTF-8"));
        Instrument instrument = JSONObject.parseObject(jsonString, Instrument.class);

        if (order.getInstrument() != null && !order.getInstrument().isEmpty()) {
            instrumentPrice = new BigDecimal(instrument.getInstruments().get(instrumentId).get("referencePrice"));
            instrumentName = (String) instrument.getInstruments().get(instrumentId).get("index") + "-" +
                    (String) instrument.getInstruments().get(instrumentId).get("name");
        }

        //2 版本为3.0（ 26），不收乐器费用，收押金800放乐器费用
        if (courseGroupInfo.getFeeType().equals(26) && order.getInstrument() != null && !order.getInstrument().isEmpty()) {
            instrumentPrice = new BigDecimal("800");
        }
        amount = amount.add(instrumentPrice);

        //辅件价格
        String adjunctIds = order.getAdjunct();
        BigDecimal adjunctPrice = new BigDecimal("0");//辅件价格
        String adjunctName = "";//辅件名称
        if (adjunctIds != null && !adjunctIds.isEmpty()) {
            String[] adjunctIdArr = adjunctIds.split(",");
            for (String adjunctId : adjunctIdArr) {
                adjunctPrice = adjunctPrice.add(new BigDecimal(instrument.getAuxiliaries().get(adjunctId).get("referencePrice")));
                adjunctName += (String) instrument.getAuxiliaries().get(adjunctId).get("name") + "|";
            }
        }
        amount = amount.add(adjunctPrice);

        ApplyInfo applyInfo = applyInfoService.get(order.getUserId());

        order.setPoName(school.getName());
        order.setVoicyPart(courseGroupInfo.getSubName());
        order.setGroupId(courseGroupInfo.getId());
        order.setAmount(amount);
        order.setRemark(instrumentName);
        order.setTuiFee(courseFee);
        order.setGoodsFee(instrumentPrice);
        order.setSdName(adjunctName + "教材|琴谱");
        order.setSdFee(adjunctPrice);
        order.setType(1);
        order.setUserName(applyInfo.getName());


        String orderNo = GenerateNum.getInstance().GenerateOrderNo(); //自己系统订单号
        order.setOrderNo(orderNo);
        order.setCreateTime(new Date()); //订单提交时间
        order.setStatus(1); //订单状态

        //获取分佣账户
        Integer branchId = 1002;//默认分佣账
        Account routingAccount = accountService.getRoutingAccount(branchId, amount);

        order.setAccount(routingAccount.getSellerNo());
        order.setUAccount(routingAccount.getId().toString());


        //1、插入订单
        orderService.insert(order);
        //2、修改已报名人数
        courseGroupInfo.setRegNum(courseGroupInfo.getRegNum() + 1);
        CourseGroupInfoService.upByIdAndVersion(courseGroupInfo);
        //3、修改分佣账户已收金额
        BigDecimal HasRouting = routingAccount.getHasRouting().add(order.getAmount());
        routingAccount.setHasRouting(HasRouting);
        accountService.upByIdAndVersion(routingAccount);

        Map rqMap = orderService.getPayMap(routingAccount, order, school); //获取支付map

        return succeed(rqMap);
    }


    /**
     * 重新支付订单
     *
     * @param order
     * @return
     * @throws Exception
     */
    @PostMapping("/rePay")
    @Transactional(rollbackFor = Exception.class)
    public Object rePay(@ModelAttribute @Validated Order order) throws Exception {
        BigDecimal amount = new BigDecimal("0");
        School school = schoolService.get(order.getClassId());

        Order userOrder = orderService.findRegOrderByStatus(order.getUserId(), 2);
        if (userOrder != null) {
            return failed("您已支付成功，请勿重复支付");
        }

        //判断用户是否已存在订单
        userOrder = orderService.findRegOrderByStatus(order.getUserId(), 1);
        if (userOrder == null) {
            return failed("您没有支付中的订单，请勿非法请求");
        }

        CourseGroupInfo courseGroupInfo = CourseGroupInfoService.get(order.getCourseId());

        //课程组价格
        BigDecimal courseFee = courseGroupInfo.getFeeAmount();
        amount = amount.add(courseFee);

        //获取乐器的价格
        ClassPathResource classPathResource = new ClassPathResource("instruments.json"); //解析乐器数据

        BigDecimal instrumentPrice = new BigDecimal("0");//乐器价格
        String instrumentName = "";//乐器名称

        String instrumentId = order.getInstrument();
        String jsonString = IOUtils.toString(new InputStreamReader(classPathResource.getInputStream(), "UTF-8"));
        Instrument instrument = JSONObject.parseObject(jsonString, Instrument.class);

        if (order.getInstrument() != null && !order.getInstrument().isEmpty()) {
            instrumentPrice = new BigDecimal(instrument.getInstruments().get(instrumentId).get("referencePrice"));
            instrumentName = (String) instrument.getInstruments().get(instrumentId).get("index") + "-" +
                    (String) instrument.getInstruments().get(instrumentId).get("name");
        }

        //2 版本为3.0（ 26），不收乐器费用，收押金800放乐器费用
        if (courseGroupInfo.getFeeType().equals(26) && order.getInstrument() != null && !order.getInstrument().isEmpty()) {
            instrumentPrice = new BigDecimal("800");
        }
        amount = amount.add(instrumentPrice);

        //辅件价格
        String adjunctIds = order.getAdjunct();
        BigDecimal adjunctPrice = new BigDecimal("0");//辅件价格
        String adjunctName = "";//辅件名称
        if (adjunctIds != null && !adjunctIds.isEmpty()) {
            String[] adjunctIdArr = adjunctIds.split(",");
            for (String adjunctId : adjunctIdArr) {
                adjunctPrice = adjunctPrice.add(new BigDecimal(instrument.getAuxiliaries().get(adjunctId).get("referencePrice")));
                adjunctName += (String) instrument.getAuxiliaries().get(adjunctId).get("name") + "|";
            }
        }
        amount = amount.add(adjunctPrice);

        ApplyInfo applyInfo = applyInfoService.get(order.getUserId());

        order.setPoName(school.getName());
        order.setVoicyPart(courseGroupInfo.getSubName());
        order.setGroupId(courseGroupInfo.getId());
        order.setAmount(amount);
        order.setRemark(instrumentName);
        order.setTuiFee(courseFee);
        order.setGoodsFee(instrumentPrice);
        order.setSdName(adjunctName + "教材|琴谱");
        order.setSdFee(adjunctPrice);
        order.setType(1);
        order.setUserName(applyInfo.getName());


        String orderNo = GenerateNum.getInstance().GenerateOrderNo(); //自己系统订单号
        order.setOrderNo(orderNo);
        order.setCreateTime(new Date()); //订单提交时间
        order.setStatus(1); //订单状态

        //获取分佣账户
        int accountId = Integer.parseInt(userOrder.getUAccount());
        Account routingAccount = accountService.get(accountId);

        order.setAccount(userOrder.getAccount());
        order.setUAccount(userOrder.getUAccount());

        //1.关闭订单
        HashMap<String, Object> upMap = new HashMap<>();
        upMap.put("status", 0);
        upMap.put("oldStatus", 1);
        upMap.put("id", userOrder.getId());
        orderService.updateByIdAndStatus(upMap);
        //2、插入订单
        orderService.insert(order);
        //3、修改分佣账户已收金额
        BigDecimal HasRouting = routingAccount.getHasRouting().add(order.getAmount()).subtract(userOrder.getAmount());
        routingAccount.setHasRouting(HasRouting);
        accountService.upByIdAndVersion(routingAccount);

        Map rqMap = orderService.getPayMap(routingAccount, order, school); //获取支付map

        return succeed(rqMap);
    }


    /**
     * 续费支付
     *
     * @return String
     * @throws Exception
     */
//    @ApiOperation(value = "续费支付", notes = "续费支付")
    @PostMapping("/renewalsPay")
    public Object renewalsPay(@ModelAttribute @Validated Renewals renewals) throws Exception {
        MecUser mecUser = applyInfoService.findMecUser(renewals.getUserId());
        if (mecUser == null) {
            return failed("续费用户不存在");
        }
        renewals.setBranchId(mecUser.getBranchId());

        //课程组价格
        List<MecCourse> courses = applyInfoService.queryUserCourse(renewals.getUserId());//获取续费课程
        if (courses == null) {
            return failed("您没有续费的课程");
        }
        MecCourse mecCourse4json = JSON.parseObject(renewals.getCourses(), MecCourse.class);
        if (mecCourse4json == null) {
            return failed("请选择续费课程");
        }

        //classType 小课1 大课2
        Integer buyCount = mecCourse4json.getBuyCount();
        if (buyCount <= 0 || buyCount > 20) {
            return failed("购买课程次数不能小于1,大于20");
        }
        BigDecimal amount = new BigDecimal("0"); //课程总价
        String remark = "";
        List<MecCourse> pickCourses = new ArrayList<>();
        for (int i = 0; i < courses.size(); i++) {
            MecCourse course = courses.get(i);
            if (mecCourse4json.getCourseId().equals(course.getCourseId().intValue())) {
                BigDecimal price = course.getClassType().equals(1) ? course.getPrice().multiply(BigDecimal.valueOf(buyCount)) : course.getPrice().multiply(BigDecimal.valueOf(course.getBuyCount()));
                amount = amount.add(price);
                remark += course.getClassName();
                if (course.getClassType().equals(1)) {
                    course.setBuyCount(buyCount);
                }
                pickCourses.add(course);
            }
        }
        if (pickCourses.size() == 0) {
            return failed("请选择续费课程");
        }

        String orderNo = GenerateNum.getInstance().GenerateOrderNo(); //自己系统订单号
        //获取分佣账户
        Integer branchId = 1002;//默认分佣账户;
        Account routingAccount = accountService.getRoutingAccount(branchId, amount);

        Order order = renewalsService.addRenewalsOrder(renewals, amount, orderNo, pickCourses, routingAccount, remark);

        Map rqMap = orderService.getPayMap(routingAccount, order, null); //获取支付map
        return succeed(rqMap);
    }

    /**
     * 交易查询
     *
     * @param merOrderNoList 用户订单号
     * @return
     * @throws Exception
     */
    //@PostMapping("/query")
    //@Scheduled(cron = "0/3 40 11 * * ?")
    public Object query(String merOrderNoList) throws Exception {
        String notifyUrl = ""; //回调地址
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("merOrderNoList", merOrderNoList);
        Map<String, Object> requestMap = new YqPayUtil(notifyUrl, resultMap).getRequestMap();
        return yqQueryService.orderQuery(requestMap);
    }

    /**
     * 用户信息(商户)查询
     *
     * @param sonMerNo 子商户号
     * @return
     * @throws Exception
     */
    @PostMapping("/queryaccount")
    public String queryAccount(String sonMerNo) throws Exception {
        String notifyUrl = ""; //回调地址
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("merOrderNoList", sonMerNo);
        Map<String, Object> requestMap = new YqPayUtil(notifyUrl, resultMap).getRequestMap();
        return yqQueryService.queryAccount(requestMap);
    }

    /**
     * 对账查询(定时任务每天对账)
     *
     * @return
     */
    public String queryBill() throws Exception {
        String notifyUrl = ""; //回调地址
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("tradeDate", ""); //交易日期
        resultMap.put("payState", ""); //订单状态
        resultMap.put("tradeType", ""); //交易类型,不填为全部
        resultMap.put("channelType", ""); //通道类型,不填为全部
        Map<String, Object> requestMap = new YqPayUtil(notifyUrl, resultMap).getRequestMap();
        return yqQueryService.billQuery(requestMap);
    }


    /**
     * 平台转账
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/platformtransferacc")
    public String platformTransferAcc(String payeeNo, String payeeName, String amount, String remarks) throws Exception {
        String notifyUrl = ""; //回调地址
        String orderNo = GenerateNum.getInstance().GenerateOrderNo(); //自己系统订单号
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("payeeNo", payeeNo); //收款方商户号
        resultMap.put("payeeName", payeeName); //收款方姓名
        resultMap.put("amount", amount); //金额
        resultMap.put("merOrderNo", orderNo); //商户订单号
        resultMap.put("remarks", remarks); //备注
        Map<String, Object> requestMap = new YqPayUtil(notifyUrl, resultMap).getRequestMap();
        return yqPayService.platformTransferAcc(requestMap);
    }

    /**
     * 提现短信
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/sendsms")
    public Msg sendSms(@ModelAttribute Intfc intfc) throws Exception {
        String notifyUrl = ""; //回调地址
        String merMerOrderNo = GenerateNum.getInstance().GenerateOrderNo();
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("wdMerNo", intfc.getWdMerNo()); //提现商户号
        resultMap.put("merMerOrderNo", merMerOrderNo); //商户订单号
        resultMap.put("amount", intfc.getAmount()); //提现金额
        resultMap.put("cardNo", intfc.getCardNo()); //提现银行卡号
//        resultMap.put("phone", intfc.getPhone()); //预留手机号(选填)
//        resultMap.put("cardType", intfc.getCardType()); //卡类型 0-个人银行卡，1-企业银行卡。(选填)
        Map<String, Object> requestMap = new YqPayUtil(notifyUrl, resultMap).getRequestMap();
        return yqPayService.intfc(requestMap);
    }

    /**
     * 提现
     *
     * @return
     * @throws Exception
     */
    @PostMapping("/intfc")
    public Msg intfc(@ModelAttribute Intfc intfc) throws Exception {
        String notifyUrl = "http://47.99.212.176:9000/yqpay/notify"; //回调地址
        String merMerOrderNo = GenerateNum.getInstance().GenerateOrderNo();
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("wdMerNo", intfc.getWdMerNo()); //提现商户号
        resultMap.put("merMerOrderNo", merMerOrderNo); //商户订单号
        resultMap.put("amount", intfc.getAmount()); //提现金额
        resultMap.put("cardNo", intfc.getCardNo()); //提现银行卡号
//        resultMap.put("phone", intfc.getPhone()); //预留手机号(选填)
//        resultMap.put("cardType", intfc.getCardType()); //卡类型 0-个人银行卡，1-企业银行卡。(选填)
        resultMap.put("seqNo", ""); //流水号(选填)
        resultMap.put("smsCode", ""); //验证码(选填)
        Map<String, Object> requestMap = new YqPayUtil(notifyUrl, resultMap).getRequestMap();
        return yqPayService.intfc(requestMap);
    }


    /**
     * 易乾异步通知接口
     *
     * @param msg
     * @return String
     * @throws Exception
     */
    @PostMapping("/notify")
    public Msg notify(@ModelAttribute Msg msg) throws Exception {
        logger.info(msg.toString());
        Map<String, Object> rqMap = new LinkedHashMap<String, Object>();
        rqMap.put("code", msg.getCode());
        rqMap.put("msg", msg.getMsg());
        rqMap.put("responseType", msg.getResponseType());
        rqMap.put("responseParameters", msg.getResponseParameters());
        rqMap.put("sign", msg.getSign());
        boolean rs = YqPayUtil.verify(rqMap);
        msg.setMsg("fail");
        Map<String, String> notifyMap = new HashMap<>();
        if (rs) {
            notifyMap = JSON.parseObject(msg.getResponseParameters(), Map.class);
        }
        //支付中订单存在，更新状态
        if (msg.getResponseType().equals("1") && notifyMap.size() > 0) {
            String tradeState = msg.getCode().equals("88") ? "1" : "0";
            notifyMap.put("tradeState", tradeState);
            notifyMap.put("totalMoney", notifyMap.get("payAmount"));
            notifyMap.put("merOrderNo", notifyMap.get("merMerOrderNo"));
            this.updateOrder(notifyMap);
            msg.setCode("000000");
            msg.setMsg("success");
        }
        return msg;
    }


    //@Scheduled(cron = "0/5 * * * * ?")
    //@RequestMapping("/getOrderStatus")
    public void getOrderStatus() throws Exception {

        List<Order> payingOrders = orderService.findPayingOrders();

        String merOrderNos = ""; //
        ArrayList<String> orderNoList = new ArrayList<String>();

        for (Order payingOrder : payingOrders) {
            String orderNo = payingOrder.getOrderNo();
            orderNoList.add(orderNo);
            merOrderNos += orderNo + ",";
        }
        if (merOrderNos.isEmpty()) {
            return;
        }
        merOrderNos = merOrderNos.substring(0, merOrderNos.length() - 1);

        String notifyUrl = ""; //回调地址
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("merOrderNoList", merOrderNos);
        Map<String, Object> requestMap = new YqPayUtil(notifyUrl, resultMap).getRequestMap();
        Msg queryRs = yqQueryService.orderQuery(requestMap);
        logger.info("查询易乾结果" + queryRs.toString());
        if (queryRs.getCode().equals("88")) {
            //更新订单状态
            String[] statusArr = {"0", "1", "7"};
            String responseParameters = queryRs.getResponseParameters();
            List<Map<String, String>> responseList = JSON.parseObject(responseParameters, List.class);
            for (Map<String, String> response : responseList) {
                Map<String, String> rpMap = response;
                if (Arrays.asList(statusArr).contains(rpMap.get("tradeState"))) {
                    this.updateOrder(rpMap);
                }
                if (orderNoList.contains(rpMap.get("merOrderNo"))) {
                    orderNoList.remove(rpMap.get("merOrderNo"));
                }
            }
            this.failOrders(orderNoList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateOrder(Map<String, String> rpMap) throws Exception {
        int status = rpMap.get("tradeState").equals("1") ? 2 : 0;
        Order order = orderService.getOrderByOrderNo(rpMap.get("merOrderNo"));
        if (order == null) {
            return;
        }
        HashMap<String, Object> upMap = new HashMap<>();
        upMap.put("id", order.getId());
        upMap.put("oldStatus", 1);
        upMap.put("status", status);
        upMap.put("bank", rpMap.get("channelType"));

        if (order.getPayId() == null) {
            upMap.put("payId", rpMap.get("orderNo"));
        }
        ApplyInfo applyInfo = applyInfoService.get(order.getUserId());
        if (status == 2) {
            upMap.put("pay", rpMap.get("totalMoney"));
            upMap.put("payTime", new Date());
            if (order.getTuiFee() != null) { //乐团报名
                applyInfo.setStatus(1);
                applyInfoService.update(applyInfo);
            }
        }
        if (status == 0) {
            //失败减去已收款金额
            Account account = accountService.get(Integer.parseInt(order.getUAccount()));
            BigDecimal HasRouting = account.getHasRouting().subtract(order.getAmount());
            account.setHasRouting(HasRouting);
            accountService.upByIdAndVersion(account);

            //减去报名人数
            if (order.getTuiFee() != null) {
                CourseGroupInfo courseGroupInfo = CourseGroupInfoService.get(order.getGroupId());
                courseGroupInfo.setRegNum(courseGroupInfo.getRegNum() - 1);
                CourseGroupInfoService.upByIdAndVersion(courseGroupInfo);
            }
        }
        orderService.updateByIdAndStatus(upMap);

        //推送mec
        if (status == 2) {
            if (order.getTuiFee() != null) { //乐团报名
                applyInfoService.userRegister(applyInfo.getPatriarchPhone(), order.getId()); //推送mec
                schoolService.sendPayMsg(applyInfo.getPatriarchPhone(), order.getAmount().toString());
            } else {
                Renewals renewals = renewalsService.getRenewalsByOrderId(order.getId());
                RenewBean renewBean = new RenewBean();
//                renewBean.setUserId(renewals.getUserId());
//                renewBean.setClassId(renewals.getClassId());
//                renewBean.setWay(renewals.getWay());
//                renewBean.setPay(renewals.getPay());
//                renewBean.setChargeMode(renewals.getChangeMode());
//                renewBean.setBuy(new BigDecimal(renewals.getBuy()));
//                renewBean.setPrice(renewals.getPrice());
                renewBean.setUserId(renewals.getUserId());
                renewBean.setType(101);
                renewBean.setIn(renewals.getPay());
                renewBean.setOut(new BigDecimal(0));
                renewBean.setWay(renewals.getWay());
                applyInfoService.pushRenew(renewBean);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void failOrders(ArrayList<String> orderNoList) throws Exception {
        if (orderNoList.size() == 0) {
            return;
        }
        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.MINUTE, -15);// 5分钟之前的时间
        Date beforeDate = beforeTime.getTime();
        Map<String, Object> rqMap = new HashMap<>();
        rqMap.put("orderNoList", orderNoList);
        rqMap.put("beforeTime", beforeDate);
        List<Order> payingOrders = orderService.findPayingOrdersOver(rqMap);

        for (Order order : payingOrders) {
            HashMap<String, Object> upMap = new HashMap<>();
            upMap.put("id", order.getId());
            upMap.put("oldStatus", 1);
            upMap.put("status", 0);

            //失败减去已收款金额
            Account account = accountService.get(Integer.parseInt(order.getUAccount()));
            BigDecimal HasRouting = account.getHasRouting().subtract(order.getAmount());
            account.setHasRouting(HasRouting);
            accountService.upByIdAndVersion(account);

            //减去报名人数
            if (order.getTuiFee() != null) {
                CourseGroupInfo courseGroupInfo = CourseGroupInfoService.get(order.getGroupId());
                courseGroupInfo.setRegNum(courseGroupInfo.getRegNum() - 1);
                CourseGroupInfoService.upByIdAndVersion(courseGroupInfo);
            }
            orderService.updateByIdAndStatus(upMap);
        }

    }
}
