package com.liquidnet.service.platform.utils;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.commons.lang.util.DateUtil;
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.KylinOrderTicketVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinPerformanceVo;
import com.liquidnet.service.kylin.dto.vo.returns.KylinOrderListVo;
import com.liquidnet.service.kylin.entity.*;
import com.liquidnet.service.kylin.mapper.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Component
public class MongoVoUtils {
    @Autowired
    private KylinPerformancesMapper performancesMapper;
    @Autowired
    private KylinPerformanceStatusMapper performanceStatusMapper;
    @Autowired
    private KylinPerformanceRelationsMapper performanceRelationsMapper;
    @Autowired
    private KylinTicketTimesMapper ticketTimesMapper;
    @Autowired
    private KylinTicketTimeRelationMapper ticketTimeRelationMapper;
    @Autowired
    private KylinTicketsMapper ticketsMapper;
    @Autowired
    private KylinTicketStatusMapper ticketStatusMapper;
    @Autowired
    private KylinTicketRelationsMapper ticketRelationsMapper;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private DataUtils dataUtils;

    public KylinPerformanceVo combinePerformanceVoData(String performancesId) {
        try {
            KylinPerformanceVo voData = new KylinPerformanceVo();

            //演出数据
            KylinPerformances p1 = performancesMapper.selectOne(new UpdateWrapper<KylinPerformances>().eq("performances_id", performancesId));
            KylinPerformanceStatus p2 = performanceStatusMapper.selectOne(new UpdateWrapper<KylinPerformanceStatus>().eq("performance_id", performancesId));
            KylinPerformanceRelations p3 = performanceRelationsMapper.selectOne(new UpdateWrapper<KylinPerformanceRelations>().eq("performance_id", performancesId));
            //场地相关数据
            KylinFields fields = new KylinFields();
            String cityName = (String) redisUtil.hget(KylinRedisConst.FIELDS + ":" + p3.getFieldId(), "city_name");
            fields.setCityId(Integer.parseInt((String) redisUtil.hget(KylinRedisConst.FIELDS + ":" + p3.getFieldId(), "city_id")));
            fields.setLatitude((String) redisUtil.hget(KylinRedisConst.FIELDS + ":" + p3.getFieldId(), "latitude"));
            fields.setLongitude((String) redisUtil.hget(KylinRedisConst.FIELDS + ":" + p3.getFieldId(), "longitude"));
            fields.setCityName((String) redisUtil.hget(KylinRedisConst.FIELDS + ":" + p3.getFieldId(), "city_name"));
            fields.setName((String) redisUtil.hget(KylinRedisConst.FIELDS + ":" + p3.getFieldId(), "name"));

            //相关状态时间初始变量
            LocalDateTime stopSellTime = null;
            LocalDateTime sellTime = null;
            LocalDateTime sellMemberTime = null;

            int isLackRegister = 0;
            int isMember = 0;
            int isExclusive = 0;
            int isAdvance = 0;
            int isDiscount = 0;
            int payCountdownMinute = 15;
            BigDecimal price = new BigDecimal("0.00");

            //场次数据
            List<KylinTicketTimeRelation> tt3 = ticketTimeRelationMapper.selectList(new UpdateWrapper<KylinTicketTimeRelation>().eq("performance_id", performancesId));
            List<KylinTicketTimesVo> timeList = new ArrayList<>();
            for (int x = 0; x < tt3.size(); x++) {
                KylinTicketTimeRelation times = tt3.get(x);
                KylinTicketTimes tt1 = ticketTimesMapper.selectOne(new UpdateWrapper<KylinTicketTimes>().eq("ticket_times_id", times.getTimesId()));

                //票种数据
                List<KylinTicketRelations> t3 = ticketRelationsMapper.selectList(new UpdateWrapper<KylinTicketRelations>().eq("times_id", times.getTimesId()));
                List<KylinTicketVo> ticketList = new ArrayList<>();
                for (int y = 0; y < t3.size(); y++) {
                    KylinTicketRelations ticket = t3.get(y);
                    KylinTickets t1 = ticketsMapper.selectOne(new UpdateWrapper<KylinTickets>().eq("tickets_id", ticket.getTicketId()));
                    KylinTicketStatus t2 = ticketStatusMapper.selectOne(new UpdateWrapper<KylinTicketStatus>().eq("ticket_id", ticket.getTicketId()));
//                    if(t2.getStatus()==7){
//                        continue;
//                    }
                    KylinTicketVo kylinTicketVo = new KylinTicketVo();
                    kylinTicketVo.setTimeId(ticket.getTimesId());
                    kylinTicketVo.setTicket(t1);
                    kylinTicketVo.setTicketStatus(t2);
                    ticketList.add(kylinTicketVo);

//                    //票种 库存redis
//                    if (!redisUtil.hHasKey(KylinRedisConst.PERFORMANCES_INVENTORY + kylinTicketVo.getTicketsId(), KylinRedisConst.SURPLUS_GENERAL)) {
//                        dataUtils.setSurplusGeneral(kylinTicketVo.getTicketsId(), t2.getTotalGeneral());
//                        dataUtils.setSurplusExchange(kylinTicketVo.getTicketsId(), t2.getSurplusExchange());
//                    }

                    if (kylinTicketVo.getIsMember() == 1) {
                        if (kylinTicketVo.getMemberPrice().compareTo(kylinTicketVo.getPrice()) != 0) {
                            isDiscount = 1;
                        }

                        if (DateUtil.compareStrDay(DateUtil.getNowTime(), kylinTicketVo.getMemberTimeStart()) < 0) {
                            isAdvance = 1;
                        }
                        if (kylinTicketVo.getIsMember() == 1) {
                            isMember = 1;
                        }
                        if (kylinTicketVo.getIsExclusive() == 1) {
                            isExclusive = 1;
                        }

                        if (isAdvance == 0 && isDiscount == 0 && isExclusive == 0) {
                            isMember = 0;
                        }
                    }
                    if (kylinTicketVo.getIsLackRegister() == 1) {
                        isLackRegister = 1;
                    }
                    payCountdownMinute = t1.getPayCountdownMinute();
                    if (price.compareTo(new BigDecimal("0.00")) == 0) {
                        price = kylinTicketVo.getPrice();
                    } else {
                        if (kylinTicketVo.getPrice().compareTo(price) < 0) {
                            price = kylinTicketVo.getPrice();
                        }
                    }
                    if ((stopSellTime == null || stopSellTime.isBefore(t1.getTimeEnd())) && (t2.getStatus() >= 6 && t2.getStatus() != 7)) {
                        stopSellTime = t1.getTimeEnd();
                    }
                    if ((sellMemberTime == null || sellMemberTime.isAfter(t1.getTimeStart().plusMinutes(-t1.getAdvanceMinuteMember()))) && (t2.getStatus() >= 6 && t2.getStatus() != 7)) {
                        sellMemberTime = t1.getTimeStart().plusMinutes(-t1.getAdvanceMinuteMember());
                    }
                    if ((sellTime == null || sellTime.isAfter(t1.getTimeStart())) && (t2.getStatus() >= 6 && t2.getStatus() != 7)) {
                        sellTime = t1.getTimeStart();
                    }
                }

//                if(ticketList.size()>0) {
                KylinTicketTimesVo kylinTicketTimesVo = new KylinTicketTimesVo();
                kylinTicketTimesVo.setTicketTimes(tt1);
                kylinTicketTimesVo.setPerformanceId(times.getPerformanceId());
                kylinTicketTimesVo.setTimeId(times.getTimesId());
                kylinTicketTimesVo.setTicketList(ticketList);
                timeList.add(kylinTicketTimesVo);
//                }
            }

            voData.setPerformance(p1);
            voData.setPerformanceStatus(p2);
            voData.setPerformanceRelations(p3);
            voData.setFieldsData(fields, cityName);
            if (stopSellTime == null) {
                stopSellTime = DateUtil.Formatter.yyyyMMddHHmmss.parse("2030-12-01 12:00:00");
            }
            if (sellTime == null) {
                sellTime = DateUtil.Formatter.yyyyMMddHHmmss.parse("2030-12-01 12:00:00");
            }
            if (sellMemberTime == null) {
                sellMemberTime = DateUtil.Formatter.yyyyMMddHHmmss.parse("2030-12-01 12:00:00");
            }

            voData.setTimePriceVipAndLack(isLackRegister, isMember, isExclusive, price, stopSellTime, sellMemberTime, sellTime, isAdvance, isDiscount, payCountdownMinute);
            voData.setTicketTimeList(timeList);
            voData.setAppStatus(p2.getStatus());
            return voData;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @param userId  用户id
     * @param type    1新增 2修改
     * @param orderId 订单id [需要新增或者修改的订单id]
     */
    public Boolean resetOrderListVo(String userId, Integer type, String orderId, KylinOrderTicketVo dataSingle) {
        List<KylinOrderListVo> vo = new ArrayList<>();
        List<KylinOrderListVo> redisVo = new ArrayList();
        KylinOrderListVo voItem = new KylinOrderListVo();
        KylinOrderTicketVo data;
        if (dataSingle == null) {
            data = dataUtils.getOrderTicketVo(orderId);
        } else {
            data = dataSingle;
        }
        BeanUtils.copyProperties(data, voItem);
        List<KylinOrderListVo> redisData = dataUtils.getOrderList(userId);
        if (type == 1) {
            redisVo.add(voItem);
            if (redisData.size() > 0) {
                if (redisData.get(0).getOrderTicketsId().equals(orderId)) {
                    redisData.remove(0);
                }
            }
        }

        redisVo.addAll(redisData);

        switch (type) {
            case 1:
                for (int i = 0; i < redisVo.size(); i++) {
                    if (i == 40) {
                        break;
                    }
                    if (i == 0) {
                        vo.add(voItem);
                    } else {
                        vo.add(redisVo.get(i));
                    }
                }
                if (redisVo.size() == 0) {
                    vo.add(voItem);
                }
                dataUtils.setOrderList(userId, vo);
                return true;
            case 2:
                for (int i = 0; i < redisVo.size(); i++) {
                    if (i == 40) {
                        break;
                    }
                    if (redisVo.get(i).getOrderTicketsId().equals(orderId)) {
                        vo.add(voItem);
                    } else {
                        vo.add(redisVo.get(i));
                    }
                }
                dataUtils.setOrderList(userId, vo);
                return true;
            default:
                return false;
        }
    }
}
