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.FhjwFeedbackDao;
import io.hmit.modules.fhjw.dto.FeedbackCountDTO;
import io.hmit.modules.fhjw.dto.FeedbackCountListDTO;
import io.hmit.modules.fhjw.dto.FhjwCaseDTO;
import io.hmit.modules.fhjw.dto.FhjwCommentDTO;
import io.hmit.modules.fhjw.dto.FhjwFeedbackDTO;
import io.hmit.modules.fhjw.dto.RoleDTO;
import io.hmit.modules.fhjw.entity.FhjwCaseEntity;
import io.hmit.modules.fhjw.entity.FhjwCommentEntity;
import io.hmit.modules.fhjw.entity.FhjwFeedbackEntity;
import io.hmit.modules.fhjw.entity.FhjwTempEntity;
import io.hmit.modules.fhjw.entity.UserEntity;
import io.hmit.modules.fhjw.service.FhjwCaseService;
import io.hmit.modules.fhjw.service.FhjwFeedbackService;
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.service.SysDeptService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 人员反馈表，包含意见反馈，控告申诉，代表委员有话说
 *
 * @author zsh 408538940@qq.com
 * @since 1.0.0 2021-06-02
 */
@Service
public class FhjwFeedbackServiceImpl extends CrudServiceImpl<FhjwFeedbackDao, FhjwFeedbackEntity, FhjwFeedbackDTO> implements FhjwFeedbackService {
    @Autowired
    private UserService userService;

    @Autowired
    private FhjwCaseService fhjwCaseService;

    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

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

        QueryWrapper<FhjwFeedbackEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.eq(StringUtils.isNotBlank(feedbackType), "feedback_type", feedbackType);
        wrapper.like(StringUtils.isNotBlank(content), "content", content);

        return wrapper;
    }

    @Override
    public PageData<FhjwFeedbackDTO> page(Map<String, Object> params) {
        IPage<FhjwFeedbackEntity> page = super.page2(params);
        //在返回的page中增加 相关信息字段
        page.getRecords().stream().forEach(item ->addInfo(item));

        return getPageData(page, currentDtoClass());
    }

    @Override
    public FhjwFeedbackDTO get(Long id){

        FhjwFeedbackEntity entity = baseDao.selectById(id);
        //在返回的中增加 相关信息字段
        FhjwFeedbackDTO dto = addInfo(entity);
        return dto;
    }

    @Override
    public List<FhjwFeedbackEntity> getByCaseNum(String caseNum) {
        List<FhjwFeedbackEntity> lists= baseDao.selectList(new QueryWrapper<FhjwFeedbackEntity>().eq("case_num",caseNum));
        return lists;
    }

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

    @Override
    public List<FeedbackCountListDTO> getCountLists(Map<String, Object> params) {

        List<FeedbackCountListDTO>  countListDTOList = new ArrayList<>();

        //所有反馈统计(统计各个类别的总数）
        FeedbackCountDTO countDTO = baseDao.getCount(params);

        FeedbackCountListDTO count = new FeedbackCountListDTO()
                .assembleCountListDTO("反馈统计",countDTO);


        //反馈意见统计
        Map<String, Object> fdbQuery = params;
        fdbQuery.put("feedbackType","feedback");

        FeedbackCountDTO fdbCountDTO = baseDao.getCount(fdbQuery);

        FeedbackCountListDTO fbdCount = new FeedbackCountListDTO()
                .assembleCountListDTO("反馈意见统计",fdbCountDTO);

/*
        if(fdbCountDTO.getTotalCount() !=0){
            fbdCount.setFeedbackCount(fdbCountDTO);
        }else{
            fbdCount.setFeedbackCount(new FeedbackCountDTO().assembleZeroCountDTO());
        }
        fbdCount.setName("反馈意见统计");
*/

        //代表委员意见统计
        Map<String, Object> committeeQuery = params;
        committeeQuery.put("feedbackType","committee");
        FeedbackCountDTO committeeCountDTO = baseDao.getCount(committeeQuery);

        FeedbackCountListDTO committeeCount = new FeedbackCountListDTO()
                .assembleCountListDTO("代表委员意见统计",committeeCountDTO);

/*
        committeeCount.setFeedbackCount(baseDao.getCount(committeeQuery));
        committeeCount.setName("代表委员意见统计");
*/


        countListDTOList.add(fbdCount);
        countListDTOList.add(committeeCount);
        countListDTOList.add(count);

        return countListDTOList;
    }

    /**
     * 在返回的实体中添加如下字段信息
     * 用户名字
     * 用户权限
     * 承办人
     * 案件名称
     * 当事人
     * 所属部门名称
     * @param dto
     * @return
     */
    public FhjwFeedbackDTO addInfo(FhjwFeedbackEntity dto){

        Optional<UserEntity> users = Optional.ofNullable(userService.selectById(dto.getUserId()));
        users.ifPresent( u -> dto.setUserName(u.getUsername()));

        Optional<FhjwCaseDTO> caseDTO = Optional.ofNullable(fhjwCaseService.getByCaseNum(dto.getCaseNum(),dto.getPeopleName()));
//        Optional<FhjwCaseDTO> caseDTO = Optional.ofNullable(fhjwCaseService.get(dto.getCaseNum()));
        caseDTO.ifPresent(c ->{
            dto.setCaseName(c.getCaseName());
            dto.setPeopleName(c.getPeopleName());
            dto.setDeptName(sysDeptService.get(c.getDeptId()).getName());
            dto.setUndertaker(c.getUndertaker());
        });
        //用户权限由前端传，因为可能存在一个用户多个权限的情况（此案件的当事人，其他案件的代理人）
        if(dto.getRoleId() !=null){
            Optional<RoleDTO> roleDTO = Optional.ofNullable(roleService.get(dto.getRoleId()));
            roleDTO.ifPresent(r-> dto.setUserRole(r.getName()));
        }

        return ConvertUtils.sourceToTarget(dto,FhjwFeedbackDTO.class);
    }

}
