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.github.pagehelper.PageInfo;
import com.liquidnet.client.admin.zhengzai.kylin.dto.OrderOutLineVo;
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 com.liquidnet.service.merchant.constant.MerchantRedisConst;
import com.liquidnet.service.merchant.dto.vo.MerchantFieldsVo;
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);
    }

    // 【场地】获取详情
    public MerchantFieldsVo getFieldsVoByFieldId(String fieldId) {
        String key = MerchantRedisConst.INFO_FIELD.concat(fieldId);
        long s = System.currentTimeMillis();
        MerchantFieldsVo vo = (MerchantFieldsVo) redisUtil.get(key);
        if (null == vo) {
            vo = mongoTemplate.findOne(Query.query(Criteria.where("fieldId").is(fieldId)), MerchantFieldsVo.class, MerchantFieldsVo.class.getSimpleName());
            redisUtil.set(MerchantRedisConst.INFO_FIELD.concat(fieldId), vo);
        }
        return vo;
    }

    /**
     * 获取普通剩余库存
     *
     * @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());
            for (KylinOrderListVo item : voList) {
                item.setStatus(item.getStatus());
            }
            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 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;
        }
    }

    // 获取 用户维度 演出购买数量
    public int getUserPBuyCount(String userId, String performanceId) {
        try {
            return (int) redisUtil.get(KylinRedisConst.USERID_BUY_INFO + userId + ":" + KylinRedisConst.PERFORMANCE_ID + ":" + performanceId);
        } catch (Exception e) {
            return 0;
        }
    }

    // 获取 用户维度 票种购买数量
    public int getUserTBuyCount(String userId, String ticketId) {
        try {
            return (int) redisUtil.get(KylinRedisConst.USERID_BUY_INFO + userId + ":" + KylinRedisConst.TICKET_ID + ":" + ticketId);
        } catch (Exception e) {
            return 0;
        }
    }

    // 获取 证件维度 演出购买数量
    public int getIdCardPBuyCount(String idCard, String performanceId) {
        try {
            return (int) redisUtil.get(KylinRedisConst.IDCARD_BUY_INFO + idCard + ":" + KylinRedisConst.PERFORMANCE_ID + ":" + performanceId);
        } catch (Exception e) {
            return 0;
        }
    }

    // 获取 证件维度 票种购买数量
    public int getIdCardTBuyCount(String idCard, String ticketId) {
        try {
            return (int) redisUtil.get(KylinRedisConst.IDCARD_BUY_INFO + idCard + ":" + KylinRedisConst.TICKET_ID + ":" + ticketId);
        } catch (Exception e) {
            return 0;
        }
    }


    //设置 订单导入错误数据
    public void setOrderImportFail(String importId, List<OrderOutLineVo> vos) {
        String redisKey = KylinRedisConst.ORDER_IMPORT_FAIL.concat(importId);
        PageInfo<OrderOutLineVo> vo = new PageInfo(vos);
        vo.setTotal(vos.size());
        redisUtil.set(redisKey, vo);
    }

    //获取 订单导入错误数据
    public PageInfo<OrderOutLineVo> getOrderImportFail(String importId) {
        String redisKey = KylinRedisConst.ORDER_IMPORT_FAIL.concat(importId);
        Object obj = redisUtil.get(redisKey);
        if (obj == null) {
            return new PageInfo();
        } else {
            return (PageInfo<OrderOutLineVo>) obj;
        }
    }
}
