package com.ssj.aijia.kmt.arrange.controller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ssj.bean.kmt.arrange.dto.DutyTemplate;
import com.ssj.bean.kmt.arrange.dto.TeacherArrangeVO;
import com.ssj.bean.kmt.arrange.dto.TeacherNextArrangeVO;
import com.ssj.bean.kmt.arrange.vo.DutyRequestVO;
import com.ssj.bean.kmt.arrange.vo.DutySysRequestVO;
import com.ssj.bean.kmt.arrange.vo.TeacherDutyRequestVO;
import com.ssj.bean.weixin.libmy.domain.TbLibManager;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.common.controller.BaseController;
import com.ssj.framework.core.security.manager.TokenManager;
import com.ssj.framework.core.util.Constant;
import com.ssj.framework.core.util.ResponseConstant;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.service.kmt.arrange.dto.ArrangeCalendarDto;
import com.ssj.service.kmt.arrange.dto.ArrangeTeacherDto;
import com.ssj.service.kmt.arrange.dto.ArrangeTeamTeacherDto;
import com.ssj.service.kmt.arrange.dto.CurCalendarDto;
import com.ssj.service.kmt.arrange.request.ArrangeByAddReq;
import com.ssj.service.kmt.arrange.request.ArrangeByDeleteReq;
import com.ssj.service.kmt.arrange.request.ArrangeCalendarListReq;
import com.ssj.service.kmt.arrange.request.ArrangeTeacherListReq;
import com.ssj.service.kmt.arrange.request.ArrangeTeamTeacherListReq;
import com.ssj.service.kmt.arrange.service.KmtArrangeAllotService;
import com.ssj.service.kmt.arrange.service.KmtArrangeDetailService;
import com.ssj.service.kmt.arrange.service.KmtArrangeTemplateService;
import com.ssj.service.weixin.library.service.IBookManagerService;


@RestController
@RequestMapping("/api/kmt/arrange")
@Api(value = "kmt排班接口", tags = "kmt排班接口")
public class KmtArrangeController extends BaseController {

    @Autowired
    private TokenManager tokenManager;
    
    @Reference(version = "1.0" ,timeout = 60000)
    private IBookManagerService managerService;
    
    @Reference(version = "1.0" ,timeout = 60000)
    private KmtArrangeAllotService kmtArrangeAllotService;
    
    @Reference(version = "1.0" ,timeout = 60000)
    private KmtArrangeDetailService kmtArrangeDetailService;

    @Reference(version = "1.0" ,timeout = 60000)
    private KmtArrangeTemplateService kmtArrangeTemplateService;

    @RequestMapping(value = "/teacherThisMonthDutyList", method = RequestMethod.POST)
    @ApiOperation(value = "本月排班情况接口", httpMethod = "POST",  notes = "本月排班情况接口")
    public ResponseEntity teacherThisMonthDutyList(@RequestParam(name = "accessToken") String accessToken,@RequestBody TeacherDutyRequestVO requestVO) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
            String teacherUserId = "";
            if(requestVO ==null || requestVO.getTeacherId()==null || requestVO.getTeacherId().equals("")){
                teacherUserId = tokenManager.getUserId(accessToken);
            }else {
                teacherUserId = requestVO.getTeacherId();
            }

            TeacherArrangeVO vo = kmtArrangeAllotService.teacherMonthDutyList(teacherUserId);
            responseEntity.success(vo, "查询成功");
        } catch (Exception e) {
            logger.error("本月排班情况接口", e);
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }

    @RequestMapping(value = "/teacherNextMonthDutyList", method = RequestMethod.POST)
    @ApiOperation(value = "下月排班情况接口", httpMethod = "POST",  notes = "本月排班情况接口")
    public ResponseEntity teacherNextMonthDutyList(@RequestParam(name = "accessToken") String accessToken) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
            String teacherUserId = tokenManager.getUserId(accessToken);
            TeacherNextArrangeVO vo = kmtArrangeAllotService.teacherNextMonthDutyList(teacherUserId);
            responseEntity.success(vo, "查询成功");
        } catch (Exception e) {
            logger.error("下月排班情况接口", e);
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }



    @RequestMapping(value = "/findCalendarList", method = RequestMethod.POST)
    @ApiOperation(value = "排班日历表(校区管理员)", httpMethod = "POST", notes = "排班日历表(校区管理员)")
    public ResponseEntity findCalendarList(@RequestParam(name = "accessToken") String accessToken, @RequestBody ArrangeCalendarListReq req) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
        	ArrangeCalendarDto arrangeCalendarDto=kmtArrangeDetailService.findCalendarList(req.getMonth(),req.getType(), req.getSubject());
            responseEntity.success(arrangeCalendarDto, "成功");
        } catch (Exception e) {
            logger.error("异常", e);
            responseEntity = new ResponseEntity();
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }


    @RequestMapping(value = "/findHaveTeacherList", method = RequestMethod.POST)
    @ApiOperation(value = "已选时段老师列表", httpMethod = "POST", notes = "已选时段老师列表")
    public ResponseEntity findHaveTeacherList(@RequestParam(name = "accessToken") String accessToken, @RequestBody ArrangeTeacherListReq req) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
        	String parentTeacherId = tokenManager.getUserId(accessToken);
        	TbLibManager libManager=managerService.findAllByUserIdAndType(parentTeacherId, Constant.CORRECT_SUPER_MANAGER);
        	if(libManager!=null){
        		parentTeacherId=null;
        	}
        	ArrangeTeacherDto arrangeTeacherDto=kmtArrangeDetailService.findHaveTeacherList(parentTeacherId, req.getId(),req.getTeacherName());
            responseEntity.success(arrangeTeacherDto, "成功");
        } catch (Exception e) {
            logger.error("异常", e);
            responseEntity = new ResponseEntity();
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }


    @RequestMapping(value = "/findNoHaveTeacherList", method = RequestMethod.POST)
    @ApiOperation(value = "未选时段老师列表(添加老师)", httpMethod = "POST", notes = "未选时段老师列表(添加老师)")
    public ResponseEntity findNoHaveTeacherList(@RequestParam(name = "accessToken") String accessToken, @RequestBody ArrangeTeacherListReq req) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
        	String parentTeacherId = tokenManager.getUserId(accessToken);
        	TbLibManager libManager=managerService.findAllByUserIdAndType(parentTeacherId, Constant.CORRECT_SUPER_MANAGER);
        	if(libManager!=null){
        		parentTeacherId=null;
        	}
        	ArrangeTeacherDto arrangeTeacherDto=kmtArrangeDetailService.findNoHaveTeacherList(parentTeacherId,  req.getId(), req.getTeacherName());
            responseEntity.success(arrangeTeacherDto, "成功");
        } catch (Exception e) {
            logger.error("异常", e);
            responseEntity = new ResponseEntity();
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }



    @RequestMapping(value = "/deleteArrangeByTeacher", method = RequestMethod.POST)
    @ApiOperation(value = "时段移除老师", httpMethod = "POST", notes = "时段移除老师")
    public ResponseEntity deleteArrangeByTeacher(@RequestParam(name = "accessToken") String accessToken, @RequestBody ArrangeByDeleteReq req) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
        	kmtArrangeDetailService.deleteArrangeByTeacher(req.getId(),req.getTeacherId());
            responseEntity.success("成功");
        } catch (Exception e) {
            logger.error("异常", e);
            responseEntity = new ResponseEntity();
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }


    @RequestMapping(value = "/addArrangeByTeacher", method = RequestMethod.POST)
    @ApiOperation(value = "时段添加老师", httpMethod = "POST", notes = "时段添加老师")
    public ResponseEntity addArrangeByTeacher(@RequestParam(name = "accessToken") String accessToken, @RequestBody ArrangeByAddReq req) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
        	Integer reqCode=kmtArrangeDetailService.addArrangeByTeacher(req.getId(), req.getTeacherIds());
        	if(1==reqCode){
        		responseEntity.success("成功");
        	}else if(2==reqCode){
        		responseEntity.failure("必须提前于排班时段前 4 个小时进行");
        	}else if(3==reqCode){
        		responseEntity.failure("此时段添加老师量已超出饱和量");
        	}else if(4==reqCode){
        		responseEntity.failure("此时段数据不存在");
        	}else if(500==reqCode){
        		responseEntity.failure("数据处理异常,请刷新后重试");
        	}
        } catch (Exception e) {
            logger.error("异常", e);
            responseEntity = new ResponseEntity();
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }




    @RequestMapping(value = "/findTeamTeacherList", method = RequestMethod.POST)
    @ApiOperation(value = "组内排班老师列表", httpMethod = "POST", notes = "组内排班老师列表")
    public ResponseEntity findTeamTeacherList(@RequestParam(name = "accessToken") String accessToken, @RequestBody ArrangeTeamTeacherListReq req) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
        	String parentTeacherId = tokenManager.getUserId(accessToken);
        	Pageable pageable = initPage(
        			req.getPageNo()!=null ? req.getPageNo() : 1 ,
        					req.getPageSize()!=null ? req.getPageSize() : 10);
        	if(StringUtils.isNotEmpty(req.getManagerId())){
        		parentTeacherId=req.getManagerId();
        	}
        	ArrangeTeamTeacherDto arrangeTeamTeacherDto=kmtArrangeDetailService.findTeamTeacherList(parentTeacherId, req.getType(),req.getId(),req.getTeacherName(),pageable);
            responseEntity.success(arrangeTeamTeacherDto,"成功");
        } catch (Exception e) {
            logger.error("异常", e);
            responseEntity = new ResponseEntity();
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }






    @RequestMapping(value = "/saveTeacherDuty", method = RequestMethod.POST)
    @ApiOperation(value = "老师保存排班设置", httpMethod = "POST",  notes = "老师保存排班设置")
    public ResponseEntity saveTeacherDuty(@RequestParam(name = "accessToken") String accessToken,@RequestBody DutyRequestVO requestVO) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
            String teacherUserId = tokenManager.getUserId(accessToken);
            responseEntity = kmtArrangeAllotService.saveTeacherDuty(requestVO,teacherUserId);
           // responseEntity.success("保存成功");
        } catch (Exception e) {
            logger.error("老师保存排班设置接口", e);
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }

    @RequestMapping(value = "/dutyTemplateList", method = RequestMethod.POST)
    @ApiOperation(value = "排班设置列表", httpMethod = "POST",  notes = "老师保存排班设置")
    public ResponseEntity dutyTemplateList(@RequestParam(name = "accessToken") String accessToken) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
            String teacherUserId = tokenManager.getUserId(accessToken);
            Map<String,Object> data = new HashMap<>();
            List<DutyTemplate> list = kmtArrangeAllotService.dutyTemplateList(teacherUserId);
            data.put("dayList",list);
            data.put("month", DateHelper.format(DateHelper.getNextMonthFirstDay(new Date()),"MM"));
            responseEntity.success(data, "查询成功");
        } catch (Exception e) {
            logger.error("排班设置列表接口", e);
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }

    @RequestMapping(value = "/saveSysTeacherDuty", method = RequestMethod.POST)
    @ApiOperation(value = "保存排班设置", httpMethod = "POST",  notes = "老师保存排班设置")
    public ResponseEntity saveSysTeacherDuty(@RequestParam(name = "accessToken") String accessToken,@RequestBody DutySysRequestVO vo1) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
           // String teacherUserId = tokenManager.getUserId(accessToken);
            kmtArrangeAllotService.saveSysTeacherDuty(vo1);
            responseEntity.success("保存成功");
        } catch (Exception e) {
            logger.error("保存排班设置接口", e);
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }

    @RequestMapping(value = "teacherDayAttendance",method = RequestMethod.POST)
    @ApiOperation(value = "老师当日出勤记录",httpMethod = "POST",notes ="老师当月出勤记录" )
    public void getTeacherDayAttendance(@RequestParam(name="accessToken")String accessToken,@RequestParam String time){



    }
    
    
    
    @RequestMapping(value = "/findArrangeTemplateIntervalList", method = RequestMethod.POST)
    @ApiOperation(value = "查询当月日历时间列表", httpMethod = "POST", notes = "查询当月日历时间列表")
    public ResponseEntity findArrangeIntervalList(@RequestParam(name = "accessToken") String accessToken) {
        ResponseEntity responseEntity = new ResponseEntity();
        try {
        	List<CurCalendarDto> curCalendarDtos=kmtArrangeTemplateService.findArrangeTemplateIntervalList();
            Map<String,Object> data=new LinkedHashMap<String, Object>();
            data.put("list", curCalendarDtos);
			responseEntity.success(data,"成功");
        } catch (Exception e) {
            logger.error("异常", e);
            responseEntity = new ResponseEntity();
            responseEntity.failure(ResponseConstant.CODE_500, "系统繁忙，请稍后重试");
        }
        return responseEntity;
    }
    
    
}
