package com.ym.mec.web.controller.education;


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.page.ActivityStudentQueryInfo;
import com.ym.mec.biz.dal.page.CloudTeacherActiveQueryInfo;
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.tenant.TenantContextHolder;
import com.ym.mec.util.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

@RequestMapping("activity")
@Api(tags = "活动")
@RestController
public class ActivityController extends BaseController {
    @Autowired
    private StudentPaymentOrderDao studentPaymentOrderDao;
    @Autowired
    private SporadicChargeInfoDao sporadicChargeInfoDao;
    @Autowired
    private StudentRegistrationDao studentRegistrationDao;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private VipGroupActivityService vipGroupActivityService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private VipGroupDefaultClassesUnitPriceDao vipGroupDefaultClassesUnitPriceDao;
    @Autowired
    private VipGroupService vipGroupService;
    @Autowired
    private PracticeGroupService practiceGroupService;

    @ApiOperation(value = "获取待排课的活动方案列表")
    @RequestMapping("/queryWaitCourseActivity")
    public Object queryWaitCourseActivity(String organId){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        Employee employee = employeeDao.get(sysUser.getId());
        if (organId == null) {
            organId = employee.getOrganIdList();
        }else if(StringUtils.isEmpty(employee.getOrganIdList())){
            return failed("用户所在分部异常");
        }else {
            List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
            if(!list.containsAll(Arrays.asList(organId.split(",")))){
                return failed("非法请求");
            }
        }
        return succeed(vipGroupActivityService.queryWaitCourseActivity(null,organId));
    }

    @ApiOperation(value = "获取活动待排课学员数量")
    @RequestMapping("/getActivityWaitCourseStudentNum")
    public Object getActivityWaitCourseStudentNum(Integer activityId){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(sysUser == null){
            return failed("用户信息获取失败");
        }
        ActivityWaitCourseStudentNumDto courseStudentNum = vipGroupActivityService.getActivityWaitCourseStudentNum(null, activityId);
        VipGroupActivity vipGroupActivity = courseStudentNum.getVipGroupActivity();
        Employee employee = employeeDao.get(sysUser.getId());
        List<Integer> activityOrgans = Arrays.stream(vipGroupActivity.getOrganId().split(",")).mapToInt(Integer::valueOf).boxed().collect(Collectors.toList());
        if(StringUtils.isEmpty(employee.getOrganIdList())){
            courseStudentNum.setEmployeeAndActivityOrganIds(StringUtils.join(activityOrgans,","));
            return succeed(courseStudentNum);
        }
        List<Integer> employeeOrgans = Arrays.stream(employee.getOrganIdList().split(",")).mapToInt(Integer::valueOf).boxed().collect(Collectors.toList());
        employeeOrgans.retainAll(activityOrgans);
        courseStudentNum.setEmployeeAndActivityOrganIds(StringUtils.join(employeeOrgans,","));
        return succeed(courseStudentNum);
    }

    @ApiOperation(value = "获取活动学员课排课次数")
    @RequestMapping("/getActivityStudentCanCourseNum")
    public Object getActivityStudentCanCourseNum(ActivityStudentQueryInfo queryInfo){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(sysUser == null){
            return failed("用户信息获取失败");
        }
        return succeed(vipGroupActivityService.getActivityStudentCanCourseNum(queryInfo));
    }

    @ApiOperation(value = "分部双11活动统计")
    @GetMapping("/organDoubleEleven2021Statis")
    public HttpResponseResult organDoubleEleven2021Statis(OrganDoubleEleven2021StatisDto queryInfo){
        return succeed(vipGroupActivityService.organDoubleEleven2021Statis(queryInfo));
    }

    @ApiOperation(value = "双11活动统计")
    @GetMapping("/doubleEleven2021Statis")
    public HttpResponseResult doubleEleven2021Statis(){
        return succeed(vipGroupActivityService.doubleEleven2021Statis());
    }

    @ApiOperation(value = "分部双11活动统计")
    @GetMapping("/doubleEleven2020Statis")
    public HttpResponseResult<LuckStatisDto> doubleEleven2020Statis() {
        //获取所有参与分部
        List<Organization> organs = sporadicChargeInfoDao.getActiveOrgans(12, TenantContextHolder.getTenantId());
        //获取所有分部参与的订单
        List<OrderStatisDto> orders = studentPaymentOrderDao.doubleEleven2020Statis(organs);
        Set<Integer> orderOrganIds = orders.stream().map(OrderStatisDto::getOrganId).collect(Collectors.toSet());
        //获取所有分部预计的人数
        List<OrderStatisDto> organNormalStudents = studentRegistrationDao.getOrganNormalStudent(TenantContextHolder.getTenantId());
        //获取分部的目标金额
        List<OrganMaxAmountDto> maxAmount4Organs = sporadicChargeInfoDao.getActiveOrgansMaxAmount(12, TenantContextHolder.getTenantId());

        for (Organization organ : organs) {
            if (!orderOrganIds.contains(organ.getId())) {
                OrderStatisDto orderStatisDto = new OrderStatisDto();
                orderStatisDto.setOrganId(organ.getId());
                orderStatisDto.setOrganName(organ.getName());
                orders.add(orderStatisDto);
            }
        }
        BigDecimal totalMoney = BigDecimal.ZERO;
        Integer totalEstimatedNums = 0;
        Integer totalNum = 0;
        Integer totalTimes = 0;
        BigDecimal totalMaxAmount = BigDecimal.ZERO;
        for (OrderStatisDto order : orders) {
            for (OrganMaxAmountDto maxAmount4Organ : maxAmount4Organs) {
                if (order.getOrganId().equals(maxAmount4Organ.getId())) {
                    order.setMaxAmount(maxAmount4Organ.getMaxAmount() == null ? BigDecimal.ZERO.setScale(2,RoundingMode.HALF_UP) : maxAmount4Organ.getMaxAmount().setScale(2,RoundingMode.HALF_UP));
                    break;
                }
            }

            for (OrderStatisDto organNormalStudent : organNormalStudents) {
                if (order.getOrganId().equals(organNormalStudent.getOrganId())) {
                    order.setEstimatedNums(organNormalStudent.getEstimatedNums());
                    break;
                }
            }
            totalEstimatedNums += order.getEstimatedNums();
            totalNum += order.getNums();
            totalTimes += order.getTimes();
            totalMoney = totalMoney.add(order.getMoney());
            totalMaxAmount = totalMaxAmount.add(order.getMaxAmount());
            if (order.getMaxAmount().compareTo(BigDecimal.ZERO) <= 0) {
                order.setScale(new BigDecimal("100.00"));
            } else {
                order.setScale(order.getMoney().multiply(new BigDecimal(100)).divide(order.getMaxAmount(), 2, BigDecimal.ROUND_HALF_UP));
            }
        }
        orders.sort(Comparator.comparing(OrderStatisDto::getScale).reversed());

        LuckStatisDto luckStatisDto = new LuckStatisDto();
        luckStatisDto.setOrderStatisDtoList(orders);
        luckStatisDto.setTotalEstimatedNums(totalEstimatedNums);
        luckStatisDto.setTotalNum(totalNum);
        luckStatisDto.setTotalTimes(totalTimes);
        luckStatisDto.setTotalMoney(totalMoney);
        luckStatisDto.setTotalMaxAmount(totalMaxAmount);
        if (luckStatisDto.getTotalMaxAmount().compareTo(BigDecimal.ZERO) <= 0) {
            totalMaxAmount = BigDecimal.ONE;
        }
        luckStatisDto.setScale(totalMoney.multiply(new BigDecimal(100)).divide(totalMaxAmount, 2, BigDecimal.ROUND_HALF_UP));
        return succeed(luckStatisDto);
    }

    @ApiOperation(value = "云教练活动统计")
    @GetMapping("/countCloudTeacherActive")
    public Object countCloudTeacherActive(CloudTeacherActiveQueryInfo queryInfo) throws Exception {
        List<Organization> organizations = organizationService.queryEmployeeOrgan();
        List<Integer> organIds = new ArrayList<>();
        if(StringUtils.isNotBlank(queryInfo.getOrganIds())){
            organIds = Arrays.stream(queryInfo.getOrganIds().split(",")).map(id->Integer.valueOf(id)).collect(Collectors.toList());
        }else if(!CollectionUtils.isEmpty(organizations)){
            organIds = organizations.stream().map(Organization::getId).collect(Collectors.toList());
        }
        List<Integer> ids = organIds.stream().filter(id -> !OrganizationService.EXCLUDE_ORGAN_IDS.contains(id)).collect(Collectors.toList());
        return succeed(studentService.countCloudTeacherActive(ids, queryInfo));
    }
}
