package com.ym.mec.student.controller;

import com.ym.mec.auth.api.client.SysUserFeignService;
import com.ym.mec.auth.api.entity.SysUser;
import com.ym.mec.biz.dal.dao.ClassGroupDao;
import com.ym.mec.biz.dal.dao.CourseScheduleEvaluateDao;
import com.ym.mec.biz.dal.dao.PracticeGroupDao;
import com.ym.mec.biz.dal.dao.SysConfigDao;
import com.ym.mec.biz.dal.dto.PracticeGroupBuyDto;
import com.ym.mec.biz.dal.entity.ClassGroup;
import com.ym.mec.biz.dal.entity.CourseScheduleEvaluate;
import com.ym.mec.biz.dal.entity.PracticeGroup;
import com.ym.mec.biz.dal.entity.SysConfig;
import com.ym.mec.biz.dal.enums.GroupType;
import com.ym.mec.biz.dal.enums.MessageTypeEnum;
import com.ym.mec.biz.service.PracticeGroupService;
import com.ym.mec.biz.service.SysConfigService;
import com.ym.mec.biz.service.SysMessageService;
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.thirdparty.message.MessageSenderPluginContext;
import com.ym.mec.util.http.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Author Joburgess
 * @Date 2020/1/31
 */
@RequestMapping("practiceGroup")
@Api(tags = "陪练课服务")
@RestController
public class PracticeGroupController extends BaseController {

    @Autowired
    private PracticeGroupService practiceGroupService;
    @Autowired
    private SysUserFeignService sysUserFeignService;
    List<Integer> excludeOrganIds=new ArrayList<>(Arrays.asList(new Integer[]{36}));

    @Autowired
    private SysMessageService sysMessageService;
    @Autowired
    private PracticeGroupDao practiceGroupDao;
    @Autowired
    private ClassGroupDao classGroupDao;
    @Autowired
    private SysConfigDao sysConfigDao;
    @Autowired
    private CourseScheduleEvaluateDao courseScheduleEvaluateDao;

//    private static final Set<Integer> ENABLE_APPLY_ORGANIDS = new HashSet<>(Arrays.asList(new Integer[]{28,34,37}));

    @ApiOperation("获取学生的陪练课")
    @GetMapping(value = "/findUserPracticeCourses")
    public Object findUserPracticeCourses(){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(practiceGroupService.findUserPracticeCourses(sysUser.getId()));
    }

    @ApiOperation("检测用户是否能够申请免费陪练课")
    @GetMapping(value = "/checkCanApplyFreePracticeGroup")
    private HttpResponseResult checkCanApplyFreePracticeGroup(){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        Map<String,Object> result=practiceGroupService.checkCanApplyFreePracticeGroup(sysUser.getId());
//        if(ENABLE_APPLY_ORGANIDS.contains(sysUser.getOrganId())){
        Integer applyTimes = practiceGroupDao.countUserPracticeApplyRecord(sysUser.getId());
        result.put("canApply", applyTimes < 1 ? 1 : 0);
//        }else{
//            result.put("canApply", 0);
//        }
        result.put("organId", sysUser.getOrganId());
        return succeed(result);
    }

    @ApiOperation("获取陪练课预约参数")
    @GetMapping(value = "/getPracticeApplyParams")
    public Object getPracticeApplyParams(){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        Map<String,Object> result=practiceGroupService.getPracticeApplyParams(sysUser.getId());
//        if(ENABLE_APPLY_ORGANIDS.contains(sysUser.getOrganId())){
            Integer applyTimes = practiceGroupDao.countUserPracticeApplyRecord(sysUser.getId());
            result.put("enableApply", applyTimes < 1 ? 1 : 0);
//        }else{
//            result.put("enableApply", 0);
//        }
        return succeed(result);
    }

    @ApiOperation("获取可以预约的教师")
    @GetMapping(value = "/getEnableApplyTeachers")
    public Object getEnableApplyTeachers(Integer subjectId){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(practiceGroupService.getEnableApplyTeachers(sysUser.getId(), subjectId));
    }

    @ApiOperation("获取可以预约的教师--付费")
    @GetMapping(value = "/getEnableApplyTeachersWithPay")
    public Object getEnableApplyTeachersWithPay(Integer subjectId){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(practiceGroupService.getEnableApplyTeachersWithPay(sysUser.getId(), subjectId));
    }

    @ApiOperation("获取指定学员所在分部下的教师空闲时间")
    @GetMapping(value = "/getTeacherFreeTimes")
    public Object getTeacherFreeTimes(Integer teacherId, Date firstClassTime){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(practiceGroupService.getTeacherFreeTimes(sysUser.getId(),teacherId,firstClassTime));
    }

    @ApiOperation("获取指定学员所在分部下的教师空闲时间")
    @GetMapping(value = "/getTeachersFreeTimes")
    public Object getTeachersFreeTimes(Integer subjectId, Date firstClassTime){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(practiceGroupService.getTeachersFreeTimes(sysUser.getId(),subjectId,firstClassTime));
    }

    @ApiOperation("陪练课预约")
    @PostMapping(value = "/practiceApply")
    public Object practiceApply(PracticeGroup practiceGroup){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        if(excludeOrganIds.contains(sysUser.getOrganId())){
            throw new BizException("请联系老师确认您的所属分部");
        }
//        if(!ENABLE_APPLY_ORGANIDS.contains(sysUser.getOrganId())){
//            throw new BizException("陪练课预约活动已结束");
//        }
        practiceGroup.setStudentId(sysUser.getId());
        return succeed(practiceGroupService.practiceApply(practiceGroup));
    }

    @ApiOperation("获取陪练课预约参数——付费")
    @GetMapping(value = "/getPayPracticeApplyParams")
    public Object getPayPracticeApplyParams(Integer organId){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(practiceGroupService.getPayPracticeApplyParams(sysUser.getId(), Objects.nonNull(organId)?organId:sysUser.getOrganId()));
    }

    @ApiOperation("获取指定教师的空闲时间——付费")
    @GetMapping(value = "/getPayPracticeTeacherFreeTimes")
    public Object getPayPracticeTeacherFreeTimes(Integer teacherId,Integer buyMonths, boolean renew, Long groupId){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(practiceGroupService.getPayPracticeTeacherFreeTimes(sysUser.getId(),teacherId, buyMonths,renew,groupId));
    }

    @ApiOperation("获取学生上一次的购买信息--付费")
    @GetMapping(value = "/findUserLatestPracticeGroup")
    public HttpResponseResult findUserLatestPracticeGroup(Long groupId){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(practiceGroupService.findUserLatestPracticeGroup(sysUser.getId(),groupId));
    }

    @ApiOperation("检测学生是否是新用户")
    @GetMapping(value = "/isNewStudent")
    public HttpResponseResult isNewStudent(){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        int studentExitChargePractices = practiceGroupDao.checkStudentExitChargePractice(sysUser.getId());
        Map<String, Integer> result=new HashMap<>();
        result.put("isNewStudent", studentExitChargePractices<=0?0:1);
        return succeed(result);
    }

    @ApiOperation("陪练课购买")
    @PostMapping(value = "/buyPracticeGroup")
    public HttpResponseResult buyPracticeGroup(@RequestBody PracticeGroupBuyDto practiceGroupBuyParams){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        if(excludeOrganIds.contains(sysUser.getOrganId())){
            throw new BizException("请联系老师确认您的所属分部");
        }
        practiceGroupBuyParams.setStudentId(sysUser.getId());
        return practiceGroupService.buyPracticeGroup(practiceGroupBuyParams);
    }

    @ApiOperation("获取用户历史购买的陪练课")
    @GetMapping(value = "/findUserHistoryBuyPracticeGroups")
    public HttpResponseResult findUserHistoryBuyPracticeGroups(Long groupId){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(practiceGroupService.findUserHistoryBuyPracticeGroups(sysUser.getId(), groupId));
    }

    @ApiOperation("查询订单信息")
    @GetMapping(value = "/queryOrderInfo")
    public HttpResponseResult queryOrderInfo(String orderNo){
        return succeed(practiceGroupService.queryOrderInfo(orderNo));
    }

    @ApiOperation("重新支付")
    @PostMapping(value = "/repay")
    public HttpResponseResult repay(Integer groupId, boolean useBalancePayment) throws Exception {
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return practiceGroupService.repay(sysUser.getId(),groupId,useBalancePayment);
    }

    @ApiOperation("免费陪练课定点推送")
    @GetMapping(value = "/freePush")
    public HttpResponseResult freePush(Integer userId, String pushType){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        String baseApiUrl = sysConfigDao.findConfigValue("base_api_url");

        String pushUrl = baseApiUrl + "/#/auditionbanner/id";

//        String smsUrl = baseApiUrl + "/#/transfer?url=" + baseApiUrl + "/#/auditionbanner/id";
//
//        SysUser student = sysUserFeignService.queryUserById(userId);

        if(pushType.equals("ALL")||pushType.equals("JIGUANG")){
            Map<Integer, String> userMap = new HashMap<>();
            userMap.put(userId, userId.toString());
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.FREE_PRACTICE_APPLY_PUSH,
                    userMap, null, 0, "5?" + pushUrl, "STUDENT");
        }

//        if(pushType.equals("ALL")||pushType.equals("SMS")){
//            Map<Integer, String> userPhoneMap = new HashMap<>();
//            userPhoneMap.put(userId, student.getPhone());
//            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.YIMEI, MessageTypeEnum.FREE_PRACTICE_APPLY_PUSH,
//                    userPhoneMap, null, 0, null, "STUDENT", HttpUtil.getSortUrl(smsUrl));
//        }

        return succeed();
    }

    @ApiOperation("陪练课完成报告推送")
    @GetMapping(value = "/reportPush")
    public HttpResponseResult reportPush(Integer userId, String pushType){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        String baseApiUrl = sysConfigDao.findConfigValue("base_api_url");
        PracticeGroup userFreePracticeGroup = practiceGroupDao.getUserFreePracticeGroup(userId);
        ClassGroup classGroup = classGroupDao.findByMusicGroupAndType(userFreePracticeGroup.getId().toString(), GroupType.PRACTICE.getCode());

        CourseScheduleEvaluate courseScheduleEvaluate = courseScheduleEvaluateDao.findByClassGroupId(classGroup.getId());
        if(Objects.isNull(courseScheduleEvaluate)){
            return failed("未生成课程报告");
        }

        String pushUrl = baseApiUrl + "/#/reportDetail?classGroupId=" + classGroup.getId();

        String smsUrl = baseApiUrl + "/#/transfer?url=" + baseApiUrl + "&hash=reportDetail&classGroupId=" + classGroup.getId();

        SysUser student = sysUserFeignService.queryUserById(userId);

        if(pushType.equals("ALL")||pushType.equals("JIGUANG")){
            Map<Integer, String> userMap = new HashMap<>();
            userMap.put(userId, userId.toString());
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.JIGUANG, MessageTypeEnum.PRACTICE_COMPLETED_STUDY_REPORT,
                    userMap, null, 0, "5?" + pushUrl, "STUDENT", pushUrl);
        }

        if(pushType.equals("ALL")||pushType.equals("SMS")){
            Map<Integer, String> userPhoneMap = new HashMap<>();
            userPhoneMap.put(userId, student.getPhone());
            sysMessageService.batchSendMessage(MessageSenderPluginContext.MessageSender.AWSMS, MessageTypeEnum.PRACTICE_COMPLETED_STUDY_REPORT,
                    userPhoneMap, null, 0, null, "STUDENT", HttpUtil.getSortUrl(smsUrl));
        }

        return succeed();
    }

    @ApiOperation("陪练课完成报告推送")
    @GetMapping(value = "/pushStudyReport")
    public HttpResponseResult pushStudyReport(Date expiredDate, String pushType){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        practiceGroupService.pushStudyReport(expiredDate,pushType);
        return succeed();
    }

    @ApiOperation("检测用户是否存在待支付的课程组订单")
    @GetMapping(value = "/checkExistWaitPayOrder")
    public HttpResponseResult checkExistWaitPayOrder(Long groupId){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return succeed(practiceGroupService.checkExistWaitPayOrder(sysUser.getId(),groupId));
    }

    @ApiOperation("取消待支付的订单")
    @PostMapping(value = "/cancelWaitPayOrder")
    public HttpResponseResult cancelWaitPayOrder(Integer groupId){
        SysUser sysUser = sysUserFeignService.queryUserInfo();
        if (sysUser == null) {
            return failed(HttpStatus.FORBIDDEN, "请登录");
        }
        return practiceGroupService.cancelWaitPayOrder(sysUser.getId(), groupId);
    }
}
