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

import com.alibaba.fastjson.JSON;
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.kylin.dto.param.CreateTicketTimesParam;
import com.liquidnet.service.kylin.dto.vo.partner.TicketTimesPartnerVo;
import com.liquidnet.service.kylin.entity.KylinPerformanceStatus;
import com.liquidnet.service.kylin.entity.KylinTicketTimeRelation;
import com.liquidnet.service.kylin.entity.KylinTicketTimes;
import com.liquidnet.service.kylin.mapper.KylinPerformanceStatusMapper;
import com.liquidnet.service.kylin.mapper.KylinTicketTimeRelationMapper;
import com.liquidnet.service.kylin.mapper.KylinTicketTimesMapper;
import com.liquidnet.service.kylin.service.partner.IKylinTicketTimesPartnerService;
import com.mongodb.BasicDBObject;
import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.model.ReturnDocument;
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 KylinTicketTimesPartnerServiceImpl extends ServiceImpl<KylinTicketTimesMapper, KylinTicketTimes> implements IKylinTicketTimesPartnerService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private MongoConverter mongoConverter;

    @Autowired
    private KylinTicketTimesMapper ticketTimesMapper;

    @Autowired
    private KylinTicketTimeRelationMapper ticketTimeRelationMapper;

    @Autowired
    private KylinPerformanceStatusMapper performanceStatusMapper;

    @Override
    public TicketTimesPartnerVo createTimesSummary(CreateTicketTimesParam createTicketTimesParam) {
        TicketTimesPartnerVo ticketTimesPartnerVo = null;
        //获取演出状态
        KylinPerformanceStatus performanceStatus = performanceStatusMapper.selectOne(
                new UpdateWrapper<KylinPerformanceStatus>().eq("performance_id", createTicketTimesParam.getPerformancesId()));
        if (null == performanceStatus) {
            ticketTimesPartnerVo = createTimes(createTicketTimesParam);
            log.info(" PERFORMANCE 场次 创建");
        } else if (performanceStatus.getStatus() >= 3 && performanceStatus.getStatus() != 4) {//未被拒绝 且 通过审核的演出
            ticketTimesPartnerVo = addNewTimes(createTicketTimesParam);
            log.info(" PERFORMANCE 场次 新增");
        } else {
            ticketTimesPartnerVo = createTimes(createTicketTimesParam);
            log.info(" PERFORMANCE 场次 创建");
        }
        return ticketTimesPartnerVo;
    }

    @Override
    public TicketTimesPartnerVo createTimes(CreateTicketTimesParam createTicketTimesParam) {

        // 获取 主键id
        String ticketTimesId = IDGenerator.nextSnowId().toString();
        // 获取 当前时间 -> 创建时间
        LocalDateTime createdAt = LocalDateTime.now();
        // 标题
        String title = "";
        if (createTicketTimesParam.getType() == 1) {
            title = createTicketTimesParam.getUseStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        } else {
            title = createTicketTimesParam.getUseStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) + "-" + createTicketTimesParam.getUseEnd().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        }

        // mongo 操作
        TicketTimesPartnerVo ticketTimesPartnerVo = new TicketTimesPartnerVo();
        ticketTimesPartnerVo.setTicketTimesId(ticketTimesId);
        ticketTimesPartnerVo.setUseStart(createTicketTimesParam.getUseStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        ticketTimesPartnerVo.setUseEnd(createTicketTimesParam.getUseEnd().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        ticketTimesPartnerVo.setStatus(1);
        ticketTimesPartnerVo.setTitle(title);
        ticketTimesPartnerVo.setPerformancesId(createTicketTimesParam.getPerformancesId());
        ticketTimesPartnerVo.setType(createTicketTimesParam.getType());
        ticketTimesPartnerVo.setCreatedAt(createdAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        TicketTimesPartnerVo data = mongoTemplate.insert(
                ticketTimesPartnerVo, TicketTimesPartnerVo.class.getSimpleName()
        );

        return ticketTimesPartnerVo;
    }

    @Override
    public TicketTimesPartnerVo addNewTimes(CreateTicketTimesParam createTicketTimesParam) {
        // 获取 主键id
        String ticketTimesId = IDGenerator.nextSnowId().toString();
        // 获取 当前时间 -> 创建时间
        LocalDateTime createdAt = LocalDateTime.now();
        // 标题
        String title = "";
        if (createTicketTimesParam.getType() == 1) {
            title = createTicketTimesParam.getUseStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        } else {
            title = createTicketTimesParam.getUseStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) + "-" + createTicketTimesParam.getUseEnd().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        }

        // mongo 操作
        TicketTimesPartnerVo ticketTimesPartnerVo = new TicketTimesPartnerVo();
        ticketTimesPartnerVo.setTicketTimesId(ticketTimesId);
        ticketTimesPartnerVo.setUseStart(createTicketTimesParam.getUseStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        ticketTimesPartnerVo.setUseEnd(createTicketTimesParam.getUseEnd().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        ticketTimesPartnerVo.setStatus(-1);
        ticketTimesPartnerVo.setTitle(title);
        ticketTimesPartnerVo.setPerformancesId(createTicketTimesParam.getPerformancesId());
        ticketTimesPartnerVo.setType(createTicketTimesParam.getType());
        ticketTimesPartnerVo.setCreatedAt(createdAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        TicketTimesPartnerVo data = mongoTemplate.insert(
                ticketTimesPartnerVo, TicketTimesPartnerVo.class.getSimpleName()
        );
        return ticketTimesPartnerVo;
    }

    @Override
    public Boolean deleteTimes(String ticketTimesId) {
        try {
            LocalDateTime updatedAt = LocalDateTime.now();

            TicketTimesPartnerVo data = mongoTemplate.findOne(Query.query(Criteria.where("ticketTimesId").is(ticketTimesId)), TicketTimesPartnerVo.class, TicketTimesPartnerVo.class.getSimpleName());
            if (data.getStatus() == 0) {
                return false;
            }
            KylinTicketTimeRelation ticketTimeRelation = ticketTimeRelationMapper.selectOne(
                    new UpdateWrapper<KylinTicketTimeRelation>().eq("times_id", ticketTimesId));
            if (ticketTimeRelation != null) {
                KylinPerformanceStatus performanceStatus = performanceStatusMapper.selectOne(
                        new UpdateWrapper<KylinPerformanceStatus>().eq("performance_id", ticketTimeRelation.getPerformanceId()));
                if (performanceStatus.getStatus() == 0 || performanceStatus.getStatus() == 4) {//未提审||被拒绝
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("updatedAt", updatedAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    map.put("status", 0);

                    BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
                    Document doc = mongoTemplate.getCollection(TicketTimesPartnerVo.class.getSimpleName()).findOneAndUpdate(
                            Query.query(Criteria.where("ticketTimesId").is(ticketTimesId)).getQueryObject(),
                            object,
                            new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)
                    );
                    return true;
                } else {
                    return false;
                }
            } else {
                mongoTemplate.remove(Query.query(Criteria.where("ticketTimesId").is(ticketTimesId)), TicketTimesPartnerVo.class, TicketTimesPartnerVo.class.getSimpleName());
                return true;
            }
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public TicketTimesPartnerVo changeTimes(CreateTicketTimesParam createTicketTimesParam) {
        try {
            LocalDateTime updatedAt = LocalDateTime.now();
            String title = "";
            if (createTicketTimesParam.getType() == 1) {
                title = createTicketTimesParam.getUseStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            } else {
                title = createTicketTimesParam.getUseStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) + "-" + createTicketTimesParam.getUseEnd().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            }
            createTicketTimesParam.setTitle(title);

            // mongo 操作
            TicketTimesPartnerVo ticketTimesPartnerVo = new TicketTimesPartnerVo();
            BeanUtils.copyProperties(createTicketTimesParam, ticketTimesPartnerVo);
            ticketTimesPartnerVo.setTicketTimesId(createTicketTimesParam.getTicketTimesId());
            ticketTimesPartnerVo.setUpdatedAt(updatedAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            ticketTimesPartnerVo.setUseStart(createTicketTimesParam.getUseStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            ticketTimesPartnerVo.setUseEnd(createTicketTimesParam.getUseEnd().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            ticketTimesPartnerVo.setStatus(null);

            BasicDBObject object = new BasicDBObject("$set", JSON.parse(JsonUtils.toJson(ticketTimesPartnerVo)));
            Document doc = mongoTemplate.getCollection(TicketTimesPartnerVo.class.getSimpleName()).findOneAndUpdate(
                    Query.query(Criteria.where("ticketTimesId").is(createTicketTimesParam.getTicketTimesId())).getQueryObject(),
                    object,
                    new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)
            );

            return JsonUtils.fromJson(doc.toJson(), TicketTimesPartnerVo.class);

        } catch (Exception e) {
            return null;
        }
    }

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

    @Override
    public TicketTimesPartnerVo getTimesMongo(String timesId) {
        return mongoTemplate.findOne(Query.query(Criteria.where("ticketTimesId").is(timesId)), TicketTimesPartnerVo.class, TicketTimesPartnerVo.class.getSimpleName());
    }
}
