package com.mortals.xhx.module.feedback.service.impl;
import cn.hutool.core.date.DateUtil;
import com.mortals.framework.model.PageInfo;
import com.mortals.framework.model.Result;
import com.mortals.xhx.common.code.ProcessStatusEnum;
import com.mortals.xhx.module.feedback.model.*;
import com.mortals.xhx.module.feedback.model.vo.FeedbackStaffInfoVo;
import com.mortals.xhx.module.feedback.model.vo.OptionSummaryVo;
import com.mortals.xhx.module.feedback.model.vo.QuestionAnswerVo;
import com.mortals.xhx.module.feedback.service.FeedbackStaffService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import com.mortals.framework.service.impl.AbstractCRUDServiceImpl;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.xhx.module.feedback.dao.FeedbackDao;
import com.mortals.xhx.module.feedback.service.FeedbackService;
import org.springframework.beans.factory.annotation.Autowired;
import com.mortals.xhx.module.feedback.service.FeedbackQuestionService;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;
/**
* FeedbackService
* 绩效反馈记录信息 service实现
*
* @author zxfei
* @date 2023-07-05
*/
@Service("feedbackService")
@Slf4j
public class FeedbackServiceImpl extends AbstractCRUDServiceImpl<FeedbackDao, FeedbackEntity, Long> implements FeedbackService {
    @Autowired
    private FeedbackQuestionService feedbackQuestionService;
    @Autowired
    private FeedbackStaffService feedbackStaffService;


    @Override
    protected void findAfter(FeedbackEntity params, PageInfo pageInfo, Context context, List<FeedbackEntity> list) throws AppException {
        updateProcessStatus(list);
    }

    @Override
    protected void findAfter(FeedbackEntity entity, Context context, List<FeedbackEntity> list) throws AppException {
        updateProcessStatus(list);
    }

    private  void updateProcessStatus(List<FeedbackEntity> list) {
        list.stream().forEach(item->{
            Date feedbackTimeStart = item.getFeedbackTimeStart();
            Date feedbackTimeEnd = item.getFeedbackTimeEnd();

            if(DateUtil.compare(new Date(),feedbackTimeStart)<0){
               item.setProcessStatus(0);
            }

            boolean in = DateUtil.isIn(new Date(), item.getFeedbackTimeStart(), item.getFeedbackTimeEnd());
            if(in){
                item.setProcessStatus(1);
            }

            if(DateUtil.compare(new Date(),feedbackTimeEnd)>0){
                item.setProcessStatus(2);
            }

        });
    }

    @Override
    protected void saveBefore(FeedbackEntity entity, Context context) throws AppException {
        if(!ObjectUtils.isEmpty(entity.getStaffList())){
            entity.setInviteNum(entity.getStaffList().size());
        }
    }

    @Override
    protected void updateBefore(FeedbackEntity entity, Context context) throws AppException {
        if(!ObjectUtils.isEmpty(entity.getStaffList())){
            entity.setInviteNum(entity.getStaffList().size());
        }
    }

    @Override
    protected void saveAfter(FeedbackEntity entity, Context context) throws AppException {
        if(!ObjectUtils.isEmpty(entity.getFeedbackQuestionList())){
            entity.getFeedbackQuestionList().stream().peek(item->{
                item.setFeedbackId(entity.getId());
                item.setCreateUserId(this.getContextUserId(context));
                item.setCreateTime(new Date());
            }).count();
            for(FeedbackQuestionEntity questionEntity:entity.getFeedbackQuestionList()) {
                feedbackQuestionService.save(questionEntity);
            }
        }
        if(!ObjectUtils.isEmpty(entity.getStaffList())){
            List<FeedbackStaffEntity> staffEntityList = new ArrayList<>();
            for(Long staffId:entity.getStaffList()){
                FeedbackStaffEntity feedbackStaffEntity = new FeedbackStaffEntity();
                feedbackStaffEntity.setFeedbackId(entity.getId());
                feedbackStaffEntity.setStaffId(staffId);
                feedbackStaffEntity.setCreateTime(new Date());
                feedbackStaffEntity.setCreateUserId(this.getContextUserId(context));
                staffEntityList.add(feedbackStaffEntity);
            }
            feedbackStaffService.save(staffEntityList,context);
        }
        super.saveAfter(entity, context);
    }

    @Override
    protected void updateAfter(FeedbackEntity entity, Context context) throws AppException {
        if(!ObjectUtils.isEmpty(entity.getFeedbackQuestionList())){
            Long[] feedbackQuestionIds = feedbackQuestionService.find(new FeedbackQuestionQuery().feedbackId(entity.getId())).stream().map(FeedbackQuestionEntity::getId).toArray(Long[]::new);
            feedbackQuestionService.remove(feedbackQuestionIds,context);
            entity.getFeedbackQuestionList().stream().peek(item ->{
                item.setFeedbackId(entity.getId());
                item.setCreateUserId(this.getContextUserId(context));
                item.setCreateTime(new Date());
                item.setUpdateUserId(this.getContextUserId(context));
                item.setUpdateTime(new Date());
            }).count();
            for(FeedbackQuestionEntity questionEntity:entity.getFeedbackQuestionList()) {
                feedbackQuestionService.save(questionEntity);
            }
        }
        if(!ObjectUtils.isEmpty(entity.getStaffList())){
            Long[] feedbackStaffIds = feedbackStaffService.find(new FeedbackStaffQuery().feedbackId(entity.getId())).stream().map(FeedbackStaffEntity::getId).toArray(Long[]::new);
            feedbackStaffService.remove(feedbackStaffIds,context);
            List<FeedbackStaffEntity> staffEntityList = new ArrayList<>();
            for(Long staffId:entity.getStaffList()){
                FeedbackStaffEntity feedbackStaffEntity = new FeedbackStaffEntity();
                feedbackStaffEntity.setFeedbackId(entity.getId());
                feedbackStaffEntity.setStaffId(staffId);
                feedbackStaffEntity.setCreateTime(new Date());
                feedbackStaffEntity.setCreateUserId(this.getContextUserId(context));
                staffEntityList.add(feedbackStaffEntity);
            }
            feedbackStaffService.save(staffEntityList,context);
        }
        super.updateAfter(entity, context);
    }

    @Override
    protected void removeAfter(Long[] ids, Context context, int result) throws AppException {
        List<FeedbackQuestionEntity> feedbackQuestionlist = feedbackQuestionService.find(new FeedbackQuestionQuery().feedbackIdList(Arrays.asList(ids)));
        feedbackQuestionService.removeList(feedbackQuestionlist,context);
        List<FeedbackStaffEntity> staffEntityList = feedbackStaffService.find(new FeedbackStaffQuery().feedbackIdList(Arrays.asList(ids)));
        feedbackStaffService.removeList(staffEntityList,context);
        super.removeAfter(ids, context, result);
    }

    @Override
    public Result<FeedbackStaffInfoVo> getFeedbackStaffList(FeedbackEntity query,PageInfo pageInfo) throws AppException {
        if(query.getFeedbackId()==null){
            throw new AppException("绩效反馈记录Id不能为空");
        }
        if(pageInfo==null){
            pageInfo = new PageInfo();
        }
        return dao.getFeedbackStaffList(query,pageInfo);
    }

    @Override
    public List<OptionSummaryVo> getOptionSummaryList(Long feedbackId) throws AppException {
        if(feedbackId==null){
            throw new AppException("绩效反馈记录Id不能为空");
        }
        return dao.getOptionSummaryList(feedbackId);
    }

    @Override
    public Result<QuestionAnswerVo> getQuestionAnswerList(Long questionId, PageInfo pageInfo) throws AppException {
        if(questionId == null){
            throw new AppException("绩效反馈记录问题Id不能为空");
        }
        if(pageInfo==null){
            pageInfo = new PageInfo();
        }
        return dao.getQuestionAnswerList(questionId,pageInfo);
    }

    @Override
    public Map<String, Integer> summaryFeedback() throws AppException {
        Map<String,Integer> resultMap = new HashMap<>();
        resultMap.put("total",0);
        resultMap.put("notStart",0);
        resultMap.put("progress",0);
        resultMap.put("ended",0);
        List<FeedbackEntity> allList = this.getAllList();
        if(CollectionUtils.isNotEmpty(allList)) {
            resultMap.put("total", allList.size());
            Map<Integer, List<FeedbackEntity>> groupMap = allList.stream().collect(Collectors.groupingBy(FeedbackEntity::getProcessStatus));
            for (Map.Entry<Integer, List<FeedbackEntity>> entry : groupMap.entrySet()) {
                if (entry.getKey() == 0) {
                    resultMap.put("notStart", entry.getValue().size());
                }
                if (entry.getKey() == 1) {
                    resultMap.put("progress", entry.getValue().size());
                }
                if (entry.getKey() == 2) {
                    resultMap.put("ended", entry.getValue().size());
                }
            }
        }
        return resultMap;
    }
}