package com.ym.mec.web.controller;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.CloudTeacherOrderDao;
import com.ym.mec.biz.dal.dao.StudentInstrumentDao;
import com.ym.mec.biz.dal.dao.TeacherDao;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.enums.OrderDetailTypeEnum;
import com.ym.mec.biz.dal.enums.SysUserRoleEnum;
import com.ym.mec.biz.dal.page.MusicGroupQuitQueryInfo;
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.util.collection.MapUtil;
import com.ym.mec.util.date.DateUtil;
import com.ym.mec.util.json.JsonUtil;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

@RequestMapping("musicGroupQuit")
@Api(tags = "退团服务")
@RestController
public class MusicGroupQuitController extends BaseController {

    @Autowired
    private MusicGroupService musicGroupService;
    @Autowired
    private MusicGroupQuitService musicGroupQuitService;
    @Autowired
    private StudentRegistrationService studentRegistrationService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private StudentInstrumentDao studentInstrumentDao;
    @Autowired
    private CloudTeacherOrderDao cloudTeacherOrderDao;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private OrganizationService organizationService;
    @Autowired
    private SysEmployeePositionService employeePositionService;

    @ApiOperation(value = "分页查询")
    @RequestMapping("/queryPage")
    @PreAuthorize("@pcs.hasPermissions('musicGroupQuit/queryPage')")
    public HttpResponseResult queryPage(MusicGroupQuitQueryInfo queryInfo) throws Exception {
        queryInfo.setOrganId(organizationService.getEmployeeOrgan(queryInfo.getOrganId()));
        PageInfo<MusicGroupQuit> musicGroupQuitPageInfo = musicGroupQuitService.queryPage(queryInfo);
        List<MusicGroupQuit> rows = musicGroupQuitPageInfo.getRows();
        if (rows != null && rows.size() > 0) {
            List<Integer> applyUserIds = rows.stream().map(e -> e.getApplyUserId()).collect(Collectors.toList());
            applyUserIds.removeAll(Collections.singleton(null));
            Map<Integer, String> nameByIdList = new HashMap<>(applyUserIds.size());
            if(applyUserIds.size() > 0){
                nameByIdList = MapUtil.convertMybatisMap(teacherDao.queryNameByIdList(applyUserIds));
            }
            //查询是否有有效期内乐保
            Date nowDate = new Date();
            for (MusicGroupQuit row : rows) {
                if(row.getApplyUserId() != null){
                    row.setApplyUserName(nameByIdList.get(row.getApplyUserId()));
                }
                if (!row.getStatus().equals(ApprovalStatus.PROCESSING)) {
                    continue;
                }
                StudentInstrument studentMaintenance = studentInstrumentDao.getStudentMaintenance(row.getUserId(), row.getMusicGroupId());
                if (studentMaintenance != null) {
                    row.setHasMaintenance(true);
                }
                List<CloudTeacherOrder> cloudTeacherOrders = cloudTeacherOrderDao.getStudentCloudTeacherOrder(row.getUserId(),row.getMusicGroupId());
                if(cloudTeacherOrders.size() > 0){
                    BigDecimal orderAmount = BigDecimal.ZERO;
                    for (CloudTeacherOrder cloudTeacherOrder : cloudTeacherOrders) {
                        if (cloudTeacherOrder.getEndTime() == null || DateUtil.stringToDate(DateUtil.format(cloudTeacherOrder.getEndTime(),DateUtil.ISO_EXPANDED_DATE_FORMAT),DateUtil.ISO_EXPANDED_DATE_FORMAT).compareTo(
                                DateUtil.stringToDate(DateUtil.format(nowDate,DateUtil.ISO_EXPANDED_DATE_FORMAT),DateUtil.ISO_EXPANDED_DATE_FORMAT)) >= 0) {
                            orderAmount = orderAmount.add(cloudTeacherOrder.getAmount());
                        }
                    }
                    row.setCloudTeacherAmount(orderAmount);
                }
            }
        }
        return succeed(musicGroupQuitPageInfo);
    }

    @ApiOperation(value = "单查询")
    @GetMapping("/query")
    @PreAuthorize("@pcs.hasPermissions('musicGroupQuit/query')")
    public HttpResponseResult query(Long id) throws Exception {
        MusicGroupQuit musicGroupQuit = musicGroupQuitService.get(id);
        if (musicGroupQuit == null) {
            return failed("参数不正确");
        }

        SysUser user = sysUserFeignService.queryUserById(musicGroupQuit.getUserId());
        musicGroupQuit.getUser().setUsername(user.getUsername());

        MusicGroup musicGroup = musicGroupService.get(musicGroupQuit.getMusicGroupId());
        musicGroupQuit.setMusicGroup(musicGroup);
        
        if(StringUtils.isBlank(musicGroupQuit.getFeeJson())){
        	//从数据库中查询费用
        	Map<String,BigDecimal> map = studentRegistrationService.queryRefundsDetail(musicGroupQuit.getUserId(), musicGroupQuit.getMusicGroupId());
        	MusicGroupReturnFeeDto dto = new MusicGroupReturnFeeDto();
        	dto.setIsReturnAccessoriesFee(false);
        	dto.setAccessoriesFee(map.get(OrderDetailTypeEnum.ACCESSORIES.getCode()));
        	
        	dto.setIsReturnCourseFee(false);
        	dto.setCourseFee(map.get(OrderDetailTypeEnum.COURSE.getCode()));
        	
        	dto.setIsReturnMaintenanceFee(false);
        	dto.setMaintenanceFee(map.get(OrderDetailTypeEnum.MAINTENANCE.getCode()));
        	
        	dto.setIsReturnMemberFee(false);
        	dto.setMemberFee(map.get(OrderDetailTypeEnum.CLOUD_TEACHER.getCode()));
        	
        	dto.setIsReturnMusicalFee(false);
        	dto.setMusicalFee(map.get(OrderDetailTypeEnum.MUSICAL.getCode()));
        	
        	musicGroupQuit.setReturnFeeDto(dto);
        } else {
        	musicGroupQuit.setReturnFeeDto(JsonUtil.parseObject(musicGroupQuit.getFeeJson(), MusicGroupReturnFeeDto.class));
        }

        return succeed(musicGroupQuit);
    }
    
    @ApiOperation(value = "查询退费明细")
    @GetMapping("/queryRefundsDetail")
    @PreAuthorize("@pcs.hasPermissions('musicGroupQuit/queryRefundsDetail')")
	public HttpResponseResult queryRefundsDetail(Integer userId, String musicGroupId) throws Exception {
		Map<String, BigDecimal> map = studentRegistrationService.queryRefundsDetail(userId, musicGroupId);
		MusicGroupReturnFeeDto dto = new MusicGroupReturnFeeDto();
		dto.setIsReturnAccessoriesFee(false);
		dto.setAccessoriesFee(map.get(OrderDetailTypeEnum.ACCESSORIES.getCode()));

		dto.setIsReturnCourseFee(false);
		dto.setCourseFee(map.get(OrderDetailTypeEnum.COURSE.getCode()));

		dto.setIsReturnMaintenanceFee(false);
		dto.setMaintenanceFee(map.get(OrderDetailTypeEnum.MAINTENANCE.getCode()));

		dto.setIsReturnMemberFee(false);
		dto.setMemberFee(map.get(OrderDetailTypeEnum.CLOUD_TEACHER.getCode()));

		dto.setIsReturnMusicalFee(false);
		dto.setMusicalFee(map.get(OrderDetailTypeEnum.MUSICAL.getCode()));

		return succeed(dto);
	}

    @ApiOperation(value = "申请退团")
    @PostMapping("/apply")
    @PreAuthorize("@pcs.hasPermissions('musicGroupQuit/apply')")
    public HttpResponseResult applyQuitMusicGroup(@RequestBody MusicGroupQuit musicGroupQuit){
		SysUser sysUser = sysUserFeignService.queryUserInfo();
		if (sysUser == null) {
			return failed(HttpStatus.FORBIDDEN, "请登录");
		}
        List<SysUserRoleEnum> roleIds = employeePositionService.queryAllRole(sysUser.getId(),sysUser.getIsSuperAdmin());
        return succeed(musicGroupService.applyQuitMusicGroup(roleIds, musicGroupQuit, sysUser.getId()));
    }

    @ApiOperation(value = "退团")
    @PostMapping("/quitMusicGroup")
    @PreAuthorize("@pcs.hasPermissions('musicGroupQuit/quitMusicGroup')")
    public HttpResponseResult quitMusicGroup(@RequestBody MusicGroupQuit musicGroupQuit){
		SysUser sysUser = sysUserFeignService.queryUserInfo();
		if (sysUser == null || sysUser.getId() == null) {
			return failed(HttpStatus.FORBIDDEN, "请登录");
		}
        List<SysUserRoleEnum> roleIds = employeePositionService.queryAllRole(sysUser.getId(),sysUser.getIsSuperAdmin());
		if (!(roleIds.contains(SysUserRoleEnum.ORGAN_MANAGER) || roleIds.contains(SysUserRoleEnum.EDUCATION))) {
			return failed("未经授权，不能操作");
		}
        return succeed(musicGroupService.approveQuitMusicGroup(roleIds, musicGroupQuit));
    }

    @ApiOperation(value = "批量退团")
    @PostMapping("/batchQuitMusicGroup")
    @PreAuthorize("@pcs.hasPermissions('musicGroupQuit/batchQuitMusicGroup')")
    public HttpResponseResult batchQuitMusicGroup(@RequestBody List<MusicGroupQuit> musicGroupQuits) throws Exception {
		SysUser sysUser = sysUserFeignService.queryUserInfo();
		if (sysUser == null) {
			return failed(HttpStatus.FORBIDDEN, "请登录");
		}
        List<SysUserRoleEnum> roleIds = employeePositionService.queryAllRole(sysUser.getId(),sysUser.getIsSuperAdmin());
		if (!(roleIds.contains(SysUserRoleEnum.ORGAN_MANAGER) || roleIds.contains(SysUserRoleEnum.EDUCATION))) {
			throw new BizException("未经授权，不能操作");
		}
        for (MusicGroupQuit musicGroupQuit : musicGroupQuits) {
            musicGroupService.approveQuitMusicGroup(roleIds, musicGroupQuit);
        }
        return succeed();
    }

    @ApiOperation(value = "一键退团")
    @PostMapping("/directQuitMusicGroup")
    @PreAuthorize("@pcs.hasPermissions('musicGroupQuit/directQuitMusicGroup')")
    @ApiImplicitParams({@ApiImplicitParam(name = "musicGroupId", value = "乐团编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "userId", value = "用户编号", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "reason", value = "原因", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isRefundCourseFee", value = "是否退还课程费用", required = true, dataType = "Boolean"),
            @ApiImplicitParam(name = "isRefundInstrumentFee", value = "是否退还乐器费用（租金）", required = true, dataType = "Boolean"),
            @ApiImplicitParam(name = "isRefundTeachingAssistantsFee", value = "是否退还教辅费用", required = true, dataType = "Boolean"),
            @ApiImplicitParam(name = "maintenanceFee", value = "退乐保费用", required = true, dataType = "num"),
    })
    public HttpResponseResult directQuitMusicGroup(String musicGroupId, Integer userId, String reason, boolean isRefundCourseFee,
                                                   boolean isRefundInstrumentFee, boolean isRefundTeachingAssistantsFee,boolean isRefundMemberFee,
                                                   BigDecimal maintenanceFee) throws Exception {
        return succeed(musicGroupService.directQuitMusicGroup(musicGroupId, userId, reason, isRefundCourseFee, isRefundInstrumentFee,
                isRefundTeachingAssistantsFee,isRefundMemberFee, maintenanceFee));
    }
}
