package com.miaxis.carousel.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miaxis.carousel.domain.HomePageDataInfo;
import com.miaxis.carousel.mapper.HomePageDataInfoMapper;
import com.miaxis.carousel.service.IHomePageDataInfoService;
import com.miaxis.carousel.vo.HomePageDataInfoVo;
import com.miaxis.common.constant.Constants;
import com.miaxis.common.core.domain.Response;
import com.miaxis.common.core.domain.entity.SysDictData;
import com.miaxis.common.exception.CustomException;
import com.miaxis.common.utils.bean.BeanUtils;
import com.miaxis.file.domain.FileInfo;
import com.miaxis.file.service.IFileInfoService;
import com.miaxis.system.mapper.SysDictDataMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 首页数据Service业务层处理
 *
 * @author miaxis
 * @date 2021-03-11
 */
@Service
@RequiredArgsConstructor
public class HomePageDataInfoServiceImpl extends ServiceImpl<HomePageDataInfoMapper, HomePageDataInfo> implements IHomePageDataInfoService {

    private final HomePageDataInfoMapper homePageDataInfoMapper;

    private final RedisTemplate redisTemplate;

    private final IFileInfoService fileInfoService;

    private final SysDictDataMapper dictDataMapper;

    /**
     * 查询首页数据列表
     *
     * @param homePageDataInfo 首页数据
     * @return 首页数据
     */
    @Override
    public List<HomePageDataInfoVo> selectHomePageDataInfoList(HomePageDataInfo homePageDataInfo){
        return homePageDataInfoMapper.selectHomePageDataInfoList(homePageDataInfo);
    }

    /**
     * 新增首页数据
     * @param homePageDataInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response saveHomePageDataInfo(HomePageDataInfo homePageDataInfo) {
        try{
            HomePageDataInfo chartInfo = new HomePageDataInfo();
            BeanUtils.copyProperties(homePageDataInfo,chartInfo);
            homePageDataInfoMapper.insert(chartInfo);
            //更新缓存
            updateHomePageDataRedis(chartInfo);
            return Response.success();
        }catch (Exception e){
            throw new CustomException("系统异常");
        }
    }

    /**
     * 修改首页数据
     * @param homePageDataInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response<Integer> updateHomePageDataInfoById(HomePageDataInfo homePageDataInfo) {
        try {
            homePageDataInfoMapper.updateById(homePageDataInfo);
            if ("1".equals(homePageDataInfo.getStatus())){
                //删除缓存
                redisTemplate.delete(Constants.HOME_PAGE_DATA_KEY+homePageDataInfo.getDataType()+":"+ homePageDataInfo.getId());
            }else{
                //更新缓存
                updateHomePageDataRedis(homePageDataInfo);
            }
            return Response.success();
        }catch (Exception e){
            throw new CustomException("系统异常");
        }
    }

    @Override
    public int updateHomePageDataByPictureName(HomePageDataInfoVo homePageDataInfoVo) {
       return  homePageDataInfoMapper.updateHomePageDataByPictureName(homePageDataInfoVo);
    }

    /**
     * 获取首页数据详细信息
     * @param id
     * @return
     */
    @Override
    public Response<HomePageDataInfoVo> getHomePageDataById(Long id) {
        return Response.success(homePageDataInfoMapper.getHomePageDataById(id));
    }


    /**
     * 删除首页数据(伪删除)
     * @param ids
     * @return
     */
    @Override
    @SneakyThrows
    @Transactional(rollbackFor = Exception.class)
    public Response removeCarouselByIds(Long[] ids) {

        //首页字典类型
        List<SysDictData> sysDictData = dictDataMapper.selectDictDataByType("wx_menu_type");
        //删除数据
        for (Long id : ids) {
            this.update(new UpdateWrapper<HomePageDataInfo>().set("status","1").eq("id",id));
        }
        //根据字典类型 更新缓存
        for (SysDictData dictData : sysDictData) {
            for (Long id : ids) {
                //判断类型 删除缓存
                if (redisTemplate.hasKey(Constants.HOME_PAGE_DATA_KEY  + dictData.getDictValue()+":"+id)){
                    redisTemplate.delete(Constants.HOME_PAGE_DATA_KEY  + dictData.getDictValue() + ":" + id);
                }
            }
        }
        return Response.success();
    }


    /**
     * applet
     * 获取首页数据列表
     * @return
     */
    @Override
    public Response getHomePageDataList() {
        Map<String, List<HomePageDataInfoVo>> map = new HashMap<>();

        //首页字典类型
        List<SysDictData> sysDictData = dictDataMapper.selectDictDataByType("wx_menu_type");
        for (SysDictData dictData : sysDictData) {
            List<HomePageDataInfoVo> newInfos = new ArrayList<>();
            Set carouselChartkeys = redisTemplate.keys(Constants.HOME_PAGE_DATA_KEY + dictData.getDictValue()+":*");
            if (!carouselChartkeys.isEmpty()){
                for (Object key : carouselChartkeys) {
                    String jsonStr = (String) redisTemplate.opsForValue().get(key);
                    HomePageDataInfoVo homePageDataInfoVo = JSONObject.parseObject(jsonStr).toJavaObject(HomePageDataInfoVo.class);
                    newInfos.add(homePageDataInfoVo);
                }
            }else {
                //数据库获取(此处可不做查询！)
                HomePageDataInfo homePageDataInfo = new HomePageDataInfo();
                homePageDataInfo.setDataType(dictData.getDictValue());
                homePageDataInfo.setStatus("0");//启用状态
                newInfos = homePageDataInfoMapper.selectHomePageDataInfoList(homePageDataInfo);
            }
            //排序
            List<HomePageDataInfoVo> infoVos = newInfos.stream()
                    .sorted(Comparator.comparing(HomePageDataInfoVo::getWeight).reversed())
                    .collect(Collectors.toList());

            map.put(dictData.getDictValue(),infoVos);
        }

        return Response.success(map);
    }


    /**
     * 查询首页数据列表--字典参数
     * @param dictValues
     * @return
     */
    @Override
    public Response dictValueHomePageDataList(String[] dictValues) {
        Map<String, List<HomePageDataInfoVo>> map = new HashMap<>();

        for (String dictData : dictValues) {
            List<HomePageDataInfoVo> newInfos = new ArrayList<>();
            Set carouselChartkeys = redisTemplate.keys(Constants.HOME_PAGE_DATA_KEY + dictData+":*");
            if (!carouselChartkeys.isEmpty()){
                for (Object key : carouselChartkeys) {
                    String jsonStr = (String) redisTemplate.opsForValue().get(key);
                    HomePageDataInfoVo homePageDataInfoVo = JSONObject.parseObject(jsonStr).toJavaObject(HomePageDataInfoVo.class);
                    newInfos.add(homePageDataInfoVo);
                }
            }else {
                //数据库获取(此处可不做查询！)
                HomePageDataInfo homePageDataInfo = new HomePageDataInfo();
                homePageDataInfo.setDataType(dictData);
                homePageDataInfo.setStatus("0");//启用状态
                newInfos = homePageDataInfoMapper.selectHomePageDataInfoList(homePageDataInfo);
            }
            //排序
            List<HomePageDataInfoVo> infoVos = newInfos.stream()
                    .sorted(Comparator.comparing(HomePageDataInfoVo::getWeight).reversed())
                    .collect(Collectors.toList());

            map.put(dictData,infoVos);
        }

        return Response.success(map);
    }


    /**
     * 同步数据
     * @return
     */
    @Override
    public Response synchroData() {
        //查询全部启用数据
        List<HomePageDataInfo> dataInfos = homePageDataInfoMapper.selectByMap(new HashMap<String, Object>() {{
            put("status", 0);
        }});
        //删除全部缓存
        redisTemplate.delete( redisTemplate.keys(Constants.HOME_PAGE_DATA_KEY +"*"));
        //同步缓存
        for (HomePageDataInfo dataInfo : dataInfos) {
            updateHomePageDataRedis(dataInfo);
        }
        return Response.success();
    }


    /**
     * 更新首页数据缓存
     * @param homePageDataInfo
     */
    private void updateHomePageDataRedis(HomePageDataInfo homePageDataInfo){
        //更新缓存
        FileInfo fileInfo = fileInfoService.getById(homePageDataInfo.getFileId());
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(homePageDataInfo));
        jsonObject.put("fileUrl",fileInfo.getFileUrl());

        //首页字典类型
        List<SysDictData> sysDictData = dictDataMapper.selectDictDataByType("wx_menu_type");
        //根据字典类型 删除缓存
        for (SysDictData dictData : sysDictData) {
            if (redisTemplate.hasKey(Constants.HOME_PAGE_DATA_KEY  + dictData.getDictValue()+":"+homePageDataInfo.getId())){
                redisTemplate.delete(Constants.HOME_PAGE_DATA_KEY  + dictData.getDictValue() + ":" + homePageDataInfo.getId());
            }
        }

        //同时更新缓存(根据type拼接)
        redisTemplate.opsForValue().set(Constants.HOME_PAGE_DATA_KEY +homePageDataInfo.getDataType()+":"+ homePageDataInfo.getId(),JSONObject.toJSONString(jsonObject));
    }


}
