package com.liquidnet.client.admin.zhengzai.kylin.utils;

import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.service.kylin.constant.KylinRedisConst;
import com.liquidnet.service.kylin.dto.vo.middle.KylinTicketTimesVo;
import com.liquidnet.service.kylin.dto.vo.middle.KylinTicketVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinOrderTicketEntitiesVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinOrderTicketVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinPerformanceVo;
import com.liquidnet.service.kylin.dto.vo.returns.KylinOrderListVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
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.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Component
public class DataUtils {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private MongoVoUtils mongoVoUtils;

    /**
     * 初始化普通库存
     *
     * @param ticketId     票id
     * @param totalGeneral 普通库存
     */
    public void setSurplusGeneral(String ticketId, int totalGeneral) {
        redisUtil.set(KylinRedisConst.PERFORMANCES_INVENTORY + ticketId + ":" + KylinRedisConst.SURPLUS_GENERAL, totalGeneral);
    }

    /**
     * 获取普通剩余库存
     *
     * @param ticketId 票id
     * @return 普通剩余库存
     */
    public int getSurplusGeneral(String ticketId) {
        return (int) redisUtil.get(KylinRedisConst.PERFORMANCES_INVENTORY + ticketId + ":" + KylinRedisConst.SURPLUS_GENERAL);
    }

    /**
     * 修改普通库存 并 返回修改后的数量
     *
     * @param ticketId       票id
     * @param surplusGeneral 普通库存
     * @return 普通剩余库存
     */
    public int changeSurplusGeneral(String ticketId, int surplusGeneral) {
        return (int) redisUtil.incr(KylinRedisConst.PERFORMANCES_INVENTORY + ticketId + ":" + KylinRedisConst.SURPLUS_GENERAL, surplusGeneral);
    }

    /**
     * 初始化兑换库存
     *
     * @param ticketId      票id
     * @param totalExchange 兑换库存
     */
    public void setSurplusExchange(String ticketId, int totalExchange) {
        redisUtil.set(KylinRedisConst.PERFORMANCES_INVENTORY + ticketId + ":" + KylinRedisConst.SURPLUS_EXCHANGE, totalExchange);
    }

    /**
     * 删除演出redis
     *
     * @param performanceId
     */
    public void delPerformanceRedis(String performanceId) {
        redisUtil.del(KylinRedisConst.PERFORMANCES + performanceId);
    }

    /**
     * 删除场次redis
     *
     * @param ticketTimeId
     */
    public void delTicketTimesRedis(String ticketTimeId) {
        redisUtil.del(KylinRedisConst.TIMES + ticketTimeId);
    }

    /**
     * 删除票种redis
     *
     * @param ticketId
     */
    public void delTicketRedis(String ticketId) {
        redisUtil.del(KylinRedisConst.TICKET + ticketId);
    }

    public void setOrderList(String userId, List<KylinOrderListVo> vo) {
        redisUtil.set(KylinRedisConst.ORDER_LIST + userId, vo);
    }

    public List<KylinOrderListVo> getOrderList(String userId) {
        if (redisUtil.hasKey(KylinRedisConst.ORDER_LIST + userId)) {
        } else {
            List<KylinOrderListVo> voList = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId))
                            .with(Sort.by(Sort.Direction.DESC, "createdAt")).limit(40),
                    KylinOrderListVo.class, KylinOrderTicketVo.class.getSimpleName());
            redisUtil.set(KylinRedisConst.ORDER_LIST + userId, voList);
        }
        return (List<KylinOrderListVo>) redisUtil.get(KylinRedisConst.ORDER_LIST + userId);
    }

    /**
     * 根据订单id 获取 订单vo 详情
     *
     * @param orderId
     * @return
     */
    public KylinOrderTicketVo getOrderTicketVo(String orderId) {
        if (redisUtil.hasKey(KylinRedisConst.ORDER + orderId)) {
        } else {
            KylinOrderTicketVo ticketData = mongoTemplate.findOne(Query.query(Criteria.where("orderTicketsId").is(orderId)), KylinOrderTicketVo.class, KylinOrderTicketVo.class.getSimpleName());
            List<KylinOrderTicketEntitiesVo> kylinOrderTicketEntitiesVoList = mongoTemplate.find(Query.query(Criteria.where("orderId").is(orderId)), KylinOrderTicketEntitiesVo.class, KylinOrderTicketEntitiesVo.class.getSimpleName());
            ticketData.setEntitiesVoList(kylinOrderTicketEntitiesVoList);
            redisUtil.set(KylinRedisConst.ORDER + orderId, ticketData);
        }
        return (KylinOrderTicketVo) redisUtil.get(KylinRedisConst.ORDER + orderId);
    }

    /**
     * 删除订单redis
     *
     * @param orderId
     */
    public void delOrderTicketRedis(String orderId) {
        redisUtil.del(KylinRedisConst.ORDER + orderId);
    }

    /**
     * 删除订单redis
     *
     * @param orderEntitiesId
     */
    public void delOrderTicketEntitiesRedis(String orderEntitiesId) {
        redisUtil.del(KylinRedisConst.ORDER_ENTITIES + orderEntitiesId);
    }

    /**
     * 删除 验票账号 redis
     * @param checkUserId
     */
    public void delCheckUserRedis(String checkUserId) {
        redisUtil.del(KylinRedisConst.CHECK_USER + checkUserId);
    }

    /**
     * 删除 验票账号关系 vo
     * @param checkUserId
     */
    public void delCheckUserRelationRedis(String checkUserId) {
        redisUtil.del(KylinRedisConst.CHECK_USER_RELATION + checkUserId);
    }

    public void updatePerformanceMongo(String performanceIds, KylinPerformanceVo paramVo) {
        //查询 mysql 数据
        KylinPerformanceVo vo;
        if (null == paramVo) {
            vo = mongoVoUtils.combinePerformanceVoData(performanceIds);
        } else {
            vo = paramVo;
        }
        if (vo != null) {
            try {
                //删除 mongo数据
                mongoTemplate.remove(Query.query(Criteria.where("performancesId").is(performanceIds)), KylinPerformanceVo.class, KylinPerformanceVo.class.getSimpleName());
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                //新增 mongo数据
                mongoTemplate.insert(vo, KylinPerformanceVo.class.getSimpleName());
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                //删除redis
                redisUtil.del(KylinRedisConst.PERFORMANCES + performanceIds);
                // 大龙相关 演出列表
                redisUtil.del(KylinRedisConst.PERFORMANCES_LIST_CITYNAME  + vo.getCityName());
                redisUtil.del(KylinRedisConst.PERFORMANCES_ROADLIST + vo.getRoadShowId());
                redisUtil.del(KylinRedisConst.PERFORMANCES_LIST_SYSTEM_RECOMMEND);
                redisUtil.del(KylinRedisConst.PERFORMANCES_LIST_RECOMMEND);
                redisUtil.del(KylinRedisConst.PERFORMANCES_LIST_NOTICE);
                redisUtil.del(KylinRedisConst.PERFORMANCES_LIST_EXCLUSIVE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("创建Vo异常");
        }
    }

    /**
     * 根据演出id 获取 演出vo 详情
     *
     * @param performanceId
     * @return
     */
    public KylinPerformanceVo getPerformanceVo(String performanceId) {
        if (redisUtil.hasKey(KylinRedisConst.PERFORMANCES + performanceId)) {
        } else {
            KylinPerformanceVo performanceData = mongoTemplate.findOne(Query.query(Criteria.where("performancesId").is(performanceId)), KylinPerformanceVo.class, KylinPerformanceVo.class.getSimpleName());
            redisUtil.set(KylinRedisConst.PERFORMANCES + performanceId, performanceData);
        }
        return (KylinPerformanceVo) redisUtil.get(KylinRedisConst.PERFORMANCES + performanceId);
    }

    /**
     * @param performanceId 演出id
     * @param ticketId      票种id
     * @param buyCount      购买数量 大于 0 增加 小于 0 减少 对应 支付 退款表
     */
    public void changeBuyInfo(String userId, String idCard, String performanceId, String ticketId, int buyCount) {
        String redisKey;

        KylinPerformanceVo vo = getPerformanceVo(performanceId);
        int isTrueName = vo.getIsTrueName();
        int ticketType = 0;
        String useTime = "";
        HashMap<String, ArrayList<String>> allTicketId = new HashMap<>();
        for (int x = 0; x < vo.getTicketTimeList().size(); x++) {
            KylinTicketTimesVo timeItem = vo.getTicketTimeList().get(x);
            ArrayList<String> ticketList = new ArrayList<>();
            for (int y = 0; y < timeItem.getTicketList().size(); y++) {
                KylinTicketVo ticketItem = timeItem.getTicketList().get(y);
                if (ticketItem.getType() == 1) {
                    ticketList.add(ticketItem.getTicketsId());
                }
                if (ticketItem.getTicketsId().equals(ticketId)) {
                    useTime = ticketItem.getUseStart();
                    ticketType = ticketItem.getType();
                }
            }
            allTicketId.put(timeItem.getUseStart(), ticketList);
        }

        System.out.println(" PERFORMANCE_ID = "+performanceId);

        if (0 == isTrueName) {
            redisKey = KylinRedisConst.USERID_BUY_INFO + userId;
        } else {
            redisKey = KylinRedisConst.IDCARD_BUY_INFO + idCard;
        }

        System.out.println(" REDIS KEY= "+redisKey);

        String performanceIdKey = redisKey + ":" + KylinRedisConst.PERFORMANCE_ID + ":" + performanceId;
        String ticketIdKey = redisKey + ":" + KylinRedisConst.TICKET_ID + ":" + ticketId;
        String ticketUseTimeKey = ticketIdKey + ":" + KylinRedisConst.USE_TIME;
        System.out.println("PERFORMANCEID REDIS KEY = "+performanceIdKey);
        System.out.println("TICKETID REDIS KEY = "+ticketIdKey);
        redisUtil.set(ticketUseTimeKey, useTime);
        if (buyCount > 0) {
            redisUtil.incr(ticketIdKey, buyCount);
            if (1 == ticketType) {
                int count = 0;
                for (int i = 0; i < allTicketId.get(useTime).size(); i++) {
                    String item = allTicketId.get(useTime).get(i);
                    if (allTicketId.get(useTime).size() == 1) {
                        redisUtil.incr(performanceIdKey, buyCount);
                        break;
                    }
                    if (null == redisUtil.get(redisKey + ":" + KylinRedisConst.TICKET_ID + ":" + item)) {
                        redisUtil.set(redisKey + ":" + KylinRedisConst.TICKET_ID + ":" + item, 0);
                    }
                    if (i == 0) {
                        count = (int) redisUtil.get(redisKey + ":" + KylinRedisConst.TICKET_ID + ":" + item);
                    } else {
                        if (count != (int) redisUtil.get(redisKey + ":" + KylinRedisConst.TICKET_ID + ":" + item)) {
                            redisUtil.incr(performanceIdKey, buyCount);
                            break;
                        }
                    }
                }
            } else {
                System.out.println("BUY_COUNT = "+buyCount);
                redisUtil.incr(performanceIdKey, buyCount);
            }
        } else {
            redisUtil.decr(ticketIdKey, Math.abs(buyCount));
            if (1 == ticketType) {
                int count = 0;
                for (int i = 0; i < allTicketId.get(useTime).size(); i++) {
                    String item = allTicketId.get(useTime).get(i);
                    if (allTicketId.get(useTime).size() == 1) {
                        redisUtil.decr(performanceIdKey, Math.abs(buyCount));
                        break;
                    }
                    if (null == redisUtil.get(redisKey + ":" + KylinRedisConst.TICKET_ID + ":" + item)) {
                        redisUtil.set(redisKey + ":" + KylinRedisConst.TICKET_ID + ":" + item, 0);
                    }
                    if (i == 0) {
                        count = (int) redisUtil.get(redisKey + ":" + KylinRedisConst.TICKET_ID + ":" + item);
                    } else {
                        if (count != (int) redisUtil.get(redisKey + ":" + KylinRedisConst.TICKET_ID + ":" + item)) {
                            redisUtil.decr(performanceIdKey, Math.abs(buyCount));
                            break;
                        }
                    }
                }
            } else {
                redisUtil.decr(performanceIdKey, Math.abs(buyCount));
            }
        }
    }
}
