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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.common.cache.redis.util.RedisUtil;
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.kylin.dto.param.PerformanceCreateParam;
import com.liquidnet.service.kylin.dto.vo.partner.PerformanceCreatePartnerVo;
import com.liquidnet.service.kylin.dto.vo.partner.TicketTimesTicketCreatePartnerVo;
import com.liquidnet.service.kylin.dto.vo.partner.TicketTimesCreatePartnerVo;
import com.liquidnet.service.kylin.dto.vo.partner.TicketCreatePartnerVo;
import com.liquidnet.service.kylin.entity.*;
import com.liquidnet.service.kylin.mapper.*;
import com.liquidnet.service.kylin.service.admin.IKylinPerformancesAdminService;
import com.liquidnet.service.kylin.service.impl.partner.KylinTicketTimesPartnerServiceImpl;
import com.liquidnet.service.kylin.service.impl.partner.KylinTicketsPartnerServiceImpl;
import com.mongodb.BasicDBObject;
import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.model.ReturnDocument;
import org.bson.Document;
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.convert.MongoConverter;
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.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 演出 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-05-05
 */
@Service
public class KylinPerformancesAdminServiceImpl extends ServiceImpl<KylinPerformancesMapper, KylinPerformances> implements IKylinPerformancesAdminService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    private MongoConverter mongoConverter;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private KylinPerformancesMapper performancesMapper;

    @Autowired
    private KylinPerformanceStatusMapper performanceStatusMapper;

    @Autowired
    private KylinPerformanceRelationsMapper performanceRelationsMapper;

    @Autowired
    private KylinTicketTimesPartnerServiceImpl ticketTimesPartnerService;

    @Autowired
    private KylinTicketsMapper ticketsMapper;

    @Autowired
    private KylinTicketStatusMapper ticketStatusMapper;

    @Autowired
    private KylinTicketRelationsMapper ticketRelationsMapper;

    @Autowired
    private KylinTicketTimesMapper ticketTimesMapper;

    @Autowired
    private KylinTicketTimeRelationMapper ticketTimeRelationMapper;

    @Autowired
    private KylinTicketsPartnerServiceImpl ticketsPartnerService;

    @Override
    public PerformanceCreatePartnerVo performanceDetails(String performancesId) {
        PerformanceCreateParam performanceData = mongoTemplate.findOne(Query.query(Criteria.where("performancesId").is(performancesId)), PerformanceCreateParam.class, PerformanceCreateParam.class.getSimpleName());
        List<TicketTimesCreatePartnerVo> ticketTimesCreatePartnerVos = ticketTimesPartnerService.getTimesMongoList(performancesId);
        List<TicketTimesTicketCreatePartnerVo> ticketTimesTicketCreatePartnerVoList = new ArrayList<TicketTimesTicketCreatePartnerVo>();

        ArrayList<BigDecimal> floatList = new ArrayList<>();
        ArrayList<String> StringList = new ArrayList<>();

        for (TicketTimesCreatePartnerVo ticketTimes : ticketTimesCreatePartnerVos) {
            TicketTimesTicketCreatePartnerVo ticketTimesTicketCreatePartnerVo = new TicketTimesTicketCreatePartnerVo();
            BeanUtils.copyProperties(ticketTimes, ticketTimesTicketCreatePartnerVo);
            List<TicketCreatePartnerVo> ticketCreatePartnerVos = ticketsPartnerService.getTicketMongoList(ticketTimes.getTicketTimesId());
            ticketTimesTicketCreatePartnerVo.setTicket(ticketCreatePartnerVos);
            ticketTimesTicketCreatePartnerVoList.add(ticketTimesTicketCreatePartnerVo);
            for (TicketCreatePartnerVo ticketCreatePartnerVoItem : ticketCreatePartnerVos) {
                floatList.add(ticketCreatePartnerVoItem.getPrice());
                StringList.add(ticketCreatePartnerVoItem.getTimeEnd());
            }
        }
        PerformanceCreatePartnerVo performanceCreatePartnerVo = new PerformanceCreatePartnerVo();
        BeanUtils.copyProperties(performanceData, performanceCreatePartnerVo);

        floatList.sort(Comparator.reverseOrder());
        StringList.sort(Comparator.naturalOrder());

        performanceCreatePartnerVo.setPrice(floatList.get(0) + "起");
        performanceCreatePartnerVo.setStopSellTime(StringList.get(0));
        performanceCreatePartnerVo.setTicketTimes(ticketTimesTicketCreatePartnerVoList);
        performanceCreatePartnerVo.setStatus(1);
        performanceCreatePartnerVo.setStatusSell(1);
        performanceCreatePartnerVo.setRejectTxt("");

        performanceCreatePartnerVo.setIsShow(1);
        performanceCreatePartnerVo.setIsDistribution(0);
        performanceCreatePartnerVo.setSyncAgent(0);
        performanceCreatePartnerVo.setAuditStatus(0);

        boolean exists = mongoTemplate.exists(Query.query(Criteria.where("performancesId").is(performancesId)), PerformanceCreatePartnerVo.class, PerformanceCreatePartnerVo.class.getSimpleName());

        if (!exists) {
            PerformanceCreatePartnerVo data = mongoTemplate.insert(
                    performanceCreatePartnerVo, PerformanceCreatePartnerVo.class.getSimpleName()
            );
        }
        return performanceCreatePartnerVo;
    }

    @Override
    public boolean performanceAudit(String performancesId, int status, String rejectTxt) {
        try {
            LocalDateTime updatedAt = LocalDateTime.now();
            if (status == 3) {
                //修改演出
                HashMap<String, Object> map = new HashMap<>();
                map.put("rejectTxt", "");
                map.put("status", status);
                map.put("updatedAt", updatedAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                BasicDBObject objectPerformanceVo = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
                Document docPerformance = mongoTemplate.getCollection(PerformanceCreatePartnerVo.class.getSimpleName()).findOneAndUpdate(
                        Query.query(Criteria.where("performancesId").is(performancesId)).getQueryObject(),
                        objectPerformanceVo,
                        new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)
                );
                PerformanceCreatePartnerVo performanceCreatePartnerVo = JsonUtils.fromJson(docPerformance.toJson(), PerformanceCreatePartnerVo.class);

                //创建演出
                KylinPerformances performances = new KylinPerformances();
                BeanUtils.copyProperties(performanceCreatePartnerVo, performances);
                KylinPerformanceStatus performanceStatus = new KylinPerformanceStatus();
                BeanUtils.copyProperties(performanceCreatePartnerVo, performanceStatus);
                KylinPerformanceRelations performanceRelations = new KylinPerformanceRelations();
                BeanUtils.copyProperties(performanceCreatePartnerVo, performanceRelations);

                performances.setCreatedAt(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(performanceCreatePartnerVo.getCreatedAt())));
                performances.setTimeStart(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(performanceCreatePartnerVo.getTimeStart())));
                performances.setTimeEnd(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(performanceCreatePartnerVo.getTimeEnd())));
                performances.setUpdatedAt(updatedAt);

                performanceStatus.setPerformanceId(performances.getPerformancesId());
                performanceStatus.setPerformanceStatusId(IDGenerator.nextSnowId().toString());
                performanceStatus.setCreatedAt(performances.getCreatedAt());
                performanceStatus.setUpdatedAt(updatedAt);

                performanceRelations.setPerformanceId(performances.getPerformancesId());
                performanceRelations.setPerformanceRelationsId(IDGenerator.nextSnowId().toString());
                performanceRelations.setCreatedAt(performances.getCreatedAt());
                performanceRelations.setUpdatedAt(updatedAt);

                performancesMapper.insert(performances);
                performanceStatusMapper.insert(performanceStatus);
                performanceRelationsMapper.insert(performanceRelations);


                //场次数据
                List<TicketTimesCreatePartnerVo> ticketTimesCreatePartnerVos = ticketTimesPartnerService.getTimesMongoList(performancesId);
                for (TicketTimesCreatePartnerVo ticketTimeItem : ticketTimesCreatePartnerVos) {
                    //创建场次
                    KylinTicketTimes ticketTimes = new KylinTicketTimes();
                    BeanUtils.copyProperties(ticketTimeItem, ticketTimes);
                    KylinTicketTimeRelation ticketTimeRelation = new KylinTicketTimeRelation();
                    BeanUtils.copyProperties(ticketTimeItem, ticketTimeRelation);

                    ticketTimes.setUseStart(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketTimeItem.getUseStart())));
                    ticketTimes.setUseEnd(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketTimeItem.getUseEnd())));
                    ticketTimes.setCreatedAt(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketTimeItem.getCreatedAt())));
                    ticketTimes.setUpdatedAt(updatedAt);

                    ticketTimeRelation.setPerformanceId(performancesId);
                    ticketTimeRelation.setTicketTimeRelationId(IDGenerator.nextSnowId().toString());
                    ticketTimeRelation.setTimesId(ticketTimes.getTicketTimesId());
                    ticketTimeRelation.setCreatedAt(ticketTimes.getCreatedAt());
                    ticketTimeRelation.setUpdatedAt(updatedAt);

                    ticketTimesMapper.insert(ticketTimes);
                    ticketTimeRelationMapper.insert(ticketTimeRelation);

                    //修改票
                    for (TicketCreatePartnerVo ticketItem : ticketsPartnerService.getTicketMongoList(ticketTimeItem.getTicketTimesId())) {
                        BasicDBObject objectTicketVo = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
                        Document docTicket = mongoTemplate.getCollection(TicketCreatePartnerVo.class.getSimpleName()).findOneAndUpdate(
                                Query.query(Criteria.where("ticketsId").is(ticketItem.getTicketsId())).getQueryObject(),
                                objectTicketVo,
                                new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)
                        );
                        TicketCreatePartnerVo ticketCreatePartnerVo = JsonUtils.fromJson(docTicket.toJson(), TicketCreatePartnerVo.class);

                        //创建演出
                        KylinTickets tickets = new KylinTickets();
                        BeanUtils.copyProperties(ticketCreatePartnerVo, tickets);
                        KylinTicketStatus ticketStatus = new KylinTicketStatus();
                        BeanUtils.copyProperties(ticketCreatePartnerVo, ticketStatus);
                        KylinTicketRelations ticketRelations = new KylinTicketRelations();
                        BeanUtils.copyProperties(ticketCreatePartnerVo, ticketRelations);

                        tickets.setPriceExpress(new BigDecimal(0.00));
                        tickets.setPriceDiscountMember(new BigDecimal(0.00));
                        tickets.setPriceDiscount(new BigDecimal(0.00));
                        tickets.setTimeStart(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketItem.getTimeStart())));
                        tickets.setTimeEnd(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketItem.getTimeEnd())));
                        tickets.setTimeEndExpress(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketItem.getTimeEndExpress())));
                        tickets.setUseStart(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketTimeItem.getUseStart())));
                        tickets.setUseEnd(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketTimeItem.getUseEnd())));
                        tickets.setSaleRemindMinute(60);
                        tickets.setCreatedAt(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketItem.getCreatedAt())));
                        tickets.setUpdatedAt(updatedAt);

                        ticketStatus.setTicketStatusId(IDGenerator.nextSnowId().toString());
                        ticketStatus.setTicketId(tickets.getTicketsId());
                        ticketStatus.setCounts(1);
                        ticketStatus.setIsMember(1);
                        ticketStatus.setStatusExchange(7);
                        ticketStatus.setQrCodeShowTime(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketItem.getQrCodeShowTime())));

                        ticketRelations.setCreatedAt(tickets.getCreatedAt());
                        ticketRelations.setUpdatedAt(updatedAt);

                        ticketRelations.setTicketRelationsId(IDGenerator.nextSnowId().toString());
                        ticketRelations.setTicketId(tickets.getTicketsId());
                        ticketRelations.setCreatedAt(tickets.getCreatedAt());
                        ticketRelations.setUpdatedAt(updatedAt);

                        ticketsMapper.insert(tickets);
                        ticketStatusMapper.insert(ticketStatus);
                        ticketRelationsMapper.insert(ticketRelations);
                    }
                }
            } else if (status == 4) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("rejectTxt", rejectTxt);
                map.put("status", status);
                map.put("updatedAt", updatedAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
                mongoTemplate.getCollection(PerformanceCreatePartnerVo.class.getSimpleName()).updateMany(
                        Query.query(Criteria.where("performancesId").is(performancesId)).getQueryObject(),
                        object
                );
            } else {
                return false;
            }
            return true;
        } catch (Exception e) {
            System.out.println("ERROR DATA = " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
}
