package com.ym.mec.web.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.dal.dao.EmployeeDao;
import com.ym.mec.biz.dal.dto.UpdateStudentFeeDto;
import com.ym.mec.biz.dal.entity.Employee;
import com.ym.mec.biz.dal.entity.Student;
import com.ym.mec.biz.dal.page.MusicGroupStudentQueryInfo;
import com.ym.mec.biz.dal.page.StudentManageAttendanceQueryInfo;
import com.ym.mec.biz.dal.page.StudentManageCourseQueryInfo;
import com.ym.mec.biz.dal.page.StudentManageQueryInfo;
import com.ym.mec.biz.dal.page.StudentManageVipClassQueryInfo;
import com.ym.mec.biz.dal.page.StudentOperatingQueryInfo;
import com.ym.mec.biz.dal.page.StudentSignQueryInfo;
import com.ym.mec.biz.dal.page.TeacherPaymentRecordInfo;
import com.ym.mec.biz.service.MusicGroupStudentFeeService;
import com.ym.mec.biz.service.StudentCourseHomeworkService;
import com.ym.mec.biz.service.StudentManageService;
import com.ym.mec.biz.service.StudentRegistrationService;
import com.ym.mec.biz.service.StudentService;
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.QueryInfo;

@Api(tags = "学生管理")
@RestController
@RequestMapping("studentManage")
public class StudentManageController extends BaseController {

    @Autowired
    private StudentManageService studentManageService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private StudentRegistrationService studentRegistrationService;
    @Autowired
    private MusicGroupStudentFeeService musicGroupStudentFeeService;
    @Autowired
    private StudentCourseHomeworkService studentCourseHomeworkService;
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private StudentService studentService;

    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
    @ApiOperation(value = "获取学生列表")
    @GetMapping("/queryStudentList")
    @PreAuthorize("@pcs.hasPermissions('studentManage/queryStudentList')")
    public Object queryStudentList(StudentManageQueryInfo queryInfo){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        if(!sysUser.getIsSuperAdmin()){
            Employee employee = employeeDao.get(sysUser.getId());
            if (StringUtils.isEmpty(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("非法请求");
                }
            }
        }
        queryInfo.setIsExport(false);
        return succeed(studentManageService.findStudentsByOrganId(queryInfo));
    }

    @ApiOperation(value = "获取指定分部学生列表")
    @GetMapping("/queryOrganStudentList")
    @PreAuthorize("@pcs.hasPermissions('studentManage/queryOrganStudentList')")
    public Object queryOrganStudentList(StudentManageQueryInfo queryInfo){
        if(StringUtils.isBlank(queryInfo.getOrganId())){
            return failed("请指定分部");
        }
        queryInfo.setIsExport(false);
        return succeed(studentManageService.findStudentsByOrganId(queryInfo));
    }

    @ApiOperation(value = "学员注册")
    @PostMapping("/register")
    @PreAuthorize("@pcs.hasPermissions('studentManage/register')")
    public Object studentRegister(Student student){
        return succeed(studentManageService.studentRegister(student));
    }

    @ApiOperation(value = "修改学员信息")
    @PostMapping("/studentUpdate")
    @PreAuthorize("@pcs.hasPermissions('studentManage/studentUpdate')")
    public Object studentUpdate(Student student){
        return succeed(studentManageService.studentUpdate(student));
    }

    @ApiOperation(value = "乐团管理--乐团详情--获取学员列表")
    @GetMapping("/queryMusicGroupStudent")
    @PreAuthorize("@pcs.hasPermissions('studentManage/queryMusicGroupStudent')")
    public Object queryMusicGroupStudent(MusicGroupStudentQueryInfo queryInfo){
        return succeed(studentManageService.queryMusicGroupStudent(queryInfo));
    }

    @ApiOperation(value = "乐团管理--乐团详情--学员列表--获取学员可排课时长")
    @GetMapping("/queryStudentSubTotalCourseTimes")
    @PreAuthorize("@pcs.hasPermissions('studentManage/queryStudentSubTotalCourseTimes')")
    public Object queryStudentSubTotalCourseTimes(String musicGroupId){
        return succeed(studentManageService.queryStudentSubTotalCourseTimes(musicGroupId));
    }

    @ApiOperation(value = "乐团修改--学员缴费记录--可新增学员列表")
    @GetMapping("/queryCanAddStudent")
    @PreAuthorize("@pcs.hasPermissions('studentManage/queryCanAddStudent')")
    public Object queryCanAddStudent(String musicGroupId,String batchNo,String search,Integer subjectId){
        return succeed(studentManageService.queryCanAddStudent(musicGroupId,batchNo,search,subjectId));
    }

    @ApiOperation(value = "乐团管理--乐团详情--学员列表--查看班级")
    @GetMapping("/queryStudentClassGroup")
    @PreAuthorize("@pcs.hasPermissions('studentManage/queryStudentClassGroup')")
    @ApiImplicitParams({@ApiImplicitParam(name = "teacherId", value = "学生编号", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "musicGroupId", value = "乐团编号", required = true, dataType = "String")})
    public Object queryStudentClassGroup(String musicGroupId,Integer teacherId){
        if(StringUtils.isEmpty(musicGroupId) || teacherId == null){
            return failed("参数校验失败");
        }
        return succeed(studentManageService.queryStudentClassGroup(musicGroupId,teacherId));
    }

    @ApiOperation(value = "乐团管理--乐团详情--学员列表，汇总数据接口")
    @GetMapping("/musicGroupStudentsSum")
    @PreAuthorize("@pcs.hasPermissions('studentManage/musicGroupStudentsSum')")
    public Object musicGroupStudentsSum(String musicGroupId){
        return succeed(studentManageService.musicGroupStudentsSum(musicGroupId));
    }

    @ApiOperation(value = "乐团管理--乐团详情--点名总览")
    @GetMapping("/queryMusicGroupStudentsSign")
    @PreAuthorize("@pcs.hasPermissions('studentManage/queryMusicGroupStudentsSign')")
    public Object queryMusicGroupStudentsSign(StudentSignQueryInfo queryInfo){
        return succeed(studentManageService.queryMusicGroupStudentsSign(queryInfo));
    }

    @ApiOperation(value = "根据学生ID获取学生基本报名信息")
    @GetMapping("/findStudentBaseInfo")
    @PreAuthorize("@pcs.hasPermissions('studentManage/findStudentBaseInfo')")
    public Object findStudentBaseInfo(@ApiParam(value = "学生编号", required = true) Integer userId){
        return succeed(studentManageService.findStudentManageBaseInfo(userId));
    }

    @ApiOperation(value = "根据学生ID获取其所在的乐团")
    @GetMapping("/findStudentMusicGroups")
    @PreAuthorize("@pcs.hasPermissions('studentManage/findStudentMusicGroups')")
    public Object findStudentMusicGroups(@ApiParam(value = "学生编号", required = true) Integer userId){
        return succeed(studentManageService.findStudentMusicGroupsByUserId(userId));
    }

    @ApiOperation("获取学生所在乐团列表名称")
    @GetMapping(value = "/queryUserMusicInfos")
    @PreAuthorize("@pcs.hasPermissions('studentManage/queryUserMusicInfos')")
    public Object queryUserMusicInfos(Integer userId) {
        return succeed(studentManageService.queryUserMusicInfos(userId));
    }

    @ApiOperation(value = "根据乐团获取排课列表")
    @GetMapping("/findStudentCourses")
    @PreAuthorize("@pcs.hasPermissions('studentManage/findStudentCourses')")
    public Object findStudentCourses(StudentManageCourseQueryInfo queryInfo){
        return succeed(studentManageService.findStudentCourseList(queryInfo));
    }

    @ApiOperation(value = "获取学生签到列表")
    @GetMapping("/findStudentAttendances")
    @PreAuthorize("@pcs.hasPermissions('studentManage/findStudentAttendances')")
    public Object findStudentAttendances(StudentManageAttendanceQueryInfo queryInfo){
        return succeed(studentManageService.findStudentAttendances(queryInfo));
    }

    @ApiOperation(value = "获取学生vip课程")
    @GetMapping("/findStudentVipGroups")
    @PreAuthorize("@pcs.hasPermissions('studentManage/findStudentVipGroups')")
    public Object findStudentVipGroups(StudentManageCourseQueryInfo queryInfo){
        return succeed(studentManageService.findStudentVipGroups(queryInfo));
    }

    @ApiOperation(value = "获取学生vip班级列表")
    @GetMapping("/findStudentVipGroupClass")
    @PreAuthorize("@pcs.hasPermissions('studentManage/findStudentVipGroupClass')")
    public Object findStudentVipGroupClass(StudentManageVipClassQueryInfo queryInfo){
        return succeed(studentManageService.findStudentVipGroupClass(queryInfo));
    }

    @ApiOperation(value = "获取用户默认账户基本信息")
    @GetMapping("/getUserCashAccountBaseInfo")
    @PreAuthorize("@pcs.hasPermissions('studentManage/getUserCashAccountBaseInfo')")
    public Object getUserCashAccountBaseInfo(Integer userId){
        return succeed(studentManageService.getStudentAccountBaseInfo(userId));
    }

    @ApiOperation(value = "获取学员扣费记录列表")
    @GetMapping("/queryStudentPayment")
    @PreAuthorize("@pcs.hasPermissions('studentManage/queryStudentPayment')")
    public Object queryStudentPayment(TeacherPaymentRecordInfo queryInfo){
        return succeed(studentManageService.queryStudentPayment(queryInfo));
    }

    /**
     * 获取学员基本信息
     * @param mobile
     * @return
     */
    @GetMapping(value = "/queryUserByPhone")
    @PreAuthorize("@pcs.hasPermissions('studentManage/queryUserByPhone')")
    public Object queryUserByPhone(String mobile) {
        return succeed(studentRegistrationService.queryUserByPhone(mobile));
    }

    /**
     * 修改学员缴费金额和缴费周期
     * @return
     */
    @PostMapping(value = "/updateStudentFee")
    @PreAuthorize("@pcs.hasPermissions('studentManage/updateStudentFee')")
    public Object updateStudentFee(UpdateStudentFeeDto studentFeeDto) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(sysUser == null){
            throw new BizException("用户信息获取失败");
        }
        LOGGER.info("修改学员缴费金额和缴费周期,user:{},参数:{}",sysUser.getId(),studentFeeDto);
        musicGroupStudentFeeService.updateStudentFee(studentFeeDto);
        return succeed();
    }

    /**
     * 修改学员缴费周期锁定状态
     * @return
     */
    @PostMapping(value = "/updateStudentFeeIsLock")
    @PreAuthorize("@pcs.hasPermissions('studentManage/updateStudentFeeIsLock')")
    public Object updateStudentFeeIsLock(UpdateStudentFeeDto studentFeeDto) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(sysUser == null){
            throw new BizException("用户信息获取失败");
        }
        LOGGER.info("修改学员缴费周期锁定状态,user:{},参数:{}",sysUser.getId(),studentFeeDto);
        musicGroupStudentFeeService.updateStudentFeeIsLock(studentFeeDto);
        return succeed();
    }

    /**
     * 获取学员缴费日历信息
     * @return
     */
    @GetMapping(value = "/findMusicGroupStudentFee")
    @PreAuthorize("@pcs.hasPermissions('studentManage/findMusicGroupStudentFee')")
    public Object findMusicGroupStudentFee(Integer studentId,String musicGroupId) {
        if(studentId == null || StringUtils.isEmpty(musicGroupId)){
            throw new BizException("参数校验异常");
        }
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(sysUser == null){
            throw new BizException("用户信息获取失败");
        }
        return succeed(musicGroupStudentFeeService.findByUser(studentId,musicGroupId));
    }

    /**
     * 获取课程学员作业列表
     * @return
     */
    @GetMapping(value = "/findStudentCourseHomeworks")
    @PreAuthorize("@pcs.hasPermissions('studentManage/findStudentCourseHomeworks')")
    public Object findStudentCourseHomeworks(QueryInfo queryInfo) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(sysUser == null){
            throw new BizException("用户信息获取失败");
        }
        return succeed(studentCourseHomeworkService.findStudentCourseHomeworks(queryInfo));
    }

    /**
     * 获取课程学员作业列表
     * @return
     */
    @GetMapping(value = "/sumStudentAttendance")
    @PreAuthorize("@pcs.hasPermissions('studentManage/sumStudentAttendance')")
    public Object sumStudentAttendance(Integer courseScheduleId) {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if(sysUser == null){
            throw new BizException("用户信息获取失败");
        }
        return succeed(studentManageService.sumStudentAttendance(courseScheduleId));
    }

    @ApiOperation(value = "获取运营指标列表")
    @GetMapping("/getOperatingStudents")
    @PreAuthorize("@pcs.hasPermissions('studentManage/getOperatingStudents')")
    public Object getOperatingStudents(StudentOperatingQueryInfo queryInfo){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        if(!sysUser.getIsSuperAdmin()){
            Employee employee = employeeDao.get(sysUser.getId());
            if (StringUtils.isEmpty(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("非法请求");
                }
            }
        }
        return succeed(studentManageService.getOperatingStudents(queryInfo));
    }

    @ApiOperation(value = "初始化教师编号")
    @GetMapping("/initTeacherId")
    @PreAuthorize("@pcs.hasPermissions('studentManage/initTeacherId')")
    public HttpResponseResult initTeacherId(){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        studentService.initTeacherId();
        return succeed();
    }

    @ApiOperation(value = "修改学员的指导老师")
    @PostMapping("/batchUpdateAdviser")
    @PreAuthorize("@pcs.hasPermissions('studentManage/batchUpdateAdviser')")
    public Object batchUpdateAdviser(Integer teacherId,String studentIds){
        studentService.batchUpdateAdviser(teacherId,studentIds);
        return succeed();
    }
}
