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

import com.liquidnet.service.kylin.dto.vo.admin.OrderRefundAddress;
import com.liquidnet.service.kylin.dto.vo.admin.OrderRefundPoundage;
import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.service.kylin.constant.KylinRedisConst;
import com.liquidnet.service.kylin.dto.vo.express.KylinOrderExpressVo;
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.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
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);
    }

    /**
     * 演出是否实名
     *
     * @param performanceId
     * @param isTrueName
     */
    public void setPerformanceIsTrueName(String performanceId,int isTrueName) {
        redisUtil.set(KylinRedisConst.PERFORMANCES_TRUE_NAME + performanceId,isTrueName);
    }

    /**
     * 删除场次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 {
        }
    }

    /**
     * 根据演出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
     */
    public int getPerformanceIsTrueName(String performanceId) {
        Object obj = redisUtil.get(KylinRedisConst.PERFORMANCES_TRUE_NAME + performanceId);
        if (obj!=null) {
            return (int)obj;
        }else{
            int isTrueName = getPerformanceVo(performanceId).getIsTrueName();
            redisUtil.set(KylinRedisConst.PERFORMANCES_TRUE_NAME + performanceId,isTrueName);
            return isTrueName;
        }
    }

    /**
     * @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;

        int isTrueName = getPerformanceIsTrueName(performanceId);
//        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();
//                }
//            }
//            allTicketId.put(timeItem.getUseStart(), ticketList);
//        }

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

        String performanceIdKey = redisKey + ":" + KylinRedisConst.PERFORMANCE_ID + ":" + performanceId;
        String ticketIdKey = redisKey + ":" + KylinRedisConst.TICKET_ID + ":" + ticketId;
//        String ticketUseTimeKey = ticketIdKey + ":" + KylinRedisConst.USE_TIME;
//        redisUtil.set(ticketUseTimeKey, useTime);

        if (buyCount > 0) {
            redisUtil.incr(ticketIdKey, buyCount);
            redisUtil.incr(performanceIdKey, buyCount);
        }else{
            redisUtil.decr(ticketIdKey, Math.abs(buyCount));
            redisUtil.decr(performanceIdKey, Math.abs(buyCount));
        }
    }

    /**
     * 演出订单快递信息
     * @param orderId
     * @param kylinOrderExpressVo
     */
    public void setOrderExpressInfo(String orderId, KylinOrderExpressVo kylinOrderExpressVo) {
        String redisKey = KylinRedisConst.ORDER_EXPRESS_INFO.concat(orderId);
        redisUtil.set(redisKey, kylinOrderExpressVo);
    }
    public void delOrderExpressInfo(String orderId) {
        String redisKey = KylinRedisConst.ORDER_EXPRESS_INFO.concat(orderId);
        redisUtil.del(redisKey);
    }

    /**
     * 退款redis
     */
    public void delOrderRefundVo(List<String> orderRefundIds){
        for (String id : orderRefundIds) {
            redisUtil.del(KylinRedisConst.ORDER_REFUND.concat(id));
        }
    }

    public void delOrderRefundVoByOrderId(List<String>  orderIds){
        for (String id : orderIds) {
            redisUtil.del(KylinRedisConst.ORDER_REFUND_BY_ORDER_ID.concat(id));
        }
    }

    public void delOrderIdUserIdRedis(List<String> orderTicketIdList,List<String> userIdList){
        redisUtil.delList(orderTicketIdList);
        redisUtil.delList(userIdList);
    }

    /**
     * Object转BigDecimal类型
     *
     * @param value 要转的object类型
     * @return 转成的BigDecimal类型数据
     */
    public BigDecimal getBigDecimal(Object value) {
        BigDecimal ret = null;
        if (value != null) {
            if (value instanceof BigDecimal) {
                ret = (BigDecimal) value;
            } else if (value instanceof String) {
                String str = ((String) value).replace("元","");
                ret = new BigDecimal(str);
            } else if (value instanceof BigInteger) {
                ret = new BigDecimal((BigInteger) value);
            } else if (value instanceof Number) {
                ret = new BigDecimal(((Number) value).doubleValue());
            } else {
                throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass() + " into a BigDecimal.");
            }
        }
        return ret;
    }

    // 获取手续费
    public ArrayList<OrderRefundPoundage> getRefundPoundage(){
        Object obj = redisUtil.get(KylinRedisConst.ORDER_REFUND_POUNDAGE);
        if(obj==null){
            ArrayList<OrderRefundPoundage> voList = new ArrayList();
            OrderRefundPoundage vo1 = OrderRefundPoundage.getNew();
            vo1.setDay(15);
            vo1.setContent("距离演出开始日期>15天");
            vo1.setPresent(0.9f);
            vo1.setIsCanRefund(1);
            OrderRefundPoundage vo2 = OrderRefundPoundage.getNew();
            vo2.setDay(3);
            vo2.setContent("距离演出开始日期>3天-15天(含15天)");
            vo2.setPresent(0.5f);
            vo2.setIsCanRefund(1);
            OrderRefundPoundage vo3 = OrderRefundPoundage.getNew();
            vo3.setDay(0);
            vo3.setContent("距离演出开始日期≤3天(含演出当天)");
            vo3.setPresent(1.0f);
            vo3.setIsCanRefund(0);
            voList.add(vo1);
            voList.add(vo2);
            voList.add(vo3);
            redisUtil.set(KylinRedisConst.ORDER_REFUND_POUNDAGE,voList);
            return voList;
        }else{
            return (ArrayList<OrderRefundPoundage>)obj;
        }
    }

    // 获取 快递地址
    public OrderRefundAddress getRefundAddress(){
        Object obj = redisUtil.get(KylinRedisConst.ORDER_REFUND_ADDRESS);
        if(obj==null){
            OrderRefundAddress vo = OrderRefundAddress.getNew();
            vo.setName("张三");
            vo.setPhone("010 124412");
            vo.setAddress("北京 北京市朝阳区广渠路3-12");
            redisUtil.set(KylinRedisConst.ORDER_REFUND_ADDRESS,vo);
            return vo;
        }else{
            return (OrderRefundAddress)obj;
        }
    }
}
