package com.ym.mec.education.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.ym.mec.education.base.PageResponse;
import com.ym.mec.education.entity.CourseSchedule;
import com.ym.mec.education.entity.LeaveCategory;
import com.ym.mec.education.entity.TeacherLeaveRecord;
import com.ym.mec.education.mapper.TeacherLeaveRecordMapper;
import com.ym.mec.education.req.TeacherLeaveRecordReq;
import com.ym.mec.education.resp.TeacherLeaveRecordResp;
import com.ym.mec.education.service.ILeaveCategoryService;
import com.ym.mec.education.service.ITeacherLeaveRecordService;
import com.ym.mec.education.utils.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * <p>
 * 老师请假记录表 服务实现类
 * </p>
 *
 * @author lemeng
 * @since 2019-09-25
 */
@Service("ITeacherLeaveRecordService")
@Slf4j
public class TeacherLeaveRecordServiceImpl extends ServiceImpl<TeacherLeaveRecordMapper, TeacherLeaveRecord> implements ITeacherLeaveRecordService {

    @Autowired
    private ILeaveCategoryService leaveCategoryService;

    @Override
    public PageResponse getPage(TeacherLeaveRecordReq teacherLeaveRecordReq) {
        if (Objects.isNull(teacherLeaveRecordReq.getTeacherId()) || Objects.isNull(teacherLeaveRecordReq.getLeaveTime())) {
            return PageResponse.errorParam();
        }
        Page<TeacherLeaveRecord> teacherLeaveRecordPage = new Page(teacherLeaveRecordReq.getPageNo(), teacherLeaveRecordReq.getPageSize());
        QueryWrapper<TeacherLeaveRecord> recordQueryWrapper = new QueryWrapper();
        recordQueryWrapper.lambda().eq(TeacherLeaveRecord::getUserId, teacherLeaveRecordReq.getTeacherId())
                .ge(TeacherLeaveRecord::getCreateTime, teacherLeaveRecordReq.getLeaveTime())
                .lt(TeacherLeaveRecord::getCreateTime, DateUtil.getFirstDayOfNextMonth(teacherLeaveRecordReq.getLeaveTime()));
        IPage<TeacherLeaveRecord> page = page(teacherLeaveRecordPage, recordQueryWrapper);
        Page<TeacherLeaveRecordResp> pageResult = new Page();
        List<TeacherLeaveRecordResp> list = Lists.newArrayList();
        List<TeacherLeaveRecordResp.AdjustCourse> adjustCourseList = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(page.getRecords())) {
            page.getRecords().forEach(item -> {
                TeacherLeaveRecordResp teacherLeaveRecordResp = new TeacherLeaveRecordResp();
                Optional.ofNullable(item.getCreateTime()).ifPresent(date ->
                        teacherLeaveRecordResp.setCommitDate(DateUtil.date2String(date, DateUtil.DATE_FORMAT_MIN)));
                Optional.ofNullable(item.getStartTime()).ifPresent(date ->
                        teacherLeaveRecordResp.setStartDate(DateUtil.date2String(date, DateUtil.DATE_FORMAT_MIN)));
                Optional.ofNullable(item.getEndTime()).ifPresent(date ->
                        teacherLeaveRecordResp.setEndDate(DateUtil.date2String(date, DateUtil.DATE_FORMAT_MIN)));
                Optional.ofNullable(item.getLeaveCategoryId()).ifPresent(leaveCategoryId -> {
                    LeaveCategory leaveCategory = leaveCategoryService.getById(leaveCategoryId);
                    if (Objects.nonNull(leaveCategory) && Objects.nonNull(leaveCategory.getName())) {
                        teacherLeaveRecordResp.setLeaveCategory(leaveCategory.getName());
                    }
                });
                //解析课程调整json
                try {
                    if (StringUtils.isNotBlank(item.getCoursesScheduleJson())) {
                        JSONArray courseScheduleArray = JSON.parseArray(item.getCoursesScheduleJson());
                        courseScheduleArray.forEach(courseSchedule ->{
                            JSONObject coursesSchedule = (JSONObject)courseSchedule;
                            TeacherLeaveRecordResp.AdjustCourse adjustCourse = new TeacherLeaveRecordResp.AdjustCourse();
                            JSONObject before = coursesSchedule.getJSONObject("before");
                            adjustCourse.setClassDate(before.getString("classDate").substring(5) + " " +
                                    before.getString("startClassTime").substring(0, before.getString("startClassTime").length() - 3));
                            JSONObject after = coursesSchedule.getJSONObject("after");
                            adjustCourse.setClassAdjustDate(after.getString("classDate").substring(5) + " " +
                                    before.getString("startClassTime").substring(0, before.getString("startClassTime").length() - 3));
                            adjustCourse.setCourseType(CourseSchedule.CourseScheduleType.getMsgByCode(before.getString("type")));
                            adjustCourse.setCourseName(before.getString("name"));
                            adjustCourseList.add(adjustCourse);
                        });
                        teacherLeaveRecordResp.setAdjustCourseList(adjustCourseList);
                    }
                } catch (Exception e) {
                    log.error("老师请假记录中解析课程json出现异常 {}", e.getMessage(), e);
                }
                list.add(teacherLeaveRecordResp);
            });
        }
        BeanUtils.copyProperties(page, pageResult);
        pageResult.setRecords(list);
        return PageResponse.success(pageResult);
    }
}
