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.common.utils.bean.BeanUtils;
import com.liquidnet.client.admin.zhengzai.smile.dto.SmileOrgAndUserVo;
import com.liquidnet.client.admin.zhengzai.smile.dto.SmileOrganizationParam;
import com.liquidnet.client.admin.zhengzai.smile.dto.SmileOrganizationVo;
import com.liquidnet.client.admin.zhengzai.smile.dto.SmileUserVoOrg;
import com.liquidnet.client.admin.zhengzai.smile.service.ISmileOrganizationService;
import com.liquidnet.client.admin.zhengzai.smile.utils.SmileRedisUtils;
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.SmileUser;
import com.liquidnet.service.smile.mapper.SmileOrganizationMapper;
import com.liquidnet.service.smile.mapper.SmileUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2022-03-14
 */
@Slf4j
@Service
public class SmileOrganizationServiceImpl extends ServiceImpl<SmileOrganizationMapper, SmileOrganization> implements ISmileOrganizationService {

    @Autowired
    SmileOrganizationMapper smileOrganizationMapper;

    @Autowired
    SmileUserMapper smileUserMapper;

    @Autowired
    SmileRedisUtils smileRedisUtils;

    @Override
    public TableDataInfo organizationList(SmileOrganizationParam smileOrganizationParam) {
        PageInfo<SmileOrganization> pageInfo;
        TableDataInfo rspData = new TableDataInfo();
        try {
            Map<String, Object> map = BeanUtil.convertBeanToMap(smileOrganizationParam);
            List<SmileOrganization> smileOrganizations = smileOrganizationMapper.selectOrganizationList(map);
            pageInfo = new PageInfo<>(smileOrganizations);
            List<SmileOrganizationVo> smileOrganizationVos = smileOrganizations.stream().map(smileOrganization -> {
                SmileOrganizationVo smileOrganizationVo = new SmileOrganizationVo();
                BeanUtils.copyProperties(smileOrganization, smileOrganizationVo);
                log.info("organizationList orgId:{}", smileOrganization.getId());
                //根据代理id  用户uid查询用户名称
                if (StringUtils.isNotEmpty(smileOrganization.getAgentId())) {
                    SmileUserVO smileUserVO = smileRedisUtils.getSmileUserVO(smileOrganization.getAgentId());
                    if (smileUserVO != null) {
                        smileOrganizationVo.setAgentName(smileUserVO.getName());
                    }
                }
                //关联查询人数
                smileOrganizationVo.setProper(smileUserMapper.strip(smileOrganization.getId()));
                return smileOrganizationVo;
            }).collect(Collectors.toList());
            rspData.setCode(0);
            rspData.setRows(smileOrganizationVos);
            rspData.setTotal(pageInfo.getTotal());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return rspData;
    }

    @Override
    public AjaxResult create(SmileOrganizationVo smileOrganizationVo) {
        log.info("smileOrganizationVo:{}", smileOrganizationVo);
        LambdaQueryWrapper<SmileOrganization> queryWrapper = Wrappers.lambdaQuery(SmileOrganization.class);
        queryWrapper.eq(SmileOrganization::getName, smileOrganizationVo.getName());
        queryWrapper.eq(SmileOrganization::getDelTag, 0);
        if (smileOrganizationMapper.selectOne(queryWrapper) == null) {
            SmileOrganization smileOrganization = new SmileOrganization();
            BeanUtils.copyProperties(smileOrganizationVo, smileOrganization);
            smileOrganization.setCreatedDate(LocalDateTime.now());
            smileOrganization.setUpdatedDate(LocalDateTime.now());
            smileOrganization.setDelTag(0);
            smileOrganizationMapper.insert(smileOrganization);
            return AjaxResult.success();
        }
        return AjaxResult.warn("组织已添加");
    }

    @Override
    public AjaxResult update(SmileOrganization smileOrganization) {
        smileOrganization.setUpdatedDate(LocalDateTime.now());
        //查询组织信息
        LambdaQueryWrapper<SmileOrganization> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SmileOrganization::getId, smileOrganization.getId());
        lambdaQueryWrapper.eq(SmileOrganization::getDelTag, 0);
        SmileOrganization oleOrganization = smileOrganizationMapper.selectOne(lambdaQueryWrapper);
        LambdaQueryWrapper<SmileOrganization> organizationQueryWrapper = new LambdaQueryWrapper<>();
        organizationQueryWrapper.ne(SmileOrganization::getId, smileOrganization.getId());
        organizationQueryWrapper.eq(SmileOrganization::getName, smileOrganization.getName());
        organizationQueryWrapper.eq(SmileOrganization::getDelTag, 0);
        List<SmileOrganization> smileOrganizations = smileOrganizationMapper.selectList(organizationQueryWrapper);
        if (smileOrganizations != null && smileOrganizations.size() > 0) {
            return AjaxResult.warn("组织名重复！");
        }
        //判断该uid是否为总代
        LambdaQueryWrapper<SmileUser> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(SmileUser::getUid, smileOrganization.getAgentId());
        userLambdaQueryWrapper.eq(SmileUser::getDelTag, 0);
        userLambdaQueryWrapper.eq(SmileUser::getState, 0);
        SmileUser user = smileUserMapper.selectOne(userLambdaQueryWrapper);
        if (user != null && user.getType() == 1) {
            return AjaxResult.warn("该成员为其他组织总代！");
        } else if (user == null) {
            return AjaxResult.warn("用户不存在！");
        }
        //修改总代与原总代不同
        if (!StringUtils.isEmpty(smileOrganization.getAgentId()) && !StringUtils.isEmpty(oleOrganization.getAgentId()) && !oleOrganization.getAgentId().equals(smileOrganization.getAgentId())) {
            //修改user信息
            user.setType(1);
            user.setOrgId(smileOrganization.getId());
            user.setAgentId(smileOrganization.getAgentId());
            smileUserMapper.updateById(user);
            //查询所有原总代的普代成员
            LambdaQueryWrapper<SmileUser> smileUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
            smileUserLambdaQueryWrapper.eq(SmileUser::getAgentId, oleOrganization.getAgentId());
            smileUserLambdaQueryWrapper.eq(SmileUser::getDelTag, 0);
            smileUserLambdaQueryWrapper.in(SmileUser::getType, 1, 2);
            List<SmileUser> oldSmileUsers = smileUserMapper.selectList(smileUserLambdaQueryWrapper);
            log.info("原总代id:{},修改总代id:{},受影响普代{}个", oleOrganization.getAgentId(), smileOrganization.getAgentId(), oldSmileUsers.size());
            oldSmileUsers.forEach(smileUser -> {
                //修改缓存用户redis总代信息
                SmileUserVO smileUserVO = smileRedisUtils.getSmileUserVO(smileUser.getUid());
                smileUserVO.setType(smileUser.getUid().equals(smileOrganization.getAgentId()) ? 1 : 2);
                smileUserVO.setAgentId(smileOrganization.getAgentId());
                //修改redis缓存
                smileRedisUtils.setSmileUserVO(smileUser.getUid(), smileUserVO);

                smileUser.setType(smileUserVO.getType());
                smileUser.setAgentId(smileOrganization.getAgentId());
                //修改smile_user中普代总代信息
                smileUserMapper.updateById(smileUser);
            });
            oleOrganization.setName(smileOrganization.getName());
            oleOrganization.setAgentId(smileOrganization.getAgentId());
            smileOrganizationMapper.updateById(oleOrganization);
            return AjaxResult.success();
        }
        //只改名  或者原组织没有总代id
        oleOrganization.setName(smileOrganization.getName());
        if (!StringUtils.isEmpty(smileOrganization.getAgentId())) {
            //修改总代
            oleOrganization.setAgentId(smileOrganization.getAgentId());
            //查询uid
            LambdaQueryWrapper<SmileUser> smileUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
            smileUserLambdaQueryWrapper.eq(SmileUser::getUid, smileOrganization.getAgentId());
            smileUserLambdaQueryWrapper.eq(SmileUser::getDelTag, 0);
            SmileUser smileUser = smileUserMapper.selectOne(smileUserLambdaQueryWrapper);
            smileUser.setType(1);
            smileUser.setOrgId(smileOrganization.getId());
            smileUserMapper.updateById(smileUser);
        }
        smileOrganizationMapper.updateById(oleOrganization);
        return AjaxResult.success();
    }

    @Override
    public SmileOrgAndUserVo getOrgById(Long id) {
        SmileOrgAndUserVo smileOrgAndUserVo = new SmileOrgAndUserVo();
        //根据组id查询代理信息
        LambdaQueryWrapper<SmileOrganization> orgQueryWrapper = Wrappers.lambdaQuery(SmileOrganization.class);
        orgQueryWrapper.eq(SmileOrganization::getId, id);
        orgQueryWrapper.eq(SmileOrganization::getDelTag, 0);
        SmileOrganization smileOrganization = smileOrganizationMapper.selectOne(orgQueryWrapper);
        if (smileOrganization != null) {
            BeanUtils.copyProperties(smileOrganization, smileOrgAndUserVo);
            LambdaQueryWrapper<SmileUser> userQueryWrapper = Wrappers.lambdaQuery(SmileUser.class);
            userQueryWrapper.eq(SmileUser::getOrgId, id);
            userQueryWrapper.eq(SmileUser::getDelTag, 0);
            List<SmileUser> smileUsers = smileUserMapper.selectList(userQueryWrapper);
            List<SmileUserVoOrg> smileUserVoOrgList = new ArrayList<>();
            smileUsers.forEach(smileUser -> {
                SmileUserVoOrg smileUserVoOrg = new SmileUserVoOrg();
                BeanUtils.copyProperties(smileUser, smileUserVoOrg);
                //关联组织id筛选
                if (smileOrganization.getAgentId() != null && smileOrganization.getAgentId().equals(smileUser.getUid())) {
                    smileOrgAndUserVo.setSmileUserVoOrgListTotal(smileUserVoOrg);
                } else {
                    smileUserVoOrgList.add(smileUserVoOrg);
                }
            });
            smileOrgAndUserVo.setSmileUserVoOrgListOrdinary(smileUserVoOrgList);
            return smileOrgAndUserVo;
        }
        return null;
    }


}
