package com.ym.mec.web.controller;

import com.ym.mec.auth.api.entity.SysUserRole;
import com.ym.mec.biz.dal.dao.CloudTeacherOrderDao;
import com.ym.mec.biz.dal.dao.StudentInstrumentDao;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.page.MusicGroupQuitQueryInfo;
import com.ym.mec.biz.service.EmployeeService;
import com.ym.mec.common.page.PageInfo;
import com.ym.mec.util.date.DateUtil;
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.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.service.MusicGroupQuitService;
import com.ym.mec.biz.service.MusicGroupService;
import com.ym.mec.common.controller.BaseController;
import com.ym.mec.common.entity.HttpResponseResult;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

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

    @Autowired
    private MusicGroupService musicGroupService;

    @Autowired
    private MusicGroupQuitService musicGroupQuitService;

    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private StudentInstrumentDao studentInstrumentDao;
    @Autowired
    private CloudTeacherOrderDao cloudTeacherOrderDao;

    @ApiOperation(value = "分页查询")
    @RequestMapping("/queryPage")
    @PreAuthorize("@pcs.hasPermissions('musicGroupQuit/queryPage')")
    public HttpResponseResult queryPage(MusicGroupQuitQueryInfo queryInfo) throws Exception {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        Employee employee = employeeService.get(sysUser.getId());
        if (StringUtils.isBlank(queryInfo.getOrganId())) {
            queryInfo.setOrganId(employee.getOrganIdList());
        } else if (StringUtils.isEmpty(employee.getOrganIdList())) {
            return failed("用户所在分部异常");
        } else {
            List<String> list = Arrays.asList(employee.getOrganIdList().split(","));
            if (!list.containsAll(Arrays.asList(queryInfo.getOrganId().split(",")))) {
                return failed("非法请求");
            }
        }
        List<Integer> userRole = employeeService.queryUserRole(sysUser.getId());
        //如果当前用户只有教务老师角色，那么只能看到他所管理的课程组的信息
        if (userRole.size() == 1 && userRole.contains(SysUserRole.EDUCATIONAL_TEACHER)) {
            queryInfo.setEducationUserId(sysUser.getId());
        }
        PageInfo<MusicGroupQuit> musicGroupQuitPageInfo = musicGroupQuitService.queryPage(queryInfo);

        if (musicGroupQuitPageInfo.getRows() != null && musicGroupQuitPageInfo.getRows().size() > 0) {
            //查询是否有有效期内乐保
            Date nowDate = new Date();
            for (MusicGroupQuit row : musicGroupQuitPageInfo.getRows()) {
                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);

        return succeed(musicGroupQuit);
    }

    @ApiOperation(value = "退团")
    @PostMapping("/quitMusicGroup")
    @PreAuthorize("@pcs.hasPermissions('musicGroupQuit/quitMusicGroup')")
    @ApiImplicitParams({@ApiImplicitParam(name = "id", value = "退团申请id", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "status", value = "审批状态（APPROVED, DENIED, PROCESSING）", required = true, dataType = "String"),
            @ApiImplicitParam(name = "reason", value = "原因", required = true, dataType = "String"),
            @ApiImplicitParam(name = "isRefundMemberFee", value = "是否退还云教练费用", required = true, dataType = "Boolean"),
            @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 quitMusicGroup(Long id, ApprovalStatus status, String reason, boolean isRefundCourseFee, boolean isRefundInstrumentFee,
                                             boolean isRefundTeachingAssistantsFee,boolean isRefundMemberFee, BigDecimal maintenanceFee,BigDecimal cloudTeacherAmount) throws Exception {
        return succeed(musicGroupService.approveQuitMusicGroup(id, status, reason, isRefundCourseFee, isRefundInstrumentFee, isRefundTeachingAssistantsFee
                ,isRefundMemberFee, maintenanceFee, cloudTeacherAmount));
    }

    @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 = "isRefundMemberFee", value = "是否退还云教练费用", required = true, dataType = "Boolean"),
            @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, BigDecimal cloudTeacherAmount) throws Exception {
        return succeed(musicGroupService.directQuitMusicGroup(musicGroupId, userId, reason, isRefundCourseFee, isRefundInstrumentFee,
                isRefundTeachingAssistantsFee,isRefundMemberFee, maintenanceFee, cloudTeacherAmount));
    }
}
