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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.hmit.common.service.impl.CrudServiceImpl;
import io.hmit.common.utils.ConvertUtils;
import io.hmit.entity.UserEntity;
import io.hmit.modules.fhjw.dao.FhjwCaseDao;
import io.hmit.modules.fhjw.dto.FhjwCaseDTO;
import io.hmit.modules.fhjw.dto.UserCaseDTO;
import io.hmit.modules.fhjw.entity.FhjwCaseEntity;
import io.hmit.modules.fhjw.service.FhjwCaseService;
import io.hmit.modules.fhjw.service.UserCaseService;
import io.hmit.modules.user.dto.RoleDTO;
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 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.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 案件表
 *
 * @author zsh 408538940@qq.com
 * @since 1.0.0 2021-06-02
 */
@Service
public class FhjwCaseServiceImpl extends CrudServiceImpl<FhjwCaseDao, FhjwCaseEntity, FhjwCaseDTO> implements FhjwCaseService {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserCaseService userCaseService;

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

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

        return wrapper;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(Map<String, Object> params) {

        String caseNum = (String)params.get("caseNum");
        //录入的承办人ID
        Long undertakerId = Long.parseLong(params.get("userId").toString());
        System.out.println("保存的params:"+params);
        FhjwCaseDTO dto= JSON.parseObject(JSON.toJSONString(params), FhjwCaseDTO.class);

        dto.getPeopleInfo().stream().forEach(item ->{
            if("嫌疑人".equals(item.getUserRole()) || "被害人".equals(item.getUserRole())){
                dto.setPeopleName(item.getUserName());
            }
            if("代理人".equals(item.getUserRole()) && StringUtils.isNotBlank(item.getUserName())){
                dto.setAgentName(item.getUserName());
            }
        });

        FhjwCaseEntity entity = baseDao.selectOne(new QueryWrapper<FhjwCaseEntity>()
                .eq(StringUtils.isNotBlank(caseNum),"case_num", caseNum)
                .eq("people_name",dto.getPeopleName()));

        //案件信息保存或更新
        if(entity !=null){
            dto.setId(entity.getId());
            dto.setUpdateDate(new Date());
            //设置更新标志（默认未更新：2）用来更新承办人所属部门
            if(entity.getDeptId() ==null){
                dto.setFlag("2");
            }
            update(dto);
        } else{
            dto.setFlag("2");
            dto.setCreator(undertakerId);
            dto.setCreateDate(new Date());
            super.save(dto);
        }

        //若是包含承办人信息，则保存案件和承办人的关联关系
        if(undertakerInfoNotNull(params)){
            dto.setUndertaker(params.get("undertaker").toString());
        }

        //保存案件相关人员关联信息（不包含承办人）
        if(dto.getPeopleInfo()!=null && dto.getPeopleInfo().size()>0){
            dto.getPeopleInfo().stream().forEach(item ->{
                UserEntity userEntity = null;
                if(StringUtils.isNotBlank(item.getUserMobile()) ){
                    userEntity = userService.getByMobile(item.getUserMobile());
                }

                //当事人 角色细分为 嫌疑人身份 和 被害人身份
                String actRoleName = item.getUserRole();

                if("嫌疑人".equals(item.getUserRole()) || "被害人".equals(item.getUserRole())){
                    actRoleName = "当事人";
                    if(StringUtils.isNotBlank(item.getUserName()) ){
                        Map<String, Object> query = new HashMap<>();
                        query.put("username",item.getUserName());
                        userEntity = userService.getByParams(query);
                    }
                }

                //案件相关人员不存在人员表中则插入
                if(userEntity==null){
                    if(StringUtils.isBlank(item.getUserName())){
                       return;
                    }
                    //tb_user中添加人员
                    UserEntity user = new UserEntity();
                    user.setUsername(item.getUserName());
                    user.setMobile(StringUtils.isBlank(item.getUserMobile())?"":item.getUserMobile());
                    user.setCreateDate(new Date());
                    user.setUserIdno(item.getUserIdNo());
                    user.setIdentity(item.getUserRole());
                    userService.insert(user);

                    //人员-权限对应关系表

                    Optional<RoleDTO> roleDTO = Optional.ofNullable(roleService.getRoleByName(actRoleName));
                    roleDTO.ifPresent(role -> {
                        UserRoleDTO userRole = new UserRoleDTO().assembleUserRole(role.getId(),user.getId());
                        userRoleService.save(userRole);
                    });

                    //人员-案件对应关系表
                    UserCaseDTO userCaseDTO = new UserCaseDTO().assembleUserCase(user.getId(),dto.getId());
                    userCaseService.save(userCaseDTO);

                }else {
                    //相关人员ID(当事人、代理人）
                    Long userId = userEntity.getId();

                    //人员信息更新
                    userEntity.setMobile(StringUtils.isBlank(item.getUserMobile())?userEntity.getMobile():item.getUserMobile());
                    userEntity.setUsername(item.getUserName());
                    userEntity.setUserIdno(StringUtils.isBlank(item.getUserIdNo())?userEntity.getUserIdno():item.getUserIdNo());
                    userEntity.setIdentity(item.getUserRole());
                    userService.updateById(userEntity);

                    //人员已经存在，人员-案件新增
                    UserCaseDTO userCase = userCaseService.getByUserACase(userId,dto.getId());
                    if (userCase==null){
                        UserCaseDTO userCaseDTO = new UserCaseDTO().assembleUserCase(userId,dto.getId());
                        userCaseService.save(userCaseDTO);
                    }

                    //人员已经存在，人员-权限新增（权限不一致则新增）
                    Optional<RoleDTO> roleDTO = Optional.ofNullable(roleService.getRoleByName(actRoleName));
                    roleDTO.ifPresent(role ->{
                        UserRoleDTO userRoleDTO = userRoleService.getByRoleAUser(role.getId(),userId);
                        if (userRoleDTO == null) {
                            UserRoleDTO userRole = new UserRoleDTO().assembleUserRole(role.getId(),userId);
                            userRoleService.save(userRole);
                        }
                    });
                }

            });
        }
    }

    @Override
    public FhjwCaseDTO getByCaseNum(String caseNum) {
        FhjwCaseEntity entity = baseDao.selectOne(new QueryWrapper<FhjwCaseEntity>().eq("case_num",caseNum));
        return ConvertUtils.sourceToTarget(entity,FhjwCaseDTO.class);
    }

    @Override
    public List<FhjwCaseDTO> selectByCaseNum(String caseNum) {
        List<FhjwCaseEntity> entity = baseDao.selectList(new QueryWrapper<FhjwCaseEntity>().eq("case_num",caseNum));
        return ConvertUtils.sourceToTarget(entity,FhjwCaseDTO.class);
    }

    /**
     * 判断是否为第一次录入信息
     * 第一次录入的信息中包含承办人数据
     * @param params
     * @return
     */
    public boolean undertakerInfoNotNull(Map<String, Object> params){

        if(params.get("undertaker")!=null && params.get("undertakerMobile")!=null
                && StringUtils.isNotBlank(params.get("undertaker").toString())
                && StringUtils.isNotBlank(params.get("undertakerMobile").toString())){
            return true;
        }
        return false;
    }

}
