package com.liquidnet.service.sweet.utils;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinPerformanceVo;
import com.liquidnet.service.sweet.constant.SweetConstant;
import com.liquidnet.service.sweet.dto.SweetManualAppletDto;
import com.liquidnet.service.sweet.dto.SweetManualArtistList2Dto;
import com.liquidnet.service.sweet.dto.SweetManualArtistListDto;
import com.liquidnet.service.sweet.dto.SweetManualArtistStageListDto;
import com.liquidnet.service.sweet.entity.*;
import com.liquidnet.service.sweet.mapper.*;
import com.liquidnet.service.sweet.vo.SweetAnswerVo;
import com.liquidnet.service.sweet.vo.SweetArtistsRelationVo;
import com.liquidnet.service.sweet.vo.SweetRemindVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.*;

@Component
public class RedisDataUtils {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private QueueUtils queueUtils;

    @Autowired
    private SweetManualMapper sweetManualMapper;
    @Autowired
    private SweetManualArtistsMapper sweetManualArtistsMapper;
    @Autowired
    private SweetRichtextMapper sweetRichtextMapper;
    @Autowired
    private SweetManualSortMapper sweetManualSortMapper;
    @Autowired
    private SweetManualNotifyMapper sweetManualNotifyMapper;
    @Autowired
    private SweetManualShopMapper sweetManualShopMapper;
    @Autowired
    private SweetArtistsMapper sweetArtistsMapper;


    public List<SweetManualAppletDto> setPushList() {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_MANUAL_PUSH_LIST;
        List<SweetManualAppletDto> data = sweetManualMapper.getManualAppletDto();
        for (SweetManualAppletDto item : data) {
            if(!item.getIsMember().equals(1)){
                item.setTimeSell(DateUtil.format(DateUtil.addMin(DateUtil.parse(item.getTimeSell(),"yyyy-MM-dd HH:mm:ss"),item.getPayCountdownMinute()),DateUtil.Formatter.yyyyMMddHHmmss));
            }
            item.setFieldName((String) redisUtil.hget("kylin:fields:id" + ":" + item.getFieldId(), "name"));
            item.setCityName((String) redisUtil.hget("kylin:fields:id" + ":" + item.getFieldId(), "city_name"));
            item.setLatitude((String) redisUtil.hget("kylin:fields:id" + ":" + item.getFieldId(), "latitude"));
            item.setLongitude((String) redisUtil.hget("kylin:fields:id" + ":" + item.getFieldId(), "longitude"));
        }
        redisUtil.set(redisKey, data);
        return data;
    }

    //获取电子手册列表 (城市)
    public List<SweetManualAppletDto> getPushList() {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_MANUAL_PUSH_LIST;
        Object obj = redisUtil.get(redisKey);
        if (obj == null) {
            return setPushList();
        } else {
            return (List<SweetManualAppletDto>) obj;
        }
    }

    //获取电子手册演出详情
    public SweetManualAppletDto getAppletPerformance(String manualId) {
        List<SweetManualAppletDto> data = getPushList();
        SweetManualAppletDto returnData = SweetManualAppletDto.getNew();
        for (SweetManualAppletDto item : data) {
            if (item.getManualId().equalsIgnoreCase(manualId)) {
                returnData = item;
                break;
            }
        }
        return returnData;
    }

    public SweetManualArtistList2Dto setTimeList(String manualId, String content) {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_MANUAL_TIME_LIST.concat(manualId);
        HashMap<String, Object> map = CollectionUtil.mapStringObject();
        map.put("manualId", manualId);
        List<SweetManualArtistListDto> data = sweetManualArtistsMapper.getManualList(map);

        //获取时间
        SweetManualAppletDto sweetManualAppletDto = getAppletPerformance(manualId);
        Date dateEnd = DateUtil.parse(sweetManualAppletDto.getTimeEnd(), DateUtil.DATE_SMALL_STR);
        Date dateStart = DateUtil.parse(sweetManualAppletDto.getTimeStart(), DateUtil.DATE_SMALL_STR);
        int intervalDay = (int) DateUtil.intervalDays(dateStart, dateEnd);
        ArrayList<String> list = CollectionUtil.arrayListString();
        list.add(DateUtil.format(dateStart, DateUtil.Formatter.yyyy_MM_dd));
        for (int i = 0; i < intervalDay; i++) {
            list.add(DateUtil.format(DateUtil.addDay(dateStart, i + 1), DateUtil.Formatter.yyyy_MM_dd));
        }

        //获取舞台
        List<SweetManualArtistStageListDto> stageData = sweetManualArtistsMapper.getStageNameList(map);

        SweetManualArtistList2Dto returnData = SweetManualArtistList2Dto.getNew();
        returnData.setDate(list);
        returnData.setData(data);
        returnData.setStage(stageData);
        redisUtil.set(redisKey, returnData);
        return returnData;
    }

    //获取时间表
    public SweetManualArtistList2Dto getTimeList(String manualId) {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_MANUAL_TIME_LIST.concat(manualId);
        Object obj = redisUtil.get(redisKey);
        if (obj == null) {
            return setTimeList(manualId, null);
        } else {
            return (SweetManualArtistList2Dto) obj;
        }
    }

    public SweetRichtext setRichTextRedisData(String manualId, String type, SweetRichtext content) {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_MANUAL_RICH_TEXT.concat(manualId).concat(":type:" + type);
        SweetRichtext sweetRichtext;
        if (content != null) {
            sweetRichtext = content;
        } else {
            sweetRichtext = sweetRichtextMapper.selectOne(Wrappers.lambdaQuery(SweetRichtext.class).eq(SweetRichtext::getManualId, manualId).eq(SweetRichtext::getType, type));
        }
        redisUtil.set(redisKey, sweetRichtext);
        return sweetRichtext;
    }

    //获取富文本详情
    public SweetRichtext getRichTextRedisData(String manualId, String type) {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_MANUAL_RICH_TEXT.concat(manualId).concat(":type:" + type);
        Object obj = redisUtil.get(redisKey);
        if (obj == null) {
            return setRichTextRedisData(manualId, type, null);
        } else {
            return (SweetRichtext) obj;
        }
    }

    public List<String> setTagRedisData(String manualId) {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_MANUAL_SORT.concat(manualId);
        SweetManualSort data = sweetManualSortMapper.selectOne(Wrappers.lambdaQuery(SweetManualSort.class).eq(SweetManualSort::getManualId, manualId));
        String[] arrays = data.getShowPosition().split(",");
        List<String> returnData = new ArrayList<>();
        for (String item : arrays) {
            returnData.add(item);
//            returnData.add(SweetConstant.ManualPosition.getMessage(item));
        }
        redisUtil.set(redisKey, returnData);
        return returnData;
    }

    //获取显示的标签
    public List<String> getTagRedisData(String manualId) {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_MANUAL_SORT.concat(manualId);
        Object obj = redisUtil.get(redisKey);
        if (obj == null) {
            return setTagRedisData(manualId);
        } else {
            return (List<String>) obj;
        }
    }

    public List<SweetManualNotify> setNotifyRedisData(String manualId, List<SweetManualNotify> content) {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_MANUAL_NOTIFY_LIST.concat(manualId);
        List<SweetManualNotify> data;
        if (content != null) {
            data = content;
        } else {
            data = sweetManualNotifyMapper.selectList(Wrappers.lambdaQuery(SweetManualNotify.class).eq(SweetManualNotify::getManualId, manualId).eq(SweetManualNotify::getStatus, 1));
        }
        redisUtil.set(redisKey, data);
        return data;
    }

    //获取通知
    public List<SweetManualNotify> getNotifyRedisData(String manualId) {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_MANUAL_NOTIFY_LIST.concat(manualId);
        Object obj = redisUtil.get(redisKey);
        if (obj == null) {
            return setNotifyRedisData(manualId, null);
        } else {
            return (List<SweetManualNotify>) obj;
        }
    }

    public void deletePushListRedisData() {
        redisUtil.del(SweetConstant.REDIS_KEY_SWEET_MANUAL_PUSH_LIST);//列表
    }

    public void deleteTimeListRedisData(String manualId) {
        redisUtil.del(SweetConstant.REDIS_KEY_SWEET_MANUAL_TIME_LIST.concat(manualId));//列表
    }

    public void deleteSortRedisData(String manualId) {
        redisUtil.del(SweetConstant.REDIS_KEY_SWEET_MANUAL_SORT.concat(manualId));//列表
    }

    public void setArtistsRelationRedisVo(String uid, String artistsId, String manualId, String type) {

        LinkedList<String> sqls = CollectionUtil.linkedListString();
        LinkedList<Object[]> sqlsDataA = CollectionUtil.linkedListObjectArr();
        LocalDateTime now = LocalDateTime.now();

        String redisKey = SweetConstant.REDIS_KEY_SWEET_ARTISTS_RELATION.concat(uid).concat(":manualId:").concat(manualId);
        SweetArtistsRelationVo vo = getArtistsRelationRedisVo(uid, manualId);
        vo.setUid(uid);
        if (type.equalsIgnoreCase("sign")) {
            if (vo.getSignList() == null) {
                ArrayList<String> signList = CollectionUtil.arrayListString();
                signList.add(artistsId);
                vo.setSignList(signList);
                sqls.add(SqlMapping.get("sweet_user_relation.insert"));
                sqlsDataA.add(new Object[]{
                        uid, 2, artistsId, manualId, now
                });
            } else {
                if (vo.getSignList().contains(artistsId)) {
                    vo.getSignList().remove(artistsId);
                    sqls.add(SqlMapping.get("sweet_user_relation.delete"));
                    sqlsDataA.add(new Object[]{
                            uid, artistsId, manualId, 2
                    });
                } else {
                    vo.getSignList().add(artistsId);
                    sqls.add(SqlMapping.get("sweet_user_relation.insert"));
                    sqlsDataA.add(new Object[]{
                            uid, 2, artistsId, manualId, now
                    });
                }
            }
        } else if (type.equalsIgnoreCase("watch")) {
            if (vo.getWatchList() == null) {
                ArrayList<String> watchList = CollectionUtil.arrayListString();
                watchList.add(artistsId);
                vo.setWatchList(watchList);
                sqls.add(SqlMapping.get("sweet_user_relation.insert"));
                sqlsDataA.add(new Object[]{
                        uid, 1, artistsId, manualId, now
                });
            } else {
                if (vo.getWatchList().contains(artistsId)) {
                    vo.getWatchList().remove(artistsId);
                    sqls.add(SqlMapping.get("sweet_user_relation.delete"));
                    sqlsDataA.add(new Object[]{
                            uid, artistsId, manualId, 1
                    });
                } else {
                    vo.getWatchList().add(artistsId);
                    sqls.add(SqlMapping.get("sweet_user_relation.insert"));
                    sqlsDataA.add(new Object[]{
                            uid, 1, artistsId, manualId, now
                    });
                }
            }
        }
        redisUtil.set(redisKey, vo);

        queueUtils.sendMsgByRedis(MQConst.SweetQueue.ARTISTS_RELATION.getKey(),
                SqlMapping.gets(sqls, sqlsDataA));
    }

    //获取 签售
    //获取 想看
    public SweetArtistsRelationVo getArtistsRelationRedisVo(String uid, String manualId) {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_ARTISTS_RELATION.concat(uid).concat(":manualId:").concat(manualId);
        Object obj = redisUtil.get(redisKey);
        if (obj == null) {
            return SweetArtistsRelationVo.getNew();
        } else {
            return (SweetArtistsRelationVo) obj;
        }
    }

    //获取 商铺
    public List<SweetManualShop> setManualShopRedisData(String manualId) {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_SHOP.concat(manualId);
        List<SweetManualShop> list = sweetManualShopMapper.selectList(Wrappers.lambdaQuery(SweetManualShop.class).eq(SweetManualShop::getManualId, manualId).orderBy(true, false, SweetManualShop::getSort));
        redisUtil.set(redisKey, list);
        return list;
    }

    public List<SweetManualShop> getManualShopRedisData(String manualId) {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_SHOP.concat(manualId);
        Object obj = redisUtil.get(redisKey);
        if (obj == null) {
            return setManualShopRedisData(manualId);
        } else {
            return (List<SweetManualShop>) obj;
        }
    }

    // 小程序演出提醒
    public void setSweetRemind(String openId, String unionId, String performancesId) {
        SweetRemindVo sweetRemindVo = SweetRemindVo.getNew();
        sweetRemindVo.setRemindId(IDGenerator.nextSnowId());
        sweetRemindVo.setCreatedAt(DateUtil.getNowTime());
        sweetRemindVo.setPerformancesId(performancesId);
        sweetRemindVo.setUnionId(unionId);
        sweetRemindVo.setOpenId(openId);

        LinkedList<String> sqls = CollectionUtil.linkedListString();
        LinkedList<Object[]> sqlsDataA = CollectionUtil.linkedListObjectArr();
        LocalDateTime now = LocalDateTime.now();
        sqls.add(SqlMapping.get("sweet_remind.insert"));
        sqlsDataA.add(new Object[]{
                sweetRemindVo.getRemindId(), sweetRemindVo.getOpenId(), sweetRemindVo.getUnionId(), sweetRemindVo.getPerformancesId(),
        });
        queueUtils.sendMsgByRedis(MQConst.SweetQueue.SWEET_REMIND_INSERT_DRAW.getKey(),
                SqlMapping.gets(sqls, sqlsDataA));
    }

    // 正在现场服务号关注事件储存用户信息
    public void setSweetWechatUser(SweetWechatUser sweetWechatUser) {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_WECHAT_USER_INFO.concat(sweetWechatUser.getUnionId());
        String redisKeyUnid = SweetConstant.REDIS_KEY_SWEET_WECHAT_USER_UNIONID.concat(sweetWechatUser.getOpenId());
        redisUtil.set(redisKey, sweetWechatUser);
        redisUtil.set(redisKeyUnid, sweetWechatUser.getUnionId());
    }
    public String getSweetWechatUserUnionid(String openid) {
        if (openid.isEmpty()) {
            return null;
        }
        String redisKey = SweetConstant.REDIS_KEY_SWEET_WECHAT_USER_UNIONID.concat(openid);
        return (String) redisUtil.get(redisKey);
    }
    public SweetWechatUser getSweetWechatUser(String unionid) {
        if (unionid.isEmpty()) {
            return null;
        }
        String redisKey = SweetConstant.REDIS_KEY_SWEET_WECHAT_USER_INFO.concat(unionid);
        return (SweetWechatUser) redisUtil.get(redisKey);
    }
    public void delSweetWechatUser(String unionid, String openid) {
        if (!unionid.isEmpty()) {
            String redisKey = SweetConstant.REDIS_KEY_SWEET_WECHAT_USER_INFO.concat(unionid);
            redisUtil.del(redisKey);
            String redisKeyUnid = SweetConstant.REDIS_KEY_SWEET_WECHAT_USER_UNIONID.concat(openid);
            redisUtil.del(redisKeyUnid);
        }
    }

    // 艺人详情
    public SweetArtists setArtistsDetails(String artistsId) {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_ARTISTS_DETAILS.concat(artistsId);
        SweetArtists sweetArtists = sweetArtistsMapper.selectOne(Wrappers.lambdaQuery(SweetArtists.class).eq(SweetArtists::getArtistsId, artistsId).eq(SweetArtists::getStatus, 1));
        redisUtil.set(redisKey, sweetArtists);
        return sweetArtists;
    }

    public SweetArtists getArtistsDetails(String artistsId) {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_ARTISTS_DETAILS.concat(artistsId);
        Object obj = redisUtil.get(redisKey);
        if (obj == null) {
            return setArtistsDetails(artistsId);
        } else {
            return (SweetArtists) obj;
        }
    }

    //获取抽奖状态
    public Boolean getLuckDrawStatus(String uid, String luckDrawNum) {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_LUCK_DRAW.concat(uid).concat(":luckDrawNum:" + luckDrawNum);
        return redisUtil.hasKey(redisKey);
    }

    //修改抽奖状态
    public void changeLuckDrawStatus(String uid, String luckDrawNum) {
        LinkedList<String> sqls = CollectionUtil.linkedListString();
        LinkedList<Object[]> sqlsDataA = CollectionUtil.linkedListObjectArr();
        LocalDateTime now = LocalDateTime.now();

        String redisKey = SweetConstant.REDIS_KEY_SWEET_LUCK_DRAW.concat(uid).concat(":luckDrawNum:" + luckDrawNum);
        redisUtil.set(redisKey, 1);
        sqls.add(SqlMapping.get("sweet_luck_draw.insert"));
        sqlsDataA.add(new Object[]{
                uid, luckDrawNum, now
        });
        queueUtils.sendMsgByRedis(MQConst.SweetQueue.LUCK_DRAW.getKey(),
                SqlMapping.gets(sqls, sqlsDataA));
    }

    // 答案
    public void setSweetAnswer(SweetAnswerVo sweetAnswerVo) {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_ANSWER_PHONE.concat(sweetAnswerVo.getPhone());
        redisUtil.set(redisKey, sweetAnswerVo);
    }
    public SweetAnswerVo getSweetAnswer(String phone) {
        String redisKey = SweetConstant.REDIS_KEY_SWEET_ANSWER_PHONE.concat(phone);
        SweetAnswerVo sweetAnswerVo = (SweetAnswerVo) redisUtil.get(redisKey);
        return sweetAnswerVo;
    }
}
