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.QRCodeUtil;
import com.liquidnet.client.admin.zhengzai.smile.utils.SmileRedisUtils;
import com.liquidnet.commons.lang.util.BeanUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.goblin.dto.vo.SmileAgentVo;
import com.liquidnet.service.goblin.dto.vo.SmileUserVO;
import com.liquidnet.service.kylin.entity.KylinPerformances;
import com.liquidnet.service.kylin.mapper.KylinPerformancesMapper;
import com.liquidnet.service.smile.entity.SmileAgent;
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.SmileAgentMapper;
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.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SmileUserServiceImpl extends ServiceImpl<SmileUserMapper, SmileUser> implements ISmileUserService {

    @Autowired
    SmileUserMapper smileUserMapper;

    @Autowired
    SmileRedisUtils smileRedisUtils;

    @Autowired
    SmileOrganizationMapper smileOrganizationMapper;

    @Autowired
    SmileSchoolMapper smileSchoolMapper;

    @Autowired
    SmileAgentMapper smileAgentMapper;

    @Autowired
    KylinPerformancesMapper kylinPerformancesMapper;

    /*@Value("${client:admin:h5Url}")
    private String h5Url;*/

    @Override
    public List<SmileUser> userList(SmileUserParam smileUserParam) {
        try {
            //查询通过审核通过的用户 type！=0、1   未删除用户
            Map<String, Object> map = BeanUtil.convertBeanToMap(smileUserParam);
            return smileUserMapper.selectUserList(map);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    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 SmileUserVo 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);
        //判断是否为特邀代理
        SmileUserVo smileUserVo;
        if (smileUser.getType() == 5) {
            smileUserVo = new SmileUserVo().copyInvited(smileUser);
            LambdaQueryWrapper<SmileAgent> agentLambdaQueryWrapper = new LambdaQueryWrapper<>();
            agentLambdaQueryWrapper.eq(SmileAgent::getTicketId, smileUserVo.getUid());
            agentLambdaQueryWrapper.eq(SmileAgent::getDelTag, 0);
            SmileAgent smileAgent = smileAgentMapper.selectOne(agentLambdaQueryWrapper);
            smileUserVo.setTicket(smileAgent.getTotalCarry().multiply(new BigDecimal("100")));
            //获取演出名
            KylinPerformances kylinPerformances = kylinPerformancesMapper.selectOne(Wrappers.lambdaQuery(KylinPerformances.getNew())
                    .eq(KylinPerformances::getPerformancesId, smileAgent.getPerformanceId())
                    .select(KylinPerformances::getTitle));
            smileUserVo.setTitle(kylinPerformances.getTitle());
            smileUserVo.setPerId(smileAgent.getPerformanceId());
            //获取特邀代理二维码url地址
            /*String url = h5Url + "/#/ticket/detail?id=" + smileUserVo.getPerId() + "&agentId=" + smileUserVo.getUid();
            QRCodeUtil.createCodeToFile(url,null,smileUserVo.getUid().count(".png"));*/
        } else {
            smileUserVo = new SmileUserVo().copy(smileUser);
        }
        return smileUserVo;
    }

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

    @Override
    public AjaxResult updateUserStateById(String uid, Integer state, String reason) {
        SmileUserVO smileUserVO = getSmileUserVO(uid);
        //修改黑名单
        smileUserMapper.updateUserStateById(uid, state, reason);
        updateRedisSetUser(smileUserVO, uid, state, reason);
        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查询用户信息
        SmileUserVO smileUserVO = getSmileUserVO(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 (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("参数错误");
    }

    @Override
    public List<SmileUser> listByState(SmileUserStateParam smileUserStateParam) {
        LambdaQueryWrapper<SmileUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(smileUserStateParam.getName())) {
            lambdaQueryWrapper.like(SmileUser::getName, smileUserStateParam.getName());
        }
        if (!StringUtils.isEmpty(smileUserStateParam.getPhone())) {
            lambdaQueryWrapper.eq(SmileUser::getPhone, smileUserStateParam.getPhone());
        }
        if (smileUserStateParam.getType() != null) {
            lambdaQueryWrapper.eq(SmileUser::getType, smileUserStateParam.getType());
        }
        lambdaQueryWrapper.eq(SmileUser::getState, 1);
        lambdaQueryWrapper.eq(SmileUser::getDelTag, 0);
        lambdaQueryWrapper.orderByDesc(SmileUser::getUpdatedDate);
        return smileUserMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public AjaxResult saveInvitedAgent(SmileUserInvitedVo smileUserInvitedVo) {
        //票提转换%-》0.00
        BigDecimal ticket = smileUserInvitedVo.getTicket().divide(BigDecimal.valueOf(100), 2, RoundingMode.DOWN);
        //生成uid
        String uid = IDGenerator.nextMilliId2();
        SmileUser smileUser = SmileUser.getNew();
        smileUser.setUid(uid);
        smileUser.setAgentId(uid);
        smileUser.setName(smileUserInvitedVo.getName());
        smileUser.setPhone(smileUserInvitedVo.getPhone());
        smileUser.setIntroduce(smileUserInvitedVo.getDescribe());
        smileUser.setDelTag(0);
        smileUser.setType(5);
        smileUser.setAgent(1);
        smileUser.setCreatedDate(LocalDateTime.now());
        smileUser.setUpdatedDate(LocalDateTime.now());
        int insert = smileUserMapper.insert(smileUser);
        //票提新增
        SmileAgent smileAgent = SmileAgent.getNew();
        smileAgent.setPerformanceId(smileUserInvitedVo.getPerformancesId());
        smileAgent.setTicketId(uid);
        smileAgent.setTotalCarry(ticket);
        smileAgent.setOrdCarry(BigDecimal.ZERO);
        smileAgent.setDelTag(0);
        smileAgentMapper.insert(smileAgent);
        if (insert > 0) {
            //新增缓存
            SmileUserVO smileUserVO = getSmileUserVO(uid, smileUser);
            smileRedisUtils.setSmileUserVo(uid, smileUserVO);
            SmileAgentVo smileAgentVo = SmileAgentVo.getNew();
            BeanUtils.copyProperties(smileAgent, smileAgentVo);
            smileRedisUtils.setAgent(smileAgent.getPerformanceId(), smileAgent.getTicketId(), smileAgentVo);
            return AjaxResult.success();
        }
        return AjaxResult.warn("添加失败，请联系管理员!");
    }

    @Override
    public List<SmileUserVo> getList(String phone) {
        List<SmileUserVo> smileUserVoList = new ArrayList<>();
        if (!StringUtils.isEmpty(phone) && phone.length() >= 6) {
            LambdaQueryWrapper<SmileUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(SmileUser::getPhone, phone);
            queryWrapper.eq(SmileUser::getDelTag, 0);
            queryWrapper.eq(SmileUser::getState, 0);
            queryWrapper.in(SmileUser::getType, 1, 2);
            List<SmileUser> smileUsers = smileUserMapper.selectList(queryWrapper);
            smileUserVoList = smileUsers.stream().map(smileUser -> {
                SmileUserVo smileUserVo = SmileUserVo.getNew();
                smileUserVo.setId(smileUser.getId());
                smileUserVo.setUid(smileUser.getUid());
                smileUserVo.setPhone(smileUser.getPhone());
                smileUserVo.setName(smileUser.getName());
                smileUserVo.setType(smileUser.getType());
                return smileUserVo;
            }).collect(Collectors.toList());
        }
        return smileUserVoList;
    }

    private SmileUserVO getSmileUserVO(String uid, SmileUser smileUser) {
        SmileUserVO smileUserVO = new SmileUserVO();
        smileUserVO.setUid(smileUser.getUid());
        smileUserVO.setPhone(smileUser.getPhone());
        smileUserVO.setDelTag(0);
        smileUserVO.setState(0);
        smileUserVO.setIntroduce(smileUser.getIntroduce());
        smileUserVO.setType(5);
        smileUserVO.setAgentId(uid);
        smileUserVO.setAgent(1);
        smileUserVO.setCreatedDate(smileUser.getCreatedDate());
        smileUserVO.setUpdatedDate(smileUser.getUpdatedDate());
        return smileUserVO;
    }

    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 getSmileUserVO(String uid) {
        //根据uid查询用户
        LambdaQueryWrapper<SmileUser> userQueryWrapper = Wrappers.lambdaQuery(SmileUser.class);
        userQueryWrapper.eq(SmileUser::getUid, uid);
        userQueryWrapper.eq(SmileUser::getDelTag, 0);
        SmileUser smileUser = smileUserMapper.selectOne(userQueryWrapper);
        SmileUserVO smileUserVO = new SmileUserVO();
        BeanUtils.copyProperties(smileUser, smileUserVO);
        return 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, String reason) {
        SmileUserVO userVO = smileRedisUtils.getSmileUserVO(uid);
        if (StringUtils.isNotNull(userVO)) {
            userVO.setState(state);
            userVO.setUpdatedDate(LocalDateTime.now());
            userVO.setErrorReason(reason != null && !reason.equals("") ? reason : userVO.getErrorReason());
        }
        //存入黑白名单状态
        smileRedisUtils.setSmileUserVO(uid, userVO);
    }

    //审核失败插入原因
    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());
        smileUserVO.setAuthStatus(0);
        smileRedisUtils.setSmileUserVO(uid, smileUserVO);
    }
}