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.common.utils.Result;
import io.hmit.config.ZhelibanUtils;
import io.hmit.entity.TokenEntity;
import io.hmit.entity.UserEntity;
import io.hmit.modules.fhjw.dao.FhiwFunctionDao;
import io.hmit.modules.fhjw.dto.FhiwFunctionDTO;
import io.hmit.modules.fhjw.dto.FhjwCaseDTO;
import io.hmit.modules.fhjw.dto.FhjwRoleFunctionDTO;
import io.hmit.modules.fhjw.dto.UserCaseDTO;
import io.hmit.modules.fhjw.entity.FhiwFunctionEntity;
import io.hmit.modules.fhjw.entity.UserCaseEntity;
import io.hmit.modules.fhjw.service.FhiwFunctionService;
import io.hmit.modules.fhjw.service.FhjwCaseService;
import io.hmit.modules.fhjw.service.FhjwRoleFunctionService;
import io.hmit.modules.fhjw.service.UserCaseService;
import io.hmit.modules.user.dto.UserRoleDTO;
import io.hmit.modules.user.service.RoleService;
import io.hmit.modules.user.service.UserRoleService;
import io.hmit.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 评价模块
 *
 * @author zsh 408538940@qq.com
 * @since 1.0.0 2021-06-22
 */
@Service
public class FhiwFunctionServiceImpl extends CrudServiceImpl<FhiwFunctionDao, FhiwFunctionEntity, FhiwFunctionDTO> implements FhiwFunctionService {
    private static Logger logger = LoggerFactory.getLogger(FhiwFunctionServiceImpl.class);


    @Autowired
    private FhjwRoleFunctionService fhjwRoleFunctionService;

    @Autowired
    private UserCaseService userCaseService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private FhjwCaseService fhjwCaseService;


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

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

        return wrapper;
    }


    @Override
    public List<FhiwFunctionDTO> getByRole(Map<String, Object> params) {

        //获取权限时传入的信息，用户权限ID,登录的用户ID，案件ID
        Long roleId = Long.parseLong(params.get("roleId").toString());
        Long userId = Long.parseLong(params.get("userId").toString());
        String caseNum = params.get("caseNum").toString().replace("%5B","[").replace("%5D","]");
        List<Long> caseIds = fhjwCaseService.selectByCaseNum(caseNum).stream()
                .map(FhjwCaseDTO::getId).collect(Collectors.toList());
//        Long caseId = fhjwCaseService.getByCaseNum(caseNum).getId();
        String roleName = roleService.get(roleId).getName();
        List<FhiwFunctionDTO> dtos = new ArrayList<>();
        //判断案件是否存在代理人
        boolean flag = false;
        //判断是否有评价权限
        boolean ifComment = false;

        //判断人员和案件是否已经绑定，当事人、代理人需要和案件关联后才能进行操作，否则显示无权限
        //律师、代表委员、监督听证则无需和案件关联也可进行评价
        if("当事人".equals(roleName)||"代理人".equals(roleName)){
            for (Long caseId:caseIds) {
                logger.info("caseId:"+caseId);
                Map<String, Object> query = new HashMap<>();
                query.put("caseId",caseId);
                query.put("userId",userId);
                List<UserCaseDTO> userCases = userCaseService.list(query);
                //当事人权限，则需要判断此案件是否有代理人，有代理人则不允许评价，无代理人则可以评价
                if(userCases.size()>0){
                    ifComment = true;
                    if("当事人".equals(roleName)){
                        String agentName = fhjwCaseService.get(caseId).getAgentName();
                        logger.info("案件ID："+caseId+"的代理人："+agentName);
                        if(StringUtils.isNotBlank(agentName) && agentName !=null){
                            flag = true;
                            break;
                        }
                    }
                }
            }
            //人员和案件没有关联信息则返回权限为空
            if(!ifComment){
                return dtos;
            }
        }

/*
// 0827版本（修改多用户评价BUG）--最后改一次系列
        if("当事人".equals(roleService.get(roleId).getName())){
            for (Long caseId:caseIds) {
                logger.info("caseId:"+caseId);
                Map<String, Object> query = new HashMap<>();
                query.put("caseId",caseId);
                query.put("userId",userId);
                List<UserCaseDTO> userCases = userCaseService.list(query);
                if(userCases.size()>0){
                    logger.info("代理人："+fhjwCaseService.get(caseId).getAgentName());
                    if(StringUtils.isNotBlank(fhjwCaseService.get(caseId).getAgentName())
                            && fhjwCaseService.get(caseId).getAgentName() !=null){
                        flag = true;
                        break;
                    }
                }
            }
        }
*/

        //根据是否存在代理人，判断是否添加 "我要填写测评" 的权限！
        Long funcId = baseDao.selectOne(new QueryWrapper<FhiwFunctionEntity>().eq("name","我要填写测评")).getId();
        List<Long> funIds = new ArrayList<>();
        if(flag){
            logger.info("存在代理人");
            funIds = fhjwRoleFunctionService.list(params).stream()
                    .filter(roleFunc -> !roleFunc.getFunctionId().equals(funcId))
                    .map(FhjwRoleFunctionDTO::getFunctionId).collect(Collectors.toList());
        }else {
            logger.info("不存在代理人");
            funIds = fhjwRoleFunctionService.list(params).stream()
                    .map(FhjwRoleFunctionDTO::getFunctionId).collect(Collectors.toList());
        }

        funIds.stream().forEach(id ->{
            FhiwFunctionDTO dto  = get(id);
            logger.info("拥有的权限名称："+dto.getName());
            dtos.add(dto);
        });

        return dtos;
    }

}
