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

import com.liquidnet.service.kylin.dto.vo.KylinExpressModuleVo;
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.RedisDataSourceUtil;
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.partner.KylinTicketExpressModuleVo;
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.List;

@Component
public class DataUtils {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisDataSourceUtil redisDataSourceUtil;
    @Autowired
    private MongoVoUtils mongoVoUtils;

    /**
     * 初始化普通库存
     *
     * @param ticketId     票id
     * @param totalGeneral 普通库存
     */
    public void setSurplusGeneral(String ticketId, int totalGeneral) {
        redisDataSourceUtil.getRedisKylinUtil().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) redisDataSourceUtil.getRedisKylinUtil().get(key);
        if (null == vo) {
            vo = mongoTemplate.findOne(Query.query(Criteria.where("fieldId").is(fieldId)), MerchantFieldsVo.class, MerchantFieldsVo.class.getSimpleName());
            redisDataSourceUtil.getRedisKylinUtil().set(MerchantRedisConst.INFO_FIELD.concat(fieldId), vo);
        }
        return vo;
    }

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

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

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

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

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

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

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

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

    public List<KylinOrderListVo> getOrderList(String userId) {
        if (redisDataSourceUtil.getRedisKylinUtil().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());
            }
            redisDataSourceUtil.getRedisKylinUtil().set(KylinRedisConst.ORDER_LIST + userId, voList);
        }
        return (List<KylinOrderListVo>) redisDataSourceUtil.getRedisKylinUtil().get(KylinRedisConst.ORDER_LIST + userId);
    }

    /**
     * 根据订单id 获取 订单vo 详情
     *
     * @param orderId
     * @return
     */
    public KylinOrderTicketVo getOrderTicketVo(String orderId) {
        if (redisDataSourceUtil.getRedisKylinUtil().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);
            redisDataSourceUtil.getRedisKylinUtil().set(KylinRedisConst.ORDER + orderId, ticketData);
        }
        return (KylinOrderTicketVo) redisDataSourceUtil.getRedisKylinUtil().get(KylinRedisConst.ORDER + orderId);
    }

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

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

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

    /**
     * 删除 验票账号关系 vo
     *
     * @param checkUserId
     */
    public void delCheckUserRelationRedis(String checkUserId) {
        redisDataSourceUtil.getRedisKylinUtil().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
                redisDataSourceUtil.getRedisKylinUtil().del(KylinRedisConst.PERFORMANCES + performanceIds);
                // 大龙相关 演出列表
                redisDataSourceUtil.getRedisKylinUtil().del(KylinRedisConst.PERFORMANCES_LIST_CITYNAME + vo.getCityName());
                redisDataSourceUtil.getRedisKylinUtil().del(KylinRedisConst.PERFORMANCES_ROADLIST + vo.getRoadShowId());
                redisDataSourceUtil.getRedisKylinUtil().del(KylinRedisConst.PERFORMANCES_LIST_SYSTEM_RECOMMEND);
                redisDataSourceUtil.getRedisKylinUtil().del(KylinRedisConst.PERFORMANCES_LIST_RECOMMEND);
                redisDataSourceUtil.getRedisKylinUtil().del(KylinRedisConst.PERFORMANCES_LIST_NOTICE);
                redisDataSourceUtil.getRedisKylinUtil().del(KylinRedisConst.PERFORMANCES_LIST_EXCLUSIVE);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
        }
    }

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

    /**
     * 演出是否实名
     *
     * @param performanceId
     */
    public int getPerformanceIsTrueName(String performanceId) {
        Object obj = redisDataSourceUtil.getRedisKylinUtil().get(KylinRedisConst.PERFORMANCES_TRUE_NAME + performanceId);
        if (obj != null) {
            return (int) obj;
        } else {
            int isTrueName = getPerformanceVo(performanceId).getIsTrueName();
            redisDataSourceUtil.getRedisKylinUtil().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;
//        redisDataSourceUtil.getRedisKylinUtil().set(ticketUseTimeKey, useTime);

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

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

    public void delOrderExpressInfo(String orderId) {
        String redisKey = KylinRedisConst.ORDER_EXPRESS_INFO.concat(orderId);
        redisDataSourceUtil.getRedisKylinUtil().del(redisKey);
    }

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

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

    public void delOrderIdUserIdRedis(List<String> orderTicketIdList, List<String> userIdList) {
        redisDataSourceUtil.getRedisKylinUtil().delList(orderTicketIdList);
        redisDataSourceUtil.getRedisKylinUtil().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 = redisDataSourceUtil.getRedisKylinUtil().get(KylinRedisConst.ORDER_REFUND_ADDRESS);
        if(obj==null){
            OrderRefundAddress vo = OrderRefundAddress.getNew();
            vo.setName("张三");
            vo.setPhone("010 124412");
            vo.setAddress("北京 北京市朝阳区广渠路3-12");
            redisDataSourceUtil.getRedisKylinUtil().set(KylinRedisConst.ORDER_REFUND_ADDRESS,vo);
            return vo;
        }else{
            return (OrderRefundAddress)obj;
        }
    }

    // 获取 用户维度 演出购买数量
    public int getUserPBuyCount(String userId, String performanceId) {
        try {
            return (int) redisDataSourceUtil.getRedisKylinUtil().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) redisDataSourceUtil.getRedisKylinUtil().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) redisDataSourceUtil.getRedisKylinUtil().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) redisDataSourceUtil.getRedisKylinUtil().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());
        redisDataSourceUtil.getRedisKylinUtil().set(redisKey, vo);
    }

    //获取 订单导入错误数据
    public PageInfo<OrderOutLineVo> getOrderImportFail(String importId) {
        String redisKey = KylinRedisConst.ORDER_IMPORT_FAIL.concat(importId);
        Object obj = redisDataSourceUtil.getRedisKylinUtil().get(redisKey);
        if (obj == null) {
            return new PageInfo();
        } else {
            return (PageInfo<OrderOutLineVo>) obj;
        }
    }
    //订单信息存redis
    public void orderSetRedis(String orderCode){
        KylinOrderTicketVo orderTicketVo = mongoTemplate.findOne(Query.query(Criteria.where("orderCode").is(orderCode)), KylinOrderTicketVo.class, KylinOrderTicketVo.class.getSimpleName());
        String orderTicketsId = orderTicketVo.getOrderTicketsId();
        List<KylinOrderTicketEntitiesVo> kylinOrderTicketEntitiesVoList = mongoTemplate.find(Query.query(Criteria.where("orderId").is(orderTicketsId)), KylinOrderTicketEntitiesVo.class, KylinOrderTicketEntitiesVo.class.getSimpleName());
        orderTicketVo.setEntitiesVoList(kylinOrderTicketEntitiesVoList);
        redisDataSourceUtil.getRedisKylinUtil().set(KylinRedisConst.ORDER +orderTicketsId, orderTicketVo);
    }

    public void setkylinExpressModules(List<KylinExpressModuleVo> voList) {
        String redisKey = KylinRedisConst.KYLIN_EXPRESS_MODULES;
        redisDataSourceUtil.getRedisKylinUtil().set(redisKey, voList);
    }

    /**
     * 获取 票种快递票模板关联vo [第三方非线上]
     *
     * @param ticketId
     * @return
     */
    public KylinTicketExpressModuleVo getTEMMerchantVo(String ticketId) {
        String redisKey = KylinRedisConst.TICKET_EXPRESS_MODULE_P.concat(ticketId);
        Object obj =  redisDataSourceUtil.getRedisKylinUtil().get(redisKey);
        if (obj != null) {
            return (KylinTicketExpressModuleVo) obj;
        } else {
            return null;
        }
    }

    /**
     * 设置 票种快递票模板关联vo [线上]
     *
     * @param ticketId 票id
     */
    public void setTEMVo(String ticketId, KylinTicketExpressModuleVo vo) {
        redisDataSourceUtil.getRedisKylinUtil().set(KylinRedisConst.TICKET_EXPRESS_MODULE.concat(ticketId), vo);
    }

    /**
     * 获取 票种快递票模板关联vo [线上]
     *
     * @param ticketId
     * @return
     */
    public KylinTicketExpressModuleVo getTEMVo(String ticketId) {
        String redisKey = KylinRedisConst.TICKET_EXPRESS_MODULE.concat(ticketId);
        Object obj = redisDataSourceUtil.getRedisKylinUtil().get(redisKey);
        if (obj != null) {
            return (KylinTicketExpressModuleVo) obj;
        } else {
            return null;
        }
    }
}
