package com.ym.mec.student.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.*;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.enums.DealStatusEnum;
import com.ym.mec.biz.dal.enums.GroupType;
import com.ym.mec.biz.dal.enums.OrderTypeEnum;
import com.ym.mec.biz.service.*;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.thirdparty.adapay.ConfigInit;
import com.ym.mec.thirdparty.adapay.Payment;
import com.ym.mec.thirdparty.yqpay.Msg;
import com.ym.mec.thirdparty.yqpay.RsqMsg;
import com.ym.mec.thirdparty.yqpay.YqPayFeignService;
import com.ym.mec.thirdparty.yqpay.YqPayUtil;
import com.ym.mec.util.date.DateUtil;
import com.ym.mec.util.http.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@RequestMapping("studentOrder")
@Api(tags = "订单回调")
@RestController
@EnableScheduling
public class StudentOrderController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(StudentOrderController.class);
    @Autowired
    private StudentPaymentOrderService studentPaymentOrderService;
    @Autowired
    private VipGroupService vipGroupService;
    @Autowired
    private MusicGroupService musicGroupService;
    @Autowired
    private StudentPaymentOrderDetailService studentPaymentOrderDetailService;
    @Autowired
    private YqPayFeignService yqPayFeignService;
    @Autowired
    private StudentPaymentOrderDao studentPaymentOrderDao;
    @Autowired
    private SysConfigDao sysConfigDao;
    @Autowired
    private SporadicChargeInfoService sporadicChargeInfoService;
    @Autowired
    private OrganizationDao organizationDao;
    @Autowired
    private CourseScheduleEvaluateDao courseScheduleEvaluateDao;
    @Autowired
    private TenantPaymentOrderService tenantPaymentOrderService;
    @Autowired
    private StudentPaymentRouteOrderDao studentPaymentRouteOrderDao;
    @Autowired
    private StudentGoodsSellDao studentGoodsSellDao;
    @Autowired
    private LuckDrawCountService luckDrawCountService;
    @Autowired
    private DegreeRegistrationDao degreeRegistrationDao;
    @Autowired
    private SysUserFeignService sysUserFeignService;


    @Value("${spring.profiles.active:dev}")
    private String profiles;

    @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";
            String channelType = notifyMap.get("channelType").equals("1") ? "WXPay" : (notifyMap.get("channelType").equals("2") ? "Alipay" : "quickPay");
            notifyMap.put("tradeState", tradeState);
            notifyMap.put("totalMoney", notifyMap.get("payAmount"));
            notifyMap.put("merOrderNo", notifyMap.get("merMerOrderNo"));
            notifyMap.put("channelType", channelType);
            studentPaymentOrderService.updateOrder(notifyMap);
            msg.setCode("000000");
            msg.setMsg("success");
        }
        return msg;
    }


    @ApiOperation(value = "查询订单状态")
    @PostMapping("/checkOrderStatus")
    public Object checkOrderStatus(String orderNo) {
        if (StringUtils.isBlank(orderNo)) {
            return failed("请指定订单");
        }
        StudentPaymentOrder orderByOrderNo = studentPaymentOrderService.findOrderByOrderNo(orderNo);
        if (Objects.isNull(orderByOrderNo)) {
            return failed("未找到指定订单");
        }
        HashMap<String, Object> orderDetail = new HashMap<>();
        orderDetail.put("order", orderByOrderNo);
        orderDetail.put("groupType", orderByOrderNo.getGroupType());
        if (orderByOrderNo.getGroupType().equals(GroupType.MUSIC)) {
            MusicGroup musicGroup = musicGroupService.get(orderByOrderNo.getMusicGroupId());
            List<Goods> goodsList = studentPaymentOrderDetailService.findApplyOrderGoods(orderByOrderNo.getId());
            List<String> orderDetailType = studentPaymentOrderDetailService.getOrderDetailType(orderByOrderNo.getId());
            List<StudentPaymentOrderDetail> orderDetail1 = studentPaymentOrderDetailService.getOrderDetail(orderByOrderNo.getId());
            String kitGroupPurchaseType = orderDetail1.stream().filter(e -> e.getGoodsList() != null).filter(e -> e.getKitGroupPurchaseType() != null).map(e -> e.getKitGroupPurchaseType().getCode()).collect(Collectors.joining(","));
            orderDetail.put("goods", goodsList);
            orderDetail.put("kitGroupPurchaseType", kitGroupPurchaseType);
            orderDetail.put("course", musicGroup.getCourseForm());
            orderDetail.put("ownershipType", musicGroup.getOwnershipType());
            orderDetail.put("detailType", orderDetailType);
        } else if (orderByOrderNo.getGroupType().equals(GroupType.VIP)) {
            VipBuyResultDto vipBuyResultInfo = vipGroupService.findVipBuyResultInfo(Integer.valueOf(orderByOrderNo.getMusicGroupId()));
            orderDetail.put("detail", vipBuyResultInfo);
        } else if (orderByOrderNo.getGroupType().equals(GroupType.SPORADIC)) {
            if (Objects.nonNull(orderByOrderNo.getMusicGroupId())) {
                SporadicChargeInfo info = sporadicChargeInfoService.get(Integer.valueOf(orderByOrderNo.getMusicGroupId()));
                orderDetail.put("detail", info);
            }
            if (orderByOrderNo.getType().equals(OrderTypeEnum.DOUBLE_ELEVEN2020)) {
                LuckDrawCount luckDrawCount = luckDrawCountService.get(orderByOrderNo.getUserId().longValue());
                orderDetail.put("drawTimes", luckDrawCount == null ? 0 : luckDrawCount.getAvailableCount());
            } else if (OrderTypeEnum.DEGREE_REGISTRATION.equals(orderByOrderNo.getType())) {
                DegreeRegistration degreeRegistration = degreeRegistrationDao.get(orderByOrderNo.getClassGroupId());
                orderDetail.put("degree", degreeRegistration);
                List<StudentPaymentOrderDetail> studentPaymentOrderDetails = studentPaymentOrderDetailService.getOrderDetail(orderByOrderNo.getId());
                if (!CollectionUtils.isEmpty(studentPaymentOrderDetails)) {
                    orderDetail.put("additionCourseInfo", studentPaymentOrderDetails.get(0).getGoodsIdList());
                }
            }
        } else if (orderByOrderNo.getGroupType().equals(GroupType.GOODS_SELL)) {
            orderDetail.put("detail", studentGoodsSellDao.getStudentGoodsSellDto(orderNo));
        }
        return succeed(orderDetail);
    }

    @ApiOperation(value = "台牌支付")
    @PostMapping("/executePayment")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "amount", value = "支付金额", required = true, dataType = "BigDecimal"),
            @ApiImplicitParam(name = "orderNo", value = "订单号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "payChannel", value = "支付方式（alipay-支付宝app支付）", required = true, dataType = "String"),
    })
    public Object executePayment(BigDecimal amount, String orderNo, String payChannel, String notifyUrl, String returnUrl, String orderSubject, String orderBody, String sign, String code, String platform) throws Exception {
        Map<String, Object> signParams = new LinkedHashMap<>();
        signParams.put("appId", ConfigInit.appId);
        signParams.put("amount", amount.setScale(2, BigDecimal.ROUND_HALF_UP));
        signParams.put("orderNo", orderNo);
//        signParams.put("notifyUrl", notifyUrl);
//        signParams.put("returnUrl", returnUrl);
        signParams.put("orderSubject", orderSubject);
        signParams.put("orderBody", orderBody);
        signParams.put("wxAppId", ConfigInit.wxAppId);

        String originalStr = JSONObject.toJSONString(signParams);
        String mewSign = DigestUtils.md5DigestAsHex(originalStr.getBytes());
        if (!mewSign.equals(sign)) {
            return failed("请勿非法请求");
        }

        String openId = "";
        if (payChannel.equals("wx_pub")) {
            if (code == null || code.isEmpty()) {
                return failed("微信支付请先授权");
            }
            String wxMpOAuth2AccessTokenUrl = String.format(ConfigInit.wxMpOAuth2AccessTokenUrl, ConfigInit.wxAppId, ConfigInit.wxAppSecret, code);
            Map<String, String> weChatRes = JSON.parseObject(HttpUtil.get(wxMpOAuth2AccessTokenUrl, new HashMap<>()), Map.class);
            if (!weChatRes.containsKey("openid")) {
                return failed("授权失败,请重新授权");
            }
            openId = weChatRes.get("openid");
        }

        Date createTime = null;
        TenantPaymentOrder tenantPaymentOrder = null;
        StudentPaymentOrder studentPaymentOrder = null;
        if (platform != null && platform.equals("teacher")) {
            tenantPaymentOrder = tenantPaymentOrderService.queryByOrderNo(orderNo);
        } else {
            studentPaymentOrder = studentPaymentOrderService.findOrderByOrderNo(orderNo);
        }

        if (studentPaymentOrder == null && tenantPaymentOrder == null) {
            return failed("订单不存在");
        }
        if (studentPaymentOrder != null && !studentPaymentOrder.getStatus().equals(DealStatusEnum.ING)) {
            String msg = studentPaymentOrder.getStatus().equals(DealStatusEnum.SUCCESS) ? "订单已支付，请勿重复支付" : "订单已关闭，不能支付";
            return failed(msg);
        }
        if (tenantPaymentOrder != null && !tenantPaymentOrder.getStatus().equals(DealStatusEnum.ING)) {
            String msg = tenantPaymentOrder.getStatus().equals(DealStatusEnum.SUCCESS) ? "订单已支付，请勿重复支付" : "订单已关闭，不能支付";
            return failed(msg);
        }

        if (studentPaymentOrder != null) {
            createTime = studentPaymentOrder.getCreateTime();
        } else {
            createTime = tenantPaymentOrder.getCreateTime();
        }

        Calendar beforeTime = Calendar.getInstance();
        beforeTime.add(Calendar.MINUTE, -28);// 28 分钟之前的时间
        Date beforeDate = beforeTime.getTime();
        if (createTime.before(beforeDate)) {
            return failed("订单已超时,请重新下单");
        }

        Date expireDate = DateUtil.addMinutes(createTime, 30);
        String timeExpire = new SimpleDateFormat("yyyyMMddHHmmss").format(expireDate);

        Map<String, Object> paymentParams = new HashMap<>();
        paymentParams.put("app_id", ConfigInit.appId);
        paymentParams.put("order_no", orderNo);
        paymentParams.put("pay_channel", payChannel);
        paymentParams.put("pay_amt", amount.setScale(2, BigDecimal.ROUND_HALF_UP));
        paymentParams.put("goods_title", orderSubject);
        paymentParams.put("goods_desc", orderBody);
        paymentParams.put("time_expire", timeExpire);
        paymentParams.put("pay_mode", "delay");

        //延时分账时不需要
//        List<StudentPaymentRouteOrder> routeOrders = studentPaymentRouteOrderDao.getRouteOrders(orderNo);
//        List<Map<String, Object>> divMembers = new ArrayList<>();
//        for (StudentPaymentRouteOrder routeOrder : routeOrders) {
//            Map<String, Object> divMember = new HashMap<>();
//            divMember.put("member_id", routeOrder.getMerNo());//分佣账户
//            divMember.put("amount", routeOrder.getRouteAmount().setScale(2, BigDecimal.ROUND_HALF_UP));//分佣金额
//            divMember.put("fee_flag", routeOrder.getFeeFlag());
//            if (routeOrder.getMerNo().equals(ConfigInit.merNo)) {
//                divMember.put("member_id", 0);
//            }
//            divMembers.add(divMember);
//        }
//        if (divMembers.size() > 0) {
//            paymentParams.put("div_members", JSON.toJSONString(divMembers));
//        }

        Map<String, Object> expendParams = new HashMap<>(5);

        expendParams.put("open_id", openId);
        expendParams.put("is_raw", "1");
        expendParams.put("callback_url", returnUrl);
        expendParams.put("limit_pay", "1");

        paymentParams.put("expend", expendParams);

        Map<String, Object> payment = Payment.executePayment(paymentParams);

        if (studentPaymentOrder != null) {
            studentPaymentOrder.setTransNo((String) payment.get("id"));
            studentPaymentOrderService.update(studentPaymentOrder);
        } else {
            tenantPaymentOrder.setTransNo((String) payment.get("id"));
            tenantPaymentOrderService.update(tenantPaymentOrder);
        }

        return succeed(payment);
    }

    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl) {
        String appId = "wxcf8e8b33a9477845";
        String url = URLEncoder.encode("http://wxwechat.utools.club/studentOrder/userInfo");

        String redirectURL = String.format("https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect",
                appId, url);

        return "redirect:" + redirectURL;
    }

    @GetMapping("/userInfo")
    public Object userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) throws Exception {
        String appId = "wxcf8e8b33a9477845";
        String appSecret = "1286452b9c68b13325dece7cdf892645";

        String wxMpOAuth2AccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

        wxMpOAuth2AccessTokenUrl = String.format(wxMpOAuth2AccessTokenUrl, appId, appSecret, code);

        Map<String, String> map = JSON.parseObject(HttpUtil.get(wxMpOAuth2AccessTokenUrl, new HashMap<>()), Map.class);

        if (!map.containsKey("openid")) {
            return failed("授权失败，请重新授权");
        }

        return map.get("openid");

    }

    //    @Scheduled(cron = "0/30 * * * * ?")
    @GetMapping("/setSuccessStatus")
    public HttpResponseResult setSuccessStatus() throws Exception {
//        if (!profiles.equals("dev")) {
//            return failed("非法操作");
//        }
        List<StudentPaymentOrder> payingOrders = studentPaymentOrderService.findOrdersByStatus(DealStatusEnum.ING, "ADAPAY");

        String[] statusArr = {"0", "1", "7"};
        for (StudentPaymentOrder payingOrder : payingOrders) {
            Map<String, String> rpMap = new HashMap<>();
            rpMap.put("tradeState", "1");
            rpMap.put("remarks", "模拟支付成功");
            rpMap.put("merOrderNo", payingOrder.getOrderNo());
            rpMap.put("orderNo", payingOrder.getOrderNo());
            rpMap.put("channelType", "1");
            rpMap.put("simulation", "1");

            String channelType = rpMap.get("channelType").equals("1") ? "WXPay" : (rpMap.get("channelType").equals("2") ? "Alipay" : "quickPay");
            rpMap.put("channelType", channelType);
            if (Arrays.asList(statusArr).contains(rpMap.get("tradeState"))) {
                try {
                    studentPaymentOrderService.updateOrder(rpMap); //更新订单
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
            }
        }
        return succeed();
    }

    @GetMapping("/getOrderStatus")
    private HttpResponseResult getOrderStatus(String orderNo) throws Exception {

        if (orderNo == null || orderNo.isEmpty()) {
            return failed("订单号必须填");
        }

        String notifyUrl = ""; //回调地址
        Map<String, Object> resultMap = new LinkedHashMap<>();
        resultMap.put("merOrderNoList", orderNo);
        Map<String, Object> requestMap = YqPayUtil.getRequestMap(notifyUrl, resultMap);

        RsqMsg rsqMsg = new RsqMsg(requestMap);

        Msg queryRs = yqPayFeignService.orderQuery(rsqMsg);

        if (queryRs.getCode().equals("88")) {
            String responseParameters = queryRs.getResponseParameters();
            List<Map<String, Object>> responseList = JSON.parseObject(responseParameters, List.class);
            return succeed(responseList);
        }
        return succeed("订单不存在");
    }


    @RequestMapping("paymentResult")
    public void paymentResult(HttpServletResponse response, String orderNo, String type) {
        try {
            String baseApiUrl = sysConfigDao.findConfigValue(SysConfigService.BASE_API_URL);
            if (type != null && type.equals("edu")) {
                baseApiUrl = sysConfigDao.findConfigValue(SysConfigService.EDU_TEACHER_BASE_URL);
            }
            response.sendRedirect(baseApiUrl + "/#/paymentresult?orderNo=" + orderNo);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/getLuckStatis")
    public HttpResponseResult getLuckStatis() {
        List<Organization> organs = organizationDao.findAllOrgans();
        List<OrderStatisDto> orders = studentPaymentOrderDao.getLuckStatis();


        for (Organization organ : organs) {
            boolean flag = false;
            for (OrderStatisDto order : orders) {
                if (organ.getName().equals(order.getOrganName())) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                OrderStatisDto orderStatisDto = new OrderStatisDto();
                orderStatisDto.setOrganName(organ.getName());
                orderStatisDto.setMoney(BigDecimal.ZERO);
                orderStatisDto.setNums(0);
                orders.add(orderStatisDto);
            }
        }

        BigDecimal totalMoney = BigDecimal.ZERO;
        Integer totalNum = 0;
        Iterator<OrderStatisDto> iterator = orders.iterator();
        while (iterator.hasNext()) {
            OrderStatisDto order = iterator.next();
            if (order.getOrganName().equals("总部国际") || order.getOrganName().equals("阳光总部国际") || order.getOrganName().equals("武汉小学")) {
                iterator.remove();
                continue;
            }
            totalMoney = totalMoney.add(order.getMoney());
            totalNum += order.getNums();
        }
        orders = orders.stream().sorted(Comparator.comparing(OrderStatisDto::getNums).reversed()).collect(Collectors.toList());

        LuckStatisDto luckStatisDto = new LuckStatisDto();
        luckStatisDto.setOrderStatisDtoList(orders);
        luckStatisDto.setTotalNum(totalNum);
        luckStatisDto.setTotalMoney(totalMoney);
        return succeed(luckStatisDto);
    }

    @GetMapping("/getPracticeGroupStatis")
    public HttpResponseResult getPracticeGroupStatis() {
        List<Organization> organs = organizationDao.findAllOrgans();
        List<PracticeGroupsDto> hasReportNums = courseScheduleEvaluateDao.getHasReportNums();
        List<PracticeGroupsDto> organMoneys = courseScheduleEvaluateDao.getOrganMoney();
        List<PracticeGroupsDto> organPracticeGroups = courseScheduleEvaluateDao.getOrganPracticeGroups();
        List<PracticeGroupsDto> practiceGroupsFrees = courseScheduleEvaluateDao.getPracticeGroupsFree();
        List<PracticeGroupsDto> practiceGroupsBuys = courseScheduleEvaluateDao.getPracticeGroupsBuy();
        List<PracticeGroupsDto> practiceGroupsRenews = courseScheduleEvaluateDao.getPracticeGroupsRenew();

        Date startTime = DateUtil.getFirstDayOfMonth(new Date());

        List<PracticeGroupsDto> monthOrganBuyMoneys = courseScheduleEvaluateDao.getMonthOrganMoney(OrderTypeEnum.PRACTICE_GROUP_BUY, startTime);
        List<PracticeGroupsDto> monthOrganRenewMoneys = courseScheduleEvaluateDao.getMonthOrganMoney(OrderTypeEnum.PRACTICE_GROUP_RENEW, startTime);

        //List<PracticeGroupsDto> monthOrganBuyMoneys = courseScheduleEvaluateDao.getOrganNewPracticeGroupsOfMonth(OrderTypeEnum.PRACTICE_GROUP_BUY,startTime);
        //List<PracticeGroupsDto> monthOrganRenewMoneys = courseScheduleEvaluateDao.getOrganNewPracticeGroupsOfMonth(OrderTypeEnum.PRACTICE_GROUP_RENEW,startTime);

        List<PracticeGroupsDto> practiceGroups = new ArrayList<>();
        for (Organization organ : organs) {
            PracticeGroupsDto practiceGroupsDto = new PracticeGroupsDto();
            practiceGroupsDto.setOrganName(organ.getName());
            practiceGroupsDto.setOrganId(organ.getId());
            //体验人数
            for (PracticeGroupsDto practiceGroupsFree : practiceGroupsFrees) {
                if (organ.getId().equals(practiceGroupsFree.getOrganId())) {
                    practiceGroupsDto.setTotalNums(practiceGroupsFree.getTotalNums());
                    break;
                }
            }
            //购买人数
            for (PracticeGroupsDto practiceGroupsBuy : practiceGroupsBuys) {
                if (organ.getId().equals(practiceGroupsBuy.getOrganId())) {
                    practiceGroupsDto.setBuyNums(practiceGroupsBuy.getBuyNums());
                    break;
                }
            }
            //续费人数
            for (PracticeGroupsDto practiceGroupsRenew : practiceGroupsRenews) {
                if (organ.getId().equals(practiceGroupsRenew.getOrganId())) {
                    practiceGroupsDto.setRenewNums(practiceGroupsRenew.getRenewNums());
                    break;
                }
            }
            //已完成人数
            for (PracticeGroupsDto organPracticeGroup : organPracticeGroups) {
                if (organ.getId().equals(organPracticeGroup.getOrganId()) && organPracticeGroup.getBuyNums() >= organPracticeGroup.getTotalNums()) {
                    practiceGroupsDto.setOverNums(practiceGroupsDto.getOverNums() + 1);
                }
            }

            //已提交报告人数
            for (PracticeGroupsDto hasReportNum : hasReportNums) {
                if (organ.getId().equals(hasReportNum.getOrganId())) {
                    practiceGroupsDto.setReportNums(hasReportNum.getReportNums());
                    break;
                }
            }
            //成交金额
            for (PracticeGroupsDto organMoney : organMoneys) {
                if (organ.getId().equals(organMoney.getOrganId())) {
                    practiceGroupsDto.setTotalMoney(organMoney.getTotalMoney());
                    break;
                }
            }
            //当月新增金额和人数
            for (PracticeGroupsDto monthOrganBuyMoney : monthOrganBuyMoneys) {
                if (organ.getId().equals(monthOrganBuyMoney.getOrganId())) {
                    practiceGroupsDto.setMonthBuyMoney(monthOrganBuyMoney.getTotalMoney());
                    practiceGroupsDto.setMonthBuyNums(monthOrganBuyMoney.getBuyNums());
                    break;
                }
            }

            //当月续费金额和人数
            for (PracticeGroupsDto monthOrganRenewMoney : monthOrganRenewMoneys) {
                if (organ.getId().equals(monthOrganRenewMoney.getOrganId())) {
                    practiceGroupsDto.setMonthRenewNums(monthOrganRenewMoney.getBuyNums());
                    practiceGroupsDto.setMonthRenewMoney(monthOrganRenewMoney.getTotalMoney());
                    break;
                }
            }

            if (practiceGroupsDto.getTotalNums() > 0) {
                double scale = new BigDecimal(practiceGroupsDto.getBuyNums()).multiply(new BigDecimal(100)).divide(new BigDecimal(practiceGroupsDto.getTotalNums()), 2, BigDecimal.ROUND_HALF_UP).doubleValue();
                practiceGroupsDto.setBuyScale(scale);
            }

            practiceGroups.add(practiceGroupsDto);
        }

        BigDecimal totalMoney = BigDecimal.ZERO;
        Integer totalNum = 0;
        Integer buyNum = 0;
        Integer renewNum = 0;
        Integer overNum = 0;
        Integer reportNum = 0;
        Integer monthBuyNums = 0;
        Integer monthRenewNums = 0;
        BigDecimal monthBuyMoney = BigDecimal.ZERO;
        BigDecimal monthRenewMoney = BigDecimal.ZERO;

        Iterator<PracticeGroupsDto> iterator = practiceGroups.iterator();
        while (iterator.hasNext()) {
            PracticeGroupsDto next = iterator.next();
            if (next.getOrganName().equals("总部国际") || next.getOrganName().equals("阳光总部国际") || next.getOrganName().equals("武汉小学")) {
                iterator.remove();
                continue;
            }
            totalMoney = totalMoney.add(next.getTotalMoney());
            totalNum += next.getTotalNums();
            overNum += next.getOverNums();
            buyNum += next.getBuyNums();
            reportNum += next.getReportNums();
            renewNum += next.getRenewNums();
            monthBuyNums += next.getMonthBuyNums();
            monthRenewNums += next.getMonthRenewNums();
            monthBuyMoney = monthBuyMoney.add(next.getMonthBuyMoney());
            monthRenewMoney = monthRenewMoney.add(next.getMonthRenewMoney());
        }
        practiceGroups = practiceGroups.stream().sorted(Comparator.comparingDouble(PracticeGroupsDto::getBuyScale).reversed()).collect(Collectors.toList());

        PracticeGroupStatisDto practiceGroupStatisDto = new PracticeGroupStatisDto();
        practiceGroupStatisDto.setPracticeGroupsDtoList(practiceGroups);
        practiceGroupStatisDto.setTotalMoney(totalMoney);
        practiceGroupStatisDto.setTotalNum(totalNum);
        practiceGroupStatisDto.setBuyNum(buyNum);
        practiceGroupStatisDto.setRenewNum(renewNum);
        practiceGroupStatisDto.setOverNum(overNum);
        practiceGroupStatisDto.setReportNum(reportNum);
        practiceGroupStatisDto.setMonthBuyNums(monthBuyNums);
        practiceGroupStatisDto.setMonthBuyMoney(monthBuyMoney);
        practiceGroupStatisDto.setMonthRenewNums(monthRenewNums);
        practiceGroupStatisDto.setMonthRenewMoney(monthRenewMoney);

        if (totalNum > 0) {
            BigDecimal scale = new BigDecimal(buyNum).multiply(new BigDecimal(100)).divide(new BigDecimal(totalNum), 2, BigDecimal.ROUND_HALF_UP);
            practiceGroupStatisDto.setBuyScale(scale);
        }

        return succeed(practiceGroupStatisDto);
    }

    @GetMapping("/getPracticeStatis")
    public HttpResponseResult getPracticeStatis() {
        Date nowDate = new Date();
        List<Organization> organs = organizationDao.findAllOrgans();
        //除去禁止的体验人数
//        List<Practice4OrganDto> organTryNums = courseScheduleEvaluateDao.getTryNums();
//        List<Practice4OrganDto> organPracticeTryNums = courseScheduleEvaluateDao.getPracticeTryNums();
//        List<Practice4OrganDto> organVipTryNums = courseScheduleEvaluateDao.getVipTryNums();
//        List<Practice4OrganDto> organPracticeAndVipTryNums = courseScheduleEvaluateDao.getPracticeAndVipTryNums();
        List<Practice4OrganDto> allTryNums = courseScheduleEvaluateDao.getAllTryNums();

        List<Practice4OrganDto> practiceBuyNums = courseScheduleEvaluateDao.getPracticeBuyNums(nowDate, null);
        List<Practice4OrganDto> vipBuyNums = courseScheduleEvaluateDao.getVipBuyNums(nowDate, null);

        List<Practice4OrganDto> practiceAndVipBuyNums = courseScheduleEvaluateDao.getPracticeAndVipNums(nowDate, null);
        Date startTime = DateUtil.getFirstDayOfMonth(nowDate);
        Date endTime = DateUtil.addMonths(startTime, 1);


        //当月新增网管课人数
        List<PracticeGroupsDto> monthOrganPracticeBuyMoneys = courseScheduleEvaluateDao.getMonthOrganMoney(OrderTypeEnum.PRACTICE_GROUP_BUY, startTime);
        //当月新增VIP人数
        List<PracticeGroupsDto> monthOrganVipBuyMoneys = courseScheduleEvaluateDao.getMonthOrganMoney(OrderTypeEnum.SMALL_CLASS_TO_BUY, startTime);
        //当月续费人数
        List<PracticeGroupsDto> monthOrganRenewMoneys = courseScheduleEvaluateDao.getMonthOrganMoney(OrderTypeEnum.PRACTICE_GROUP_RENEW, startTime);

        //本月总人数
        List<Practice4OrganDto> nowMonthPracticeBuyNums = courseScheduleEvaluateDao.getPracticeBuyNums(startTime, endTime);
        List<Practice4OrganDto> nowMonthVipBuyNums = courseScheduleEvaluateDao.getVipBuyNums(startTime, endTime);
        List<Practice4OrganDto> nowMonthPracticeAndVipBuyNums = courseScheduleEvaluateDao.getPracticeAndVipNums(startTime, endTime);

        //上月总人数
        Date lastMonthStartTime = DateUtil.addMonths(startTime, -1);
        List<Practice4OrganDto> lastMonthPracticeBuyNums = courseScheduleEvaluateDao.getPracticeBuyNums(lastMonthStartTime, startTime);
        List<Practice4OrganDto> lastMonthVipBuyNums = courseScheduleEvaluateDao.getVipBuyNums(lastMonthStartTime, startTime);
        List<Practice4OrganDto> lastMonthPracticeAndVipBuyNums = courseScheduleEvaluateDao.getPracticeAndVipNums(lastMonthStartTime, startTime);

        List<Practice4OrganDto> practice4Organs = new ArrayList<>();
        for (Organization organ : organs) {
            Practice4OrganDto practice4OrganDto = new Practice4OrganDto();
            practice4OrganDto.setOrganName(organ.getName());
            practice4OrganDto.setOrganId(organ.getId());
            //体验人数(除去禁止)
//            for (Practice4OrganDto organTryNum : organTryNums) {
//                if (organ.getId().equals(organTryNum.getOrganId())) {
//                    practice4OrganDto.setTryNum(practice4OrganDto.getTryNum() + organTryNum.getTryNum());
//                    break;
//                }
//            }
//            //网管课体验人数（禁止）
//            for (Practice4OrganDto organPracticeTryNum : organPracticeTryNums) {
//                if (organ.getId().equals(organPracticeTryNum.getOrganId())) {
//                    practice4OrganDto.setTryNum(practice4OrganDto.getTryNum() + organPracticeTryNum.getTryNum());
//                    break;
//                }
//            }
//            //vip课体验人数（禁止）
//            for (Practice4OrganDto organVipTryNum : organVipTryNums) {
//                if (organ.getId().equals(organVipTryNum.getOrganId())) {
//                    practice4OrganDto.setTryNum(practice4OrganDto.getTryNum() + organVipTryNum.getTryNum());
//                    break;
//                }
//            }
//            //减去vip中在网管课的人数
//            for (Practice4OrganDto organPracticeAndVipTryNum : organPracticeAndVipTryNums) {
//                if (organ.getId().equals(organPracticeAndVipTryNum.getOrganId())) {
//                    practice4OrganDto.setTryNum(practice4OrganDto.getTryNum() - organPracticeAndVipTryNum.getTryNum());
//                    break;
//                }
//            }

            for (Practice4OrganDto allTryNum : allTryNums) {
                if (organ.getId().equals(allTryNum.getOrganId())) {
                    practice4OrganDto.setTryNum(allTryNum.getTryNum());
                }
            }
            //网管课转化人数
            for (Practice4OrganDto practiceBuyNum : practiceBuyNums) {
                if (organ.getId().equals(practiceBuyNum.getOrganId())) {
                    practice4OrganDto.setPracticeNum(practiceBuyNum.getPracticeNum());
                    break;
                }
            }
            //VIP课转化人数
            for (Practice4OrganDto vipBuyNum : vipBuyNums) {
                if (organ.getId().equals(vipBuyNum.getOrganId())) {
                    practice4OrganDto.setVipNum(vipBuyNum.getVipNum());
                    break;
                }
            }
            for (Practice4OrganDto practiceAndVipBuyNum : practiceAndVipBuyNums) {
                if (organ.getId().equals(practiceAndVipBuyNum.getOrganId())) {
                    practice4OrganDto.setVipNum(practice4OrganDto.getVipNum() - practiceAndVipBuyNum.getPracticeNum());
                    break;
                }
            }
            practice4OrganDto.setTotalNum(practice4OrganDto.getPracticeNum() + practice4OrganDto.getVipNum());

            //当月新增网管课人数
            for (PracticeGroupsDto monthOrganPracticeBuyMoney : monthOrganPracticeBuyMoneys) {
                if (organ.getId().equals(monthOrganPracticeBuyMoney.getOrganId())) {
                    practice4OrganDto.setPractice4MonthNum(monthOrganPracticeBuyMoney.getBuyNums());
                    practice4OrganDto.setTotalMoney(practice4OrganDto.getTotalMoney().add(monthOrganPracticeBuyMoney.getTotalMoney()));
                    break;
                }
            }
            //当月新增VIP课人数
            for (PracticeGroupsDto monthOrganVipBuyMoney : monthOrganVipBuyMoneys) {
                if (organ.getId().equals(monthOrganVipBuyMoney.getOrganId())) {
                    practice4OrganDto.setVip4MonthNum(monthOrganVipBuyMoney.getBuyNums());
                    practice4OrganDto.setTotalMoney(practice4OrganDto.getTotalMoney().add(monthOrganVipBuyMoney.getTotalMoney()));
                    break;
                }
            }
            //当月续费人数
            for (PracticeGroupsDto monthOrganRenewMoney : monthOrganRenewMoneys) {
                if (organ.getId().equals(monthOrganRenewMoney.getOrganId())) {
                    practice4OrganDto.setRenew4MonthNum(monthOrganRenewMoney.getBuyNums());
                    practice4OrganDto.setTotalMoney(practice4OrganDto.getTotalMoney().add(monthOrganRenewMoney.getTotalMoney()));
                    break;
                }
            }
            //同比上月增减人数
            for (Practice4OrganDto nowMonthPracticeBuyNum : nowMonthPracticeBuyNums) {
                if (organ.getId().equals(nowMonthPracticeBuyNum.getOrganId())) {
                    practice4OrganDto.setChange4MonthNum(nowMonthPracticeBuyNum.getPracticeNum());
                    break;
                }
            }
            for (Practice4OrganDto nowMonthVipBuyNum : nowMonthVipBuyNums) {
                if (organ.getId().equals(nowMonthVipBuyNum.getOrganId())) {
                    practice4OrganDto.setChange4MonthNum(practice4OrganDto.getChange4MonthNum() + nowMonthVipBuyNum.getVipNum());
                    break;
                }
            }
            for (Practice4OrganDto nowMonthPracticeAndVipBuyNum : nowMonthPracticeAndVipBuyNums) {
                if (organ.getId().equals(nowMonthPracticeAndVipBuyNum.getOrganId())) {
                    practice4OrganDto.setChange4MonthNum(practice4OrganDto.getChange4MonthNum() - nowMonthPracticeAndVipBuyNum.getPracticeNum());
                    break;
                }
            }

            //上月人数
            for (Practice4OrganDto lastMonthPracticeBuyNum : lastMonthPracticeBuyNums) {
                if (organ.getId().equals(lastMonthPracticeBuyNum.getOrganId())) {
                    practice4OrganDto.setChange4MonthNum(practice4OrganDto.getChange4MonthNum() - lastMonthPracticeBuyNum.getPracticeNum());
                    break;
                }
            }
            for (Practice4OrganDto lastMonthVipBuyNum : lastMonthVipBuyNums) {
                if (organ.getId().equals(lastMonthVipBuyNum.getOrganId())) {
                    practice4OrganDto.setChange4MonthNum(practice4OrganDto.getChange4MonthNum() - lastMonthVipBuyNum.getVipNum());
                    break;
                }
            }
            for (Practice4OrganDto lastMonthPracticeAndVipBuyNum : lastMonthPracticeAndVipBuyNums) {
                if (organ.getId().equals(lastMonthPracticeAndVipBuyNum.getOrganId())) {
                    practice4OrganDto.setChange4MonthNum(practice4OrganDto.getChange4MonthNum() + lastMonthPracticeAndVipBuyNum.getPracticeNum());
                    break;
                }
            }

            if (practice4OrganDto.getTryNum() > 0) {
                double scale = new BigDecimal(practice4OrganDto.getTotalNum()).multiply(new BigDecimal(100)).divide(new BigDecimal(practice4OrganDto.getTryNum()), 2, BigDecimal.ROUND_HALF_UP).doubleValue();
                practice4OrganDto.setScale(scale);
            }

            practice4Organs.add(practice4OrganDto);
        }

        practice4Organs = practice4Organs.stream().sorted(Comparator.comparingDouble(Practice4OrganDto::getScale).reversed()).collect(Collectors.toList());
        return succeed(practice4Organs);
    }

    @GetMapping("/getUserApplyOrders")
    public HttpResponseResult<List<StudentPaymentOrderExportDto>> getUserApplyOrders(String musicGroupId) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(studentPaymentOrderDao.getUserApplyOrders(sysUser.getId(), musicGroupId));
    }

    @GetMapping("/reConfirmOrder")
    public HttpResponseResult<List<StudentPaymentOrder>> reConfirmOrder(Date startTime, Date endTime) {
        if (!profiles.equals("prod")) {
            return failed("测试环境不支持");
        }
        return succeed(studentPaymentOrderService.reConfirmOrder(startTime, endTime));
    }


}
