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

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.liquidnet.common.cache.redis.util.RedisDataSourceUtil;
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 com.liquidnet.service.slime.dto.vo.SlimeFieldsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
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.data.mongodb.core.query.Update;
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 RedisDataSourceUtil redisDataSourceUtil;
    @Autowired
    private DataUtils dataUtils;
    @Autowired
    private MongoTemplate mongoTemplate;

    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();
            SlimeFieldsVo fieldsVo =  dataUtils.getFieldsVoByFieldId(p3.getFieldId());
            String cityName =fieldsVo.getCityName();
            fields.setCityId(Integer.parseInt(fieldsVo.getCityId()));
            fields.setLatitude(fieldsVo.getLatitude());
            fields.setLongitude(fieldsVo.getLongitude());
            fields.setCityName(cityName);
            fields.setName(fieldsVo.getName());

            //相关状态时间初始变量
            LocalDateTime stopSellTime = null;
            LocalDateTime sellMemberTime = null;
            LocalDateTime sellTime = 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()));
                    KylinTicketVo kylinTicketVo = new KylinTicketVo();
                    kylinTicketVo.setTimeId(ticket.getTimesId());
                    kylinTicketVo.setTicket(t1);
                    kylinTicketVo.setTicketStatus(t2);
                    ticketList.add(kylinTicketVo);

                    //票种 库存redis
//                    if (!redisDataSourceUtil.getRedisKylinUtil().hasKey(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 (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())) {
                        stopSellTime = t1.getTimeEnd();
                    }
                    if (sellMemberTime == null || sellMemberTime.isAfter(t1.getTimeStart().plusMinutes(-t1.getAdvanceMinuteMember()))) {
                        sellMemberTime = t1.getTimeStart().plusMinutes(-t1.getAdvanceMinuteMember());
                    }
                    if (sellTime == null || sellTime.isAfter(t1.getTimeStart())) {
                        sellTime = t1.getTimeStart();
                    }
                }

                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);
            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 = (KylinOrderTicketVo) dataUtils.getOrderTicketVo(orderId);
//            data = (KylinOrderTicketVo) redisDataSourceUtil.getRedisKylinUtil().get(KylinRedisConst.ORDER + orderId);
        } else {
            data = dataSingle;
        }
        BeanUtils.copyProperties(data, voItem);
        List<KylinOrderListVo> redisData = (List<KylinOrderListVo>) dataUtils.getOrderList(userId);
//        List<KylinOrderListVo> redisData = (List<KylinOrderListVo>) redisDataSourceUtil.getRedisKylinUtil().get(KylinRedisConst.ORDER_LIST + 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);
                }
                redisDataSourceUtil.getRedisKylinUtil().set(KylinRedisConst.ORDER_LIST + 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));
                    }
                }
                redisDataSourceUtil.getRedisKylinUtil().set(KylinRedisConst.ORDER_LIST + userId, vo);
                return true;
            default:
                return false;
        }
    }
    /**
     * 修改收货人手机号
     * @param orderCode  订单编号
     * @param expressPhone    收货人手机号
     */
    public void orderSetMongo(String orderCode, String expressPhone ){
        Query query = Query.query(Criteria.where("orderCode").is(orderCode));
        Update update = Update.update("expressPhone",expressPhone);;
        mongoTemplate.updateFirst(query,update,KylinOrderTicketVo.class,KylinOrderTicketVo.class.getSimpleName());
    }
}
