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

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.commons.lang.util.BeanUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.kylin.constant.KylinRedisConst;
import com.liquidnet.service.kylin.dao.PerformanceAdminListDao;
import com.liquidnet.service.kylin.dao.PerformanceRecommendAdminDao;
import com.liquidnet.service.kylin.dao.PerformanceTitleDao;
import com.liquidnet.service.kylin.dto.param.PerformanceAdminListParam;
import com.liquidnet.service.kylin.dto.param.PerformanceRecommendAdminParam;
import com.liquidnet.service.kylin.dto.vo.PerformanceVo;
import com.liquidnet.service.kylin.dto.vo.partner.PerformanceMisVo;
import com.liquidnet.service.kylin.dto.vo.partner.PerformancePartnerVo;
import com.liquidnet.service.kylin.dto.vo.partner.TicketTimesPartnerVo;
import com.liquidnet.service.kylin.dto.vo.partner.TicketPartnerVo;
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.liquidnet.service.kylin.timerTask.PerformanceVoTask;
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.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.*;

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

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    private MongoConverter mongoConverter;

    @Autowired
    private PerformanceVoTask performanceVoTask;

    @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 PerformanceMisVo performanceDetails(String performancesId) {
        log.info(" PERFORMANCE  mis演出详情");
        PerformanceMisVo createMisVo = mongoTemplate.findOne(
                Query.query(Criteria.where("performancesId").is(performancesId)),
                PerformanceMisVo.class,
                PerformanceMisVo.class.getSimpleName());
        return createMisVo;
    }

    @Override
    public boolean performanceAudit(String performancesId, int status, String rejectTxt) {
        try {
            LocalDateTime updatedAt = LocalDateTime.now();
            HashMap<String, Object> map = new HashMap<>();
            int auditStatus = 0;
            if (status == 3) {
                log.info(" PERFORMANCE  演出审核 通过");
                rejectTxt = "";
                auditStatus = 1;
                //修改演出
                map.put("rejectTxt", rejectTxt);
                map.put("status", status);
                map.put("auditStatus", auditStatus);
                map.put("updatedAt", updatedAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                BasicDBObject objectPerformanceVo = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
                Document doc = mongoTemplate.getCollection(PerformanceMisVo.class.getSimpleName()).findOneAndUpdate(
                        Query.query(Criteria.where("performancesId").is(performancesId)).getQueryObject(),
                        objectPerformanceVo,
                        new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER)
                );

                KylinPerformanceStatus sqlStatus = performanceStatusMapper.selectOne(new UpdateWrapper<KylinPerformanceStatus>().eq("performance_id", performancesId));
                if (sqlStatus.getStatus() == 1) {
                    log.info(" PERFORMANCE  演出审核 第一次");
                    //修改
                    KylinPerformanceStatus performanceStatus = new KylinPerformanceStatus();
                    performanceStatus.setStatus(status);
                    performanceStatus.setAuditStatus(auditStatus);
                    performanceStatus.setUpdatedAt(updatedAt);
                    performanceStatusMapper.update(performanceStatus, new UpdateWrapper<KylinPerformanceStatus>().eq("performance_id", performancesId));
                    KylinPerformances performances = new KylinPerformances();
                    performances.setUpdatedAt(updatedAt);
                    performances.setRejectTxt(rejectTxt);
                    performancesMapper.update(performances, new UpdateWrapper<KylinPerformances>().eq("performances_id", performancesId));

                    List<TicketTimesPartnerVo> ticketTimesPartnerVos = ticketTimesPartnerService.getTimesMongoList(performancesId);
                    for (TicketTimesPartnerVo ticketTimeItem : ticketTimesPartnerVos) {
                        for (TicketPartnerVo ticketItem : ticketsPartnerService.getTicketMongoList(ticketTimeItem.getTicketTimesId())) {
                            BasicDBObject objectTicketVo = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
                            mongoTemplate.getCollection(TicketPartnerVo.class.getSimpleName()).updateOne(
                                    Query.query(Criteria.where("ticketsId").is(ticketItem.getTicketsId())).getQueryObject(),
                                    objectTicketVo
                            );
                            KylinTickets tickets = new KylinTickets();
                            tickets.setUpdatedAt(updatedAt);
                            ticketsMapper.update(tickets, new UpdateWrapper<KylinTickets>().eq("tickets_id", ticketItem.getTicketsId()));
                            KylinTicketStatus ticketStatus = new KylinTicketStatus();
                            ticketStatus.setUpdatedAt(updatedAt);
                            ticketStatus.setStatus(status);
                            ticketStatusMapper.update(ticketStatus, new UpdateWrapper<KylinTicketStatus>().eq("ticket_id", ticketItem.getTicketsId()));
                        }
                    }
                } else { //只修改演出相关 场次 票 (不包括 库存 售卖时间 限购)
                    log.info(" PERFORMANCE  演出审核 修改");
                    HashMap<String, Object> mapSql = new HashMap<>();
                    mapSql.put("status", 9);
                    mapSql.put("updatedAt", updatedAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    performanceVoTask.updatePerformanceMySql(performancesId, mapSql, JsonUtils.fromJson(doc.toJson(), PerformanceMisVo.class), updatedAt);
                    if (sqlStatus.getStatus() == 6) {//若 演出上 则 线判断状态
                        performanceVoTask.performanceVoStatus(performancesId);
                    }
                }

            } else if (status == 4) {
                log.info(" PERFORMANCE  演出审核 拒绝");
                auditStatus = 2;
                map.put("rejectTxt", rejectTxt);
                map.put("auditStatus", auditStatus);
                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(PerformancePartnerVo.class.getSimpleName()).updateOne(
                        Query.query(Criteria.where("performancesId").is(performancesId)).getQueryObject(),
                        object
                );
                mongoTemplate.getCollection(PerformanceMisVo.class.getSimpleName()).updateOne(
                        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;
        }
    }

    @Override
    public PageInfo<PerformanceAdminListDao> getList(PerformanceAdminListParam performanceAdminListParam) {
        PageInfo<PerformanceAdminListDao> pageInfoTmp = null;
        try {
            PageHelper.startPage(performanceAdminListParam.getPage(), performanceAdminListParam.getSize());
            List<PerformanceAdminListDao> voList = performancesMapper.misPerformanceList(BeanUtil.convertBeanToMap(performanceAdminListParam));
            pageInfoTmp = new PageInfo(voList);
        } catch (Exception e) {
            return null;
        }
        return pageInfoTmp;
    }

    @Override
    public List<PerformanceTitleDao> getListByRoadShowId(String roadShowId) {
        try {
            List<PerformanceTitleDao> voList = performancesMapper.misTitleByRoadShowIdList(roadShowId);
            return voList;
        } catch (Exception e) {
            return new ArrayList<>();
        }
    }

    @Override
    public List<PerformanceTitleDao> getListByStatus(String status) {
        List<PerformanceTitleDao> voList = performancesMapper.misTitleByStatusList(status);
        return voList;
    }

    @Override
    public boolean changeRoadShowId(String performancesId, String roadShowId) {
        try {
            //mysql
            KylinPerformanceRelations performanceRelations = new KylinPerformanceRelations();
            performanceRelations.setRoadShowId(roadShowId);
            performanceRelationsMapper.update(performanceRelations, new UpdateWrapper<KylinPerformanceRelations>().eq("performance_id", performancesId));

            //redis TODO 演出缓存
//        if(redisUtil.hHasKey(KylinRedisConst.PERFORMANCES,performancesId)){
//            redisUtil.hset()
//        }

            //mongodb
            HashMap<String, Object> map = new HashMap<>();
            map.put("roadShowId", roadShowId);
            BasicDBObject object = new BasicDBObject("$set", map);
            mongoTemplate.getCollection(PerformanceVo.class.getSimpleName()).updateOne(
                    Query.query(Criteria.where("performancesId").is(performancesId)).getQueryObject(),
                    object
            );
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public boolean setRecommend(List<PerformanceRecommendAdminParam> performancesIdList) {
        try {
            KylinPerformanceStatus performanceStatus = new KylinPerformanceStatus();
            performanceStatus.setIsRecommend(0);
            performanceStatus.setStatus(null);
            performanceStatusMapper.update(performanceStatus, new UpdateWrapper<KylinPerformanceStatus>().gt("is_recommend", 0));

            HashMap<String, Object> map = new HashMap<>();
            map.put("isRecommend", 0);
            BasicDBObject object = new BasicDBObject("$set", map);
            mongoTemplate.getCollection(PerformanceVo.class.getSimpleName()).updateMany(
                    Query.query(Criteria.where("isRecommend").gt(0)).getQueryObject(),
                    object
            );

            for (PerformanceRecommendAdminParam item : performancesIdList) {
                performanceStatus.setIsRecommend(item.getIsRecommend());
                performanceStatusMapper.update(performanceStatus, new UpdateWrapper<KylinPerformanceStatus>().eq("performance_id", item.getPerformanceId()));

                HashMap<String, Object> map2 = new HashMap<>();
                map2.put("isRecommend", item.getIsRecommend());
                BasicDBObject object2 = new BasicDBObject("$set", map2);
                mongoTemplate.getCollection(PerformanceVo.class.getSimpleName()).updateOne(
                        Query.query(Criteria.where("performancesId").is(item.getPerformanceId())).getQueryObject(),
                        object2
                );
            }
            redisUtil.del(KylinRedisConst.PERFORMANCES_RECOMMEND);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public PageInfo<PerformanceRecommendAdminDao> listRecommend() {

        PageInfo<PerformanceRecommendAdminDao> pageInfoTmp = null;
        try {
            PageHelper.startPage(1, 10);
            List<PerformanceRecommendAdminDao> voList = performancesMapper.reCommendPerformanceList();
            pageInfoTmp = new PageInfo(voList);
        } catch (Exception e) {
            return null;
        }
        return pageInfoTmp;
    }
}
