package com.liquidnet.client.admin.zhengzai.smile.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageInfo;
import com.liquidnet.client.admin.common.core.domain.AjaxResult;
import com.liquidnet.client.admin.common.utils.StringUtils;
import com.liquidnet.client.admin.zhengzai.smile.dto.*;
import com.liquidnet.client.admin.zhengzai.smile.service.ISmileUserService;
import com.liquidnet.client.admin.zhengzai.smile.utils.SmileRedisUtils;
import com.liquidnet.commons.lang.util.BeanUtil;
import com.liquidnet.service.goblin.constant.SmileRedisConst;
import com.liquidnet.service.goblin.dto.vo.SmileUserVO;
import com.liquidnet.service.smile.entity.SmileOrganization;
import com.liquidnet.service.smile.entity.SmileUser;
import com.liquidnet.service.smile.entity.dao.SmileUserCheckDao;
import com.liquidnet.service.smile.mapper.SmileOrganizationMapper;
import com.liquidnet.service.smile.mapper.SmileUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings("all")
public class SmileUserServiceImpl extends ServiceImpl<SmileUserMapper, SmileUser> implements ISmileUserService {

    @Autowired
    SmileUserMapper smileUserMapper;

    @Autowired
    SmileRedisUtils smileRedisUtils;

    @Autowired
    SmileOrganizationMapper smileOrganizationMapper;

    @Override
    public PageInfo<SmileUserVo> userList(SmileUserParam smileUserParam) {
        PageInfo<SmileUserVo> pageInfo;
        try {
            //查询通过审核通过的用户 type！=0、1   未删除用户
            Map<String, Object> map = BeanUtil.convertBeanToMap(smileUserParam);
            List<SmileUserVo> smileUserVos = smileUserMapper.selectUserList(map).stream().map(smileUser -> {
                SmileUserVo smileUserVo = new SmileUserVo();
                BeanUtils.copyProperties(smileUser, smileUserVo);
                return smileUserVo;
            }).collect(Collectors.toList());
            pageInfo = new PageInfo<SmileUserVo>(smileUserVos);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return pageInfo;
    }

    @Override
    public SmileUser getUserById(String uid) {
        log.info("查询用户uid:{}", uid);
        //查询未删除,id=uid
        LambdaQueryWrapper<SmileUser> queryWrapper = Wrappers.lambdaQuery(SmileUser.class);
        queryWrapper.eq(SmileUser::getDelTag, 0);
        queryWrapper.eq(SmileUser::getUid, uid);
        SmileUser smileUser = smileUserMapper.selectOne(queryWrapper);
        log.info("smileUser:{}", smileUser);
        return smileUser;
    }

    @Override
    public Boolean create(SmileUser smileUser) {
        smileUser.setCreatedDate(LocalDateTime.now());
        smileUser.setUpdatedDate(LocalDateTime.now());
        smileUser.setDelTag(0);
        smileUser.setState(0);
        log.debug("smileUser:{}", smileUser);
        LambdaQueryWrapper<SmileUser> queryWrapper = Wrappers.lambdaQuery(SmileUser.class);
        queryWrapper.eq(SmileUser::getUid, smileUser.getUid());
        queryWrapper.eq(SmileUser::getDelTag, 0);
        //查询是否有重复uid用户
        if (smileUserMapper.selectOne(queryWrapper) == null) {
            int id = smileUserMapper.insert(smileUser);
            log.debug("return id:{}.", smileUser.getUid());
            redisSetUser(smileUser);
            return true;
        }
        return false;
    }

    @Override
    public List<SmileUserVoOrg> getUserListByOrgId(Long orgId, Long agentId) {
        //查询根据组织ID查询人员信息
        LambdaQueryWrapper<SmileUser> queryWrapper = Wrappers.lambdaQuery(SmileUser.class);
        queryWrapper.eq(SmileUser::getOrgId, orgId);
        List<SmileUserVoOrg> smileUserVos = smileUserMapper.selectList(queryWrapper).stream().map(smileUser -> {
            SmileUserVoOrg smileUserVo = new SmileUserVoOrg();
            BeanUtils.copyProperties(smileUser, smileUserVo);
            return smileUserVo;
        }).collect(Collectors.toList());
        return smileUserVos;
    }

    @Override
    public AjaxResult updateUserStateById(String uid, Integer state) {
        //修改黑名单
        smileUserMapper.updateUserStateById(uid, state);
        updateRedisSetUser(uid,null,state,null,null,null);
        return AjaxResult.success();
    }

    @Override
    public PageInfo<SmileUserCheckDao> listUserCheck(UserCheckParam userCheckParam) {
        PageInfo<SmileUserCheckDao> pageInfo;
        try {
            Map<String, Object> map = BeanUtil.convertBeanToMap(userCheckParam);
            List<SmileUserCheckDao> smileUserCheckDaos = smileUserMapper.selectUserCheck(map);
            pageInfo = new PageInfo<>(smileUserCheckDaos);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return pageInfo;
    }

    @Override
    public AjaxResult updateUserCheckById(SmileUserCheckVo smileUserCheckVo) {
        //判断是否通过
        if (smileUserCheckVo.getState().equals(3)) {
            //申请被驳回
            smileUserMapper.updateUserCheckByUid(smileUserCheckVo.getUid(), smileUserCheckVo.getType(), smileUserCheckVo.getReason());
            updateRedisSetUser(smileUserCheckVo.getUid(),null,null,null,smileUserCheckVo.getReason(),null);
        } else {
            //通过审核
            //判断是否是总代
            if (smileUserCheckVo.getType().equals(1)) {
                //查询组织是否有总代   没有则设置  有则返回异常
                LambdaQueryWrapper<SmileOrganization> orgQueryWrapper = Wrappers.lambdaQuery(SmileOrganization.class);
                orgQueryWrapper.eq(SmileOrganization::getId, smileUserCheckVo.getOrgId());
                orgQueryWrapper.eq(SmileOrganization::getDelTag, 0);
                SmileOrganization smileOrganization = smileOrganizationMapper.selectOne(orgQueryWrapper);
                if (smileOrganization != null && smileOrganization.getAgentId() == null) {
                    //没有总代  修改代理
                    smileOrganization.setUpdatedDate(LocalDateTime.now());
                    smileOrganization.setAgentId(smileUserCheckVo.getUid());
                    smileOrganizationMapper.updateById(smileOrganization);
                } else {
                    //有总代
                    return AjaxResult.warn("该分组已经存在总代身份");
                }
            }
            //更新redis
            updateRedisSetUser(smileUserCheckVo.getUid(), smileUserCheckVo.getOrgId(),null, smileUserCheckVo.getType(),smileUserCheckVo.getReason(),1);
            //修改user代理 id 开启代理
            smileUserMapper.updateUserByUid(smileUserCheckVo.getUid(), smileUserCheckVo.getOrgId(), smileUserCheckVo.getType());
        }
        return AjaxResult.success();
    }

    //往redis中塞入用户
    private void redisSetUser(SmileUser smileUser) {
        SmileUserVO smileUserVO = new SmileUserVO();
        BeanUtils.copyProperties(smileUser, smileUserVO);
        //存入redis中
        smileRedisUtils.set(SmileRedisConst.SMILE_USER + smileUser.getUid(), smileUserVO);
    }

    //更新redis中的用户数据
    private void updateRedisSetUser(String uid,Long orgId,Integer state,Integer type,String reason,Integer agent) {
        SmileUserVO smileUserVO = (SmileUserVO) smileRedisUtils.get(SmileRedisConst.SMILE_USER + uid);
        //组织id
        if (StringUtils.isNotNull(orgId)) smileUserVO.setOrgId(orgId);
        //状态  0：正常，1：黑名单
        if (StringUtils.isNotNull(state)) smileUserVO.setState(state);
        //代理 代理类型（0：未审核，1：总代，2：普代，3：未认证）
        if (StringUtils.isNotNull(type)) smileUserVO.setType(type);
        //审核失败原因
        if (StringUtils.isNotNull(reason)) smileUserVO.setErrorReason(reason);
        //代理开启标识  type==1  type==2
        if (StringUtils.isNotNull(agent)) smileUserVO.setAgent(agent);
        //存入redis中
        smileRedisUtils.set(SmileRedisConst.SMILE_USER + uid, smileUserVO);
    }
}