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.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
    SmileRedisUtils smileRedisUtils;

    @Autowired
    SmileOrganizationMapper smileOrganizationMapper;

    @Autowired
    SmileSchoolMapper smileSchoolMapper;

    @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);
                smileUserVo.setSchoolName(getSchoolNameById(smileUser.getSchoolId()));

                return smileUserVo;
            }).collect(Collectors.toList());
            pageInfo = new PageInfo<SmileUserVo>(smileUserVos);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return pageInfo;
    }

    private String getSchoolNameById(String schoolId) {

        //从redis获取学校名称
        String schoolName = (String) smileRedisUtils.get(SmileRedisConst.SMILE_SCHOOL.concat(":").concat(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.set(SmileRedisConst.SMILE_SCHOOL.concat(":").concat(schoolId), smileSchool.getName());
        }
        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 (smileUserCheckVo.getType().equals(4)) {
            //申请被驳回
            smileUserMapper.updateUserCheckByUid(smileUserCheckVo.getUid(), smileUserCheckVo.getType(), smileUserCheckVo.getReason());
            updateRedisSetUser(smileUserVO, smileUserCheckVo.getUid(), smileUserCheckVo.getReason());
        } 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);
                        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 userCheck(SmileUserCheckVo smileUserCheckVo, SmileUserVO smileUserVO, SmileOrganization smileOrganization) {
        //更新redis
        updateRedisSetUser(smileUserVO, smileUserCheckVo.getUid(),
                smileUserCheckVo.getOrgId(),
                smileUserCheckVo.getType(),
                StringUtils.isEmpty(smileOrganization.getAgentId()) ? smileOrganization.getAgentId() : smileUserCheckVo.getUid());
        //修改user代理 id 开启代理
        smileUserMapper.updateUserByUid(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.set(SmileRedisConst.SMILE_USER + 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.set(SmileRedisConst.SMILE_USER + uid, smileUserVO);
    }

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

    }

    //审核失败插入原因
    private void updateRedisSetUser(SmileUserVO smileUserVO, String uid, String reason) {
        //审核失败原因
        if (StringUtils.isNotNull(reason)) smileUserVO.setErrorReason(reason);
        //存入redis中
        smileRedisUtils.set(SmileRedisConst.SMILE_USER + uid, smileUserVO);
    }
}