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.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.IDGenerator;
import com.liquidnet.service.kylin.constant.KylinRedisConst;
import com.liquidnet.service.kylin.dao.PerformancePartnerListDao;
import com.liquidnet.service.kylin.dto.TicketInventoryDto;
import com.liquidnet.service.kylin.dto.param.*;
import com.liquidnet.service.kylin.dto.vo.PerformanceVo;
import com.liquidnet.service.kylin.dto.vo.TicketTimesVo;
import com.liquidnet.service.kylin.dto.vo.TicketVo;
import com.liquidnet.service.kylin.dto.vo.ignore.PerformanceIgnoreVo;
import com.liquidnet.service.kylin.dto.vo.ignore.TicketIgnoreVo;
import com.liquidnet.service.kylin.dto.vo.ignore.TicketTimesIgnoreVo;
import com.liquidnet.service.kylin.dto.vo.partner.*;
import com.liquidnet.service.kylin.entity.*;
import com.liquidnet.service.kylin.mapper.*;
import com.liquidnet.service.kylin.service.partner.IKylinPerformancesPartnerService;
import com.liquidnet.service.kylin.timerTask.PerformanceVoTask;
import com.liquidnet.service.kylin.utils.DataUtils;
import com.mongodb.BasicDBObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
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.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

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

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private MongoConverter mongoConverter;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private DataUtils dataUtils;

    @Autowired
    private PerformanceVoTask performanceVoTask;

    @Autowired
    private KylinPerformancesMapper performancesMapper;

    @Autowired
    private KylinPerformanceStatusMapper performanceStatusMapper;

    @Autowired
    private KylinPerformanceRelationsMapper performanceRelationsMapper;

    @Autowired
    private KylinTicketTimesMapper ticketTimesMapper;

    @Autowired
    private KylinTicketTimeRelationMapper ticketTimeRelationMapper;

    @Autowired
    private KylinTicketsMapper ticketsMapper;

    @Autowired
    private KylinTicketStatusMapper ticketStatusMapper;

    @Autowired
    private KylinTicketRelationsMapper ticketRelationsMapper;

    @Autowired
    private KylinTicketsPartnerServiceImpl ticketsPartnerService;

    @Autowired
    private KylinTicketTimesPartnerServiceImpl ticketTimesPartnerService;

    @Override
    public String step1(PerformanceStep1Param step1Param) {
        String result = null;
        // 无 performancesId 则 创建
        if (null == step1Param.getPerformancesId()) {
            result = createStep1(step1Param);
            log.info(" PERFORMANCE  演出第一步 创建");
        } else { // 获取 create 数据 status = 0 或 无数据 创建
            PerformanceParam createParam = mongoTemplate.findOne(Query.query(Criteria.where("performancesId").is(step1Param.getPerformancesId())), PerformanceParam.class, PerformanceParam.class.getSimpleName());
            if (createParam == null) {
                result = createStep1(step1Param);
                log.info(" PERFORMANCE  演出第一步 创建");
            } else {// 修改
                result = updateStep1(step1Param);
                log.info(" PERFORMANCE  演出第一步 修改");
            }
        }
        return result;
    }

    @Override
    public String createStep1(PerformanceStep1Param step1Param) {
        // 获取 主键id
        String performanceId = IDGenerator.nextSnowId().toString();
        // 获取 当前时间 -> 创建时间
        LocalDateTime createdAt = LocalDateTime.now();

        try {
            step1Param.setPerformancesId(performanceId);
            PerformanceParam performanceParam = new PerformanceParam();
            BeanUtils.copyProperties(step1Param, performanceParam);
            performanceParam.setIsTrueName(0);
            performanceParam.setLimitCount(0);
            performanceParam.setCreatedAt(createdAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            performanceParam.setIsSubmit(0);
            performanceParam.setStatus(0);
            performanceParam.setStatusSell(1);
            performanceParam.setRoadShowId("0");
            performanceParam.setProjectId("0");
            performanceParam.setIsShow(1);
            performanceParam.setFieldName((String)redisUtil.hget(KylinRedisConst.FIELDS + ":" + performanceParam.getFieldId(), "name"));
            performanceParam.setNoticeImage(dataUtils.getBuyNoticeJsonString(step1Param.getNoticeIds()));


            mongoTemplate.insert(
                    performanceParam, PerformanceParam.class.getSimpleName()
            );

            return performanceId;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    public String updateStep1(PerformanceStep1Param step1Param) {
        // 获取 当前时间 -> 创建时间
        LocalDateTime timeNow = LocalDateTime.now();
        String performanceId = step1Param.getPerformancesId();
        try {
            step1Param.setPerformancesId(performanceId);
            PerformanceParam performanceParam = new PerformanceParam();
            BeanUtils.copyProperties(step1Param, performanceParam);
            performanceParam.setCreatedAt(timeNow.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            performanceParam.setUpdatedAt(timeNow.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            performanceParam.setIsSubmit(0);
            performanceParam.setStatus(0);
            performanceParam.setNoticeImage(dataUtils.getBuyNoticeJsonString(step1Param.getNoticeIds()));
            PerformanceParam data = mongoTemplate.findOne(Query.query(Criteria.where("performancesId").is(performanceId)),
                    PerformanceParam.class, PerformanceParam.class.getSimpleName());
            if (data != null) { // 有修改记录
                performanceParam.setIsTrueName(data.getIsTrueName());
                performanceParam.setLimitCount(data.getLimitCount());
                performanceParam.setStatusSell(data.getStatusSell());
                performanceParam.setRoadShowId(data.getRoadShowId());
                performanceParam.setProjectId(data.getProjectId());
                BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(performanceParam));
                mongoTemplate.getCollection(PerformanceParam.class.getSimpleName()).updateOne(
                        Query.query(Criteria.where("performancesId").is(performanceId)).getQueryObject(),
                        object
                );
            } else { // 无修改记录
                KylinPerformanceStatus statusData = performanceStatusMapper.selectOne(new UpdateWrapper<KylinPerformanceStatus>().eq("performanceId", performanceId));
                KylinPerformanceRelations relationsData = performanceRelationsMapper.selectOne(new UpdateWrapper<KylinPerformanceRelations>().eq("performancesId", performanceId));
                performanceParam.setIsTrueName(statusData.getIsTrueName());
                performanceParam.setLimitCount(statusData.getLimitCount());
                performanceParam.setStatusSell(statusData.getStatusSell());
                performanceParam.setRoadShowId(relationsData.getRoadShowId());
                performanceParam.setProjectId(relationsData.getProjectId());
                mongoTemplate.insert(
                        performanceParam, PerformanceParam.class.getSimpleName()
                );
            }
            return performanceId;
        } catch (Exception e) {
            return "";
        }
    }

    @Override
    public PerformancePartnerVo getStep1(String performancesId) {
        PerformancePartnerVo performancePartnerVo = new PerformancePartnerVo();
//        PerformanceParam updateData = getUpdateStep1(performancesId);
        PerformanceParam data = mongoTemplate.findOne(
                Query.query(Criteria.where("performancesId").is(performancesId)), PerformanceParam.class, PerformanceParam.class.getSimpleName()
        );
        if (data == null) {
            return performancePartnerVo;
        }
        BeanUtils.copyProperties(data, performancePartnerVo);
        log.info(" PERFORMANCE  演出第一步 获取");
        return performancePartnerVo;
    }

//    @Override
//    public PerformanceParam getCreateStep1(String performancesId) {
//        PerformanceParam data = mongoTemplate.findOne(
//                Query.query(Criteria.where("performancesId").is(performancesId)), PerformanceParam.class, PerformanceParam.class.getSimpleName()
//        );
//        if (data == null) {
//            return new PerformanceParam();
//        }
//        return data;
//    }
//
//    @Override
//    public PerformanceParam getUpdateStep1(String performancesId) {
//
//        PerformanceParam data = mongoTemplate.findOne(
//                Query.query(Criteria.where("performancesId").is(performancesId)), PerformanceParam.class, PerformanceParam.class.getSimpleName()
//        );
//        if (data == null) {
//            return new PerformanceParam();
//        }
//        return data;
//    }

    @Override
    public boolean step2(PerformanceStep2Param step2Param) {
        boolean result = false;
        // 无 performancesId 则 创建
        if (step2Param.getPerformancesId().isEmpty()) {
        } else { // 获取 create 数据 status = 0 或 无数据 创建
            KylinPerformanceStatus performanceStatus = performanceStatusMapper.selectOne(new UpdateWrapper<KylinPerformanceStatus>().eq("performance_id", step2Param.getPerformancesId()));
            if (performanceStatus == null || performanceStatus.getStatus() == 0) {
                result = createStep2(step2Param);
                log.info(" PERFORMANCE  演出第二步 创建");
            } else if (performanceStatus.getStatus() == 1 || performanceStatus.getStatus() == 3 || performanceStatus.getStatus() == 6 || performanceStatus.getStatus() == 7) {// 修改
                result = updateStep2(step2Param);
                log.info(" PERFORMANCE  演出第二步 修改");
            }
        }
        return result;
    }

    @Override
    public boolean createStep2(PerformanceStep2Param step2Param) {

        // 获取 主键id
        String performanceId = step2Param.getPerformancesId();
        // 获取 当前时间 -> 创建时间
        LocalDateTime createdAt = LocalDateTime.now();

        boolean isExistsSubmit = mongoTemplate.exists(Query.query(Criteria.where("performancesId").is(performanceId).and("status").is(1)),
                PerformanceParam.class,
                PerformanceParam.class.getSimpleName());

        if (isExistsSubmit) {
            return false;
        }

        //演出修改数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("isTrueName", step2Param.getIsTrueName());
        map.put("limitCount", step2Param.getLimitCount());
        map.put("createdAt", createdAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        map.put("isSubmit", step2Param.getIsSubmit());
        map.put("statusSell", 1);

        // 获取第一步数据
        if (step2Param.getIsSubmit() == 1) { // 提交
            map.put("status", 1);
            BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
            mongoTemplate.getCollection(PerformanceParam.class.getSimpleName()).updateOne(
                    Query.query(Criteria.where("performancesId").is(performanceId)).getQueryObject(),
                    object
            );
            //提交 票
            List<TicketTimesPartnerVo> ticketTimesPartnerVoList = ticketTimesPartnerService.getTimesMongoList(performanceId);
            for (TicketTimesPartnerVo ticketTimes : ticketTimesPartnerVoList) {
                boolean boolResult = ticketsPartnerService.submitTicketByTimes(ticketTimes.getTicketTimesId());
                if (boolResult) {
                    return false;
                }
            }
            if (ticketTimesPartnerVoList.size() <= 0) {
                return false;
            } else {
                PerformanceMisVo performanceMisVo = performanceVoTask.getPerformanceMisVo(performanceId);

                HashMap<String, Object> mapSql = new HashMap<>();
                mapSql.put("isCreateSave", 0);
                mapSql.put("rejectTxt", "");
                mapSql.put("status", 1);
                mapSql.put("updatedAt", createdAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                performanceVoTask.createPerformanceMySql(performanceId, mapSql, performanceMisVo, createdAt);
                KylinPerformances performances = new KylinPerformances();
                performances.setAuditTime(LocalDateTime.now());
                performancesMapper.update(performances, new UpdateWrapper<KylinPerformances>().eq("performances_id", performanceId));
            }
        } else { //保存
            map.put("status", 0);
            map.put("isCreateSave", 1);
            BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
            mongoTemplate.getCollection(PerformanceParam.class.getSimpleName()).updateMany(
                    Query.query(Criteria.where("performancesId").is(performanceId)).getQueryObject(),
                    object
            );
        }

        return true;
    }

    @Override
    public boolean updateStep2(PerformanceStep2Param step2Param) {
        // 获取 主键id
        String performanceId = step2Param.getPerformancesId();
        // 获取 当前时间 -> 创建时间
        LocalDateTime createdAt = LocalDateTime.now();

        boolean isExistsSubmit = mongoTemplate.exists(Query.query(Criteria.where("performancesId").is(performanceId).and("status").is(1)),
                PerformanceParam.class,
                PerformanceParam.class.getSimpleName());

        if (isExistsSubmit) {
            return false;
        }

        //演出修改数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("isTrueName", step2Param.getIsTrueName());
        map.put("limitCount", step2Param.getLimitCount());
        map.put("createdAt", createdAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        map.put("updatedAt", createdAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        map.put("isSubmit", step2Param.getIsSubmit());

        // 获取第一步数据
        if (step2Param.getIsSubmit() == 1) { // 提交
            map.put("status", 1);
            BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
            mongoTemplate.getCollection(PerformanceParam.class.getSimpleName()).updateOne(
                    Query.query(Criteria.where("performancesId").is(performanceId)).getQueryObject(),
                    object
            );
            //提交 票
            List<TicketTimesPartnerVo> ticketTimesPartnerVoList = ticketTimesPartnerService.getTimesMongoList(performanceId);
            for (TicketTimesPartnerVo ticketTimes : ticketTimesPartnerVoList) {
                boolean boolResult = ticketsPartnerService.submitTicketByTimes(ticketTimes.getTicketTimesId());
                if (boolResult) {
                    return false;
                }
            }
            if (ticketTimesPartnerVoList.size() <= 0) {
                return false;
            } else {
                PerformanceMisVo performanceMisVo = performanceVoTask.getPerformanceMisVo(performanceId);

                HashMap<String, Object> mapSql = new HashMap<>();
                mapSql.put("rejectTxt", "");
                mapSql.put("status", 1);
                mapSql.put("updatedAt", createdAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                KylinPerformances performances = new KylinPerformances();
                performances.setAuditTime(LocalDateTime.now());
                performancesMapper.update(performances, new UpdateWrapper<KylinPerformances>().eq("performances_id", performanceId));

                //提示：票种价格、售票时间、购票限制 直接生效
                List<TicketTimesTicketCreatePartnerVo> timeList = performanceMisVo.getTicketTimes();
                for (TicketTimesTicketCreatePartnerVo timesItem : timeList) {
                    List<TicketPartnerVo> ticketList = timesItem.getTicket();
                    for (TicketPartnerVo ticketItem : ticketList) {
                        //修改 redis库存
                        if (redisUtil.hHasKey(KylinRedisConst.PERFORMANCES_INVENTORY + ticketItem.getTicketsId(), KylinRedisConst.SURPLUS_GENERAL)) {
                            KylinTicketStatus ticketStatus = ticketStatusMapper.selectOne(new UpdateWrapper<KylinTicketStatus>().eq("ticket_id", ticketItem.getTicketsId()));
                            int changeGeneral = ticketStatus.getTotalGeneral() - ticketItem.getTotalGeneral();
                            int changeExchange = ticketStatus.getTotalGeneral() - ticketItem.getTotalExchange();
                            redisUtil.hincr(KylinRedisConst.PERFORMANCES_INVENTORY + ticketItem.getTicketsId(), KylinRedisConst.SURPLUS_GENERAL, changeGeneral);
                            redisUtil.hincr(KylinRedisConst.PERFORMANCES_INVENTORY + ticketItem.getTicketsId(), KylinRedisConst.SURPLUS_EXCHANGE, changeExchange);
                        }
                        //修改 mysql 库存
                        KylinTicketStatus inventory = new KylinTicketStatus();
                        inventory.setTotalExchange(ticketItem.getTotalExchange());
                        inventory.setTotalGeneral(ticketItem.getTotalGeneral());
                        inventory.setIsTrueName(performanceMisVo.getIsTrueName());
                        inventory.setLimitCount(ticketItem.getLimitCount());
                        //修改 mysql 售卖时间
                        KylinTickets ticketSellTime = new KylinTickets();
                        ticketSellTime.setTimeEnd(LocalDateTime.parse(ticketItem.getTimeEnd(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        ticketSellTime.setTimeStart(LocalDateTime.parse(ticketItem.getTimeStart(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                        ticketSellTime.setAdvanceMinuteMember(null);
                        //修改 价格
                        ticketSellTime.setPrice(ticketItem.getPrice());
                        ticketSellTime.setPriceDiscountMember(null);
                        ticketsMapper.update(ticketSellTime, new UpdateWrapper<KylinTickets>().eq("tickets_id", ticketItem.getTicketsId()));
                        //修改 mysql 购票限购
                        ticketStatusMapper.update(inventory, new UpdateWrapper<KylinTicketStatus>().eq("ticket_id", ticketItem.getTicketsId()));
                    }
                }
            }
        } else { //保存
            map.put("status", 0);
            BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
            mongoTemplate.getCollection(PerformanceParam.class.getSimpleName()).updateMany(
                    Query.query(Criteria.where("performancesId").is(performanceId)).getQueryObject(),
                    object
            );
        }

        return true;
    }

    @Override
    public PerformanceStep2Param getStep2(String performancesId) {
        PerformanceStep2Param performanceCreatePartnerVo = null;
        PerformanceParam data = mongoTemplate.findOne(
                Query.query(Criteria.where("performancesId").is(performancesId)), PerformanceParam.class, PerformanceParam.class.getSimpleName()
        );
        if (data == null) {
            return new PerformanceStep2Param();
        }
        List<TicketTimesPartnerVo> ticketTimesPartnerVos = ticketTimesPartnerService.getTimesMongoList(performancesId);
        List<TicketTimesTicketCreatePartnerVo> ticketTimesTicketCreatePartnerVoList = new ArrayList<TicketTimesTicketCreatePartnerVo>();

        for (TicketTimesPartnerVo ticketTimes : ticketTimesPartnerVos) {
            TicketTimesTicketCreatePartnerVo ticketTimesTicketCreatePartnerVo = new TicketTimesTicketCreatePartnerVo();
            BeanUtils.copyProperties(ticketTimes, ticketTimesTicketCreatePartnerVo);
            List<TicketPartnerVo> ticketPartnerVos = ticketsPartnerService.getTicketMongoList(ticketTimes.getTicketTimesId());
            ticketTimesTicketCreatePartnerVo.setTicket(ticketPartnerVos);
            ticketTimesTicketCreatePartnerVoList.add(ticketTimesTicketCreatePartnerVo);
        }

        PerformanceStep2Param performanceStep2Param = new PerformanceStep2Param();
        BeanUtils.copyProperties(data, performanceStep2Param);
        performanceStep2Param.setTicketTimes(ticketTimesTicketCreatePartnerVoList);
        performanceCreatePartnerVo = performanceStep2Param;
        log.info(" PERFORMANCE  演出第二步 获取");
        return performanceCreatePartnerVo;
    }

//    @Override
//    public PerformanceStep2Param getCreateStep2(String performancesId) {
//        PerformanceParam data = mongoTemplate.findOne(
//                Query.query(Criteria.where("performancesId").is(performancesId)), PerformanceParam.class, PerformanceParam.class.getSimpleName()
//        );
//
//        if (data == null) {
//            return new PerformanceStep2Param();
//        }
//
//        List<TicketTimesPartnerVo> ticketTimesPartnerVos = ticketTimesPartnerService.getTimesMongoList(performancesId);
//        List<TicketTimesTicketCreatePartnerVo> ticketTimesTicketCreatePartnerVoList = new ArrayList();
//
//        for (TicketTimesPartnerVo ticketTimes : ticketTimesPartnerVos) {
//            TicketTimesTicketCreatePartnerVo ticketTimesTicketCreatePartnerVo = new TicketTimesTicketCreatePartnerVo();
//            BeanUtils.copyProperties(ticketTimes, ticketTimesTicketCreatePartnerVo);
//            List<TicketPartnerVo> ticketPartnerVos = ticketsPartnerService.getTicketMongoList(ticketTimes.getTicketTimesId());
//            ticketTimesTicketCreatePartnerVo.setTicket(ticketPartnerVos);
//            ticketTimesTicketCreatePartnerVoList.add(ticketTimesTicketCreatePartnerVo);
//        }
//
//        PerformanceStep2Param performanceStep2Param = new PerformanceStep2Param();
//        BeanUtils.copyProperties(data, performanceStep2Param);
//        performanceStep2Param.setTicketTimes(ticketTimesTicketCreatePartnerVoList);
//
//        return performanceStep2Param;
//    }
//
//    @Override
//    public PerformanceStep2Param getUpdateStep2(String performancesId) {
//        PerformanceParam data = mongoTemplate.findOne(
//                Query.query(Criteria.where("performancesId").is(performancesId)), PerformanceParam.class, PerformanceParam.class.getSimpleName()
//        );
//
//        if (data == null) {
//            return new PerformanceStep2Param();
//        }
//
//        List<TicketTimesPartnerVo> ticketTimesPartnerVos = ticketTimesPartnerService.getTimesMongoList(performancesId);
//        List<TicketTimesTicketCreatePartnerVo> ticketTimesTicketCreatePartnerVoList = new ArrayList<TicketTimesTicketCreatePartnerVo>();
//
//        for (TicketTimesPartnerVo ticketTimes : ticketTimesPartnerVos) {
//            TicketTimesTicketCreatePartnerVo ticketTimesTicketCreatePartnerVo = new TicketTimesTicketCreatePartnerVo();
//            BeanUtils.copyProperties(ticketTimes, ticketTimesTicketCreatePartnerVo);
//            List<TicketPartnerVo> ticketPartnerVos = ticketsPartnerService.getTicketMongoList(ticketTimes.getTicketTimesId());
//            ticketTimesTicketCreatePartnerVo.setTicket(ticketPartnerVos);
//            ticketTimesTicketCreatePartnerVoList.add(ticketTimesTicketCreatePartnerVo);
//        }
//
//        PerformanceStep2Param performanceStep2Param = new PerformanceStep2Param();
//        BeanUtils.copyProperties(data, performanceStep2Param);
//        performanceStep2Param.setTicketTimes(ticketTimesTicketCreatePartnerVoList);
//
//        return performanceStep2Param;
//    }

    @Override
    public boolean onLinePerformance(String performancesId) {
        try {
            KylinPerformanceStatus performanceStatusData = performanceStatusMapper.selectOne(new UpdateWrapper<KylinPerformanceStatus>().eq("performance_id", performancesId));
            if (!(performanceStatusData.getStatus() == 3 || performanceStatusData.getStatus() == 7)) {
                return false;
            }
            // mysql
            LocalDateTime updatedAt = LocalDateTime.now();
            KylinPerformanceStatus performanceStatusUpdate = new KylinPerformanceStatus();
            performanceStatusUpdate.setStatus(6);
            performanceStatusUpdate.setUpdatedAt(updatedAt);
            performanceStatusMapper.update(performanceStatusUpdate
                    , new UpdateWrapper<KylinPerformanceStatus>().eq("performance_id", performancesId));

            //mongo操作 票
            KylinPerformanceRelations performanceRelationsData = performanceRelationsMapper.selectOne(new UpdateWrapper<KylinPerformanceRelations>().eq("performance_id", performancesId));
            KylinPerformances performancesData = performancesMapper.selectOne(new UpdateWrapper<KylinPerformances>().eq("performances_id", performancesId));
            PerformanceVo performanceVoData = new PerformanceVo();
            performanceVoData.setPerformance(performancesData);
            performanceVoData.setPerformanceRelations(performanceRelationsData);
            performanceVoData.setPerformanceStatus(performanceStatusData);

            String cityName=(String) redisUtil.hget(KylinRedisConst.FIELDS+":"+performanceVoData.getFieldId(),"city_name");
            KylinFields fields = new KylinFields();
            fields.setCityId(null);
            fields.setLatitude((String) redisUtil.hget(KylinRedisConst.FIELDS+":"+performanceVoData.getFieldId(),"latitude"));
            fields.setLongitude((String) redisUtil.hget(KylinRedisConst.FIELDS+":"+performanceVoData.getFieldId(),"longitude"));
            fields.setCityName((String) redisUtil.hget(KylinRedisConst.FIELDS+":"+performanceVoData.getFieldId(),"city_name"));
            fields.setName((String) redisUtil.hget(KylinRedisConst.FIELDS+":"+performanceVoData.getFieldId(),"name"));
            performanceVoData.setFieldsData(fields,cityName);

            //场次
            List<KylinTicketTimeRelation> ticketTimeRelation = ticketTimeRelationMapper.selectList(
                    new UpdateWrapper<KylinTicketTimeRelation>().eq("performance_id", performancesId)
            );

            LocalDateTime stopSellTime = null;
            LocalDateTime sellTime = null;
            int isLackRegister = 0;
            int isMember = 0;
            int isExclusive = 0;
            int isAdvance = 0;
            int isDiscount = 0;
            BigDecimal price = new BigDecimal("0.00");


            for (KylinTicketTimeRelation ticketTimeRelationItem : ticketTimeRelation) {
                KylinTicketTimes ticketTimes = ticketTimesMapper.selectOne(new UpdateWrapper<KylinTicketTimes>().eq("ticket_times_id", ticketTimeRelationItem.getTimesId()).eq("status", 1));
                TicketTimesVo ticketTimesVo = new TicketTimesVo();
                ticketTimesVo.setTicketTimes(ticketTimes);
                ticketTimesVo.setPerformanceId(ticketTimeRelationItem.getPerformanceId());
                ticketTimesVo.setTimeId(ticketTimeRelationItem.getTimesId());
                //票
                List<KylinTicketRelations> ticketRelations = ticketRelationsMapper.selectList(new UpdateWrapper<KylinTicketRelations>().eq("times_id", ticketTimes.getTicketTimesId()));
                for (KylinTicketRelations ticketRelationsItem : ticketRelations) {
                    KylinTicketStatus ticketStatus = ticketStatusMapper.selectOne(new UpdateWrapper<KylinTicketStatus>().eq("ticket_id", ticketRelationsItem.getTicketId()).between("status", 1, 10).ne("status", 7));
                    KylinTickets tickets = ticketsMapper.selectOne(
                            new UpdateWrapper<KylinTickets>().eq("tickets_id", ticketStatus.getTicketId()
                            )
                    );
                    KylinTicketStatus ticketStatusUpdate = new KylinTicketStatus();
                    ticketStatusUpdate.setStatus(9);
                    ticketStatusUpdate.setUpdatedAt(updatedAt);
                    ticketStatusMapper.update(ticketStatusUpdate
                            , new UpdateWrapper<KylinTicketStatus>().eq("ticket_id", ticketStatus.getTicketId()).eq("status", 7));
                    TicketVo ticketVo = new TicketVo();
                    ticketVo.setTimeId(ticketRelationsItem.getTimesId());
                    ticketVo.setTicket(tickets);
                    ticketVo.setTicketStatus(ticketStatus);
                    boolean ticketExists =
                            mongoTemplate.exists(Query.query(Criteria.where("ticketsId").is(ticketVo.getTicketsId())), TicketVo.class, TicketVo.class.getSimpleName());
                    if (!ticketExists) {
                        mongoTemplate.insert(
                                ticketVo, TicketVo.class.getSimpleName()
                        );
                    }

                    //票种 库存redis TODO 库存可能会丢
                    TicketInventoryDto ticketInventoryDto = new TicketInventoryDto();
                    if (!redisUtil.hHasKey(KylinRedisConst.PERFORMANCES_INVENTORY + ticketVo.getTicketsId(), KylinRedisConst.SURPLUS_GENERAL)) {
                        ticketInventoryDto.setSurplusExchange(ticketStatus.getSurplusExchange());
                        ticketInventoryDto.setSurplusGeneral(ticketStatus.getTotalGeneral());
                        ticketInventoryDto.setTicketsId(ticketVo.getTicketsId());
                        redisUtil.hset(KylinRedisConst.PERFORMANCES_INVENTORY + ticketVo.getTicketsId(), KylinRedisConst.SURPLUS_GENERAL, ticketInventoryDto.getSurplusGeneral());
                        redisUtil.hset(KylinRedisConst.PERFORMANCES_INVENTORY + ticketVo.getTicketsId(), KylinRedisConst.SURPLUS_EXCHANGE, ticketInventoryDto.getSurplusExchange());
                    } else {
                        int surplusGeneral = (int) redisUtil.hget(KylinRedisConst.PERFORMANCES_INVENTORY + ticketVo.getTicketsId(), KylinRedisConst.SURPLUS_GENERAL);
                        int surplusExchange = (int) redisUtil.hget(KylinRedisConst.PERFORMANCES_INVENTORY + ticketVo.getTicketsId(), KylinRedisConst.SURPLUS_EXCHANGE);
                        ticketInventoryDto.setSurplusExchange(ticketStatus.getSurplusExchange() - surplusGeneral);
                        ticketInventoryDto.setSurplusGeneral(ticketStatus.getTotalGeneral() - surplusExchange);
                        ticketInventoryDto.setTicketsId(ticketVo.getTicketsId());
                        redisUtil.hset(KylinRedisConst.PERFORMANCES_INVENTORY + ticketVo.getTicketsId(), KylinRedisConst.SURPLUS_GENERAL, ticketInventoryDto.getSurplusGeneral());
                        redisUtil.hset(KylinRedisConst.PERFORMANCES_INVENTORY + ticketVo.getTicketsId(), KylinRedisConst.SURPLUS_EXCHANGE, ticketInventoryDto.getSurplusExchange());
                    }

                    if (ticketVo.getIsMember() == 1) {
                        if (ticketVo.getMemberPrice().compareTo(ticketVo.getPrice()) != 0) {
                            isDiscount = 1;
                        }

                        if (!ticketVo.getTimeStart().equalsIgnoreCase(ticketVo.getMemberTimeStart())) {
                            isAdvance = 1;
                        }

                        if (ticketVo.getIsMember() == 1) {
                            isMember = 1;
                        }

                        if (ticketVo.getIsExclusive() == 1) {
                            isExclusive = 1;
                        }
                    }

                    if (ticketVo.getIsLackRegister() == 1) {
                        isLackRegister = 1;
                    }

                    if (price.subtract(ticketVo.getPrice()).compareTo(new BigDecimal("0.00")) < 0) {
                        price = ticketVo.getPrice();
                    }
                    if (stopSellTime == null || stopSellTime.isBefore(tickets.getTimeEnd())) {
                        stopSellTime = tickets.getTimeEnd();
                    }
                    if (sellTime == null || sellTime.isAfter(tickets.getTimeStart().plusMinutes(-tickets.getAdvanceMinuteMember()))) {
                        sellTime = tickets.getTimeStart().plusMinutes(-tickets.getAdvanceMinuteMember());
                    }
                }
                boolean ticketTimesExists =
                        mongoTemplate.exists(Query.query(Criteria.where("ticketTimesId").is(ticketTimesVo.getTicketTimesId())), TicketTimesVo.class, TicketTimesVo.class.getSimpleName());
                if (!ticketTimesExists) {
                    mongoTemplate.insert(
                            ticketTimesVo, TicketTimesVo.class.getSimpleName()
                    );
                }

            }
            performanceVoData.setTimePriceVipAndLack(isLackRegister, isMember, isExclusive, price, stopSellTime, sellTime, isAdvance, isDiscount);

            boolean performanceExists =
                    mongoTemplate.exists(Query.query(Criteria.where("performancesId").is(performanceVoData.getPerformancesId())), PerformanceVo.class, PerformanceVo.class.getSimpleName());
            if (!performanceExists) {
                mongoTemplate.insert(
                        performanceVoData, PerformanceVo.class.getSimpleName()
                );
            }
//            //修改 提审vo
//            Map<String, Object> map = new HashMap<>();
//            map.put("status", 3);
//            BasicDBObject objectPerformance = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
//            mongoTemplate.getCollection(PerformanceMisVo.class.getSimpleName()).updateOne(
//                    Query.query(Criteria.where("performancesId").is(performancesId)).getQueryObject(),
//                    objectPerformance
//            );
            //判断状态
            performanceVoTask.performanceVoStatus(performancesId);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean outLinePerformance(String performancesId) {
        try {

            KylinPerformanceStatus performanceStatusData = performanceStatusMapper.selectOne(new UpdateWrapper<KylinPerformanceStatus>().eq("performance_id", performancesId));

            if (performanceStatusData.getStatus() != 6) {
                return false;
            }

            LocalDateTime updatedAt = LocalDateTime.now();
            KylinPerformanceStatus performanceStatus = new KylinPerformanceStatus();
            performanceStatus.setStatus(7);
            performanceStatus.setUpdatedAt(updatedAt);
            performanceStatusMapper.update(performanceStatus
                    , new UpdateWrapper<KylinPerformanceStatus>().eq("performance_id", performancesId));

            //mongoVo 迁移 演出数据迁移
            PerformanceVo performanceVo = mongoTemplate.findOne(Query.query(Criteria.where("performancesId").is(performancesId)), PerformanceVo.class, PerformanceVo.class.getSimpleName());
            PerformanceIgnoreVo performanceIgnoreVo = new PerformanceIgnoreVo();
            BeanUtils.copyProperties(performanceVo, performanceIgnoreVo);
            performanceIgnoreVo.setAppStatus(7);
            mongoTemplate.remove(Query.query(Criteria.where("performancesId").is(performancesId)), PerformanceIgnoreVo.class, PerformanceIgnoreVo.class.getSimpleName());
            mongoTemplate.insert(performanceIgnoreVo, PerformanceIgnoreVo.class.getSimpleName());
            mongoTemplate.remove(Query.query(Criteria.where("performancesId").is(performancesId)), PerformanceVo.class, PerformanceVo.class.getSimpleName());

            List<TicketTimesVo> ticketTimesVoList = mongoTemplate.find(Query.query(Criteria.where("performanceId").is(performancesId)), TicketTimesVo.class, TicketTimesVo.class.getSimpleName());
            for (TicketTimesVo ticketTimesVoItem : ticketTimesVoList) {
                //场次数据迁移
                TicketTimesIgnoreVo ticketTimesIgnoreVo = new TicketTimesIgnoreVo();
                BeanUtils.copyProperties(ticketTimesVoItem, ticketTimesIgnoreVo);
                mongoTemplate.remove(Query.query(Criteria.where("ticketTimesId").is(ticketTimesVoItem.getTicketTimesId())), TicketTimesIgnoreVo.class, TicketTimesIgnoreVo.class.getSimpleName());
                mongoTemplate.insert(ticketTimesIgnoreVo, TicketTimesIgnoreVo.class.getSimpleName());
                mongoTemplate.remove(Query.query(Criteria.where("ticketTimesId").is(ticketTimesVoItem.getTicketTimesId())), TicketTimesVo.class, TicketTimesVo.class.getSimpleName());

                List<TicketVo> ticketVoList = mongoTemplate.find(Query.query(Criteria.where("timeId").is(ticketTimesVoItem.getTicketTimesId())), TicketVo.class, TicketVo.class.getSimpleName());
                for (TicketVo ticketVoItem : ticketVoList) {
                    // 票 迁移
                    TicketIgnoreVo ticketIgnoreVo = new TicketIgnoreVo();
                    BeanUtils.copyProperties(ticketVoItem, ticketIgnoreVo);
                    mongoTemplate.remove(Query.query(Criteria.where("ticketsId").is(ticketVoItem.getTicketsId())), TicketIgnoreVo.class, TicketIgnoreVo.class.getSimpleName());
                    mongoTemplate.insert(ticketIgnoreVo, TicketIgnoreVo.class.getSimpleName());
                    mongoTemplate.remove(Query.query(Criteria.where("ticketsId").is(ticketVoItem.getTicketsId())), TicketVo.class, TicketVo.class.getSimpleName());
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public String copyPerformance(String performancesId) {

        PerformancePartnerVo performancePartnerVo = mongoTemplate.findOne(Query.query(Criteria.where("performances_id").is(performancesId)), PerformancePartnerVo.class, PerformancePartnerVo.class.getSimpleName());
        //复制演出
        performancePartnerVo.setPerformancesId(IDGenerator.nextSnowId().toString());
        performancePartnerVo.setStatus(0);
        mongoTemplate.insert(performancePartnerVo, PerformancePartnerVo.class.getSimpleName());

        List<TicketTimesPartnerVo> ticketTimesPartnerVos = mongoTemplate.find(Query.query(Criteria.where("performances_id").is(performancesId)), TicketTimesPartnerVo.class, TicketTimesPartnerVo.class.getSimpleName());
        for (TicketTimesPartnerVo timeItem : ticketTimesPartnerVos) {
            //复制场次
            timeItem.setTicketTimesId(IDGenerator.nextSnowId().toString());
            timeItem.setPerformancesId(performancePartnerVo.getPerformancesId());
            mongoTemplate.insert(timeItem, TicketTimesPartnerVo.class.getSimpleName());

            List<TicketPartnerVo> ticketPartnerVos = mongoTemplate.find(Query.query(Criteria.where("timesId").is(timeItem.getTicketTimesId())), TicketPartnerVo.class, TicketPartnerVo.class.getSimpleName());
            for (TicketPartnerVo ticketItem : ticketPartnerVos) {
                //复制票
                ticketItem.setStatus(0);
                ticketItem.setTimesId(ticketItem.getTimesId());
                ticketItem.setTicketsId(IDGenerator.nextSnowId().toString());
                mongoTemplate.insert(ticketItem, TicketPartnerVo.class.getSimpleName());
            }
        }
        return performancePartnerVo.getPerformancesId();
    }

    @Override
    public PageInfo<PerformancePartnerListDao> getList(PerformancePartnerListParam performancePartnerListParam) {
        int status = performancePartnerListParam.getStatus();
        int page = performancePartnerListParam.getPage() - 1;
        int size = performancePartnerListParam.getSize();
        PageInfo<PerformancePartnerListDao> pageInfoTmp = null;
        if (status == 0) {//未发布演出
            log.info(" PERFORMANCE  演出列表 未提交");
            // 排序 分页
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
            //条件
            Criteria criteria = Criteria.where("status").is(status).and("isCreateSave").is(1);
            if (!performancePartnerListParam.getTitle().isEmpty()) {
                criteria.and("title").regex(".*?\\" + performancePartnerListParam.getTitle());
            }
            Query query = Query.query(criteria);
            // 查询总数
            long count = mongoTemplate.count(query, PerformanceParam.class, PerformanceParam.class.getSimpleName());
            List<PerformanceParam> performanceParam = mongoTemplate.find(query, PerformanceParam.class, PerformanceParam.class.getSimpleName());
            query.with(pageable);
            //处理Vo
            List<PerformancePartnerListVo> voList = new ArrayList<>();
            for (PerformanceParam item : performanceParam) {
                PerformancePartnerListVo voData = new PerformancePartnerListVo();
                voData.setStatus0Data(item);
                voList.add(voData);
            }
            pageInfoTmp = new PageInfo(voList);
            pageInfoTmp.setTotal(count);
        } else {//演出列表
            log.info(" PERFORMANCE  演出列表 已提交");
            try {
                PageHelper.startPage(performancePartnerListParam.getPage(), performancePartnerListParam.getSize());
                List<PerformancePartnerListDao> voList = performancesMapper.partnerPerformanceList(BeanUtil.convertBeanToMap(performancePartnerListParam));
                pageInfoTmp = new PageInfo(voList);
            } catch (Exception e) {
                return null;
            }
        }
        return pageInfoTmp;
    }
}
