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.core.page.TableDataInfo;
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.common.cache.redis.util.RedisDataSourceUtil;
import com.liquidnet.commons.lang.util.BeanUtil;
import com.liquidnet.service.goblin.dto.vo.SmileUserVO;
import com.liquidnet.service.smile.entity.SmileOrganization;
import com.liquidnet.service.smile.entity.SmileSchool;
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.SmileSchoolMapper;
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
    RedisDataSourceUtil redisDataSourceUtil;

    @Autowired
    SmileRedisUtils smileRedisUtils;

    @Autowired
    SmileOrganizationMapper smileOrganizationMapper;

    @Autowired
    SmileSchoolMapper smileSchoolMapper;

    @Override
    public TableDataInfo userList(SmileUserParam smileUserParam) {
        PageInfo<SmileUser> pageInfo;
        TableDataInfo rspData = new TableDataInfo();
        try {
            //查询通过审核通过的用户 type！=0、1   未删除用户
            Map<String, Object> map = BeanUtil.convertBeanToMap(smileUserParam);
            List<SmileUser> smileUsers = smileUserMapper.selectUserList(map);
            pageInfo = new PageInfo<SmileUser>(smileUsers);
            List<SmileUserVo> smileUserVos = smileUsers.stream().map(smileUser -> {
                //获取学校名
                SmileUserVo smileUserVo = new SmileUserVo();
                BeanUtils.copyProperties(smileUser, smileUserVo);
                smileUserVo.setSchoolName(getSchoolNameById(smileUser.getSchoolId()));
                return smileUserVo;
            }).collect(Collectors.toList());

            rspData.setCode(0);
            rspData.setRows(smileUserVos);
            rspData.setTotal(pageInfo.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return rspData;
    }

    private String getSchoolNameById(String schoolId) {

        //从redis获取学校名称
        String schoolName = smileRedisUtils.getSchoolNameById(schoolId);
        if (StringUtils.isEmpty(schoolName)) {
            //查询数据库
            LambdaQueryWrapper<SmileSchool> queryWrapper = Wrappers.lambdaQuery(SmileSchool.class);
            queryWrapper.eq(SmileSchool::getId, schoolId);
            SmileSchool smileSchool = smileSchoolMapper.selectOne(queryWrapper);
            schoolName = smileSchool.getName();
            //缓存redis中
            smileRedisUtils.setSchool(schoolId, schoolName);
        }
        return schoolName;
    }

    @Override
    public SmileUser getUserById(String uid) {
        log.debug("查询用户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.debug("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) {
        SmileUserVO smileUserVO = getSmileUserVOFromRedis(uid);
        //修改黑名单
        smileUserMapper.updateUserStateById(uid, state);
        updateRedisSetUser(smileUserVO, uid, state);
        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) {
        //根据uid查询redis中的用户缓存信息
        SmileUserVO smileUserVO = getSmileUserVOFromRedis(smileUserCheckVo.getUid());
        if (!smileUserVO.getType().equals(0)) {
            return AjaxResult.warn("已审核");
        }
        //判断是否通过
        if (smileUserCheckVo.getType().equals(4)) {
            //申请被驳回
            smileUserMapper.updateUserCheckByUid(smileUserCheckVo.getUid(), smileUserCheckVo.getType(), smileUserCheckVo.getReason());
            updateRedisSetUser(smileUserVO, smileUserCheckVo.getUid(), smileUserCheckVo.getReason());
            return AjaxResult.success();
        } else {
            //查询代理信息  查询组织是否有总代   没有则设置  有则返回异常
            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 && !StringUtils.isEmpty(smileUserCheckVo.getUid())) {
                if (smileUserCheckVo.getType().equals(1)) {
                    //总代
                    if (smileOrganization != null && StringUtils.isEmpty(smileOrganization.getAgentId())) {
                        //没有总代  修改代理
                        smileOrganization.setUpdatedDate(LocalDateTime.now());
                        smileOrganization.setAgentId(smileUserCheckVo.getUid());
                        smileOrganizationMapper.updateById(smileOrganization);
                        //查询该代理下是否有普代
                        updateUserVoRedis(smileUserCheckVo, smileOrganization);
                        //缓存redis  和修改用户状态
                        userCheck(smileUserCheckVo, smileUserVO, smileOrganization);
                        return AjaxResult.success();
                    } else {
                        //有总代
                        return AjaxResult.warn("该分组已经存在总代身份");
                    }
                }
                if (smileUserCheckVo.getType().equals(2)) {
                    //普代添加
                    userCheck(smileUserCheckVo, smileUserVO, smileOrganization);
                    return AjaxResult.success();
                }
            }
        }
        return AjaxResult.warn("参数错误");
    }

    private void updateUserVoRedis(SmileUserCheckVo smileUserCheckVo, SmileOrganization smileOrganization) {
        LambdaQueryWrapper<SmileUser> smileUserQueryWrapper = Wrappers.lambdaQuery(SmileUser.class);
        smileUserQueryWrapper.eq(SmileUser::getOrgId, smileOrganization.getId());
        smileUserQueryWrapper.ne(SmileUser::getUid, smileUserCheckVo.getUid());
        List<SmileUser> smileUsers = smileUserMapper.selectList(smileUserQueryWrapper);
        if (smileUsers != null && smileUsers.size() > 0) {
            //更新普代redis缓存
            smileUsers.forEach(smileUser -> {
                SmileUserVO smileUserVO = smileRedisUtils.getSmileUserVO(smileUser.getUid());
                smileUserVO.setAgentId(smileOrganization.getAgentId());
                smileRedisUtils.setSmileUserVO(smileUser.getUid(), smileUserVO);
            });
        }
    }

    private void userCheck(SmileUserCheckVo smileUserCheckVo, SmileUserVO smileUserVO, SmileOrganization smileOrganization) {
        //修改user代理 id 开启代理
        smileUserMapper.updateUserByUid(smileUserCheckVo.getUid(), smileUserCheckVo.getOrgId(), smileUserCheckVo.getType(), smileOrganization.getAgentId());
        //更新redis
        updateRedisSetUser(smileUserVO, smileUserCheckVo.getUid(),
                smileUserCheckVo.getOrgId(),
                smileUserCheckVo.getType(),
                smileOrganization.getAgentId());
    }

    private SmileUserVO getSmileUserVOFromRedis(String uid) {
        //根据uid查询用户
        LambdaQueryWrapper<SmileUser> userQueryWrapper = Wrappers.lambdaQuery(SmileUser.class);
        userQueryWrapper.eq(SmileUser::getUid, uid);
        SmileUser smileUser = smileUserMapper.selectOne(userQueryWrapper);
        SmileUserVO smileUserVO = new SmileUserVO();
        BeanUtils.copyProperties(smileUser, smileUserVO);
        return smileUserVO;
    }

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

    //更新redis中的用户数据
    private void updateRedisSetUser(SmileUserVO smileUserVO, String uid, Long orgId, Integer type, String agentId) {
        //组织id
        if (StringUtils.isNotNull(orgId)) smileUserVO.setOrgId(orgId);
        //代理 代理类型（0：未审核，1：总代，2：普代，3：未认证）
        if (StringUtils.isNotNull(type)) smileUserVO.setType(type);
        //代理开启标识
        smileUserVO.setAgent(1);
        //清除审核
        smileUserVO.setErrorReason(null);
        //存入总代理id
        smileUserVO.setAgentId(agentId);
        //存入redis中
        smileRedisUtils.setSmileUserVO(uid, smileUserVO);
    }

    //跟新redis中的用户  0：正常，1：黑名单
    private void updateRedisSetUser(SmileUserVO smileUserVO, String uid, Integer state) {
        SmileUserVO smileUserVO1 = smileRedisUtils.getSmileUserVO(uid);
        if (StringUtils.isNotNull(smileUserVO1)) {
            smileUserVO1.setState(state);
        } else {
            //状态  0：正常，1：黑名单
            if (StringUtils.isNotNull(state)) smileUserVO.setState(state);
        }
        //存入黑白名单状态
        smileRedisUtils.setSmileUserVO(uid, smileUserVO1);
    }

    //审核失败插入原因
    private void updateRedisSetUser(SmileUserVO smileUserVO, String uid, String reason) {
        //审核失败原因
        if (StringUtils.isNotNull(reason)) smileUserVO.setErrorReason(reason);
        smileUserVO.setType(4);
        SmileUserVO redisData = smileRedisUtils.getSmileUserVO(uid);
        //存入redis中
        smileUserVO.setAuthStatus(redisData.getAuthStatus());
        smileRedisUtils.setSmileUserVO(uid, smileUserVO);
    }
}