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

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.hmit.common.exception.HmitException;
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.UserDao;
import io.hmit.modules.fhjw.dto.FhjwCaseDTO;
import io.hmit.modules.fhjw.dto.RoleDTO;
import io.hmit.modules.fhjw.dto.UserDTO;
import io.hmit.modules.fhjw.dto.UserRoleDTO;
import io.hmit.modules.fhjw.entity.FhjwCaseEntity;
import io.hmit.modules.fhjw.entity.FhjwCommentEntity;
import io.hmit.modules.fhjw.entity.UserEntity;
import io.hmit.modules.fhjw.entity.UserRoleEntity;
import io.hmit.modules.fhjw.service.FhjwCaseService;
import io.hmit.modules.fhjw.service.FhjwCommentService;
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 org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.management.relation.Role;
import java.util.ArrayList;
import java.util.Date;
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-03
 */
@Service
public class UserServiceImpl extends CrudServiceImpl<UserDao, UserEntity, UserDTO> implements UserService {

    @Autowired
    private FhjwCaseService fhjwCaseService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private FhjwCommentService fhjwCommentService;

    @Autowired
    private FhjwFeedbackService fhjwFeedbackService;

    @Override
    public QueryWrapper<UserEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String mobile = (String)params.get("mobile");
        String caseId = params.get("caseId")==null?"":params.get("caseId").toString();

        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.like(StringUtils.isNotBlank(mobile), "mobile", mobile);
        wrapper.eq(StringUtils.isNotBlank(caseId), "case_id", caseId);

        return wrapper;
    }

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

        Long roleId = roleService.getIdByRoleName("承办人");
        page.getRecords().stream().forEach(item ->{
            Optional<FhjwCaseEntity> entity = Optional.ofNullable(fhjwCaseService.selectById(item.getCaseId()));
            entity.ifPresent( q -> item.setCaseName(q.getCaseName()));

            Optional<List<UserRoleDTO>> userRole = Optional.ofNullable(userRoleService.getByUserIds(item.getId()));
            userRole.ifPresent(ur -> {
                String userRoles = "";
                for (UserRoleDTO dto:ur) {
                    RoleDTO role = roleService.get(dto.getRoleId());
                    if("".equals(userRoles)){
                        userRoles = role.getName();
                    }else{
                        userRoles = userRoles+ " , "+role.getName();
                    }
                    item.setUserRole(userRoles);
                }
            });

/*
            Optional<UserRoleDTO> userRole = Optional.ofNullable(userRoleService.getByUserIds(item.getId()));
            userRole.ifPresent( ur -> {
                Optional<RoleDTO> role = Optional.ofNullable(roleService.get(ur.getRoleId()));
                role.ifPresent( r -> item.setUserRole(r.getName()));
            });
*/

        });
        return getPageData(page, currentDtoClass());
    }

    @Override
    public PageData<UserDTO> getUserPageByCase(Map<String, Object> params) {
        Long caseId = params.get("caseId")==null?000L:Long.parseLong(params.get("caseId").toString()) ;
        List<Long> ids = fhjwCommentService.getUserIdByCase(caseId);

        IPage<UserEntity> page = new Page<>();


        List<UserEntity> userEntitys = new ArrayList<>();

        ids.stream().forEach(userId ->{
            UserEntity user = selectById(userId);

            Optional<UserRoleDTO> userRole = Optional.ofNullable(userRoleService.getByUserId(userId));
            userRole.ifPresent( ur -> {
                Optional<RoleDTO> role = Optional.ofNullable(roleService.get(ur.getRoleId()));
                role.ifPresent( r -> user.setUserRole(r.getName()));
            });

            userEntitys.add(user);
        });

        page.setTotal(ids.size());
        page.setRecords(userEntitys);
        return getPageData(page, currentDtoClass());
    }

    @Override
    public List<UserDTO> dtoAddUserRole(Map<String, Object> params) {
        List<UserDTO> dto= list(params);
        dto.stream().forEach(item->{
            Long roleId = userRoleService.getByUserId(item.getId()).getRoleId();
            item.setUserRole(roleService.get(roleId).getName());
        });

        return dto;
    }

    @Override
    public void save(UserDTO dto){
        //添加人员
        UserEntity user = new UserEntity();
        user.setUsername(dto.getUsername());
        user.setMobile(dto.getMobile());
        user.setCreateDate(new Date());
        user.setUserIdno(dto.getUserIdno());
        user.setGender(dto.getGender());
        user.setIdentity(dto.getIdentity());
        insert(user);

        //人员-权限对应关系表
        UserRoleDTO userRole = new UserRoleDTO().assembleUserRole(dto.getUserRoleId(),user.getId());
        userRoleService.save(userRole);
    }

    @Override
    public void update(UserDTO dto){
        //添加人员
        super.update(dto);

        //删除权限
        userRoleService.deleteByUserId(dto.getId());

        //人员-权限对应关系表
        UserRoleDTO userRoleDTO = new UserRoleDTO().assembleUserRole(dto.getUserRoleId() ,dto.getId());
        userRoleService.save(userRoleDTO);

/*
        Optional<UserRoleDTO> userRole =Optional.ofNullable(userRoleService.getByUserId(dto.getId())) ;
        userRole.ifPresent(user -> {
            user.setRoleId(dto.getUserRoleId());
            userRoleService.update(user);
        });
*/

    }

    @Override
    public UserDTO get(Long id){
        UserDTO user = super.get(id);
        Optional<UserRoleDTO> userRole = Optional.ofNullable(userRoleService.getByUserId(id));
        userRole.ifPresent( ur -> {
            Optional<RoleDTO> role = Optional.ofNullable(roleService.get(ur.getRoleId()));
            role.ifPresent( r -> {
                user.setUserRole(r.getName());
                user.setUserRoleId(r.getId());
            });
        });

        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long[] ids) {
        for (Long id:ids) {
            int feedbCount = fhjwFeedbackService.getCountByUserId(id);
            int commentCount = fhjwCommentService.getCountByUserId(id);
            if(feedbCount>0){
                throw new HmitException("此用户存在相关案件反馈信息，请先删除人员下的反馈信息！");
            }

            if(commentCount>0){
                throw new HmitException("此用户存在相关案件评价信息，请先删除人员下的评价信息！");
            }
            //用户删除
            deleteById(id);
            //删除用户-权限对应关系
            userRoleService.deleteByUserId(id);
        }

    }
}
