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.auth.api.entity.SysUserRole;
import com.ym.mec.biz.dal.dao.*;
import com.ym.mec.biz.dal.dto.MusicGroupRegAndMoneyDto;
import com.ym.mec.biz.dal.dto.MusicalListDetailDto;
import com.ym.mec.biz.dal.entity.CooperationOrgan;
import com.ym.mec.biz.dal.entity.Employee;
import com.ym.mec.biz.dal.entity.MusicGroup;
import com.ym.mec.biz.dal.entity.StudentRegistration;
import com.ym.mec.biz.dal.enums.KitGroupPurchaseTypeEnum;
import com.ym.mec.biz.service.MusicGroupService;
import com.ym.mec.biz.service.OrganizationService;
import com.ym.mec.biz.service.StudentPaymentOrderDetailService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;
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.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("eduRegister")
@Api(tags = "乐团报名回款统计（教务端）")
@RestController
public class EduRegisterController extends BaseController {

    @Autowired
    private MusicGroupDao musicGroupDao;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private StudentPreRegistrationDao studentPreRegistrationDao;
    @Autowired
    private StudentRegistrationDao studentRegistrationDao;
    @Autowired
    private StudentPaymentOrderDetailService studentPaymentOrderDetailService;
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private CooperationOrganDao cooperationOrganDao;

    @ApiOperation(value = "获取分部报名、回款统计")
    @GetMapping("/getRegAndMoney")
    public HttpResponseResult<List<MusicGroupRegAndMoneyDto>> getRegAndMoney(String organId, String musicGroupName) {
        String organIds = null;
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        Employee employee = employeeDao.get(sysUser.getId());
        if (StringUtils.isEmpty(organId)) {
            organIds = 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("非法请求");
            }
            organIds = organId;
        }
        //是乐团主管，不是分部经理
        List<Integer> cooperationOrganIds = null;
        List<Integer> userRole = employeeDao.queryUserRole(sysUser.getId());
        if (!sysUser.getIsSuperAdmin() && !userRole.contains(SysUserRole.ADMINISTRATOR) && !userRole.contains(SysUserRole.SECTION_MANAGER)) {
            List<CooperationOrgan> cooperationOrgans = cooperationOrganDao.getCooperationOrganByEduTeacherId(sysUser.getId());
            if (cooperationOrgans.size() > 0) {
                cooperationOrganIds = cooperationOrgans.stream().map(CooperationOrgan::getId).collect(Collectors.toList());
            }else {
                return succeed();
            }
        }

        List<MusicGroupRegAndMoneyDto> musicGroups = musicGroupDao.getMusicGroupByStatus(organIds, cooperationOrganIds, musicGroupName);
        if (musicGroups.size() <= 0) {
            return succeed();
        }
        List<String> musicGroupIds = musicGroups.stream().map(MusicGroupRegAndMoneyDto::getMusicGroupId).collect(Collectors.toList());

        //预报名人数
        List<MusicGroupRegAndMoneyDto> preRegisters = studentPreRegistrationDao.getPreRegisterNum(musicGroupIds);
        List<MusicGroupRegAndMoneyDto> registers = studentRegistrationDao.getRegisters(musicGroupIds);

        for (MusicGroupRegAndMoneyDto musicGroup : musicGroups) {
            List<MusicalListDetailDto> musicalList = studentPaymentOrderDetailService.getMusicalListDetail(musicGroup.getMusicGroupId(), null);
            if (musicalList != null && musicalList.size() > 0) {
                Long instrumentNum = musicalList.stream().filter(e -> KitGroupPurchaseTypeEnum.GROUP.equals(e.getKitGroupPurchaseTypeEnum())).count();
                BigDecimal money = musicalList.stream().filter(e -> e.getOrderAmount() != null).map(MusicalListDetailDto::getOrderAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                musicGroup.setBuyInstrumentNum(instrumentNum.intValue());
                musicGroup.setMoney(money == null ? BigDecimal.ZERO : money);
            }

            for (MusicGroupRegAndMoneyDto preRegister : preRegisters) {
                if (!musicGroup.getMusicGroupId().equals(preRegister.getMusicGroupId())) continue;
                musicGroup.setPreRegNum(preRegister.getPreRegNum());
            }
            for (MusicGroupRegAndMoneyDto register : registers) {
                if (!musicGroup.getMusicGroupId().equals(register.getMusicGroupId())) continue;
                musicGroup.setRegNum(register.getRegNum());
                musicGroup.setPayNum(register.getPayNum());
                musicGroup.setCheckNum(register.getCheckNum());
                musicGroup.setBuyCloudTeacherNum(register.getBuyCloudTeacherNum());
            }
        }
        return succeed(musicGroups);
    }
}
