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.zhengzai.smile.dto.SmileSchoolParam;
import com.liquidnet.client.admin.zhengzai.smile.service.ISmileSchoolService;
import com.liquidnet.client.admin.zhengzai.smile.utils.SmileRedisUtils;
import com.liquidnet.commons.lang.util.BeanUtil;
import com.liquidnet.service.goblin.dto.vo.SmileSchoolVo;
import com.liquidnet.service.goblin.dto.vo.SmileUserVO;
import com.liquidnet.service.smile.entity.SmileSchool;
import com.liquidnet.service.smile.entity.SmileUser;
import com.liquidnet.service.smile.mapper.SmileSchoolMapper;
import com.liquidnet.service.smile.mapper.SmileUserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2022-03-14
 */
@Slf4j
@Service
public class SmileSchoolServiceImpl extends ServiceImpl<SmileSchoolMapper, SmileSchool> implements ISmileSchoolService {

    @Autowired
    SmileSchoolMapper smileSchoolMapper;

    @Autowired
    SmileUserMapper smileUserMapper;

    @Autowired
    SmileRedisUtils smileRedisUtils;

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public PageInfo<SmileSchool> schoolList(SmileSchoolParam smileSchoolParam) {
        PageInfo<SmileSchool> pageInfo;
        try {
            Map<String, Object> map = BeanUtil.convertBeanToMap(smileSchoolParam);
            List<SmileSchool> smileSchools = smileSchoolMapper.selectSchoolList(map);
            pageInfo = new PageInfo<>(smileSchools);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return pageInfo;
    }

    @Override
    public SmileSchool getSchoolById(Long id) {
        return smileSchoolMapper.selectById(id);
    }

    @Override
    public AjaxResult create(SmileSchool smileSchool) {
        log.debug("smileSchool:{}", smileSchool);
        LambdaQueryWrapper<SmileSchool> queryWrapper = Wrappers.lambdaQuery(SmileSchool.class);
        queryWrapper.eq(SmileSchool::getName, smileSchool.getName());
        queryWrapper.eq(SmileSchool::getDelTag, 0);
        if (smileSchoolMapper.selectOne(queryWrapper) == null) {
            smileSchoolMapper.insert(smileSchool);
            //保存学校
            smileRedisUtils.setSchool(String.valueOf(smileSchool.getId()), smileSchool.getName());
            SmileSchoolVo smileSchoolVo = new SmileSchoolVo().copy(smileSchool);
            mongoTemplate.insert(smileSchoolVo, SmileSchoolVo.class.getSimpleName());
            //判断是否需要新增redis
            List<SmileSchoolVo> schoolAll = smileRedisUtils.getSchoolAll();
            if (schoolAll != null && schoolAll.size() < 20) {
                updateSchoolRedis();
            }
            return AjaxResult.success();
        }
        return AjaxResult.warn("学校已存在");
    }

    @Override
    public AjaxResult updateSchoolById(SmileSchool smileSchool) {
        LambdaQueryWrapper<SmileSchool> queryWrapper = Wrappers.lambdaQuery(SmileSchool.class);
        queryWrapper.eq(SmileSchool::getId, smileSchool.getId());
        queryWrapper.eq(SmileSchool::getDelTag, 0);
        if (smileSchoolMapper.update(smileSchool, queryWrapper) > 0) {
            //更新User表  根据学校id修改用户学校名称
            LambdaQueryWrapper<SmileUser> smileUserLambdaQueryWrapper = Wrappers.lambdaQuery(SmileUser.class);
            smileUserLambdaQueryWrapper.select(SmileUser::getUid);
            smileUserLambdaQueryWrapper.eq(SmileUser::getSchoolId,smileSchool.getId());
            List<SmileUser> smileUsers = smileUserMapper.selectList(smileUserLambdaQueryWrapper);
            smileUsers.forEach(smileUser -> {
                SmileUserVO smileUserVO = smileRedisUtils.getSmileUserVO(smileUser.getUid());
                smileUserVO.setSchoolName(smileSchool.getName());
                smileRedisUtils.setSmileUserVO(smileUser.getUid(),smileUserVO);
            });

            smileUserMapper.updateUserSchoolBySchoolId(smileSchool.getId().toString(), smileSchool.getName());
            smileRedisUtils.setSchool(String.valueOf(smileSchool.getId()), smileSchool.getName());
            //修改数据
            SmileSchoolVo smileSchoolVo = new SmileSchoolVo().copy(smileSchool);
            mongoTemplate.save(smileSchoolVo, SmileSchoolVo.class.getSimpleName());
            //更新redis
            updateSchoolRedis();
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @Override
    public AjaxResult del(Long id) {
        //查询是否有用户使用过该学校
        LambdaQueryWrapper<SmileUser> queryWrapper = Wrappers.lambdaQuery(SmileUser.class);
        queryWrapper.eq(SmileUser::getSchoolId, id);
        queryWrapper.eq(SmileUser::getDelTag, 0);
        List<SmileUser> smileUsers = smileUserMapper.selectList(queryWrapper);
        if (smileUsers.size() > 0) {
            return AjaxResult.warn("该学校已被使用，不可删除");
        }
        //学校没有被使用  可以删除
        smileSchoolMapper.updateDel(id);
        //mongodb删除
        Query query = new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query, SmileSchoolVo.class, SmileSchoolVo.class.getSimpleName());
        smileRedisUtils.delSchool(String.valueOf(id));
        updateSchoolRedis();
        return AjaxResult.success();
    }


    private void updateSchoolRedis() {
        List<SmileSchoolVo> smileSchoolVos = new ArrayList<>();
        smileSchoolMapper.selectListLimit().forEach(smileSchool -> {
            SmileSchoolVo smileSchoolVo = new SmileSchoolVo().copy(smileSchool);
            smileSchoolVos.add(smileSchoolVo);
        });
        smileRedisUtils.setSchoolAll(smileSchoolVos);
    }

    public void saveSmileSchoolMongodb() {
        LambdaQueryWrapper<SmileSchool> queryWrapper = Wrappers.lambdaQuery(SmileSchool.class);
        queryWrapper.eq(SmileSchool::getDelTag, 0);
        List<SmileSchool> smileSchools = smileSchoolMapper.selectList(queryWrapper);
        smileSchools.forEach(smileSchool -> {
            SmileSchoolVo smileSchoolVo = new SmileSchoolVo().copy(smileSchool);
            try {
                mongoTemplate.insert(smileSchoolVo, SmileSchoolVo.class.getSimpleName());
            } catch (Exception e) {
                log.debug("数据存在：{}", smileSchoolVo);
            }
        });
    }

    /**
     * 跟新redis中学校SmileSchoolVo类：dev_kids0609初始化
     */
    private void updateRedisSchoolAll() {
        Query query = new Query();
        long count = mongoTemplate.count(query, SmileSchoolVo.class.getSimpleName());
        if (count == 0) {
            //删除旧redisSchoolAll缓存
            smileRedisUtils.delSchoolAll();
            //跟新缓存
            updateSchoolRedis();
            //mongodb初始化就数据
            saveSmileSchoolMongodb();
        }
    }


}
