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.common.exception.entity.Error;
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.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 KylinTicketTimeRelationMapper ticketTimeRelationMapper;

    @Autowired
    private KylinPerformanceStatusMapper performanceStatusMapper;

    @Override
    public ResponseDto<TicketTimesPartnerVo> createTimesSummary(CreateTicketTimesParam createTicketTimesParam) {
        ResponseDto<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.getAuditStatus()==0){
            return ResponseDto.failure(ErrorMapping.get(20101));
        }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 ResponseDto<TicketTimesPartnerVo> createTimes(CreateTicketTimesParam createTicketTimesParam) {
        try {
            // 获取 主键id
            String ticketTimesId = IDGenerator.nextSnowId().toString();
            // 获取 当前时间 -> 创建时间
            LocalDateTime createdAt = LocalDateTime.now();
            // 标题
            String title = "";
            String useStart = createTicketTimesParam.getUseStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            String useEnd = createTicketTimesParam.getUseEnd().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            if (createTicketTimesParam.getType() == 1) {
                if(!useStart.split(" ")[0].equals(useEnd.split(" ")[0])){
                    return ResponseDto.failure(ErrorMapping.get(20118));
                }
                title = useStart;
            } else {
                title = useStart + "-" + useEnd;
            }
            // 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")));
            mongoTemplate.insert(
                    ticketTimesPartnerVo, TicketTimesPartnerVo.class.getSimpleName()
            );

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

    @Override
    public ResponseDto<TicketTimesPartnerVo> addNewTimes(CreateTicketTimesParam createTicketTimesParam) {
        try {
            // 获取 主键id
            String ticketTimesId = IDGenerator.nextSnowId().toString();
            // 获取 当前时间 -> 创建时间
            LocalDateTime createdAt = LocalDateTime.now();
            // 标题
            String title = "";
            String useStart = createTicketTimesParam.getUseStart().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            String useEnd = createTicketTimesParam.getUseEnd().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            if (createTicketTimesParam.getType() == 1) {
                if(!useStart.split(" ")[0].equals(useEnd.split(" ")[0])){
                    return ResponseDto.failure(ErrorMapping.get(20118));
                }
                title = useStart;
            } else {
                title = useStart + "-" + useEnd;
            }

            // 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")));
            mongoTemplate.insert(
                    ticketTimesPartnerVo, TicketTimesPartnerVo.class.getSimpleName()
            );
            return ResponseDto.success(ticketTimesPartnerVo);
        } catch (Exception e) {
            return ResponseDto.failure(ErrorMapping.get(20101));
        }
    }

    @Override
    public ResponseDto<String> 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 ResponseDto.failure(ErrorMapping.get(20106));
            }
            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.getAuditStatus()==0){
                    return ResponseDto.failure(ErrorMapping.get(20101));
                }

                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 ResponseDto.success("删除成功");
                } else {
                    return ResponseDto.failure(ErrorMapping.get(20106));
                }
            } else {
                mongoTemplate.remove(Query.query(Criteria.where("ticketTimesId").is(ticketTimesId)), TicketTimesPartnerVo.class, TicketTimesPartnerVo.class.getSimpleName());
                return ResponseDto.success();
            }
        } catch (Exception e) {
            return ResponseDto.failure(ErrorMapping.get(20102));
        }
    }

    @Override
    public ResponseDto<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 ResponseDto.success(JsonUtils.fromJson(doc.toJson(), TicketTimesPartnerVo.class));
        } catch (Exception e) {
            return ResponseDto.failure(ErrorMapping.get(20103));
        }
    }

    @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());
    }
}
