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

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.kylin.dto.param.PerformancePartnerVo;
import com.liquidnet.service.kylin.dto.param.TicketCreateParam;
import com.liquidnet.service.kylin.dto.vo.KylinTicketVo;
import com.liquidnet.service.kylin.dto.vo.ignore.KylinTicketIgnoreVo;
import com.liquidnet.service.kylin.dto.vo.partner.KylinTicketTimesPartnerVo;
import com.liquidnet.service.kylin.dto.vo.partner.KylinTicketPartnerVo;
import com.liquidnet.service.kylin.entity.*;
import com.liquidnet.service.kylin.mapper.*;
import com.liquidnet.service.kylin.service.partner.IKylinTicketsPartnerService;
import com.mongodb.BasicDBObject;
import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.model.ReturnDocument;
import com.mongodb.client.result.UpdateResult;
import lombok.extern.slf4j.Slf4j;
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.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;

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

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    private MongoConverter mongoConverter;

    @Autowired
    private KylinPerformanceStatusMapper performanceStatusMapper;

    @Autowired
    private KylinTicketTimeRelationMapper ticketTimeRelationMapper;

    @Autowired
    private KylinTicketsMapper ticketsMapper;

    @Autowired
    private KylinTicketStatusMapper ticketStatusMapper;

    @Autowired
    private KylinTicketRelationsMapper ticketRelationsMapper;

    @Override
    public ResponseDto<KylinTicketPartnerVo> createTicketSummary(TicketCreateParam ticketCreateParam) {
        ResponseDto<KylinTicketPartnerVo> ticketPartnerVo = null;
        //获取演出状态
        KylinTicketTimesPartnerVo timesPartnerVo = mongoTemplate.findOne(Query.query(Criteria.where("ticketTimesId").is(ticketCreateParam.getTimesId())), KylinTicketTimesPartnerVo.class, KylinTicketTimesPartnerVo.class.getSimpleName());

        if (null != timesPartnerVo) {
            KylinPerformanceStatus performanceStatus = performanceStatusMapper.selectOne(
                    new UpdateWrapper<KylinPerformanceStatus>().eq("performance_id", timesPartnerVo.getPerformancesId()));
            if (null == performanceStatus) {
                ticketPartnerVo = createTicket(ticketCreateParam);
                log.info(" PERFORMANCE 票 创建");
            } else if (performanceStatus.getStatus() >= 3 && performanceStatus.getStatus() != 4) {//未被拒绝 且 通过审核的演出
                ticketPartnerVo = addNewTicket(ticketCreateParam);
                log.info(" PERFORMANCE 票 添加");
            } else {
                ticketPartnerVo = createTicket(ticketCreateParam);
                log.info(" PERFORMANCE 票 创建");
            }
        } else {
            ticketPartnerVo = createTicket(ticketCreateParam);
            log.info(" PERFORMANCE 票 创建");
        }
        return ticketPartnerVo;
    }

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

            // mongo 操作
            KylinTicketPartnerVo kylinTicketPartnerVo = new KylinTicketPartnerVo();
            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 = mongoTemplate.findOne(Query.query(Criteria.where("ticketTimesId").is(ticketCreateParam.getTimesId())), KylinTicketTimesPartnerVo.class, KylinTicketTimesPartnerVo.class.getSimpleName());
            kylinTicketPartnerVo.setUseStart(kylinTicketTimesPartnerVo.getUseStart());
            kylinTicketPartnerVo.setUseEnd(kylinTicketTimesPartnerVo.getUseEnd());
            kylinTicketPartnerVo.setType(kylinTicketTimesPartnerVo.getType());
            kylinTicketPartnerVo.setStatus(0);
            kylinTicketPartnerVo.setDefault();
            if(ticketCreateParam.getIsExpress()==1){
                kylinTicketPartnerVo.setDescribesExpress(ticketCreateParam.getExpressDescribes());
            }
            if(ticketCreateParam.getIsElectronic()==1){
                kylinTicketPartnerVo.setDescribeElectronic(ticketCreateParam.getElectronicDescribe());
            }

            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")));
            }

            KylinTicketPartnerVo data = mongoTemplate.insert(
                    kylinTicketPartnerVo, KylinTicketPartnerVo.class.getSimpleName()
            );

            return ResponseDto.success(kylinTicketPartnerVo);
        } catch (Exception e) {
            return ResponseDto.failure(ErrorMapping.get(20105));
        }
    }

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

            // mongo 操作
            KylinTicketPartnerVo kylinTicketPartnerVo = new KylinTicketPartnerVo();
            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 = mongoTemplate.findOne(Query.query(Criteria.where("ticketTimesId").is(ticketCreateParam.getTimesId())), KylinTicketTimesPartnerVo.class, KylinTicketTimesPartnerVo.class.getSimpleName());
            kylinTicketPartnerVo.setUseStart(kylinTicketTimesPartnerVo.getUseStart());
            kylinTicketPartnerVo.setUseEnd(kylinTicketTimesPartnerVo.getUseEnd());
            kylinTicketPartnerVo.setType(kylinTicketTimesPartnerVo.getType());
            if(ticketCreateParam.getIsExpress()==1){
                kylinTicketPartnerVo.setDescribesExpress(ticketCreateParam.getExpressDescribes());
            }
            if(ticketCreateParam.getIsElectronic()==1){
                kylinTicketPartnerVo.setDescribeElectronic(ticketCreateParam.getElectronicDescribe());
            }
            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")));
            }

            KylinTicketPartnerVo data = mongoTemplate.insert(
                    kylinTicketPartnerVo, KylinTicketPartnerVo.class.getSimpleName()
            );

            return ResponseDto.success(kylinTicketPartnerVo);
        } catch (Exception e) {
            return ResponseDto.failure(ErrorMapping.get(20101));
        }
    }

    @Override
    public ResponseDto<KylinTicketPartnerVo> updateTicket(TicketCreateParam ticketCreateParam) {
        log.info("票 修改");
        try {
            KylinTicketTimeRelation ticketTimeRelation = ticketTimeRelationMapper.selectOne(
                    new UpdateWrapper<KylinTicketTimeRelation>().eq("times_id", ticketCreateParam.getTimesId()));
            PerformancePartnerVo data = mongoTemplate.findOne(Query.query(Criteria.where("performancesId").is(ticketTimeRelation.getPerformanceId())),
                    PerformancePartnerVo.class, PerformancePartnerVo.class.getSimpleName());
            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 = new KylinTicketPartnerVo();
            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.setDescribesExpress(ticketCreateParam.getExpressDescribes());
            }
            if(ticketCreateParam.getIsElectronic()==1){
                kylinTicketPartnerVo.setDescribeElectronic(ticketCreateParam.getElectronicDescribe());
            }

            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")));
            }

            BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(kylinTicketPartnerVo));
            Document doc = mongoTemplate.getCollection(KylinTicketPartnerVo.class.getSimpleName()).findOneAndUpdate(
                    Query.query(Criteria.where("ticketsId").is(ticketId)).getQueryObject(),
                    object,
                    new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)
            );

            KylinTicketPartnerVo kylinTicketPartnerVoData = JsonUtils.fromJson(doc.toJson(), KylinTicketPartnerVo.class);
            return ResponseDto.success(kylinTicketPartnerVoData);
        } catch (Exception e) {
            return ResponseDto.failure(ErrorMapping.get(20103));
        }
    }

    @Override
    public ResponseDto<String> deleteTicket(String ticketsId) {
        log.info("票 删除");
        try {
            LocalDateTime updatedAt = LocalDateTime.now();

            KylinTicketRelations ticketRelations = ticketRelationsMapper.selectOne(
                    new UpdateWrapper<KylinTicketRelations>().eq("ticket_id", ticketsId));

            if (ticketRelations == null) {
                mongoTemplate.remove(Query.query(Criteria.where("ticketsId").is(ticketsId)), KylinTicketPartnerVo.class, KylinTicketPartnerVo.class.getSimpleName());
                return ResponseDto.success("删除成功");
            }
            KylinTicketTimeRelation ticketTimeRelation = ticketTimeRelationMapper.selectOne(
                    new UpdateWrapper<KylinTicketTimeRelation>().eq("times_id", ticketRelations.getTimesId()));

            PerformancePartnerVo data = mongoTemplate.findOne(Query.query(Criteria.where("performancesId").is(ticketTimeRelation.getPerformanceId())),
                    PerformancePartnerVo.class, PerformancePartnerVo.class.getSimpleName());
            if (data == null || data.getAuditStatus() == null || data.getAuditStatus() == 0) {
                return ResponseDto.failure(ErrorMapping.get("20106"));
            }

            KylinPerformanceStatus performanceStatus = performanceStatusMapper.selectOne(
                    new UpdateWrapper<KylinPerformanceStatus>().eq("performance_id", ticketTimeRelation.getPerformanceId()));

            if (performanceStatus.getStatus() == 0 || performanceStatus.getStatus() == 4) {//未提审||被拒绝
                // mongo 操作
                HashMap<String, Object> map = new HashMap<>();
                map.put("updatedAt", updatedAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                map.put("status", -1);

                BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
                Document doc = mongoTemplate.getCollection(KylinTicketPartnerVo.class.getSimpleName()).findOneAndUpdate(
                        Query.query(Criteria.where("ticketsId").is(ticketsId)).getQueryObject(),
                        object,
                        new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)
                );
                return ResponseDto.success("删除成功");
            } else {
                return ResponseDto.failure(ErrorMapping.get(20106));
            }
        } catch (Exception e) {
            return ResponseDto.failure(ErrorMapping.get(20102));
        }
    }

    @Override
    public ResponseDto<KylinTicketPartnerVo> copyTicket(String ticketsId) {
        try {
            // 获取 当前时间 -> 创建时间
            LocalDateTime createdAt = LocalDateTime.now();

            KylinTicketPartnerVo kylinTicketPartnerVo = mongoTemplate.findOne(Query.query(Criteria.where("ticketsId").is(ticketsId)), KylinTicketPartnerVo.class, KylinTicketPartnerVo.class.getSimpleName());
            kylinTicketPartnerVo.setCreatedAt(createdAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            kylinTicketPartnerVo.setTicketsId(IDGenerator.nextSnowId().toString());

            KylinTicketPartnerVo data = mongoTemplate.insert(
                    kylinTicketPartnerVo, KylinTicketPartnerVo.class.getSimpleName()
            );
            return ResponseDto.success(kylinTicketPartnerVo);
        } catch (Exception e) {
            return ResponseDto.failure(ErrorMapping.get(20107));
        }
    }

    @Override
    public boolean submitTicketByTimes(String timesId) {
        LocalDateTime updatedAt = LocalDateTime.now();

        HashMap<String, Object> map = new HashMap<>();
        map.put("status", 1);
        map.put("updatedAt", updatedAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
        UpdateResult updateResult = mongoTemplate.getCollection(KylinTicketPartnerVo.class.getSimpleName()).updateMany(
                Query.query(Criteria.where("timesId").is(timesId)).getQueryObject(),
                object
        );
        return updateResult.getModifiedCount() <= 0;
    }

    @Override
    public List<KylinTicketPartnerVo> getTicketMongoList(String timesId) {
        return mongoTemplate.find(Query.query(Criteria.where("timesId").is(timesId)), KylinTicketPartnerVo.class, KylinTicketPartnerVo.class.getSimpleName());
    }

    @Override
    public KylinTicketPartnerVo getTicketsMongo(String ticketsId) {
        return mongoTemplate.findOne(Query.query(Criteria.where("ticketsId").is(ticketsId)), KylinTicketPartnerVo.class, KylinTicketPartnerVo.class.getSimpleName());
    }

    @Override
    public ResponseDto<String> onLine(String ticketsId) {
        try {
            LocalDateTime updatedAt = LocalDateTime.now();
            KylinTicketStatus ticketStatus = ticketStatusMapper.selectOne(new UpdateWrapper<KylinTicketStatus>().eq("ticket_id", ticketsId));
            if (ticketStatus.getStatus() >= 3 && ticketStatus.getStatus() != 4 && ticketStatus.getStatus() != 6) {//未提审||被拒绝
                //mysql
                KylinTicketStatus changeStatus = new KylinTicketStatus();
                changeStatus.setUpdatedAt(updatedAt);
                changeStatus.setStatus(6);
                ticketStatusMapper.update(changeStatus, new UpdateWrapper<KylinTicketStatus>().eq("ticket_id", ticketsId));

                // mongo 操作
                KylinTicketStatus ticketStatusMySql = ticketStatusMapper.selectOne(new UpdateWrapper<KylinTicketStatus>().eq("ticket_id", ticketsId).between("status", 1, 10).ne("status", 7));
                KylinTicketRelations ticketRelation = ticketRelationsMapper.selectOne(new UpdateWrapper<KylinTicketRelations>().eq("ticket_id", ticketsId));
                KylinTickets tickets = ticketsMapper.selectOne(
                        new UpdateWrapper<KylinTickets>().eq("tickets_id", ticketsId)
                );

                HashMap<String,Object> map = new HashMap<>();
                map.put("status",6);
                BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
                mongoTemplate.getCollection(KylinTicketPartnerVo.class.getSimpleName()).updateOne(
                        Query.query(Criteria.where("ticketsId").is(ticketsId)).getQueryObject(),
                        object
                );

                KylinTicketVo kylinTicketVo = new KylinTicketVo();
                kylinTicketVo.setTimeId(ticketRelation.getTimesId());
                kylinTicketVo.setTicket(tickets);
                kylinTicketVo.setTicketStatus(ticketStatusMySql);

                boolean ticketExists =
                        mongoTemplate.exists(Query.query(Criteria.where("ticketsId").is(kylinTicketVo.getTicketsId())), KylinTicketVo.class, KylinTicketVo.class.getSimpleName());
                if (!ticketExists) {
                    mongoTemplate.insert(
                            kylinTicketVo, KylinTicketVo.class.getSimpleName()
                    );
                }
                return ResponseDto.success("上线成功");
            } else {
                return ResponseDto.failure(ErrorMapping.get(20110));
            }
        }catch (Exception e){
            return ResponseDto.failure(ErrorMapping.get(20108));
        }
    }

    @Override
    public ResponseDto<String> outLine(String ticketsId) {
        try {
            LocalDateTime updatedAt = LocalDateTime.now();
            KylinTicketStatus ticketStatus = ticketStatusMapper.selectOne(new UpdateWrapper<KylinTicketStatus>().eq("ticket_id", ticketsId));
            if (ticketStatus.getStatus() >= 3 && ticketStatus.getStatus() != 4 && ticketStatus.getStatus() != 7) {//未提审||被拒绝
                //mysql
                KylinTicketStatus changeStatus = new KylinTicketStatus();
                changeStatus.setUpdatedAt(updatedAt);
                changeStatus.setStatus(7);
                ticketStatusMapper.update(changeStatus, new UpdateWrapper<KylinTicketStatus>().eq("ticket_id", ticketsId));
                // mongo 操作
                HashMap<String,Object> map = new HashMap<>();
                map.put("status",7);
                BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
                mongoTemplate.getCollection(KylinTicketPartnerVo.class.getSimpleName()).updateOne(
                        Query.query(Criteria.where("ticketsId").is(ticketsId)).getQueryObject(),
                        object
                );


                KylinTicketVo kylinTicketVoItem = mongoTemplate.findOne(Query.query(Criteria.where("ticketsId").is(ticketsId)), KylinTicketVo.class, KylinTicketVo.class.getSimpleName());
                KylinTicketIgnoreVo kylinTicketIgnoreVo = new KylinTicketIgnoreVo();
                BeanUtils.copyProperties(kylinTicketVoItem, kylinTicketIgnoreVo);
                mongoTemplate.remove(Query.query(Criteria.where("ticketsId").is(kylinTicketVoItem.getTicketsId())), KylinTicketIgnoreVo.class, KylinTicketIgnoreVo.class.getSimpleName());
                mongoTemplate.insert(kylinTicketIgnoreVo, KylinTicketIgnoreVo.class.getSimpleName());
                mongoTemplate.remove(Query.query(Criteria.where("ticketsId").is(kylinTicketVoItem.getTicketsId())), KylinTicketVo.class, KylinTicketVo.class.getSimpleName());
                return ResponseDto.success("下线成功");
            } else {
                return ResponseDto.failure(ErrorMapping.get(20111));
            }
        }catch (Exception e){
            return ResponseDto.failure(ErrorMapping.get(20109));
        }
    }

}
