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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.FhjwAnswerDTO;
import io.hmit.modules.fhjw.dto.FhjwCaseDTO;
import io.hmit.modules.fhjw.dto.FhjwCommentDTO;
import io.hmit.modules.fhjw.dto.UserCaseDTO;
import io.hmit.modules.fhjw.entity.FhjwCommentEntity;
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.UserCaseService;
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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
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 FhjwCaseService fhjwCaseService;

    @Autowired
    private FhjwAnswerService fhjwAnswerService;

    @Autowired
    private UserCaseService userCaseService;

    @Override
    public QueryWrapper<FhjwCommentEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<FhjwCommentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(FhjwCommentDTO dto) {

        Map<String, Object> params = new HashMap<>();
        params.put("caseNum",dto.getCaseNum());


        //根据受案号查出caseID
        List<FhjwCaseDTO> caseDto = fhjwCaseService.list(params);

        //设置案件所属部门（根据承办人确定）
        dto.setDeptId(caseDto.get(0).getDeptId());
        //设置案件ID--律师、代表委员、监督听证权限和案件没有绑定了人员则根据案件号获取第一个caseID
        dto.setCaseId(caseDto.get(0).getId());
        //设置人员对应的caseID(存在相同受案号，不同当事人的情况，需要人员匹配caseID)
        List<Long> ids = caseDto.stream().map(FhjwCaseDTO::getId).collect(Collectors.toList());
        for (Long id :ids){
            UserCaseDTO  userCaseDTO= userCaseService.getByUserACase(dto.getUserId(),id);
            if(userCaseDTO != null){

                dto.setCaseId(id);

                List<Long> lists = baseDao.selectList(new QueryWrapper<FhjwCommentEntity>()
                        .eq("user_id",dto.getUserId()).eq("case_id",id))
                        .stream().map(FhjwCommentEntity::getId).collect(Collectors.toList());
                if(lists.size()>0){
                    deleteBatchIds(lists);
                }
            }
        }
        dto.getQuestionAnswerList().stream().forEach(item ->{
            FhjwCommentDTO fhjwCommentDTO = ConvertUtils.sourceToTarget(dto,FhjwCommentDTO.class);
            fhjwCommentDTO.setCreateDate(new Date());
            fhjwCommentDTO.setAnswerId(item.getAnswerId());
            //如果是"好、中、差"三个答案则去设置answerlistId 方便进行好差评统计
            //前期未考虑到统计，为尽量减少修改，则直接增加answerlistId字段（好的数据库设计真的很重要！！！）
            FhjwAnswerDTO answerDTO = fhjwAnswerService.get(item.getAnswerId());
            fhjwCommentDTO.setAnswerlistId(answerDTO.getAnswerlistId());
            fhjwCommentDTO.setQuestionId(item.getQuestionId());
            super.save(fhjwCommentDTO);
        });

    }
}
