package com.ym.mec.student.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huifu.adapay.core.AdapayCore;
import com.huifu.adapay.core.util.AdapaySign;
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.*;
import com.ym.mec.biz.dal.page.StudentPaymentOrderQueryInfo;
import com.ym.mec.biz.service.*;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
import com.ym.mec.common.exception.BizException;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.common.tenant.TenantContextHolder;
import com.ym.mec.thirdparty.yqpay.Msg;
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.collections.CollectionUtils;
import org.apache.commons.lang.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.web.bind.annotation.*;

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

@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 StudentPaymentOrderDao studentPaymentOrderDao;
    @Autowired
    private SysConfigDao sysConfigDao;
    @Autowired
    private SporadicChargeInfoService sporadicChargeInfoService;
    @Autowired
    private OrganizationDao organizationDao;
    @Autowired
    private CourseScheduleEvaluateDao courseScheduleEvaluateDao;
    @Autowired
    private StudentGoodsSellDao studentGoodsSellDao;
    @Autowired
    private LuckDrawCountService luckDrawCountService;
    @Autowired
    private DegreeRegistrationDao degreeRegistrationDao;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private MusicGroupPaymentCalenderDao musicGroupPaymentCalenderDao;
    @Autowired
    private MusicGroupPaymentCalenderCourseSettingsDao musicGroupPaymentCalenderCourseSettingsDao;
    @Autowired
    private ReplacementInstrumentActivityDao replacementInstrumentActivityDao;
    @Autowired
    private ChildrenDayDegreeDetailDao childrenDayDegreeDetailDao;
    @Autowired
    private CloudTeacherOrderService cloudTeacherOrderService;
    @Autowired
    private SysCouponCodeDao sysCouponCodeDao;
    @Autowired
    private StudentRegistrationDao studentRegistrationDao;
    @Autowired
    private VipGroupActivityDao vipGroupActivityDao;
    @Autowired
    private SellOrderService sellOrderService;
    @Autowired
    private TenantOrderRecordService tenantOrderRecordService;
    @Autowired
    private OrderPayOpsService orderPayOpsService;
    @Autowired
    private MusicGroupPaymentCalenderActivityService musicGroupPaymentCalenderActivityService;
    @Autowired
    private TenantConfigService tenantConfigService;
    @Autowired
    private OrganizationService organizationService;

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

    @ApiOperation(value = "查询订单列表")
    @GetMapping("/queryPage")
    public Object findGroupUsers(StudentPaymentOrderQueryInfo queryInfo) {
        SysUser user = sysUserFeignService.queryUserInfo();
        if (user == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        queryInfo.setStudentId(user.getId());
        PageInfo<StudentPaymentOrderDto> studentPaymentOrderPageInfo = studentPaymentOrderService.OrderQueryPage(queryInfo);
        return succeed(studentPaymentOrderPageInfo);
    }

    @PostMapping("/callback")
	public String callback(HttpServletRequest request) {
		try {
			// 验签请参data
			String data = request.getParameter("data");
			// 验签请参sign
			String sign = request.getParameter("sign");
			
			logger.info("callback request param:{}", data);

			// 验签
			if (AdapaySign.verifySign(data, sign, AdapayCore.PUBLIC_KEY)) {
				
				JSONObject dataObj = JSON.parseObject(data);
				
				String transType = request.getParameter("type");
				
				Map<String, String> notifyMap = new HashMap<>();

				switch (transType) {
				case "payment.succeeded":// 支付成功

					notifyMap.put("channelType", dataObj.getString("pay_channel"));
					notifyMap.put("tradeState", "1");
					notifyMap.put("totalMoney", dataObj.getString("pay_amt"));
					notifyMap.put("merOrderNo", dataObj.getString("order_no"));
					studentPaymentOrderService.updateOrder(notifyMap);
					break;

				case "payment.failed":// 支付失败

					notifyMap.put("channelType", dataObj.getString("pay_channel"));
					notifyMap.put("tradeState", "0");
					notifyMap.put("totalMoney", dataObj.getString("pay_amt"));
					notifyMap.put("merOrderNo", dataObj.getString("order_no"));
					studentPaymentOrderService.updateOrder(notifyMap);

					break;

				default:
					break;
				}
			} else {
				return "验签失败";
			}
		} catch (Exception e) {
			return e.getMessage();
		}
		
		return "succeeded";
	}

    @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)) {
            logger.info("checkOrderStatus >>>> tenantOrder {}", orderNo);
            Map<String, Object> tenantOrder = tenantOrderRecordService.checkTenantOrder(orderNo);
            if (Objects.nonNull(tenantOrder)) {
                return succeed(tenantOrder);
            }
            return failed("未找到指定订单");
        }
        HashMap<String, Object> orderDetail = new HashMap<>();
        orderDetail.put("order", orderByOrderNo);
        orderDetail.put("groupType", orderByOrderNo.getGroupType());
        
        //查询财务章
        //如果分部有企业信息，就用分部上的企业信息，否则用机构上的企业信息
        String financeChops = null;
        Organization organizationDto = organizationService.get(orderByOrderNo.getOrganId());
		if (organizationDto == null || StringUtils.isBlank(organizationDto.getCorporateName()) || StringUtils.isBlank(organizationDto.getCorporateCode())) {

			TenantConfig tenantConfig = tenantConfigService.queryByTenantId(orderByOrderNo.getTenantId());
			if(tenantConfig == null){
				throw new BizException("机构配置信息查询失败");
			}
			
			financeChops = tenantConfig.getCorporateFinanceChops();
		} else {
			financeChops = organizationDto.getCorporateFinancialSeal();
		}
		if(StringUtils.isNotBlank(financeChops)){
			orderDetail.put("financeChops", financeChops);
		}
		
        if (OrderTypeEnum.APPLY.equals(orderByOrderNo.getType())) {
            StudentRegistration studentRegistration = studentRegistrationDao.getStudentRegister(orderByOrderNo.getMusicGroupId(), orderByOrderNo.getUserId());
            if (studentRegistration.getPayingStatus().equals(2)) {
                orderDetail.put("payingStatus", studentRegistration.getPayingStatus());
            }
        }

        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());
            List<String> orderDetailType = orderDetail1.stream().map(e -> e.getType().getCode()).collect(Collectors.toList());
            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);
            orderDetail.put("chargeTypeId", musicGroup.getChargeTypeId());
            orderDetail.put("courseViewType", musicGroup.getCourseViewType());

            //新的课程形态10.27
            MusicGroupPaymentCalender musicGroupRegCalender = musicGroupPaymentCalenderDao.getMusicGroupRegCalender(musicGroup.getId());
            if (musicGroupRegCalender != null) {
                List<MusicGroupPaymentCalenderCourseSettings> courseSettings = musicGroupPaymentCalenderCourseSettingsDao.getMusicGroupRegCalenderCourseSettings(musicGroup.getId());
                musicGroupRegCalender.setMusicGroupPaymentCalenderCourseSettingsList(courseSettings);
                //如果包含vip和网管，代表购买了活动包
                List<Long> activityList = orderDetail1.stream().filter(e -> e.getType() == OrderDetailTypeEnum.VIP
                        || e.getType() == OrderDetailTypeEnum.PRACTICE).map(e -> e.getStudentInstrumentId())
                        .collect(Collectors.toList());
                if(activityList != null && activityList.size() > 0){
                    orderDetail.put("activity", musicGroupPaymentCalenderActivityService.findByActivityIds(activityList,musicGroupRegCalender.getId()));
                }
            }
            orderDetail.put("calender", musicGroupRegCalender);

            //判断是否是系统收费
            if (musicGroup.getCourseViewType() == CourseViewTypeEnum.MEMBER_FEE) {
                orderDetail.put("member", cloudTeacherOrderService.queryOrderInfoByOrderId(orderByOrderNo.getId()));
            }
        } else if (orderByOrderNo.getGroupType().equals(GroupType.VIP)) {
            if(orderByOrderNo.getType() == OrderTypeEnum.ACTIVITY){
                orderDetail.put("activity", vipGroupActivityDao.queryByIds(orderByOrderNo.getActivityId()));
            }else if (StringUtils.isNotEmpty(orderByOrderNo.getMusicGroupId())) {
                VipBuyResultDto vipBuyResultInfo = vipGroupService.findVipBuyResultInfo(Integer.valueOf(orderByOrderNo.getMusicGroupId()));
                orderDetail.put("detail", vipBuyResultInfo);
            }
        } else if (orderByOrderNo.getGroupType().equals(GroupType.SPORADIC)) {
            if (Objects.nonNull(orderByOrderNo.getMusicGroupId())) {
                List<SporadicChargeInfo> info = sporadicChargeInfoService.findByIds(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())) {
                List<DegreeRegistration> degreeRegistration = degreeRegistrationDao.findByByOrderId(orderByOrderNo.getOrderNo());
//                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));
        } else if (orderByOrderNo.getGroupType().equals(GroupType.REPLACEMENT)) {
            orderDetail.put("detail", replacementInstrumentActivityDao.getInfo(Integer.parseInt(orderByOrderNo.getMusicGroupId())));
        } else if (orderByOrderNo.getGroupType().equals(GroupType.DEGREE)) {
            orderDetail.put("detail", childrenDayDegreeDetailDao.getByOrderId(orderByOrderNo.getId()));
        } else if (orderByOrderNo.getGroupType().equals(GroupType.ACTIVITY)) {
            orderDetail.put("detail", vipGroupActivityDao.queryByIds(orderByOrderNo.getActivityId()));
        } else if (orderByOrderNo.getGroupType().equals(GroupType.MEMBER)) {
            CloudTeacherOrderDto orderDto = cloudTeacherOrderService.queryOrderInfoByOrderId(orderByOrderNo.getId());
            orderDetail.put("detail", orderDto);
            if (orderDto != null) {
                Map<String, Object> map = new HashMap<>(1);
                map.put("paymentOrderId", orderDto.getCloudTeacherOrder().getOrderId());
                orderDetail.put("couponList", sysCouponCodeDao.querySysCouponUseList(map));
            }
        } else if (orderByOrderNo.getGroupType().equals(GroupType.LIVE_BUY)) {
            orderDetail.put("detail", vipGroupActivityDao.queryByIds(orderByOrderNo.getActivityId()));
            orderDetail.put("goodsId",orderByOrderNo.getClassGroupId());
        }
        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(@RequestBody PaymentParam paymentParam) {
        try {
            Map<String, Object> payment = orderPayOpsService.executePayment(paymentParam);
            return succeed(payment);
        } catch (Exception e) {
            return failed(e.getMessage());
        }
    }

    @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(String orderNo) throws Exception {
        if (!profiles.equals("dev") && !profiles.equals("test")) {
            return failed("非法操作");
        }
        List<StudentPaymentOrder> payingOrders = studentPaymentOrderService.findOrdersByStatus(DealStatusEnum.ING, "ADAPAY");

        String[] statusArr = {"0", "1", "7"};
        for (StudentPaymentOrder payingOrder : payingOrders) {
            if (StringUtils.isNotBlank(orderNo) && !orderNo.equals(payingOrder.getOrderNo())) {
                continue;
            }
            if (org.apache.commons.lang3.StringUtils.isNotBlank(payingOrder.getMusicGroupId()) && Objects.nonNull(payingOrder.getUserId())) {
                StudentRegistration studentRegister = studentRegistrationDao.getStudentRegister(payingOrder.getMusicGroupId(), payingOrder.getUserId());
                if (Objects.nonNull(studentRegister) && studentRegister.getPayingStatus() == 2) {
                    //跳过审核中的
                    continue;
                }
            }

            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();
    }

    @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(TenantContextHolder.getTenantId());
        List<OrderStatisDto> orders = studentPaymentOrderDao.getLuckStatis(TenantContextHolder.getTenantId());


        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() {
        Integer tenantId = TenantContextHolder.getTenantId();
        List<Organization> organs = organizationDao.findAllOrgans(tenantId);
        List<PracticeGroupsDto> hasReportNums = courseScheduleEvaluateDao.getHasReportNums(tenantId);
        List<PracticeGroupsDto> organMoneys = courseScheduleEvaluateDao.getOrganMoney(tenantId);
        List<PracticeGroupsDto> organPracticeGroups = courseScheduleEvaluateDao.getOrganPracticeGroups(tenantId);
        List<PracticeGroupsDto> practiceGroupsFrees = courseScheduleEvaluateDao.getPracticeGroupsFree(tenantId);
        List<PracticeGroupsDto> practiceGroupsBuys = courseScheduleEvaluateDao.getPracticeGroupsBuy(tenantId);
        List<PracticeGroupsDto> practiceGroupsRenews = courseScheduleEvaluateDao.getPracticeGroupsRenew(tenantId);

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

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

        //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();
        Integer tenantId = TenantContextHolder.getTenantId();
        List<Organization> organs = organizationDao.findAllOrgans(tenantId);
        //除去禁止的体验人数
//        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(tenantId);

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

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


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

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

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

        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(studentPaymentOrderService.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));
    }

    @GetMapping("/getMusicGroupApplyCalender")
    public HttpResponseResult<MusicGroupPaymentCalender> getMusicGroupApplyCalender(String musicGroupId) {
        MusicGroupPaymentCalender musicGroupRegCalender = musicGroupPaymentCalenderDao.getMusicGroupRegCalender(musicGroupId);
        if (musicGroupRegCalender != null) {
            MusicGroup musicGroup = musicGroupService.get(musicGroupId);
            musicGroupRegCalender.setChargeTypeId(musicGroup.getChargeTypeId());
            List<MusicGroupPaymentCalenderCourseSettings> courseSettings = musicGroupPaymentCalenderCourseSettingsDao.getMusicGroupRegCalenderCourseSettings(musicGroupId);
            musicGroupRegCalender.setMusicGroupPaymentCalenderCourseSettingsList(courseSettings);
            musicGroupRegCalender.setCourseViewType(musicGroup.getCourseViewType());
        }
        return succeed(musicGroupRegCalender);
    }

    @GetMapping("fixSellOrder")
    public HttpResponseResult<List<SellOrder>> fixSellOrder(String orderNo) {
        StudentPaymentOrder order = studentPaymentOrderService.findOrderByOrderNo(orderNo);
        List<SellOrder> sellOrders = new ArrayList<>();
        if (order == null || !order.getStatus().equals(DealStatusEnum.SUCCESS) || !order.getType().equals(OrderTypeEnum.APPLY)) {
            return succeed(sellOrders);
        }

        List<StudentPaymentOrderDetail> orderDetails = studentPaymentOrderDetailService.getOrderGoodsDetail(order.getId());
        //销售订单详情
        if (orderDetails.size() > 0) {
            MusicGroup musicGroup = musicGroupService.get(order.getMusicGroupId());
            BigDecimal couponRemitFee = order.getCouponRemitFee();
            if (couponRemitFee.compareTo(BigDecimal.ZERO) > 0) {
                BigDecimal musicFee = orderDetails.stream().filter(o -> o.getType().getCode().equals("MUSICAL")
                                || o.getType().getCode().equals("ACCESSORIES") || o.getType().getCode().equals("TEACHING"))
                        .map(o -> o.getPrice()).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal expectAmount = order.getExpectAmount();
                //获取比例
                BigDecimal ratioAmount = musicFee.divide(expectAmount, 6, BigDecimal.ROUND_HALF_UP);
                //获取分配的减免金额
                couponRemitFee = couponRemitFee.multiply(ratioAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
            }
            sellOrders = sellOrderService.addOrderDetail2SellOrder(orderDetails, order, musicGroup, couponRemitFee);
        }
        return succeed(sellOrders);

    }

    @ApiImplicitParams({
            @ApiImplicitParam(name = "queryDate", dataType = "String", value = "年月"),
            @ApiImplicitParam(name = "page", dataType = "Integer", value = "页数"),
            @ApiImplicitParam(name = "rows", dataType = "Integer", value = "每页数量"),
    })
    @ApiOperation("分页查询")
    /**
     * 学生端查询订单
     */
    @PostMapping("/queryOrder")
    public Object queryOrder(@RequestBody Map<String, Object> param) throws Exception {
        return succeed(studentPaymentOrderService.queryOrder(param));
    }

    /**
     * 学生端查询订单详情
     */
    @GetMapping("/queryOrderDetail")
    public Object queryOrderDetail(String orderNo) {
        return succeed(studentPaymentOrderService.queryOrderDetail(orderNo));
    }
}
