package io.hmit.modules.fhjw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.hmit.common.page.PageData;
import io.hmit.common.service.impl.CrudServiceImpl;
import io.hmit.common.utils.ConvertUtils;
import io.hmit.modules.fhjw.dao.FhjwCommentDao;
import io.hmit.modules.fhjw.dto.CommitteeCountDTO;
import io.hmit.modules.fhjw.dto.CommitteeCountListDTO;
import io.hmit.modules.fhjw.dto.FhjwCaseDTO;
import io.hmit.modules.fhjw.dto.FhjwCommentDTO;
import io.hmit.modules.fhjw.dto.QuestionListDTO;
import io.hmit.modules.fhjw.dto.RoleDTO;
import io.hmit.modules.fhjw.entity.FhjwAnswerEntity;
import io.hmit.modules.fhjw.entity.FhjwCaseEntity;
import io.hmit.modules.fhjw.entity.FhjwCommentEntity;
import io.hmit.modules.fhjw.entity.FhjwQuestionEntity;
import io.hmit.modules.fhjw.entity.FhjwTempEntity;
import io.hmit.modules.fhjw.entity.UserEntity;
import io.hmit.modules.fhjw.service.FhjwAnswerService;
import io.hmit.modules.fhjw.service.FhjwCaseService;
import io.hmit.modules.fhjw.service.FhjwCommentService;
import io.hmit.modules.fhjw.service.FhjwQuestionService;
import io.hmit.modules.fhjw.service.FhjwTempService;
import io.hmit.modules.fhjw.service.RoleService;
import io.hmit.modules.fhjw.service.UserRoleService;
import io.hmit.modules.fhjw.service.UserService;
import io.hmit.modules.sys.dto.SysDeptDTO;
import io.hmit.modules.sys.entity.SysDeptEntity;
import io.hmit.modules.sys.service.SysDeptService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 案件评价表
 *
 * @author zsh 408538940@qq.com
 * @since 1.0.0 2021-06-02
 */
@Service
public class FhjwCommentServiceImpl extends CrudServiceImpl<FhjwCommentDao, FhjwCommentEntity, FhjwCommentDTO> implements FhjwCommentService {
    @Autowired
    private FhjwQuestionService fhjwQuestionService;

    @Autowired
    private FhjwAnswerService fhjwAnswerService;

    @Autowired
    private FhjwTempService fhjwTempService;

    @Autowired
    private FhjwCaseService fhjwCaseService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private SysDeptService sysDeptService;

    @Override
    public QueryWrapper<FhjwCommentEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String caseId = params.get("caseId")==null?"":params.get("caseId").toString();
        //查询条件--根据案件名查询
        String caseName = (String)params.get("caseName");

        List<Long> caseIdList = new ArrayList<>();

        //构造查询语句
        QueryWrapper<FhjwCommentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.eq(StringUtils.isNotBlank(caseId), "case_id", caseId);
        wrapper.groupBy( "case_id","user_id");

        //查询条件--根据案件名caseName 查询出 caseId
        if(StringUtils.isNotEmpty(caseName)){
            Map<String, Object> param = new HashMap<>();
            param.put("caseName",caseName);
           caseIdList = fhjwCaseService.list(param).stream().map(FhjwCaseDTO::getId).collect(Collectors.toList());
           //若caseIdList 中不存在值，则去查一个咋都不可能存在的数
           if (caseIdList.size()==0){
               wrapper.in("case_id",000);
           }
            wrapper.in( !(caseIdList.isEmpty()), "case_id",caseIdList);
        }

        return wrapper;
    }

    @Override
    public PageData<FhjwCommentDTO> page(Map<String, Object> params) {
        IPage<FhjwCommentEntity> page = super.page2(params);

        //在返回的page中增加 问题名字、答案、模版名字、案件名 字段
        page.getRecords().stream().forEach(item ->addBaseData(item));

        return getPageData(page, currentDtoClass());
    }

    @Override
    public List<Long> getUserIdByCase(Long caseId) {
        List<Long> userIds = baseDao.selectList(new QueryWrapper<FhjwCommentEntity>()
                .eq("case_id", caseId).groupBy("user_id"))
                .stream().map(FhjwCommentEntity::getUserId).collect(Collectors.toList());
        return userIds;
    }


    @Override
    public FhjwCommentDTO assembleDTO(Map<String, Object> params) {

        Long caseId = Long.parseLong(params.get("caseId").toString());
        Long userId = Long.parseLong(params.get("userId").toString());
        List<FhjwCommentEntity> entitys = baseDao.selectList(new QueryWrapper<FhjwCommentEntity>()
                .eq("user_id",userId).eq("case_id",caseId));

        List<QuestionListDTO> questionListDTOS = new ArrayList<>();


        FhjwCommentEntity commentDTO = entitys.get(0);
        FhjwCommentDTO dto = addBaseData(commentDTO);
        dto.setCaseId(commentDTO.getCaseId());
        dto.setUserId(commentDTO.getUserId());
        dto.setTempId(commentDTO.getTempId());
        dto.setCreateDate(commentDTO.getCreateDate());

        entitys.stream().forEach(item -> {
            QuestionListDTO questionListDTO = new QuestionListDTO();
            questionListDTO.setQuestionId(item.getQuestionId());
            questionListDTO.setAnswerId(item.getAnswerId());

            Optional<FhjwQuestionEntity> questionDTO = Optional.ofNullable(fhjwQuestionService.selectById(item.getQuestionId()));
            questionDTO.ifPresent( q -> questionListDTO.setQuestionName(q.getQuestion()));

            Optional<FhjwAnswerEntity> answerDTO = Optional.ofNullable(fhjwAnswerService.selectById(item.getAnswerId()));
            answerDTO.ifPresent( a -> questionListDTO.setAnswer(a.getAnswer()));
            questionListDTOS.add(questionListDTO);
        });
        dto.setQuestionList(questionListDTOS);
        return dto;
    }

    /**
     * 在返回的实体中添加问题名字、答案、模版名字、案件名 信息
     * @param DTO 实体
     * @return FhjwCommentDTO
     */
    public FhjwCommentDTO addBaseData(FhjwCommentEntity DTO){
        Optional<FhjwCommentEntity> optional = Optional.ofNullable(DTO);

        optional.ifPresent(item -> {

            //模版名称
            Optional<FhjwTempEntity> temp = Optional.ofNullable(fhjwTempService.selectById(item.getTempId()));
            temp.ifPresent( t -> item.setTempName(t.getTempName()));

            //案件相关信息（案件名字、部门、承办人、当事人、受案号）
            Optional<FhjwCaseEntity> caseN = Optional.ofNullable(fhjwCaseService.selectById(item.getCaseId()));
            caseN.ifPresent( c -> {
                item.setCaseName(c.getCaseName());
                item.setPeopleName(c.getPeopleName());
                item.setUndertaker(c.getUndertaker());
                item.setCaseNum(c.getCaseNum());

                Optional<SysDeptDTO> dept = Optional.ofNullable(sysDeptService.get(c.getDeptId()));
                dept.ifPresent(d -> item.setDeptName(d.getName()));

            });

            //评价人员姓名
            Optional<UserEntity> users = Optional.ofNullable(userService.selectById(item.getUserId()));
            users.ifPresent( u -> item.setUserName(u.getUsername()));

            //评价人员权限（身份）
            if(item.getRoleId() !=null){
                Optional<RoleDTO> roleDTO = Optional.ofNullable(roleService.get(item.getRoleId()));
                roleDTO.ifPresent(r-> item.setUserRole(r.getName()));
            }
/*
            Long roleId = userRoleService.getByUserId(item.getUserId()).getRoleId();
            item.setUserRole(roleService.get(roleId).getName());
*/
        });

        return ConvertUtils.sourceToTarget(DTO,FhjwCommentDTO.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long[] ids) {
        Arrays.asList(ids).stream().forEach(id ->{
            FhjwCommentEntity entity = selectById(id);
           Long case_id = entity.getCaseId();
           Long user_id = entity.getUserId();
            baseDao.delete(new QueryWrapper<FhjwCommentEntity>().eq("case_id",case_id)
                    .eq("user_id",user_id));
        });
    }

    @Override
    public int getCountByUserId(Long userId) {
        int count = baseDao.selectCount(new QueryWrapper<FhjwCommentEntity>().eq("user_id",userId));
        return count;
    }

    @Override
    public List<CommitteeCountListDTO> getCountByDept(Map<String, Object> params) {
        List<CommitteeCountListDTO> countListDTOS = new ArrayList<>();
        List<CommitteeCountDTO> countDTOList = baseDao.getCountByDept(params);
        countDTOList.stream().forEach(item ->{

            String deptName = sysDeptService.get(item.getDeptId()).getName();
            CommitteeCountListDTO countList = new CommitteeCountListDTO()
                    .assembleCountListDTO("",deptName,item);
            countListDTOS.add(countList);
        });

        return countListDTOS;
    }

    @Override
    public List<CommitteeCountListDTO> getCaseCountByDept() {
        List<CommitteeCountListDTO> countListDTOS = new ArrayList<>();
        List<CommitteeCountDTO> countDTOList =  baseDao.getCaseCountByDept();

        countDTOList.stream().forEach(item ->{

            String deptName = sysDeptService.get(item.getDeptId()).getName();
            CommitteeCountListDTO countList = new CommitteeCountListDTO()
                    .assembleCountListDTO("",deptName,item);
            countListDTOS.add(countList);
        });

        return countListDTOS;
    }

    @Override
    public List<CommitteeCountDTO> getCountByMouth() {

        List<CommitteeCountDTO> countDTOList = baseDao.getCountByMouth();

        return countDTOList;
    }

    @Override
    public List<CommitteeCountDTO> getCountByUserRole(Map<String, Object> params) {

        List<CommitteeCountDTO> countDTOList = baseDao.getCountByUserRole(params);
        //获取所有的用户权限
        List<RoleDTO> roleDTOList = roleService.getAllRoleList();
        //获取：所有用户角色ID List、已参与评价的用户角色ID List、未参与过评价的用户角色ID List
        List<Long> roleIDs = roleDTOList.stream().map(RoleDTO::getId).collect(Collectors.toList());
        List<Long> committeeRoleIDs = countDTOList.stream().map(CommitteeCountDTO::getRoleId).collect(Collectors.toList());
        List<Long> reduce1 = roleIDs.stream().filter(item -> !committeeRoleIDs.contains(item)).collect(Collectors.toList());


        //将未参与过评价的用户角色，添加到已参与评价的用户角色列表中，并设置默认的好差评数为0
        reduce1.stream().forEach(a -> {
            CommitteeCountDTO dto = new CommitteeCountDTO().assembleCountDTO();
            dto.setRoleId(a);
            countDTOList.add(dto);
        });

        //根据userRoleID设置用户userRole,返回
        List<CommitteeCountDTO> resultList2 = countDTOList.stream().map(m->{
            roleDTOList.stream().filter(m2-> Objects.equals(m.getRoleId(), m2.getId())).forEach(s-> m.setUserRole(s.getName()));
            return m;
        }).collect(Collectors.toList());

        return resultList2;
    }
}
