package com.liquidnet.service.kylin.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.IDCard;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.adam.dto.vo.AdamAddressesVo;
import com.liquidnet.service.adam.dto.vo.AdamEntersVo;
import com.liquidnet.service.adam.entity.AdamEnters;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.feign.adam.api.FeignAdamBaseClient;
import com.liquidnet.service.kylin.constant.KylinRedisConst;
import com.liquidnet.service.kylin.dto.param.PayOrderParam;
import com.liquidnet.service.kylin.dto.vo.KylinPerformanceVo;
import com.liquidnet.service.kylin.dto.vo.KylinTicketTimesVo;
import com.liquidnet.service.kylin.dto.vo.KylinTicketVo;
import com.liquidnet.service.kylin.entity.KylinOrderTickets;
import com.liquidnet.service.kylin.entity.KylinTicketTimes;
import com.liquidnet.service.kylin.mapper.KylinOrderTicketsMapper;
import com.liquidnet.service.kylin.service.IKylinOrderTicketsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.service.kylin.utils.DataUtils;
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.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-05-20
 */
@Service
public class KylinOrderTicketsServiceImpl extends ServiceImpl<KylinOrderTicketsMapper, KylinOrderTickets> implements IKylinOrderTicketsService {

    @Autowired
    private DataUtils dataUtils;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private FeignAdamBaseClient feignAdamBaseClient;

    @Override
    public boolean checkCanOrder(PayOrderParam payOrderParam) {
        String uid = CurrentUtil.getCurrentUid();
        KylinPerformanceVo performanceData = mongoTemplate.findOne(Query.query(Criteria.where("performancesId").is(payOrderParam.getPerformanceId())), KylinPerformanceVo.class, KylinPerformanceVo.class.getSimpleName());
        KylinTicketTimesVo ticketTimesData = mongoTemplate.findOne(Query.query(Criteria.where("ticketTimesId").is(payOrderParam.getTimeId())), KylinTicketTimesVo.class, KylinTicketTimes.class.getSimpleName());
        KylinTicketVo ticketData = mongoTemplate.findOne(Query.query(Criteria.where("ticketsId").is(payOrderParam.getTicketId())), KylinTicketVo.class, KylinTicketVo.class.getSimpleName());
        if (performanceData == null || ticketTimesData == null || ticketData == null) {
            return false;//参数错误
        }
        if (!ticketData.getTimeId().equals(payOrderParam.getTimeId()) || !ticketTimesData.getPerformanceId().equals(payOrderParam.getPerformanceId())) {
            return false;//参数错误
        }
        //会员时间获取
        String memberTimeStart = ticketData.getMemberTimeStart(); // 会员开售时间
        String timeStart = ticketData.getTimeStart(); // 普通开售时间
        String timeEnd = ticketData.getTimeEnd(); // 购票停售时间
        String timeExpressEnd = ticketData.getTimeEndExpress(); // 快递停售时间
        int performanceBuyCount = 0; //演出下所有票种购买数量
        int ticketBuyCount = 0; // 单一票种购买数量
        boolean isMember = false;//获取是否是会员 TODO
        int memberType; //会员状态 不需要判断会员 1判断会员逻辑 2会员专属
        if (ticketData.getIsExclusive() == 1) {
            memberType = 2;
            if (!isMember) {
                return false;//没有会员权限
            }
        } else {
            if (DateUtil.compareStrDay(DateUtil.getNowTime(), memberTimeStart) == 1 && DateUtil.compareStrDay(DateUtil.getNowTime(), timeStart) == -1 && ticketData.getIsMember() == 1) {
                // 会员购买逻辑
                memberType = 1;
                if (!isMember) {
                    return false;//没有会员权限
                }
            } else {
                // 普通用户购买逻辑
                memberType = 0;
            }
        }

        // 获取限购 实名
        int ticketLimit = ticketData.getLimitCount();//普通票种限购
        int ticketMemberLimit = ticketData.getLimitCountMember();//会员票种限购
        int performanceLimit = performanceData.getLimitCount();//普通演出限购
        int performanceMemberLimit = performanceData.getLimitCountMember();//会员演出限购
        int isTrueName = performanceData.getIsTrueName();//是否演出实名

        //通用判断时间
        if (isMember) {
            if (DateUtil.compareStrDay(DateUtil.getNowTime(), memberTimeStart) == -1) {
                return false;//未开始
            }
        } else {
            if (DateUtil.compareStrDay(DateUtil.getNowTime(), timeStart) == -1) {
                return false;//未开始
            }
        }
        if (DateUtil.compareStrDay(DateUtil.getNowTime(), timeEnd) == 1) {
            return false;//已结束
        }

        //快递票判断
        if (payOrderParam.getIsExpress() == 1 && DateUtil.compareStrDay(DateUtil.getNowTime(), timeExpressEnd) == 1) {
            return false;//快递票不卖
        }
        if (payOrderParam.getIsExpress() == 1 && payOrderParam.getAddressId().isEmpty()) {
            return false;//快递票未填写收货地址
        }
        //实名判断
        if (isTrueName == 1 && payOrderParam.getEnterIdList().size() <= 0) {
            return false;//需要实名 未实名
        }
        if (isTrueName == 1 && payOrderParam.getEnterIdList().size() != payOrderParam.getNumber()) {
            return false;//入场人数量错误
        }
        //学生票 判断
        if (payOrderParam.getIsStudent() == 1) {
            for (String enterId : payOrderParam.getEnterIdList()) {
                AdamEntersVo adamEnters = feignAdamBaseClient.queryEnters(enterId, uid).getData();
                int age = IDCard.getAgeByIdCard(adamEnters.getIdCard());
                if (age > 25) {
                    return false;//年龄超了
                }
            }
        }
        //限购判断 如果实名 则身份证维度限购 如果不实名则数量限购
        if (performanceData.getIsTrueName() == 1) {
            //已购买数量 身份证
            performanceBuyCount = 0; //演出下所有票种购买数量 TODO
            ticketBuyCount = 0; // 单一票种购买数量 TODO
        } else {
            //已购买数量 数量
            performanceBuyCount = 0; //演出下所有票种购买数量 TODO
            ticketBuyCount = 0; // 单一票种购买数量 TODO
        }
        //会员区间
        if (memberType == 1 || memberType == 2) {
            if (performanceBuyCount >= performanceMemberLimit && performanceMemberLimit != 0) {
                return false;//超过演出维度购买量
            }
            if (ticketBuyCount >= ticketMemberLimit && ticketMemberLimit != 0) {
                return false;//超过票维度购买量
            }
        } else {//非会员区间
            if (performanceBuyCount >= performanceLimit && performanceLimit != 0) {
                return false;//超过演出维度购买量
            }
            if (ticketBuyCount >= ticketLimit && ticketLimit != 0) {
                return false;//超过票维度购买量
            }
        }

        // 判断库存
        int surplusGeneral = dataUtils.changeSurplusGeneral(payOrderParam.getTicketId(), -payOrderParam.getNumber());
        if (surplusGeneral < 0) {//库存回滚
            dataUtils.changeSurplusGeneral(payOrderParam.getTicketId(), payOrderParam.getNumber());
            return false;//没抢到
        }

        //生成订单
        KylinOrderTickets orderTickets = new KylinOrderTickets();
        orderTickets.setOrderTicketsId(IDGenerator.nextSnowId().toString());
        orderTickets.setUserId(uid);
//        orderTickets.setUserName();
//        orderTickets.setUserMobile();
        orderTickets.setPerformanceTitle(performanceData.getTitle());
//        orderTickets.setOrderCode();
//        orderTickets.setQrCode();
//        orderTickets.setOrderType();
//        orderTickets.setOrderVersion();
        orderTickets.setNumber(payOrderParam.getNumber());
        orderTickets.setPrice(ticketData.getPrice());
        orderTickets.setPriceMember(ticketData.getMemberPrice());
//        orderTickets.setPriceTotal();
        orderTickets.setPriceVoucher(new BigDecimal("0.0"));
        orderTickets.setPriceActual(new BigDecimal("0.0"));
        orderTickets.setPriceExpress(ticketData.getPriceExpress());
        orderTickets.setPriceRefund(new BigDecimal("0.0"));
        orderTickets.setRefundNumber(0);
        orderTickets.setPayType(payOrderParam.getPayType());
        orderTickets.setPaymentType(null);
        orderTickets.setTimePay(null);
        if (ticketData.getIsExpress() == 1) {
            AdamAddressesVo addressesVo = feignAdamBaseClient.queryAddresses(payOrderParam.getAddressId(), uid).getData();
            orderTickets.setExpressContacts(addressesVo.getName());
            orderTickets.setExpressAddress(addressesVo.getAddress());
            orderTickets.setExpressPhone(addressesVo.getPhone());
            orderTickets.setGetTicketType("express");
        } else {
            orderTickets.setExpressContacts("");
            orderTickets.setExpressAddress("");
            orderTickets.setExpressPhone("");
            orderTickets.setGetTicketType("electronic");
        }
        orderTickets.setCouponType("no");
        orderTickets.setGetTicketDescribe("");
//        orderTickets.setPayCountdownMinute();
        orderTickets.setCreatedAt(LocalDateTime.now());
        orderTickets.setUpdatedAt(null);

        //生成票
        return true;
    }
}
