package com.hssx.pcbms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hssx.pcbms.constant.Constant;
import com.hssx.pcbms.entity.*;
import com.hssx.pcbms.entity.vo.IdeaVO;
import com.hssx.pcbms.entity.vo.ScoreVO;
import com.hssx.pcbms.mapper.*;
import com.hssx.pcbms.service.ScoreService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hssx.pcbms.util.HttpRespMsg;
import com.hssx.pcbms.util.PageUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.expression.spel.ast.Operator;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.xml.crypto.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 吴涛涛
 * @since 2019-11-02
 */
@Service
public class ScoreServiceImpl extends ServiceImpl<ScoreMapper, Score> implements ScoreService {
    @Resource
    private ScoreMapper scoreMapper;
    @Resource
    private ParameterMapper parameterMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private IdeaMapper ideaMapper;
    @Resource
    private IdeaCommentMapper ideaCommentMapper;
    @Resource
    private NewsNoticeMapper newsNoticeMapper;
    @Resource
    private NewsNoticeUserMapper newsNoticeUserMapper;
    @Resource
    private ScoringOperateRecordMapper scoringOperateRecordMapper;

    @Override
    public HttpRespMsg add(Score score) throws ParseException {
        HttpRespMsg msg = new HttpRespMsg();
        SimpleDateFormat sdfymd = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfym = new SimpleDateFormat("yyyy-MM");
        Parameter parameter = parameterMapper.selectOne(new QueryWrapper<Parameter>().eq("param_key", Constant.SCORING_DEADLINE_CODE));
        if (parameter != null) {
            if (score.getScoreId() != null) {
                Score Oldscore = scoreMapper.selectOne(new QueryWrapper<Score>().eq("score_id", score.getScoreId()));
                //修改打分
                scoreMapper.update(score,new QueryWrapper<Score>().eq("score_id",score.getScoreId()));
                //添加修改记录
                User uidUser = userMapper.selectById(Oldscore.getUid());
                User operator = userMapper.selectById(Oldscore.getRaterId());
                ScoringOperateRecord record = new ScoringOperateRecord();
                record.setContent(Constant.UPDATE_SCORE);
                record.setDeptId(Oldscore.getDeptId());
                record.setOperatorId(operator.getId());
                record.setUid(uidUser.getId());
                record.setUname(uidUser.getName());
                record.setOperator(operator.getName());
                record.setScoreId(Oldscore.getScoreId());
                scoringOperateRecordMapper.insert(record);
            } else {
                User Rater = userMapper.selectById(score.getRaterId());
                score.setRater(Rater.getName());
                score.setDeptId(Rater.getDeptId());
                if(Rater == null){
                    msg.setError("当前打分人身份异常。");
                    return msg;
                }
                Score oldScore = scoreMapper.selectOne(new QueryWrapper<Score>().eq("scoring_year_month", score.getScoringYearMonth()).eq("uid",score.getUid()));
                Date now = new Date();
                now.setDate(Integer.parseInt(parameter.getParamValue()));
                String thisMonth5 = sdfymd.format(now);
                now.setMonth(now.getMonth() - 1);
                String lastMonth5 = sdfymd.format(now);
                now.setMonth(now.getMonth() + 2);
                String nextMonth5 = sdfymd.format(now);
                Date nowDate = new Date();
                String currentDateStr = sdfymd.format(nowDate);
                //打分日期
                Date yearMonth = sdfym.parse(score.getScoringYearMonth());
                if (currentDateStr.compareTo(lastMonth5) >= 0 && currentDateStr.compareTo(thisMonth5) <= 0) {
                    //上个月五号到本月五号之间（可评上月的分）
                    msg = addScore(yearMonth, nowDate, 0, score,oldScore);
                } else if (currentDateStr.compareTo(thisMonth5) >= 0 && currentDateStr.compareTo(nextMonth5) <= 0) {
                    //本月五号到下月五号之间（可评本月的分）
                    msg = addScore(yearMonth, nowDate, 1, score,oldScore);
                }
            }
        }
        return msg;
    }

    @Override
    public HttpRespMsg getList(Score score,PageUtil page) {
        HttpRespMsg msg = new HttpRespMsg();
        PageHelper.startPage(page.getPageNum(),page.getPageSize());
        List<Score> scores = scoreMapper.selectList(new QueryWrapper<Score>().eq("uid",score.getUid()).orderByDesc("score_id"));
        PageInfo<Score> info = new PageInfo<>(scores);
        msg.data = info;
        return msg;
    }

    @Override
    public HttpRespMsg detail(Score score) {
        HttpRespMsg msg = new HttpRespMsg();
        ScoreVO vo = new ScoreVO();
        Score oldScore = scoreMapper.selectById(score.getScoreId());
        BeanUtils.copyProperties(oldScore,vo);
        Idea idea = new Idea();
        idea.setScoreId(score.getScoreId());
        List<IdeaVO> ideaVos = ideaMapper.getIdeaListByUid(idea, null);
        vo.setIdeaVO(ideaVos);
        msg.data = vo;
        return msg;
    }

    @Override
    public HttpRespMsg getDetailByTimeAndUid(Score score,String time) {
        HttpRespMsg msg = new HttpRespMsg();
        ScoreVO vo = new ScoreVO();
        Score oldScore = scoreMapper.selectOne(new QueryWrapper<Score>().eq("scoring_year_month",time).eq("uid",score.getUid()));
        if(oldScore != null){
            BeanUtils.copyProperties(oldScore,vo);
            Idea idea = new Idea();
            idea.setUid(score.getUid());
            List<IdeaVO> ideaVos = ideaMapper.getIdeaListByUid(idea, time);
            if(ideaVos.size()>0){
                double sum = 0.0;
                vo.setIdeaVO(ideaVos);
                for (IdeaVO ideaVo : ideaVos) {
                    sum+=ideaVo.getScore();
                }
                vo.setIdeaScoreSum(sum);
            }
        }
        msg.data = vo;
        return msg;
    }

    @Override
    public HttpRespMsg scoringTaskNotice() {
        HttpRespMsg msg = new HttpRespMsg();
        //条件通知消息
        NewsNotice newsNotice = new NewsNotice();
        newsNotice.setNoticeType(1);
        String content = Constant.SCORING_NEWS;
        newsNotice.setContent(content);
        newsNoticeMapper.insert(newsNotice);
        List<User> users = userMapper.selectLeaderUsersListByCondition();
        //通知所有领导
        for (User user : users) {
            NewsNoticeUser noticeUser = new NewsNoticeUser();
            noticeUser.setNewsId(newsNotice.getId());
            noticeUser.setUserId(user.getId());
            newsNoticeUserMapper.insert(noticeUser);
        }
        return msg;
    }

    @Override
    public HttpRespMsg del(Score score) {
        HttpRespMsg msg = new HttpRespMsg();
        Score Oldscore = scoreMapper.selectOne(new QueryWrapper<Score>().eq("score_id", score.getScoreId()));
        //清空该建议的评分
        List<Idea> ideas = ideaMapper.selectList(new QueryWrapper<Idea>().eq("score_id", Oldscore.getScoreId()));
        //删除建议的评论
        if(!CollectionUtils.isEmpty(ideas)){
            ideaCommentMapper.delete(new QueryWrapper<IdeaComment>().in("idea_id",ideas.stream().map(Idea::getId).collect(Collectors.toList())));
        }
        //将之前的建议打分全部修改为0
        Idea idea = new Idea();
        idea.setScore(0.0);
        idea.setScoreId(null);//这里是null没法更新
        ideaMapper.update(idea,new QueryWrapper<Idea>().eq("score_id", Oldscore.getScoreId()));
        //添加删除打分记录
        User uidUser = userMapper.selectById(Oldscore.getUid());
        User operator = userMapper.selectById(Oldscore.getRaterId());
        ScoringOperateRecord record = new ScoringOperateRecord();
        record.setContent(Constant.DELETE_SCORE);
        record.setDeptId(Oldscore.getDeptId());
        record.setOperatorId(operator.getId());
        record.setUid(uidUser.getId());
        record.setUname(uidUser.getName());
        record.setOperator(operator.getName());
        record.setScoreId(Oldscore.getScoreId());
        scoringOperateRecordMapper.insert(record);
        scoreMapper.delete(new QueryWrapper<Score>().eq("score_id",score.getScoreId()));
        return msg;
    }

    private HttpRespMsg addScore(Date yearMonth, Date nowDate, Integer type, Score score,Score oldScore) {
        HttpRespMsg msg = new HttpRespMsg();
        //评分上个月
        if (type == 0) {
            if (yearMonth.getMonth() == (nowDate.getMonth() - 1)) {
                if (oldScore != null) {
                    msg.setError("本月已打分，请勿重复打分");
                    return msg;
                } else {
                    scoreMapper.insert(score);
                    ideaMapper.updateListByTime(score);
                    User uidUser = userMapper.selectById(score.getUid());
                    User operator = userMapper.selectById(score.getRaterId());
                    ScoringOperateRecord record = new ScoringOperateRecord();
                    record.setContent(Constant.ADD_SCORE);
                    record.setDeptId(score.getDeptId());
                    record.setOperatorId(operator.getId());
                    record.setUid(uidUser.getId());
                    record.setUname(uidUser.getName());
                    record.setOperator(operator.getName());
                    record.setScoreId(score.getScoreId());
                    scoringOperateRecordMapper.insert(record);
                }
            } else {
                msg.setError("评分日期不和法，请切换日期后重试");
                return msg;
            }
        } else if (type == 1) {
            if (yearMonth.getMonth() == (nowDate.getMonth())) {
                if (oldScore != null) {
                    msg.setError("本月已打分，请勿重复打分");
                    return msg;
                } else {
                    scoreMapper.insert(score);
                    ideaMapper.updateListByTime(score);
                    User uidUser = userMapper.selectById(score.getUid());
                    User operator = userMapper.selectById(score.getRaterId());
                    ScoringOperateRecord record = new ScoringOperateRecord();
                    record.setContent(Constant.ADD_SCORE);
                    record.setDeptId(score.getDeptId());
                    record.setOperatorId(operator.getId());
                    record.setUid(uidUser.getId());
                    record.setUname(uidUser.getName());
                    record.setOperator(operator.getName());
                    record.setScoreId(score.getScoreId());
                    scoringOperateRecordMapper.insert(record);
                }
            } else {
                msg.setError("评分日期不和法，请切换日期后重试");
                return msg;
            }
        }
        return msg;
    }

    public static void main(String[] args) {
        System.out.println("2019-11-07".compareTo("2019-11-07"));
        SimpleDateFormat sdfym = new SimpleDateFormat("yyyy-MM");
        Date now = new Date();
        now.setDate(Integer.parseInt("5"));
        String thisMonth5 = sdfym.format(now);
        now.setMonth(now.getMonth() - 1);
        String lastMonth5 = sdfym.format(now);
        now.setMonth(now.getMonth() + 2);
        String nextMonth5 = sdfym.format(now);
        System.out.println(thisMonth5 + "  " + lastMonth5 + "  " + nextMonth5);
        Date nowDate = new Date();
        String currentDateStr = "2019-11-06";
        if (currentDateStr.compareTo(lastMonth5) > 0 && currentDateStr.compareTo(thisMonth5) < 0) {
            System.out.println("上月五号到这月五号之间");

        } else if (currentDateStr.compareTo(thisMonth5) > 0) {
            System.out.println("超过本月五号了");

        }
    }
}
