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.base.ErrorMapping;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.kylin.constant.KylinRedisConst;
import com.liquidnet.service.kylin.dao.PerformancePartnerListDao;
import com.liquidnet.service.kylin.dto.param.*;
import com.liquidnet.service.kylin.dto.vo.KylinPerformanceVo;
import com.liquidnet.service.kylin.dto.vo.KylinTicketTimesVo;
import com.liquidnet.service.kylin.dto.vo.KylinTicketVo;
import com.liquidnet.service.kylin.dto.vo.ignore.KylinPerformanceIgnoreVo;
import com.liquidnet.service.kylin.dto.vo.ignore.KylinTicketIgnoreVo;
import com.liquidnet.service.kylin.dto.vo.ignore.KylinTicketTimesIgnoreVo;
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 或 无数据 创建
            PerformancePartnerVo createParam = mongoTemplate.findOne(Query.query(Criteria.where("performancesId").is(step1Param.getPerformancesId())), PerformancePartnerVo.class, PerformancePartnerVo.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);
            PerformancePartnerVo performancePartnerVo = new PerformancePartnerVo();
            BeanUtils.copyProperties(step1Param, performancePartnerVo);
            performancePartnerVo.setIsTrueName(0);
            performancePartnerVo.setLimitCount(0);
            performancePartnerVo.setCreatedAt(createdAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            performancePartnerVo.setIsSubmit(0);
            performancePartnerVo.setStatus(0);
            performancePartnerVo.setStatusSell(1);
            performancePartnerVo.setAuditStatus(-1);
            performancePartnerVo.setRoadShowId("0");
            performancePartnerVo.setProjectId("0");
            performancePartnerVo.setIsShow(1);
            performancePartnerVo.setFieldName((String) redisUtil.hget(KylinRedisConst.FIELDS + ":" + performancePartnerVo.getFieldId(), "name"));
            performancePartnerVo.setNoticeImage(dataUtils.getBuyNoticeJsonString(step1Param.getNoticeIds()));

            mongoTemplate.insert(
                    performancePartnerVo, PerformancePartnerVo.class.getSimpleName()
            );
            return performanceId;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String updateStep1(PerformanceStep1Param step1Param) {
        // 获取 当前时间 -> 创建时间
        LocalDateTime timeNow = LocalDateTime.now();
        String performanceId = step1Param.getPerformancesId();
        try {
            PerformancePartnerVo data = mongoTemplate.findOne(Query.query(Criteria.where("performancesId").is(performanceId)),
                    PerformancePartnerVo.class, PerformancePartnerVo.class.getSimpleName());
            if (data == null || data.getAuditStatus() == null || data.getAuditStatus() == 0) {
                return "不可修改";
            }

            step1Param.setPerformancesId(performanceId);
            PerformancePartnerVo performancePartnerVo = new PerformancePartnerVo();
            BeanUtils.copyProperties(step1Param, performancePartnerVo);
            performancePartnerVo.setCreatedAt(timeNow.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            performancePartnerVo.setUpdatedAt(timeNow.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            performancePartnerVo.setIsSubmit(0);
            performancePartnerVo.setStatus(0);
            performancePartnerVo.setNoticeImage(dataUtils.getBuyNoticeJsonString(step1Param.getNoticeIds()));
            performancePartnerVo.setFieldName((String) redisUtil.hget(KylinRedisConst.FIELDS + ":" + performancePartnerVo.getFieldId(), "name"));
            performancePartnerVo.setNoticeImage(dataUtils.getBuyNoticeJsonString(step1Param.getNoticeIds()));
            if (data != null) { // 有修改记录
                performancePartnerVo.setIsTrueName(data.getIsTrueName());
                performancePartnerVo.setLimitCount(data.getLimitCount());
                performancePartnerVo.setStatusSell(data.getStatusSell());
                performancePartnerVo.setRoadShowId(data.getRoadShowId());
                performancePartnerVo.setProjectId(data.getProjectId());
                BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(performancePartnerVo));
                mongoTemplate.getCollection(PerformancePartnerVo.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));
                performancePartnerVo.setIsTrueName(statusData.getIsTrueName());
                performancePartnerVo.setLimitCount(statusData.getLimitCount());
                performancePartnerVo.setStatusSell(statusData.getStatusSell());
                performancePartnerVo.setRoadShowId(relationsData.getRoadShowId());
                performancePartnerVo.setProjectId(relationsData.getProjectId());
                mongoTemplate.insert(
                        performancePartnerVo, PerformancePartnerVo.class.getSimpleName()
                );
            }
            return performanceId;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public ResponseDto<PerformancePartnerVo> getStep1(String performancesId) {
        PerformancePartnerVo data = mongoTemplate.findOne(
                Query.query(Criteria.where("performancesId").is(performancesId)), PerformancePartnerVo.class, PerformancePartnerVo.class.getSimpleName()
        );
        if (data == null) {
            return ResponseDto.failure(ErrorMapping.get(20104));
        }
        log.info(" PERFORMANCE  演出第一步 获取");
        return ResponseDto.success(data);
    }

    @Override
    public ResponseDto<String> step2(PerformanceStep2Param step2Param) {
        ResponseDto<String> result = null;
        // 无 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 || performanceStatus.getStatus() == 4) {
                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 ResponseDto<String> createStep2(PerformanceStep2Param step2Param) {
        try {
            // 获取 主键id
            String performanceId = step2Param.getPerformancesId();
            // 获取 当前时间 -> 创建时间
            LocalDateTime createdAt = LocalDateTime.now();

            boolean isExistsSubmit = mongoTemplate.exists(Query.query(Criteria.where("performancesId").is(performanceId).and("auditStatus").is(0)),
                    PerformancePartnerVo.class,
                    PerformancePartnerVo.class.getSimpleName());

            if (isExistsSubmit) {
                return ResponseDto.failure(ErrorMapping.get(20112));
            }

            //演出修改数据
            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);
                map.put("auditStatus", 0);
                BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
                mongoTemplate.getCollection(PerformancePartnerVo.class.getSimpleName()).updateOne(
                        Query.query(Criteria.where("performancesId").is(performanceId)).getQueryObject(),
                        object
                );
                //提交 票
                List<KylinTicketTimesPartnerVo> kylinTicketTimesPartnerVoList = ticketTimesPartnerService.getTimesMongoList(performanceId);
                for (KylinTicketTimesPartnerVo ticketTimes : kylinTicketTimesPartnerVoList) {
                    boolean boolResult = ticketsPartnerService.submitTicketByTimes(ticketTimes.getTicketTimesId());
                    if (boolResult) {
                        return ResponseDto.failure(ErrorMapping.get(20114));
                    }
                }
                if (kylinTicketTimesPartnerVoList.size() <= 0) {
                    return ResponseDto.failure(ErrorMapping.get(20113));
                } else {
                    KylinPerformanceMisVo kylinPerformanceMisVo = 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, kylinPerformanceMisVo, createdAt);
                    KylinPerformances performances = new KylinPerformances();
                    performances.setAuditTime(LocalDateTime.now());
                    performancesMapper.update(performances, new UpdateWrapper<KylinPerformances>().eq("performances_id", performanceId));
                }
                return ResponseDto.success("操作成功");
            } else { //保存
                map.put("status", 0);
                map.put("isCreateSave", 1);
                map.put("auditStatus", -1);
                BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
                mongoTemplate.getCollection(PerformancePartnerVo.class.getSimpleName()).updateMany(
                        Query.query(Criteria.where("performancesId").is(performanceId)).getQueryObject(),
                        object
                );
                return ResponseDto.success("保存成功");
            }
        } catch (Exception e) {
            return ResponseDto.failure(ErrorMapping.get(20115));
        }
    }

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

            boolean isExistsSubmit = mongoTemplate.exists(Query.query(Criteria.where("performancesId").is(performanceId).and("auditStatus").is(0)),
                    PerformancePartnerVo.class,
                    PerformancePartnerVo.class.getSimpleName());

            if (isExistsSubmit) {
                return ResponseDto.failure(ErrorMapping.get(20112));
            }

            //演出修改数据
            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);
                map.put("auditStatus", 0);
                BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
                mongoTemplate.getCollection(PerformancePartnerVo.class.getSimpleName()).updateOne(
                        Query.query(Criteria.where("performancesId").is(performanceId)).getQueryObject(),
                        object
                );
                //提交 票
                List<KylinTicketTimesPartnerVo> kylinTicketTimesPartnerVoList = ticketTimesPartnerService.getTimesMongoList(performanceId);
                for (KylinTicketTimesPartnerVo ticketTimes : kylinTicketTimesPartnerVoList) {
                    boolean boolResult = ticketsPartnerService.submitTicketByTimes(ticketTimes.getTicketTimesId());
                    if (boolResult) {
                        return ResponseDto.failure(ErrorMapping.get(20114));
                    }
                }
                if (kylinTicketTimesPartnerVoList.size() <= 0) {
                    return ResponseDto.failure(ErrorMapping.get(20113));
                } else {
                    KylinPerformanceMisVo kylinPerformanceMisVo = 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));
                    KylinPerformanceStatus performanceStatus = new KylinPerformanceStatus();
                    performanceStatus.setAuditStatus(0);
                    performanceStatusMapper.update(performanceStatus, new UpdateWrapper<KylinPerformanceStatus>().eq("performance_id", performanceId));

                    //提示：票种价格、售票时间、购票限制 直接生效
                    List<TicketTimesTicketCreatePartnerVo> timeList = kylinPerformanceMisVo.getTicketTimes();
                    for (TicketTimesTicketCreatePartnerVo timesItem : timeList) {
                        List<KylinTicketPartnerVo> ticketList = timesItem.getTicket();
                        for (KylinTicketPartnerVo 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();
                                dataUtils.changeSurplusGeneral(ticketItem.getTicketsId(),changeGeneral);
                                dataUtils.changeSurplusExchange(ticketItem.getTicketsId(),changeExchange);
                            }
                            //修改 mysql 库存
                            KylinTicketStatus inventory = new KylinTicketStatus();
                            inventory.setTotalExchange(ticketItem.getTotalExchange());
                            inventory.setTotalGeneral(ticketItem.getTotalGeneral());
                            inventory.setIsTrueName(kylinPerformanceMisVo.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()));
                        }
                    }
                    performanceVoTask.performanceVoStatus(performanceId);
                }
                return ResponseDto.success("操作完成");
            } else { //保存
                map.put("status", 0);
                map.put("auditStatus", -1);
                BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
                mongoTemplate.getCollection(PerformancePartnerVo.class.getSimpleName()).updateMany(
                        Query.query(Criteria.where("performancesId").is(performanceId)).getQueryObject(),
                        object
                );
                return ResponseDto.success("保存成功");
            }
        } catch (Exception e) {
            return ResponseDto.failure(ErrorMapping.get(20115));
        }
    }

    @Override
    public ResponseDto<PerformanceStep2Param> getStep2(String performancesId) {
        PerformancePartnerVo data = mongoTemplate.findOne(
                Query.query(Criteria.where("performancesId").is(performancesId)), PerformancePartnerVo.class, PerformancePartnerVo.class.getSimpleName()
        );
        if (data == null) {
            return ResponseDto.failure(ErrorMapping.get(20104));
        }
        List<KylinTicketTimesPartnerVo> kylinTicketTimesPartnerVos = ticketTimesPartnerService.getTimesMongoList(performancesId);
        List<TicketTimesTicketCreatePartnerVo> ticketTimesTicketCreatePartnerVoList = new ArrayList<TicketTimesTicketCreatePartnerVo>();

        for (KylinTicketTimesPartnerVo ticketTimes : kylinTicketTimesPartnerVos) {
            TicketTimesTicketCreatePartnerVo ticketTimesTicketCreatePartnerVo = new TicketTimesTicketCreatePartnerVo();
            BeanUtils.copyProperties(ticketTimes, ticketTimesTicketCreatePartnerVo);
            List<KylinTicketPartnerVo> kylinTicketPartnerVos = ticketsPartnerService.getTicketMongoList(ticketTimes.getTicketTimesId());
            ticketTimesTicketCreatePartnerVo.setTicket(kylinTicketPartnerVos);
            ticketTimesTicketCreatePartnerVoList.add(ticketTimesTicketCreatePartnerVo);
        }

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

    @Override
    public ResponseDto<String> onLinePerformance(String performancesId) {
        try {
            KylinPerformanceStatus performanceStatusData = performanceStatusMapper.selectOne(new UpdateWrapper<KylinPerformanceStatus>().eq("performance_id", performancesId));
            if (!(performanceStatusData.getStatus() == 3 || performanceStatusData.getStatus() == 7)) {
                return ResponseDto.failure(ErrorMapping.get(20110));
            }
            // 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));
            KylinPerformanceVo kylinPerformanceVoData = new KylinPerformanceVo();
            kylinPerformanceVoData.setPerformance(performancesData);
            kylinPerformanceVoData.setPerformanceRelations(performanceRelationsData);
            kylinPerformanceVoData.setPerformanceStatus(performanceStatusData);

            String cityName = (String) redisUtil.hget(KylinRedisConst.FIELDS + ":" + kylinPerformanceVoData.getFieldId(), "city_name");
            KylinFields fields = new KylinFields();
            fields.setCityId(null);
            fields.setLatitude((String) redisUtil.hget(KylinRedisConst.FIELDS + ":" + kylinPerformanceVoData.getFieldId(), "latitude"));
            fields.setLongitude((String) redisUtil.hget(KylinRedisConst.FIELDS + ":" + kylinPerformanceVoData.getFieldId(), "longitude"));
            fields.setCityName((String) redisUtil.hget(KylinRedisConst.FIELDS + ":" + kylinPerformanceVoData.getFieldId(), "city_name"));
            fields.setName((String) redisUtil.hget(KylinRedisConst.FIELDS + ":" + kylinPerformanceVoData.getFieldId(), "name"));
            kylinPerformanceVoData.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;
            int payCountdownMinute = 15;
            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));
                KylinTicketTimesVo kylinTicketTimesVo = new KylinTicketTimesVo();
                kylinTicketTimesVo.setTicketTimes(ticketTimes);
                kylinTicketTimesVo.setPerformanceId(ticketTimeRelationItem.getPerformanceId());
                kylinTicketTimesVo.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));
                    KylinTicketVo kylinTicketVo = new KylinTicketVo();
                    kylinTicketVo.setTimeId(ticketRelationsItem.getTimesId());
                    kylinTicketVo.setTicket(tickets);
                    kylinTicketVo.setTicketStatus(ticketStatus);
                    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()
                        );
                    }

                    //票种 库存redis
                    if (!redisUtil.hHasKey(KylinRedisConst.PERFORMANCES_INVENTORY + kylinTicketVo.getTicketsId(), KylinRedisConst.SURPLUS_GENERAL)) {
                        dataUtils.setSurplusGeneral(kylinTicketVo.getTicketsId(),ticketStatus.getTotalGeneral());
                        dataUtils.setSurplusExchange(kylinTicketVo.getTicketsId(),ticketStatus.getSurplusExchange());
                    }

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

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

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

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

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

                    payCountdownMinute = tickets.getPayCountdownMinute();

                    if (price.subtract(kylinTicketVo.getPrice()).compareTo(new BigDecimal("0.00")) < 0) {
                        price = kylinTicketVo.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(kylinTicketTimesVo.getTicketTimesId())), KylinTicketTimesVo.class, KylinTicketTimesVo.class.getSimpleName());
                if (!ticketTimesExists) {
                    mongoTemplate.insert(
                            kylinTicketTimesVo, KylinTicketTimesVo.class.getSimpleName()
                    );
                }

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

            boolean performanceExists =
                    mongoTemplate.exists(Query.query(Criteria.where("performancesId").is(kylinPerformanceVoData.getPerformancesId())), KylinPerformanceVo.class, KylinPerformanceVo.class.getSimpleName());
            if (!performanceExists) {
                mongoTemplate.insert(
                        kylinPerformanceVoData, KylinPerformanceVo.class.getSimpleName()
                );
            }
            //判断状态
            performanceVoTask.performanceVoStatus(performancesId);
            return ResponseDto.success("上线成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseDto.failure(ErrorMapping.get(20108));
        }
    }

    @Override
    public ResponseDto<String> outLinePerformance(String performancesId) {
        try {

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

            if (performanceStatusData.getStatus() != 6) {
                return ResponseDto.failure(ErrorMapping.get(20111));
            }

            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 迁移 演出数据迁移
            KylinPerformanceVo kylinPerformanceVo = mongoTemplate.findOne(Query.query(Criteria.where("performancesId").is(performancesId)), KylinPerformanceVo.class, KylinPerformanceVo.class.getSimpleName());
            KylinPerformanceIgnoreVo kylinPerformanceIgnoreVo = new KylinPerformanceIgnoreVo();
            BeanUtils.copyProperties(kylinPerformanceVo, kylinPerformanceIgnoreVo);
            kylinPerformanceIgnoreVo.setAppStatus(7);
            mongoTemplate.remove(Query.query(Criteria.where("performancesId").is(performancesId)), KylinPerformanceIgnoreVo.class, KylinPerformanceIgnoreVo.class.getSimpleName());
            mongoTemplate.insert(kylinPerformanceIgnoreVo, KylinPerformanceIgnoreVo.class.getSimpleName());
            mongoTemplate.remove(Query.query(Criteria.where("performancesId").is(performancesId)), KylinPerformanceVo.class, KylinPerformanceVo.class.getSimpleName());

            List<KylinTicketTimesVo> kylinTicketTimesVoList = mongoTemplate.find(Query.query(Criteria.where("performanceId").is(performancesId)), KylinTicketTimesVo.class, KylinTicketTimesVo.class.getSimpleName());
            for (KylinTicketTimesVo kylinTicketTimesVoItem : kylinTicketTimesVoList) {
                //场次数据迁移
                KylinTicketTimesIgnoreVo kylinTicketTimesIgnoreVo = new KylinTicketTimesIgnoreVo();
                BeanUtils.copyProperties(kylinTicketTimesVoItem, kylinTicketTimesIgnoreVo);
                mongoTemplate.remove(Query.query(Criteria.where("ticketTimesId").is(kylinTicketTimesVoItem.getTicketTimesId())), KylinTicketTimesIgnoreVo.class, KylinTicketTimesIgnoreVo.class.getSimpleName());
                mongoTemplate.insert(kylinTicketTimesIgnoreVo, KylinTicketTimesIgnoreVo.class.getSimpleName());
                mongoTemplate.remove(Query.query(Criteria.where("ticketTimesId").is(kylinTicketTimesVoItem.getTicketTimesId())), KylinTicketTimesVo.class, KylinTicketTimesVo.class.getSimpleName());

                List<KylinTicketVo> kylinTicketVoList = mongoTemplate.find(Query.query(Criteria.where("timeId").is(kylinTicketTimesVoItem.getTicketTimesId())), KylinTicketVo.class, KylinTicketVo.class.getSimpleName());
                for (KylinTicketVo kylinTicketVoItem : kylinTicketVoList) {
                    // 票 迁移
                    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("下线成功");
        } catch (Exception e) {
            return ResponseDto.failure(ErrorMapping.get(20109));
        }
    }

    @Override
    public String copyPerformance(String performancesId) {
        try {
            PerformancePartnerVo performancePartnerVo = mongoTemplate.findOne(Query.query(Criteria.where("performancesId").is(performancesId)), PerformancePartnerVo.class, PerformancePartnerVo.class.getSimpleName());
            //复制演出
            performancePartnerVo.setPerformancesId(IDGenerator.nextSnowId().toString());
            performancePartnerVo.setStatus(0);
            performancePartnerVo.setAuditStatus(-1);
            performancePartnerVo.setIsCreateSave(1);
            mongoTemplate.insert(performancePartnerVo, PerformancePartnerVo.class.getSimpleName());

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

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

    @Override
    public ResponseDto<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, PerformancePartnerVo.class, PerformancePartnerVo.class.getSimpleName());
            List<PerformancePartnerVo> performancePartnerVo = mongoTemplate.find(query, PerformancePartnerVo.class, PerformancePartnerVo.class.getSimpleName());
            query.with(pageable);
            //处理Vo
            List<KylinPerformancePartnerListVo> voList = new ArrayList<>();
            for (PerformancePartnerVo item : performancePartnerVo) {
                KylinPerformancePartnerListVo voData = new KylinPerformancePartnerListVo();
                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 ResponseDto.failure(ErrorMapping.get(20104));
            }
        }
        return ResponseDto.success(pageInfoTmp);
    }

    @Override
    public ResponseDto<String> withdraw(String performancesId) {
        try {
            //mysql auditStatus
            KylinPerformanceStatus performanceStatus = performanceStatusMapper.selectOne(new UpdateWrapper<KylinPerformanceStatus>().eq("performance_id", performancesId));
            if (performanceStatus != null && performanceStatus.getAuditStatus() == 0) {
                KylinPerformanceStatus data1 = new KylinPerformanceStatus();
                HashMap<String, Object> map = new HashMap<>();
                if (performanceStatus.getStatus() >= 3) {//通过审核
                    data1.setAuditStatus(1);
                    data1.setStatus(null);
                    map.put("auditStatus", 1);
                } else if (performanceStatus.getStatus() == 4 || performanceStatus.getStatus() == 1) {//未通过审核
                    data1.setAuditStatus(-1);
                    data1.setStatus(0);
                    map.put("auditStatus", -1);
                    map.put("status", 0);
                } else {
                    data1.setAuditStatus(2);
                    data1.setStatus(null);
                    map.put("auditStatus", 2);
                }
                performanceStatusMapper.update(data1, new UpdateWrapper<KylinPerformanceStatus>().eq("performance_id", performancesId));
                BasicDBObject object = new BasicDBObject("$set", mongoConverter.convertToMongoType(map));
                mongoTemplate.getCollection(PerformancePartnerVo.class.getSimpleName()).updateOne(
                        Query.query(Criteria.where("performancesId").is(performancesId)).getQueryObject(),
                        object
                );
                return ResponseDto.success("撤回成功");
            } else {
                return ResponseDto.failure(ErrorMapping.get(20116));
            }
        } catch (Exception e) {
            return ResponseDto.failure(ErrorMapping.get(20117));
        }
    }
}
