package com.liquidnet.service.merchant.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.ErrorMapping;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.base.UserPathDto;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.kylin.dto.param.PerformancePartnerVo;
import com.liquidnet.service.kylin.dto.param.TicketCreateParam;
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.KylinPerformanceVo;
import com.liquidnet.service.kylin.dto.vo.partner.KylinTicketPartnerVo;
import com.liquidnet.service.kylin.dto.vo.partner.KylinTicketTimesPartnerVo;
import com.liquidnet.service.kylin.entity.*;
import com.liquidnet.service.kylin.mapper.*;
import com.liquidnet.service.kylin.service.partner.IKylinTicketsPartnerService;
import com.liquidnet.service.merchant.util.*;
import com.mongodb.BasicDBObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * 票 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-05-06
 */
@Service
@Slf4j
public class KylinTicketsPartnerServiceImpl implements IKylinTicketsPartnerService {

    @Autowired
    RedisMerchantUtils redisMerchantUtils;
    @Autowired
    MongoMerchantUtils mongoMerchantUtils;
    @Autowired
    PerformanceUtils performanceUtils;
    @Autowired
    QueueUtil queueUtil;

    @Override
    public ResponseDto<KylinTicketPartnerVo> createTicketSummary(TicketCreateParam ticketCreateParam) {
        ResponseDto<KylinTicketPartnerVo> ticketPartnerVo;
        //获取演出状态
        KylinTicketTimesPartnerVo timesPartnerVo = mongoMerchantUtils.getTicketTimesPartnerVo(ticketCreateParam.getTimesId());
        if (null != timesPartnerVo) {
            KylinPerformanceVo vo = mongoMerchantUtils.getPerformanceVo(timesPartnerVo.getPerformancesId());
            if (null == vo) {
                ticketPartnerVo = createTicket(ticketCreateParam);
                log.info(UserPathDto.setPartnerData("0", "createTicket", ticketCreateParam, ticketPartnerVo));
            } else if (vo.getAppStatus() >= 3 && vo.getAppStatus() != 4) {//未被拒绝 且 通过审核的演出
                ticketPartnerVo = addNewTicket(ticketCreateParam);
                log.info(UserPathDto.setPartnerData("0", "addNewTicket", ticketCreateParam, ticketPartnerVo));
            } else {
                ticketPartnerVo = createTicket(ticketCreateParam);
                log.info(UserPathDto.setPartnerData("0", "createTicket", ticketCreateParam, ticketPartnerVo));
            }
        } else {
            ticketPartnerVo = createTicket(ticketCreateParam);
            log.info(UserPathDto.setPartnerData("0", "createTicket", ticketCreateParam, ticketPartnerVo));
        }
        return ticketPartnerVo;
    }

    @Override
    public ResponseDto<KylinTicketPartnerVo> createTicket(TicketCreateParam ticketCreateParam) {
        try {
            // 获取 主键id
            String ticketsId = IDGenerator.nextSnowId();
            // 获取 当前时间 -> 创建时间
            LocalDateTime createdAt = LocalDateTime.now();
            ticketCreateParam.setTicketsId(ticketsId);
            // mongo 操作
            KylinTicketPartnerVo kylinTicketPartnerVo = KylinTicketPartnerVo.getNew();
            BeanUtils.copyProperties(ticketCreateParam, kylinTicketPartnerVo);
            kylinTicketPartnerVo.setTicketsId(ticketsId);
            kylinTicketPartnerVo.setCreatedAt(DateUtil.Formatter.yyyyMMddHHmmss.format(createdAt));
            kylinTicketPartnerVo.setTimeStart(DateUtil.Formatter.yyyyMMddHHmmss.format(ticketCreateParam.getTimeStart()));
            kylinTicketPartnerVo.setTimeEnd(ticketCreateParam.getTimeEnd().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

            KylinTicketTimesPartnerVo kylinTicketTimesPartnerVo = mongoMerchantUtils.getTicketTimesPartnerVo(ticketCreateParam.getTimesId());
            kylinTicketPartnerVo.setUseStart(kylinTicketTimesPartnerVo.getUseStart());
            kylinTicketPartnerVo.setUseEnd(kylinTicketTimesPartnerVo.getUseEnd());
            kylinTicketPartnerVo.setType(kylinTicketTimesPartnerVo.getType());
            kylinTicketPartnerVo.setStatus(0);
            kylinTicketPartnerVo.setDefault();
            if (ticketCreateParam.getIsExpress() == 1) {
                kylinTicketPartnerVo.setDescribeExpress(ticketCreateParam.getDescribeExpress() == null ? "" : ticketCreateParam.getDescribeExpress());
            } else {
                kylinTicketPartnerVo.setDescribeExpress("");
            }
            if (ticketCreateParam.getIsElectronic() == 1) {
                kylinTicketPartnerVo.setDescribeElectronic(ticketCreateParam.getDescribeElectronic() == null ? "" : ticketCreateParam.getDescribeElectronic());
            } else {
                kylinTicketPartnerVo.setDescribeElectronic("");
            }

            if (ticketCreateParam.getIsExpress() == 1) {
                kylinTicketPartnerVo.setTimeEndExpress(ticketCreateParam.getTimeEndExpress().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }

            if (ticketCreateParam.getIsShowCode() == 1) {
                kylinTicketPartnerVo.setQrCodeShowTime(ticketCreateParam.getQrCodeShowTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }

            mongoMerchantUtils.insertTicketPartnerVo(kylinTicketPartnerVo);
            return ResponseDto.success(kylinTicketPartnerVo);
        } catch (Exception e) {
            log.info(UserPathDto.setPartnerData("0", "createTicket", ticketCreateParam, e));
            return ResponseDto.failure(ErrorMapping.get(20105));
        }
    }

    @Override
    public ResponseDto<KylinTicketPartnerVo> addNewTicket(TicketCreateParam ticketCreateParam) {
        try {
            // 获取 主键id
            String ticketsId = IDGenerator.nextSnowId();
            // 获取 当前时间 -> 创建时间
            LocalDateTime createdAt = LocalDateTime.now();
            ticketCreateParam.setTicketsId(ticketsId);

            // mongo 操作
            KylinTicketPartnerVo kylinTicketPartnerVo = KylinTicketPartnerVo.getNew();
            BeanUtils.copyProperties(ticketCreateParam, kylinTicketPartnerVo);
            kylinTicketPartnerVo.setTicketsId(ticketsId);
            kylinTicketPartnerVo.setCreatedAt(createdAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            kylinTicketPartnerVo.setTimeStart(ticketCreateParam.getTimeStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            kylinTicketPartnerVo.setTimeEnd(ticketCreateParam.getTimeEnd().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

            KylinTicketTimesPartnerVo kylinTicketTimesPartnerVo = mongoMerchantUtils.getTicketTimesPartnerVo(ticketCreateParam.getTimesId());
            kylinTicketPartnerVo.setUseStart(kylinTicketTimesPartnerVo.getUseStart());
            kylinTicketPartnerVo.setUseEnd(kylinTicketTimesPartnerVo.getUseEnd());
            kylinTicketPartnerVo.setType(kylinTicketTimesPartnerVo.getType());
            if (ticketCreateParam.getIsExpress() == 1) {
                kylinTicketPartnerVo.setDescribeExpress(ticketCreateParam.getDescribeExpress() == null ? "" : ticketCreateParam.getDescribeExpress());
            } else {
                kylinTicketPartnerVo.setDescribeExpress("");
            }
            if (ticketCreateParam.getIsElectronic() == 1) {
                kylinTicketPartnerVo.setDescribeElectronic(ticketCreateParam.getDescribeElectronic() == null ? "" : ticketCreateParam.getDescribeElectronic());
            } else {
                kylinTicketPartnerVo.setDescribeElectronic("");
            }

            kylinTicketPartnerVo.setStatus(-2);
            kylinTicketPartnerVo.setDefault();

            if (ticketCreateParam.getIsExpress() == 1) {
                kylinTicketPartnerVo.setTimeEndExpress(ticketCreateParam.getTimeEndExpress().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }

            if (ticketCreateParam.getIsShowCode() == 1) {
                kylinTicketPartnerVo.setQrCodeShowTime(ticketCreateParam.getQrCodeShowTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }

            mongoMerchantUtils.insertTicketPartnerVo(kylinTicketPartnerVo);
            return ResponseDto.success(kylinTicketPartnerVo);
        } catch (Exception e) {
            log.info(UserPathDto.setPartnerData("0", "addNewTicket", ticketCreateParam, e));
            return ResponseDto.failure(ErrorMapping.get(20101));
        }
    }

    @Override
    public ResponseDto<KylinTicketPartnerVo> updateTicket(TicketCreateParam ticketCreateParam) {
        try {
            KylinTicketTimesPartnerVo ticketTimeRelation = mongoMerchantUtils.getTicketTimesPartnerVo(ticketCreateParam.getTimesId());
            PerformancePartnerVo data = mongoMerchantUtils.getPerformancePartnerVo(ticketTimeRelation.getPerformancesId());
            if (data == null || data.getAuditStatus() == null || data.getAuditStatus() == 0) {
                return ResponseDto.failure(ErrorMapping.get("20112"));
            }
            String ticketId = ticketCreateParam.getTicketsId();
            LocalDateTime updatedAt = LocalDateTime.now();
            // mongo 操作
            KylinTicketPartnerVo kylinTicketPartnerVo = KylinTicketPartnerVo.getNew();
            BeanUtils.copyProperties(ticketCreateParam, kylinTicketPartnerVo);
            kylinTicketPartnerVo.setUpdatedAt(updatedAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            kylinTicketPartnerVo.setTimeStart(ticketCreateParam.getTimeStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            kylinTicketPartnerVo.setTimeEnd(ticketCreateParam.getTimeEnd().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            kylinTicketPartnerVo.setTimesId(null);
            kylinTicketPartnerVo.setStatus(null);
            if (ticketCreateParam.getIsExpress() == 1) {
                kylinTicketPartnerVo.setDescribeExpress(ticketCreateParam.getDescribeExpress() == null ? "" : ticketCreateParam.getDescribeExpress());
            }
            if (ticketCreateParam.getIsElectronic() == 1) {
                kylinTicketPartnerVo.setDescribeElectronic(ticketCreateParam.getDescribeElectronic() == null ? "" : ticketCreateParam.getDescribeElectronic());
            }

            kylinTicketPartnerVo.setDefault();
            if (ticketCreateParam.getIsExpress() == 1) {
                kylinTicketPartnerVo.setTimeEndExpress(ticketCreateParam.getTimeEndExpress().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
            if (ticketCreateParam.getIsShowCode() == 1) {
                kylinTicketPartnerVo.setQrCodeShowTime(ticketCreateParam.getQrCodeShowTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }

            mongoMerchantUtils.updateTicketPartnerVo(kylinTicketPartnerVo);
//            KylinTicketPartnerVo kylinTicketPartnerVoData = JsonUtils.fromJson(doc.toJson(), KylinTicketPartnerVo.class);
            log.info(UserPathDto.setPartnerData("0", "updateTicket", ticketCreateParam, "SUCCESS"));
            return ResponseDto.success(null);
        } catch (Exception e) {
            e.printStackTrace();
            log.info(UserPathDto.setPartnerData("0", "updateTicket", ticketCreateParam, e));
            return ResponseDto.failure(ErrorMapping.get(20103));
        }
    }

    @Override
    public ResponseDto<String> deleteTicket(String ticketsId, String performanceId) {
        try {
            LocalDateTime updatedAt = LocalDateTime.now();
            KylinPerformanceVo vo = mongoMerchantUtils.getPerformanceVo(performanceId);
            KylinTicketTimesVo ticketTimesData;
            KylinTicketVo ticketData = null;
            for (int x = 0; x < vo.getTicketTimeList().size(); x++) {
                ticketTimesData = vo.getTicketTimeList().get(x);
                for (int y = 0; y < ticketTimesData.getTicketList().size(); y++) {
                    KylinTicketVo ticketItem = ticketTimesData.getTicketList().get(y);
                    if (ticketItem.getTicketsId().equals(ticketsId)) {
                        ticketData = ticketItem;
                        break;
                    }
                }
                break;
            }

            if (ticketData == null) {
                mongoMerchantUtils.deleteTicketPartnerVo(ticketsId);
                return ResponseDto.success("删除成功");
            }
            PerformancePartnerVo data = mongoMerchantUtils.getPerformancePartnerVo(performanceId);
            if (data == null || data.getAuditStatus() == null || data.getAuditStatus() == 0) {
                return ResponseDto.failure(ErrorMapping.get("20106"));
            }


            if (vo.getAppStatus() == 0 || vo.getAppStatus() == 4) {//未提审||被拒绝
                // mongo 操作
                KylinTicketPartnerVo ticketPartnerVo = KylinTicketPartnerVo.getNew();
                ticketPartnerVo.setUpdatedAt(updatedAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                ticketPartnerVo.setStatus(-1);
                mongoMerchantUtils.updateTicketPartnerVo(ticketPartnerVo);
                log.info(UserPathDto.setPartnerData("0", "deleteTicket", "ticketsId=" + ticketsId, "删除成功"));
                return ResponseDto.success("删除成功");
            } else {
                return ResponseDto.failure(ErrorMapping.get(20106));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(UserPathDto.setPartnerData("0", "deleteTicket", "ticketsId=" + ticketsId, e));
            return ResponseDto.failure(ErrorMapping.get(20102));
        }
    }

    @Override
    public ResponseDto<KylinTicketPartnerVo> copyTicket(String performanceId, String ticketsId) {
        try {
            // 获取 当前时间 -> 创建时间
            LocalDateTime createdAt = LocalDateTime.now();
            PerformancePartnerVo performancePartnerVo = mongoMerchantUtils.getPerformancePartnerVo(performanceId);
            if (performancePartnerVo.getAuditStatus() == 0 || performancePartnerVo.getAuditStatus() == 1) {
                return ResponseDto.failure(ErrorMapping.get(20107));
            }
            KylinTicketPartnerVo kylinTicketPartnerVo = mongoMerchantUtils.getTicketPartnerVo(ticketsId);
            kylinTicketPartnerVo.setCreatedAt(createdAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            kylinTicketPartnerVo.setTicketsId(IDGenerator.nextSnowId());

            KylinTicketPartnerVo data = mongoMerchantUtils.insertTicketPartnerVo(kylinTicketPartnerVo);
            log.info(UserPathDto.setPartnerData("0", "deleteTicket", "performanceId=" + performanceId + ",ticketsId=" + ticketsId, kylinTicketPartnerVo));
            return ResponseDto.success(kylinTicketPartnerVo);
        } catch (Exception e) {
            e.printStackTrace();
            log.info(UserPathDto.setPartnerData("0", "deleteTicket", "performanceId=" + performanceId + ",ticketsId=" + ticketsId, e));
            return ResponseDto.failure(ErrorMapping.get(20107));
        }
    }

    @Override
    public boolean submitTicketByTimes(String timesId, Integer status) {
        LocalDateTime updatedAt = LocalDateTime.now();
        KylinTicketPartnerVo ticketPartnerVo = KylinTicketPartnerVo.getNew();
        ticketPartnerVo.setTimesId(timesId);
        if (null == status) {
            ticketPartnerVo.setStatus(1);
        } else {
            ticketPartnerVo.setStatus(status);
        }
        ticketPartnerVo.setUpdatedAt(updatedAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        mongoMerchantUtils.submitTicketByTimes(ticketPartnerVo);
        long count = mongoMerchantUtils.getCountTicketPartnerByTimes(timesId);
        return count <= 0;
    }

    @Override
    public List<KylinTicketPartnerVo> getTicketMongoList(String timesId) {
        return mongoMerchantUtils.getTicketMongoList(timesId);
    }

    @Override
    public KylinTicketPartnerVo getTicketsMongo(String ticketsId) {
        return mongoMerchantUtils.getTicketsMongo(ticketsId);
    }

    @Override
    public ResponseDto<String> onLine(String ticketsId, String performancesId) {
        try {
            LocalDateTime updatedAt = LocalDateTime.now();
            KylinPerformanceVo vo = mongoMerchantUtils.getPerformanceVo(performancesId);
            KylinTicketTimesVo ticketTimesData;
            KylinTicketVo ticketData = null;
            for (int x = 0; x < vo.getTicketTimeList().size(); x++) {
                ticketTimesData = vo.getTicketTimeList().get(x);
                for (int y = 0; y < ticketTimesData.getTicketList().size(); y++) {
                    KylinTicketVo ticketItem = ticketTimesData.getTicketList().get(y);
                    if (ticketItem.getTicketsId().equals(ticketsId)) {
                        ticketData = ticketItem;
                        break;
                    }
                }
                break;
            }

            if (ticketData != null && ticketData.getStatus() >= 3 && ticketData.getStatus() != 4 && ticketData.getStatus() != 6) {//未提审||被拒绝
                //mysql
                queueUtil.sendMsgByRedis(MQConst.MerchantQueue.SQL_MERCHANT_TICKET_UPDATE.getKey(),
                        SqlMapping.get("kylin_ticket_status.update_status",
                                9, updatedAt, ticketsId, updatedAt, updatedAt
                        ));
                //mongo
                KylinTicketPartnerVo ticketPartnerVo = KylinTicketPartnerVo.getNew();
                ticketPartnerVo.setTicketsId(ticketsId);
                ticketPartnerVo.setStatus(9);
                mongoMerchantUtils.updateTicketPartnerVo(ticketPartnerVo);
                performanceUtils.performanceVoStatus(performancesId);
                log.info(UserPathDto.setPartnerData("0", "onLine", "performancesId=" + performancesId + ",ticketsId=" + ticketsId, "上线成功"));
                return ResponseDto.success("上线成功");
            } else {
                return ResponseDto.failure(ErrorMapping.get(20110));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(UserPathDto.setPartnerData("0", "onLine", "performancesId=" + performancesId + ",ticketsId=" + ticketsId, "上线失败"));
            return ResponseDto.failure(ErrorMapping.get(20108));
        }
    }

    @Override
    public ResponseDto<String> outLine(String ticketsId, String performancesId) {
        try {
            LocalDateTime updatedAt = LocalDateTime.now();
            KylinPerformanceVo vo = mongoMerchantUtils.getPerformanceVo(performancesId);
            KylinTicketTimesVo ticketTimesData;
            KylinTicketVo ticketData = null;
            for (int x = 0; x < vo.getTicketTimeList().size(); x++) {
                ticketTimesData = vo.getTicketTimeList().get(x);
                for (int y = 0; y < ticketTimesData.getTicketList().size(); y++) {
                    KylinTicketVo ticketItem = ticketTimesData.getTicketList().get(y);
                    if (ticketItem.getTicketsId().equals(ticketsId)) {
                        ticketData = ticketItem;
                        break;
                    }
                }
                break;
            }
            if (ticketData != null && ticketData.getStatus() >= 3 && ticketData.getStatus() != 4 && ticketData.getStatus() != 7) {//未提审||被拒绝
                //mysql
                queueUtil.sendMsgByRedis(MQConst.MerchantQueue.SQL_MERCHANT_TICKET_UPDATE.getKey(),
                        SqlMapping.get("kylin_ticket_status.update_status",
                                7, updatedAt, ticketsId, updatedAt, updatedAt
                        ));
                // mongo 操作
                KylinTicketPartnerVo ticketPartnerVo = KylinTicketPartnerVo.getNew();
                ticketPartnerVo.setTicketsId(ticketsId);
                ticketPartnerVo.setStatus(7);
                mongoMerchantUtils.updateTicketPartnerVo(ticketPartnerVo);
                performanceUtils.performanceVoStatus(performancesId);
                log.info(UserPathDto.setPartnerData("0", "outLine", "performancesId=" + performancesId + ",ticketsId=" + ticketsId, "下线成功"));
                return ResponseDto.success("下线成功");
            } else {
                return ResponseDto.failure(ErrorMapping.get(20111));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(UserPathDto.setPartnerData("0", "outLine", "performancesId=" + performancesId + ",ticketsId=" + ticketsId, "下线失败"));
            return ResponseDto.failure(ErrorMapping.get(20109));
        }
    }

}
