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.EmployeeDao;
import com.ym.mec.biz.dal.dao.TeacherDao;
import com.ym.mec.biz.dal.dto.ClassDateAdjustDto;
import com.ym.mec.biz.dal.dto.VipGroupApplyBaseInfoDto;
import com.ym.mec.biz.dal.dto.VipGroupApplyDto;
import com.ym.mec.biz.dal.entity.*;
import com.ym.mec.biz.dal.entity.StudentApplyRefunds.StudentApplyRefundsStatus;
import com.ym.mec.biz.dal.enums.AuditStatusEnum;
import com.ym.mec.biz.dal.enums.VipGroupStatusEnum;
import com.ym.mec.biz.dal.page.VipGroupAttendanceQueryInfo;
import com.ym.mec.biz.dal.page.VipGroupQueryInfo;
import com.ym.mec.biz.dal.page.VipGroupSalaryQueryInfo;
import com.ym.mec.biz.dal.page.VipGroupTeachingRecordQueryInfo;
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 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.security.access.prepost.PreAuthorize;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

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

/**
 * @Author Joburgess
 * @Date 2019/9/21
 */
@Api(tags = "vip课")
@RequestMapping("vipGroupManage")
@RestController
public class VipGroupManageController extends BaseController {

    @Autowired
    private VipGroupService vipGroupService;
    @Autowired
    private CourseScheduleService scheduleService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    @Autowired
    private TeacherDao teacherDao;
    @Autowired
    private EmployeeDao employeeDao;

    @Autowired
    private StudentApplyRefundsService studentApplyRefundsService;
    
    @Autowired
    private StudentPaymentOrderService studentPaymentOrderService;
    @Autowired
    private CourseScheduleTeacherSalaryService courseScheduleTeacherSalaryService;

    @GetMapping("/teacherSalarySettlement")
    public Object teacherSalarySettlement(){
        courseScheduleTeacherSalaryService.teacherSalarySettlement();
        return succeed();
    }

    @ApiOperation(value = "vip修改")
    @PostMapping("/update")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/update')")
    public HttpResponseResult update(VipGroup vipGroup){
        if(Objects.nonNull(vipGroup.getCoursesExpireDate())){
            VipGroup oldVipGroup = vipGroupService.get(vipGroup.getId());
            if(Objects.isNull(oldVipGroup)){
                throw new BizException("此课程组不存在");
            }
            if(!VipGroupStatusEnum.PROGRESS.equals(oldVipGroup.getStatus())&&!VipGroupStatusEnum.PAUSE.equals(oldVipGroup.getStatus())){
                throw new BizException("此课程组状态暂不支持修改");
            }
        }
        vipGroupService.update(vipGroup);
        return succeed();
    }

    @ApiOperation(value = "vip课申请")
    @PostMapping("/vipGroupApply")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/vipGroupApply')")
    public Object vipGroupApply(@RequestBody VipGroupApplyDto vipGroupApplyDto){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        Integer userId = vipGroupApplyDto.getVipGroupApplyBaseInfo().getUserId();
        Teacher teacher = teacherDao.get(userId);
        if(Objects.isNull(teacher)){
            return failed("请指定指导老师!");
        }
        if(Objects.isNull(vipGroupApplyDto.getVipGroupApplyBaseInfo().getOrganId())){
            Employee employee = employeeDao.get(sysUser.getId());
            if(StringUtils.isEmpty(employee.getOrganIdList()) || employee.getOrganIdList().contains(",")){
                vipGroupApplyDto.getVipGroupApplyBaseInfo().setOrganId(teacher.getTeacherOrganId());
            }else {
                vipGroupApplyDto.getVipGroupApplyBaseInfo().setOrganId(Integer.parseInt(employee.getOrganIdList()));
            }
        }
        return succeed(vipGroupService.createVipGroup(vipGroupApplyDto));
    }

    @ApiOperation(value = "获取教务与指导老师公共分部")
    @GetMapping("/getPublicOrgans")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/getPublicOrgans')")
    public HttpResponseResult getPublicOrgans(Integer eduTeacherId, Integer teacherId){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed("用户信息获取失败");
        }
        if(Objects.isNull(eduTeacherId)){
            eduTeacherId=sysUser.getId();
        }
        return succeed(vipGroupService.getPublicOrgans(eduTeacherId, teacherId));
    }

    @ApiOperation(value = "全查询")
    @GetMapping("/queryAll")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/queryAll')")
    public Object queryAll(VipGroupQueryInfo 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(vipGroupService.findVipGroups(queryInfo));
    }

    @ApiOperation(value = "删除课程组")
    @PostMapping("/deleteVipGroup")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/deleteVipGroup')")
    public HttpResponseResult deleteVipGroup(Long vipGroupId){
        vipGroupService.deleteVipGroup(vipGroupId);
        return succeed();
    }

    @ApiOperation(value = "获取小课学员")
    @GetMapping(value = "/findVipGroupStudents")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/findVipGroupStudents')")
    public Object findVipGroupStudents(VipGroupQueryInfo queryInfo){
        return succeed(vipGroupService.findVipGroupStudents(queryInfo));
    }

    @ApiOperation(value = "获取还有课程余额的学员")
    @GetMapping(value = "/findHaveCourseBalanceStudents")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/findHaveCourseBalanceStudents')")
    public Object findHaveCourseBalanceStudents(VipGroupQueryInfo queryInfo){
        return succeed(vipGroupService.findHaveCourseBalanceStudents(queryInfo));
    }

    @ApiOperation(value = "添加vip课学员")
    @GetMapping(value = "/addVipGroupStudents")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/addVipGroupStudents')")
    public Object addVipGroupStudents(Long vipGroupId, String studentIds){
        if(StringUtils.isBlank(studentIds)){
            throw new BizException("请指定学员");
        }
        List<Integer> ids=new ArrayList<>();
        String[] split = studentIds.split(",");
        for (String s : split) {
            ids.add(Integer.parseInt(s));
        }
        vipGroupService.addVipGroupStudents(vipGroupId,ids);
        return succeed();
    }

    @ApiOperation(value = "vip课详情")
    @GetMapping("/getVipGroupDetail")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/getVipGroupDetail')")
    public Object getVipGroupDetail(Long vipGroupId){
        return succeed(vipGroupService.getVipGroupDetail(vipGroupId));
    }

    @ApiOperation(value = "vip课详情")
    @GetMapping("/getVipGroupDetailForAudit")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/getVipGroupDetailForAudit')")
    public Object getVipGroupDetailForAudit(Long vipGroupId){
        return succeed(vipGroupService.getVipGroupDetailForAudit(vipGroupId));
    }

    @ApiOperation(value = "获取vip课考勤记录")
    @PostMapping("/getVipGroupAttendances")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/getVipGroupAttendances')")
    public Object getVipGroupAttendances(@RequestBody VipGroupAttendanceQueryInfo queryInfo){
        return succeed(vipGroupService.findVipGroupAttendances(queryInfo));
    }

    @ApiOperation(value = "休学")
    @PostMapping("/pauseForStudent")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/pauseForStudent')")
    public Object pauseForStudent(Long vipGroupId,Integer studentId){
        vipGroupService.pauseForStudent(vipGroupId,studentId);
        return succeed();
    }

    @ApiOperation(value = "恢复休学")
    @PostMapping("/recoverForStudent")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/recoverForStudent')")
    public Object recoverForStudent(@RequestBody StudentRecoverDto studentRecoverInfo){
        vipGroupService.recoverForStudent(studentRecoverInfo);
        return succeed();
    }

    @ApiOperation(value = "获取学生休学信息")
    @PostMapping("/getStudentPauseInfo")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/getStudentPauseInfo')")
    public Object getStudentPauseInfo(Long vipGroupId,Integer studentId){
        return succeed(vipGroupService.getStudentPauseInfo(vipGroupId,studentId));
    }

    @ApiOperation(value = "根据vip课所在部门与声部获取教师")
    @GetMapping("/findTeacherWithVipGroupOrganAndSubject")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/findTeacherWithVipGroupOrganAndSubject')")
    public Object findTeacherWithVipGroupOrganAndSubject(Long vipGroupId){
        return succeed(vipGroupService.findTeacherWithVipGroupOrganAndSubject(vipGroupId));
    }

    @ApiOperation(value = "退课申请")
    @PostMapping("/applyRefundForStudent")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/applyRefundForStudent')")
    public Object applyRefundForStudent(Long vipGroupId,Integer studentId, BigDecimal amount){
        vipGroupService.applyRefundForStudent(vipGroupId,studentId,amount);
        return succeed();
    }

    @ApiOperation(value = "退课申请审核")
    @PostMapping("/applyRefundAudit")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/applyRefundAudit')")
	public Object applyRefundAudit(Long id, StudentApplyRefundsStatus status, String remark, BigDecimal amount) {
		vipGroupService.applyRefundAudit(id, status, remark, amount);
		return succeed();
	}

    @ApiOperation(value = "查询退费详情")
    @GetMapping("/queryApplyRefundDetail")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/queryApplyRefundDetail')")
	public Object queryApplyRefundDetail(Long id) {
		StudentApplyRefunds studentApplyRefunds = studentApplyRefundsService.get(id);
		if (studentApplyRefunds == null) {
			return failed("参数输入有误");
		}

		Long orderId = studentApplyRefunds.getOrigPaymentOrderId();

		StudentPaymentOrder paymentOrder = studentPaymentOrderService.get(orderId);
		if (paymentOrder == null) {
			return failed("支付订单信息找不到");
		}
		String vipGroupId = paymentOrder.getMusicGroupId();
		VipGroup vipGroup = vipGroupService.get(Long.parseLong(vipGroupId));
		if (vipGroup == null) {
			return failed("vip课信息找不到");
		}

		SysUser student = sysUserFeignService.queryUserById(studentApplyRefunds.getUserId());

		SysUser teacher = sysUserFeignService.queryUserById(vipGroup.getUserId());

		ModelMap model = new ModelMap();
		model.put("student", student.getUsername());
		model.put("teacher", teacher.getUsername());
		model.put("className", vipGroup.getName());
		model.put("studentApplyRefunds", studentApplyRefunds);

		return succeed(model);
	}

    @ApiOperation(value = "获取VIP课教学记录")
    @GetMapping("/findVipGroupTeachingRecord")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/findVipGroupTeachingRecord')")
    public Object findVipGroupTeachingRecord(VipGroupTeachingRecordQueryInfo queryInfo){
        return succeed(vipGroupService.findVipGroupTeachingRecord(queryInfo));
    }

    @ApiOperation(value = "获取vip课基本信息")
    @GetMapping("/findTeachingRecordBaseInfo")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/findTeachingRecordBaseInfo')")
    public Object findTeachingRecordBaseInfo(Long vipGroupId){
        return succeed(vipGroupService.findTeachingRecordBaseInfo(vipGroupId));
    }

    @ApiOperation("课酬总费用")
    @PostMapping("/getVipGroupCostCount")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/getVipGroupCostCount')")
    public Object getVipGroupCostCount(VipGroupApplyBaseInfoDto vipGroup){
        Map results = vipGroupService.countVipGroupPredictFee(vipGroup,
                vipGroup.getUserId(),
                vipGroup.getOnlineClassesUnitPrice(),
                vipGroup.getOfflineClassesUnitPrice());
        return succeed(results);
    }

    @ApiOperation(value = "停止vip课")
    @PostMapping("/stopVipGroup")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/stopVipGroup')")
    public Object stopVipGroup(Long vipGroupId,String stopReason){
        if(Objects.isNull(vipGroupId)|| StringUtils.isBlank(stopReason)){
            return failed("请指定vip课并指定取消原因");
        }
        vipGroupService.stopGroup(vipGroupId,stopReason);
        return succeed();
    }

    @ApiOperation(value = "获取vip课财务信息")
    @GetMapping("/findVipGroupSalarys")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/findVipGroupSalarys')")
    public Object findVipGroupSalarys(VipGroupSalaryQueryInfo queryInfo){
        return succeed(vipGroupService.findVipGroupSalarys(queryInfo));
    }

    @ApiOperation(value = "获取当前课程上课学员")
    @GetMapping("/findVipGroupAttendanceStudents")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/findVipGroupAttendanceStudents')")
    public Object findVipGroupStudents(Long courseScheduleId){
        return succeed(vipGroupService.findVipGroupAttendanceStudents(courseScheduleId));
    }

    @ApiOperation(value = "课时调整")
    @PostMapping(value = "/classStartDateAdjust")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/classStartDateAdjust')")
    public Object classStartDateAdjust(ClassDateAdjustDto classDateAdjustDto){
        if(Objects.isNull(classDateAdjustDto.getId())){
            return failed( "请指定课程!");
        }
        CourseSchedule courseSchedule = scheduleService.get(classDateAdjustDto.getId());
        if(Objects.isNull(classDateAdjustDto.getClassGroupId())){
            classDateAdjustDto.setClassGroupId(courseSchedule.getClassGroupId());
        }
        List<CourseSchedule> courseSchedules=new ArrayList<>();
        courseSchedules.add(classDateAdjustDto);
        scheduleService.courseAdjust(courseSchedules);
        return succeed();
    }

    @ApiOperation(value = "vip课审核")
    @PostMapping(value = "/vipApplyAudit")
    @PreAuthorize("@pcs.hasPermissions('vipGroupManage/vipApplyAudit')")
    public Object vipApplyAudit(Long vipGroupId, AuditStatusEnum auditStatus, String reason){
        vipGroupService.vipApplyAudit(vipGroupId,auditStatus,reason);
        return succeed();
    }

    @ApiOperation(value = "更新vip课基本信息")
    @PostMapping(value = "/updateVipBaseInfo")
    public Object updateVipBaseInfo(@RequestBody VipGroupApplyBaseInfoDto vipGroupApplyBaseInfo){
        vipGroupService.updateVipGroupBaseInfo(vipGroupApplyBaseInfo);
        return succeed();
    }

    @ApiOperation(value = "取消达到报名时间未达到报名人数的vip课")
    @PostMapping(value = "/stopVipGroupWithNoCreate")
    public Object stopVipGroupWithNoCreate(){
        vipGroupService.stopVipGroupWithNoCreate();
        return succeed();
    }

    @ApiOperation(value = "新增vip课程计划")
    @PostMapping(value = "/appendVipGroupCourseSchedules")
    public Object appendVipGroupCourseSchedules(@RequestBody VipGroupApplyDto vipGroupApplyDto){
//        vipGroupService.appendVipGroupCourseSchedules(vipGroupApplyDto);
        return succeed();
    }

    @ApiOperation(value = "获取学生指定vip课的剩余课时费用")
    @GetMapping(value = "/getStudentSurplusCourseFee")
    public Object getStudentSurplusCourseFee(Long vipGroupId, Integer studentId){
        return succeed(vipGroupService.getStudentSurplusCourseFee(vipGroupId,studentId));
    }
}
