package com.liquidnet.service.merchant.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liquidnet.commons.lang.util.*;
import com.liquidnet.service.base.ErrorMapping;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.base.SqlMapping;
import com.liquidnet.service.base.UserPathDto;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.kylin.constant.KylinRedisConst;
import com.liquidnet.service.kylin.dao.PerformancePartnerListDao;
import com.liquidnet.service.kylin.dto.param.PerformancePartnerListParam;
import com.liquidnet.service.kylin.dto.param.PerformancePartnerVo;
import com.liquidnet.service.kylin.dto.param.PerformanceStep1Param;
import com.liquidnet.service.kylin.dto.param.PerformanceStep2Param;
import com.liquidnet.service.kylin.dto.vo.PerformanceOrderStatisticalVo;
import com.liquidnet.service.kylin.dto.vo.middle.KylinTicketTimesVo;
import com.liquidnet.service.kylin.dto.vo.middle.KylinTicketVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinPerformanceVo;
import com.liquidnet.service.kylin.dto.vo.partner.*;
import com.liquidnet.service.kylin.service.partner.IKylinPerformancesPartnerService;
import com.liquidnet.service.kylin.service.partner.IKylinTicketTimesPartnerService;
import com.liquidnet.service.kylin.service.partner.IKylinTicketsPartnerService;
import com.liquidnet.service.merchant.constant.MerchantAuthorizationConst;
import com.liquidnet.service.merchant.dto.vo.MerchantFieldsVo;
import com.liquidnet.service.merchant.util.*;
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.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

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

    @Autowired
    RedisMerchantUtils redisMerchantUtils;
    @Autowired
    MongoMerchantUtils mongoMerchantUtils;
    @Autowired
    PerformanceUtils performanceUtils;
    @Autowired
    QueueUtil queueUtil;
    @Autowired
    InnerUtils innerUtils;
    @Autowired
    IKylinTicketsPartnerService ticketsPartnerService;
    @Autowired
    IKylinTicketTimesPartnerService ticketTimesPartnerService;

    @Override
    public String step1(PerformanceStep1Param step1Param) {
        String result;
        String merchantId = CurrentUtil.getCurrentUid();
        step1Param.setMerchantId(merchantId);
        // 无 performancesId 则 创建
        if (null == step1Param.getPerformancesId()) {
            result = createStep1(step1Param);
        } else { // 获取 create 数据 status = 0 或 无数据 创建
            PerformancePartnerVo createParam = mongoMerchantUtils.getPerformancePartnerVo(step1Param.getPerformancesId());
            if (createParam == null) {
                result = createStep1(step1Param);
                log.info(UserPathDto.setPartnerData(step1Param.getMerchantId(), "createStep1", step1Param, result));
            } else {// 修改
                if (!mongoMerchantUtils.judgeIsPermission(step1Param.getPerformancesId(), step1Param.getMerchantId(), new String[]{
                        MerchantAuthorizationConst.PerformancePermission.EDIT.getId(),
                })) {
                    return "无权限";
                }
                result = updateStep1(step1Param);
                log.info(UserPathDto.setPartnerData(step1Param.getMerchantId(), "updateStep1", step1Param, result));
            }
        }
        return result;
    }

    @Override
    public String createStep1(PerformanceStep1Param step1Param) {
        // 获取 主键id
        String performanceId = IDGenerator.nextSnowId();
        // 获取 当前时间 -> 创建时间
        LocalDateTime createdAt = LocalDateTime.now();
        try {
            step1Param.setPerformancesId(performanceId);
            PerformancePartnerVo performancePartnerVo = PerformancePartnerVo.getNew();
            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(redisMerchantUtils.getFieldVo(step1Param.getFieldId()).getName());
            performancePartnerVo.setNoticeImage(innerUtils.getBuyNoticeJsonString(step1Param.getNoticeIds()));
            mongoMerchantUtils.insertPerformancePartnerVo(performancePartnerVo);
            return performanceId;
        } catch (Exception e) {
            e.printStackTrace();
            log.info(UserPathDto.setPartnerData(step1Param.getMerchantId(), "createStep1", step1Param, e));
            return null;
        }
    }

    @Override
    public String updateStep1(PerformanceStep1Param step1Param) {
        // 获取 当前时间 -> 创建时间
        LocalDateTime timeNow = LocalDateTime.now();
        String performanceId = step1Param.getPerformancesId();
        try {
            PerformancePartnerVo data = mongoMerchantUtils.getPerformancePartnerVo(performanceId);
            if (data == null || data.getAuditStatus() == null || data.getAuditStatus() == 0) {
                return "不可修改";
            }
            step1Param.setPerformancesId(performanceId);
            PerformancePartnerVo performancePartnerVo = PerformancePartnerVo.getNew();
            BeanUtils.copyProperties(step1Param, performancePartnerVo);
            performancePartnerVo.setPerformancesId(performanceId);
            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(innerUtils.getBuyNoticeJsonString(step1Param.getNoticeIds()));
            performancePartnerVo.setFieldName(redisMerchantUtils.getFieldVo(step1Param.getFieldId()).getName());
            if (data != null) { // 有修改记录
                performancePartnerVo.setIsTrueName(data.getIsTrueName());
                performancePartnerVo.setLimitCount(data.getLimitCount());
                performancePartnerVo.setStatusSell(data.getStatusSell());
                performancePartnerVo.setRoadShowId(data.getRoadShowId());
                performancePartnerVo.setProjectId(data.getProjectId());
                mongoMerchantUtils.updatePerformancePartnerVoById(performancePartnerVo);
            } else { // 无修改记录
                KylinPerformanceVo vo = redisMerchantUtils.getPerformanceVo(performanceId);
                performancePartnerVo.setIsTrueName(vo.getIsTrueName());
                performancePartnerVo.setLimitCount(vo.getLimitCount());
                performancePartnerVo.setStatusSell(vo.getStatusSell());
                performancePartnerVo.setRoadShowId(vo.getRoadShowId());
                performancePartnerVo.setProjectId(vo.getProjectId());
                mongoMerchantUtils.insertPerformancePartnerVo(performancePartnerVo);
            }
            return performanceId;
        } catch (Exception e) {
            e.printStackTrace();
            log.info(UserPathDto.setPartnerData(step1Param.getMerchantId(), "updateStep1", step1Param, e));
            return null;
        }
    }

    @Override
    public ResponseDto<PerformancePartnerVo> getStep1(String performancesId) {
        String merchantId = CurrentUtil.getCurrentUid();
        PerformancePartnerVo data = mongoMerchantUtils.getPerformancePartnerVo(performancesId);
        if (data == null) {
            return ResponseDto.failure(ErrorMapping.get(20104));
        }
        if (!mongoMerchantUtils.judgeIsPermission(performancesId, merchantId, new String[]{
                MerchantAuthorizationConst.PerformancePermission.EDIT.getId(),
        })) {
            if (!data.getMerchantId().equals(merchantId)) {
                return ResponseDto.failure(ErrorMapping.get(29999));
            }
        }
        KylinPerformanceVo vo = redisMerchantUtils.getPerformanceVo(data.getPerformancesId());
        if (null != vo) {
            data.setStatus(vo.getAppStatus());
        }
        log.info(UserPathDto.setPartnerData("0", "getStep1", "merchant=" + merchantId + "&performancesId=" + performancesId, data));
        return ResponseDto.success(data);
    }

    @Override
    public ResponseDto<String> step2(PerformanceStep2Param step2Param) {
        ResponseDto<String> result = null;
        step2Param.setMerchantId(CurrentUtil.getCurrentUid());
        // 无 performancesId 则 创建
        if (!step2Param.getPerformancesId().isEmpty()) { // 获取 create 数据 status = 0 或 无数据 创建
            KylinPerformanceVo vo = redisMerchantUtils.getPerformanceVo(step2Param.getPerformancesId());
            if (vo == null || vo.getAppStatus() == 0 || vo.getAppStatus() == 4) {
                result = createStep2(step2Param);
                log.info(UserPathDto.setPartnerData("0", "createStep2", step2Param, result));
            } else if (vo.getAppStatus() == 1 || vo.getAppStatus() == 3 || vo.getAppStatus() == 6 || vo.getAppStatus() == 7 || vo.getAppStatus() == 8 || vo.getAppStatus() == 9) {// 修改
                if (!mongoMerchantUtils.judgeIsPermission(step2Param.getPerformancesId(), step2Param.getMerchantId(), new String[]{
                        MerchantAuthorizationConst.PerformancePermission.EDIT.getId(),
                })) {
                    if (!vo.getMerchantId().equals(step2Param.getMerchantId())) {
                        return ResponseDto.failure(ErrorMapping.get(29999));
                    }
                }
                result = updateStep2(step2Param);
                log.info(UserPathDto.setPartnerData("0", "updateStep2(step2Param", step2Param, result));
            } else if (vo.getAppStatus() == 10) {
                result = ResponseDto.failure("演出已结束不可修改");
            }
        }
        return result;
    }

    @Override
    public ResponseDto<String> createStep2(PerformanceStep2Param step2Param) {
        try {
            // 获取 主键id
            String performanceId = step2Param.getPerformancesId();
            // 获取 当前时间 -> 创建时间
            LocalDateTime createdAt = LocalDateTime.now();
//            String merchantId = step2Param.getMerchantId();
            boolean isExistsSubmit = mongoMerchantUtils.isExistsSubmitPerformancePartner(performanceId);
            if (isExistsSubmit) {
                return ResponseDto.failure(ErrorMapping.get(20112));
            }

            //演出修改数据
            PerformancePartnerVo performancePartnerVo = PerformancePartnerVo.getNew();
            performancePartnerVo.setPerformancesId(performanceId);
            performancePartnerVo.setIsTrueName(step2Param.getIsTrueName());
            performancePartnerVo.setLimitCount(step2Param.getLimitCount());
            performancePartnerVo.setCreatedAt(createdAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            performancePartnerVo.setIsSubmit(step2Param.getIsSubmit());
//            performancePartnerVo.setStatusSell(1);
            // 获取第一步数据
            if (step2Param.getIsSubmit() == 1) { // 提交
                KylinPerformanceMisVo kylinPerformanceMisVo = performanceUtils.getPerformanceMisVo(performanceId);
                MerchantFieldsVo fieldsVo = redisMerchantUtils.getFieldVo(kylinPerformanceMisVo.getFieldId());
                if (fieldsVo == null) {
                    return ResponseDto.failure(ErrorMapping.get(20114));
                } else {
                    if (fieldsVo.getClaimStatus() == 1) {
                        performancePartnerVo.setFieldAuditStatus(fieldsVo.getIsCheck());
                    } else {
                        performancePartnerVo.setFieldAuditStatus(0);
                    }
                }
                performancePartnerVo.setStatus(1);
                performancePartnerVo.setIsCreateSave(0);
                performancePartnerVo.setAuditStatus(0);
                mongoMerchantUtils.updatePerformancePartnerVoById(performancePartnerVo);
                //提交 票
                List<KylinTicketTimesPartnerVo> kylinTicketTimesPartnerVoList = ticketTimesPartnerService.getTimesMongoList(performanceId);
                for (KylinTicketTimesPartnerVo ticketTimes : kylinTicketTimesPartnerVoList) {
                    boolean boolResult = ticketsPartnerService.submitTicketByTimes(ticketTimes.getTicketTimesId(), null);
                    if (boolResult) {
                        return ResponseDto.failure(ErrorMapping.get(20114));
                    }
                }
                if (kylinTicketTimesPartnerVoList.size() <= 0) {
                    return ResponseDto.failure(ErrorMapping.get(20113));
                } else {
                    LocalDateTime now = LocalDateTime.now();
                    HashMap<String, Object> mapSql = CollectionUtil.mapStringObject();
                    mapSql.put("isCreateSave", 0);
                    mapSql.put("rejectTxt", "");
                    mapSql.put("status", 1);
                    mapSql.put("updatedAt", createdAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    performanceUtils.createPerformanceMySql(performanceId, mapSql, kylinPerformanceMisVo, createdAt);
                    queueUtil.sendMsgByRedis(MQConst.MerchantQueue.SQL_MERCHANT_TICKET_UPDATE.getKey(),
                            SqlMapping.get("kylin_performances.auditTime",
                                    now, performanceId, now, now
                            ));
                }
                return ResponseDto.success("操作成功");
            } else { //保存
                performancePartnerVo.setStatus(0);
                performancePartnerVo.setIsCreateSave(1);
                performancePartnerVo.setAuditStatus(-1);
                mongoMerchantUtils.updatePerformancePartnerVoById(performancePartnerVo);
                return ResponseDto.success("保存成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(UserPathDto.setPartnerData("0", "createStep2", step2Param, e));
            return ResponseDto.failure(ErrorMapping.get(20115));
        }
    }

    @Override
    public ResponseDto<String> updateStep2(PerformanceStep2Param step2Param) {
        try {
            // 获取 主键id
            String merchantId = step2Param.getMerchantId();
            String performanceId = step2Param.getPerformancesId();
            LinkedList<String> sqls = CollectionUtil.linkedListString();
            sqls.add(SqlMapping.get("kylin_performance.updateStep2"));
            sqls.add(SqlMapping.get("kylin_performance_status.updateStep2"));
            sqls.add(SqlMapping.get("kylin_ticket.updateStep2"));
            sqls.add(SqlMapping.get("kylin_ticket_status.updateStep2"));
            sqls.add(SqlMapping.get("kylin_ticket_express_module.del"));
            sqls.add(SqlMapping.get("kylin_ticket_express_module.insert"));
            LinkedList<Object[]> sqlsDataA = CollectionUtil.linkedListObjectArr();
            LinkedList<Object[]> sqlsDataB = CollectionUtil.linkedListObjectArr();
            LinkedList<Object[]> sqlsDataC = CollectionUtil.linkedListObjectArr();
            LinkedList<Object[]> sqlsDataD = CollectionUtil.linkedListObjectArr();
            LinkedList<Object[]> sqlsDataE = CollectionUtil.linkedListObjectArr();
            LinkedList<Object[]> sqlsDataF = CollectionUtil.linkedListObjectArr();
            LocalDateTime now = LocalDateTime.now();
            // 获取 当前时间 -> 创建时间
            boolean isExistsSubmit = mongoMerchantUtils.isExistsSubmitPerformancePartner(performanceId);
            if (isExistsSubmit) {
                return ResponseDto.failure(ErrorMapping.get(20112));
            }
            //演出修改数据
            PerformancePartnerVo performancePartnerVo = PerformancePartnerVo.getNew();
            performancePartnerVo.setPerformancesId(performanceId);
            performancePartnerVo.setIsTrueName(step2Param.getIsTrueName());
            performancePartnerVo.setLimitCount(step2Param.getLimitCount());
            performancePartnerVo.setCreatedAt(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            performancePartnerVo.setUpdatedAt(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            performancePartnerVo.setIsSubmit(step2Param.getIsSubmit());
            KylinPerformanceMisVo kylinPerformanceMisVo = performanceUtils.getPerformanceMisVo(performanceId);
            MerchantFieldsVo fieldsVo = redisMerchantUtils.getFieldVo(kylinPerformanceMisVo.getFieldId());
            if (fieldsVo == null) {
                return ResponseDto.failure(ErrorMapping.get(20114));
            } else {
                if (fieldsVo.getClaimStatus() == 1) {
                    performancePartnerVo.setFieldAuditStatus(fieldsVo.getIsCheck());
                } else {
                    performancePartnerVo.setFieldAuditStatus(0);
                }
            }

            // 获取第一步数据
            if (step2Param.getIsSubmit() == 1) { // 提交
                if (performanceUtils.judgeIsAudit(performanceId)) {
                    performancePartnerVo.setAuditStatus(0);
                    performancePartnerVo.setStatus(1);
                } else {
                    performancePartnerVo.setAuditStatus(1);
                    performancePartnerVo.setStatus(9);
                }
                mongoMerchantUtils.updatePerformancePartnerVoById(performancePartnerVo);
                //提交 票
                List<KylinTicketTimesPartnerVo> kylinTicketTimesPartnerVoList = ticketTimesPartnerService.getTimesMongoList(performanceId);
                for (KylinTicketTimesPartnerVo ticketTimes : kylinTicketTimesPartnerVoList) {
                    boolean boolResult = ticketsPartnerService.submitTicketByTimes(ticketTimes.getTicketTimesId(), performancePartnerVo.getStatus());
                    if (boolResult) {
                        return ResponseDto.failure(ErrorMapping.get(20114));
                    }
                }
                if (kylinTicketTimesPartnerVoList.size() <= 0) {
                    return ResponseDto.failure(ErrorMapping.get(20113));
                } else {
                    HashMap<String, Object> mapSql = CollectionUtil.mapStringObject();
                    mapSql.put("rejectTxt", "");
                    mapSql.put("status", performancePartnerVo.getStatus());
                    mapSql.put("updatedAt", now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    sqlsDataA.add(new Object[]{
                            now, kylinPerformanceMisVo.getNoticeImage(), performanceId, now, now
                    });
                    sqlsDataB.add(new Object[]{
                            performancePartnerVo.getFieldAuditStatus(), performancePartnerVo.getAuditStatus(), step2Param.getIsTrueName(), step2Param.getLimitCount(), performanceId, now, now
                    });
                    redisMerchantUtils.setPerformanceIsTrueName(performanceId, step2Param.getIsTrueName());

                    //提示：票种价格、售票时间、票种购票限制 直接生效 (演出购票限制，购票须知 演出是否实名 票种缺货登记 票种是否电子票 票种是否快递票 票种最低购买张数 票种是否显示二维码)
                    List<TicketTimesTicketCreatePartnerVo> timeList = kylinPerformanceMisVo.getTicketTimes();
                    for (TicketTimesTicketCreatePartnerVo timesItem : timeList) {
                        List<KylinTicketPartnerVo> ticketList = timesItem.getTicket();
                        for (KylinTicketPartnerVo ticketItem : ticketList) {
                            //修改 redis库存
                            if (redisMerchantUtils.hasKey(KylinRedisConst.PERFORMANCES_INVENTORY + ticketItem.getTicketsId() + ":" + KylinRedisConst.SURPLUS_GENERAL)) {
                                KylinPerformanceVo vo = redisMerchantUtils.getPerformanceVo(performanceId);
                                KylinTicketVo ticketData = null;
                                for (int x = 0; x < vo.getTicketTimeList().size(); x++) {
                                    KylinTicketTimesVo ticketTimesData = vo.getTicketTimeList().get(x);
                                    for (int y = 0; y < ticketTimesData.getTicketList().size(); y++) {
                                        KylinTicketVo ticketStatus = ticketTimesData.getTicketList().get(y);
                                        if (ticketStatus.getTicketsId().equals(ticketItem.getTicketsId())) {
                                            ticketData = ticketStatus;
                                            break;
                                        }
                                        break;
                                    }
                                }

                                int changeGeneral = ticketItem.getTotalGeneral() - ticketData.getTotalGeneral();
                                int changeExchange = ticketItem.getTotalExchange() - ticketData.getTotalExchange();
                                redisMerchantUtils.changeSurplusGeneral(ticketItem.getTicketsId(), changeGeneral);
                                redisMerchantUtils.changeSurplusExchange(ticketItem.getTicketsId(), changeExchange);
                            }

                            //修改 mysql 售卖时间
                            sqlsDataC.add(new Object[]{
                                    DateUtil.Formatter.yyyyMMddHHmmss.parse(ticketItem.getTimeEnd()), DateUtil.Formatter.yyyyMMddHHmmss.parse(ticketItem.getTimeStart()),
                                    DateUtil.Formatter.yyyyMMddHHmmss.parse(ticketItem.getTimeEndExpress()), kylinPerformanceMisVo.getPayCountdownMinute(),
                                    ticketItem.getPrice(), ticketItem.getTicketsId(), now, now
                            });
                            //修改 mysql 购票限购、库存
                            sqlsDataD.add(new Object[]{
                                    ticketItem.getTotalExchange(), ticketItem.getTotalGeneral(), kylinPerformanceMisVo.getIsTrueName(),
                                    ticketItem.getLimitCount(), ticketItem.getIsLackRegister(), ticketItem.getIsExpress(),
                                    ticketItem.getIsElectronic(), ticketItem.getCounts(), ticketItem.getIsShowCode(),
                                    DateUtil.Formatter.yyyyMMddHHmmss.parse(ticketItem.getQrCodeShowTime()), ticketItem.getTicketsId(), now, now
                            });
                            //快递相关
                            KylinTicketExpressModuleVo moduleVo = redisMerchantUtils.getTEMMerchantVo(ticketItem.getTicketsId());
                            if (moduleVo != null) {
                                redisMerchantUtils.setTEMVo(ticketItem.getTicketsId(), moduleVo);
                                sqlsDataE.add(new Object[]{ticketItem.getTicketsId()});
                                for (ExpressModuleVo mVo : moduleVo.getProduceCodeList())
                                    sqlsDataF.add(new Object[]{
                                            ticketItem.getTicketsId(), mVo.getProductCode(), now, now
                                    });
                            }
                        }
                    }
                    String sqlData = SqlMapping.gets(sqls, sqlsDataA, sqlsDataB, sqlsDataC, sqlsDataD, sqlsDataE, sqlsDataF);
                    queueUtil.sendMsgByRedis(MQConst.MerchantQueue.SQL_MERCHANT_STEP2.getKey(),
                            sqlData);

                    performanceUtils.performanceVoStatus(performanceId, null);
                }
                return ResponseDto.success("操作完成");
            } else { //保存
                performancePartnerVo.setStatus(0);
                performancePartnerVo.setAuditStatus(-1);
                mongoMerchantUtils.updatePerformancePartnerVoById(performancePartnerVo);
                return ResponseDto.success("保存成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(UserPathDto.setPartnerData("0", "updateStep2", step2Param, e));
            return ResponseDto.failure(ErrorMapping.get(20115));
        }
    }

    @Override
    public ResponseDto<PerformanceStep2Param> getStep2(String performancesId) {
        String merchantId = CurrentUtil.getCurrentUid();
        PerformancePartnerVo data = mongoMerchantUtils.getPerformancePartnerVo(performancesId);
        if (data == null) {
            return ResponseDto.failure(ErrorMapping.get(20104));
        }
        if (!mongoMerchantUtils.judgeIsPermission(performancesId, merchantId, new String[]{
                MerchantAuthorizationConst.PerformancePermission.EDIT.getId(),
        })) {
            if (!data.getMerchantId().equals(merchantId)) {
                return ResponseDto.failure(ErrorMapping.get(29999));
            }
        }
        List<KylinTicketTimesPartnerVo> kylinTicketTimesPartnerVos = ticketTimesPartnerService.getTimesMongoList(performancesId);
        List<TicketTimesTicketCreatePartnerVo> ticketTimesTicketCreatePartnerVoList = ObjectUtil.getTicketTimesTicketCreatePartnerVoList();
        for (KylinTicketTimesPartnerVo ticketTimes : kylinTicketTimesPartnerVos) {
            TicketTimesTicketCreatePartnerVo ticketTimesTicketCreatePartnerVo = TicketTimesTicketCreatePartnerVo.getNew();
            BeanUtils.copyProperties(ticketTimes, ticketTimesTicketCreatePartnerVo);
            List<KylinTicketPartnerVo> kylinTicketPartnerVos = ticketsPartnerService.getTicketMongoList(ticketTimes.getTicketTimesId());
            for(KylinTicketPartnerVo item : kylinTicketPartnerVos){
                if(item.getIsExpress()==1) {
                    List<ExpressModuleVo> expressModuleVos = redisMerchantUtils.getTEMMerchantVo(item.getTicketsId()).getProduceCodeList();
                    item.setExpressModuleList(expressModuleVos);
                }
            }
            ticketTimesTicketCreatePartnerVo.setTicket(kylinTicketPartnerVos);
            ticketTimesTicketCreatePartnerVoList.add(ticketTimesTicketCreatePartnerVo);
        }
        PerformanceStep2Param performanceStep2Param = PerformanceStep2Param.getNew();
        BeanUtils.copyProperties(data, performanceStep2Param);
        KylinPerformanceVo vo = redisMerchantUtils.getPerformanceVo(performancesId);
        if (null != vo) {
            performanceStep2Param.setStatus(vo.getAppStatus());
        } else {
            performanceStep2Param.setStatus(-1);
        }

        performanceStep2Param.setTicketTimes(ticketTimesTicketCreatePartnerVoList);
        log.info(UserPathDto.setPartnerData("0", "getStep2", "performancesId=" + performancesId, performanceStep2Param));
        return ResponseDto.success(performanceStep2Param);
    }

    @Override
    public ResponseDto<String> onLinePerformance(String performancesId) {
        try {
            String merchantId = CurrentUtil.getCurrentUid();
//            LinkedList<String> sqls = CollectionUtil.linkedListString();
//            sqls.add(SqlMapping.get("kylin_performances_status.onLine"));
//            sqls.add(SqlMapping.get("kylin_ticket_status.onLine"));
//            LinkedList<Object[]> sqlsDataA = CollectionUtil.linkedListObjectArr();
//            LinkedList<Object[]> sqlsDataB = CollectionUtil.linkedListObjectArr();
            KylinPerformanceVo vo = redisMerchantUtils.getPerformanceVo(performancesId);
            if (!mongoMerchantUtils.judgeIsPermission(performancesId, merchantId, new String[]{
                    MerchantAuthorizationConst.PerformancePermission.LINE.getId(),
            })) {
                if (!vo.getMerchantId().equals(merchantId)) {
                    return ResponseDto.failure(ErrorMapping.get(29999));
                }
            }
            if (!(vo.getAppStatus() == 3 || vo.getAppStatus() == 7)) {
                return ResponseDto.failure(ErrorMapping.get(20110));
            }
            // mysql
            LocalDateTime updatedAt = LocalDateTime.now();
//            sqlsDataA.add(new Object[]{
//                    6, updatedAt, performancesId,updatedAt,updatedAt
//            });
            vo.setAppStatus(6);
            //场次
            List<KylinTicketTimesVo> ticketTimeVo = vo.getTicketTimeList();
            for (KylinTicketTimesVo ticketTimeItem : ticketTimeVo) {
                //票
                List<KylinTicketVo> ticketVo = ticketTimeItem.getTicketList();
                for (KylinTicketVo ticketItem : ticketVo) {
//                    sqlsDataB.add(new Object[]{
//                            9, updatedAt, ticketItem.getTicketsId(),updatedAt,updatedAt
//                    });
                    KylinTicketPartnerVo ticketPartnerVo = KylinTicketPartnerVo.getNew();
                    ticketItem.setStatus(9);
                    ticketPartnerVo.setTicketsId(ticketItem.getTicketsId());
                    ticketPartnerVo.setStatus(9);
                    ticketPartnerVo.setUpdatedAt(updatedAt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    mongoMerchantUtils.updateSubmitTicketVoById(ticketPartnerVo);
                }
            }
//            String sqlData = SqlMapping.gets(sqls, sqlsDataA, sqlsDataB);
//            queueUtil.sendMsgByRedis(MQConst.MerchantQueue.SQL_MERCHANT_LINE.getKey(),
//                    sqlData);
            mongoMerchantUtils.delPerformanceVo(performancesId);
            mongoMerchantUtils.insertPerformanceVo(vo);
//          判断状态
            performanceUtils.performanceVoStatus(performancesId, null);
            log.info(UserPathDto.setPartnerData("0", "onLinePerformance", "performancesId=" + performancesId, "上线成功"));
            return ResponseDto.success("上线成功");
        } catch (Exception e) {
            log.info(UserPathDto.setPartnerData("0", "onLinePerformance", "performancesId=" + performancesId, e));
            return ResponseDto.failure(ErrorMapping.get(20108));
        }
    }

    @Override
    public ResponseDto<String> outLinePerformance(String performancesId) {
        try {
            String merchantId = CurrentUtil.getCurrentUid();
            KylinPerformanceVo vo = redisMerchantUtils.getPerformanceVo(performancesId);
            if (!mongoMerchantUtils.judgeIsPermission(performancesId, merchantId, new String[]{
                    MerchantAuthorizationConst.PerformancePermission.LINE.getId(),
            })) {
                if (!vo.getMerchantId().equals(merchantId)) {
                    return ResponseDto.failure(ErrorMapping.get(29999));
                }
            }
            if (vo.getAppStatus() >= 3 && vo.getAppStatus() != 4 && vo.getAppStatus() != 7) {//未提审||被拒绝   && performanceStatusData.getStatus() != 10
//                HashMap<String, Object> map = CollectionUtil.mapStringObject();
//                map.put("status", 7);
//                map.put("updatedAt", DateUtil.Formatter.yyyyMMddHHmmss.format(LocalDateTime.now()));
//                mongoMerchantUtils.updatePerformanceVo(map,performancesId);
                vo.setAppStatus(7);
                mongoMerchantUtils.delPerformanceVo(performancesId);
                vo = mongoMerchantUtils.insertPerformanceVo(vo);
//                LocalDateTime updatedAt = LocalDateTime.now();
//                queueUtil.sendMsgByRedis(MQConst.MerchantQueue.SQL_MERCHANT_LINE.getKey(),
//                        SqlMapping.get("kylin_performances_status.outLine",
//                                7, updatedAt, performancesId,updatedAt,updatedAt
//                        ));
                performanceUtils.performanceVoStatus(performancesId, vo.getAppStatus());
                log.info(UserPathDto.setPartnerData("0", "outLinePerformance", "performancesId=" + performancesId, "下线成功"));
                return ResponseDto.success("下线成功");
            } else {
                return ResponseDto.failure(ErrorMapping.get(20111));
            }
        } catch (Exception e) {
            log.info(UserPathDto.setPartnerData("0", "outLinePerformance", "outLinePerformance=" + performancesId, e));
            return ResponseDto.failure(ErrorMapping.get(20109));
        }
    }

    @Override
    public String copyPerformance(String performancesId) {
        try {
            String merchantId = CurrentUtil.getCurrentUid();
            if (!mongoMerchantUtils.judgeIsPermission(performancesId, merchantId, new String[]{
                    MerchantAuthorizationConst.PerformancePermission.READ.getId(),
            })) {
                return "无权限";
            }
            PerformancePartnerVo performancePartnerVo = mongoMerchantUtils.getPerformancePartnerVo(performancesId);
            //复制演出
            performancePartnerVo.setPerformancesId(IDGenerator.nextSnowId());
            performancePartnerVo.setStatus(0);
            performancePartnerVo.setAuditStatus(-1);
            performancePartnerVo.setIsCreateSave(1);
            mongoMerchantUtils.insertPerformancePartnerVo(performancePartnerVo);

            List<KylinTicketTimesPartnerVo> kylinTicketTimesPartnerVos = mongoMerchantUtils.getTicketTimesPartnerVoList(performancesId);
            for (KylinTicketTimesPartnerVo timeItem : kylinTicketTimesPartnerVos) {
                //复制场次
                String timesId = timeItem.getTicketTimesId();
                timeItem.setTicketTimesId(IDGenerator.nextSnowId());
                timeItem.setPerformancesId(performancePartnerVo.getPerformancesId());
                mongoMerchantUtils.insertTicketTimesPartnerVo(timeItem);

                List<KylinTicketPartnerVo> kylinTicketPartnerVos = mongoMerchantUtils.getTicketPartnerVoList(timesId);
                for (KylinTicketPartnerVo ticketItem : kylinTicketPartnerVos) {
                    //复制票
                    ticketItem.setStatus(0);
                    ticketItem.setTimesId(timeItem.getTicketTimesId());
                    ticketItem.setTicketsId(IDGenerator.nextSnowId());
                    mongoMerchantUtils.insertTicketPartnerVo(ticketItem);
                }
            }
            log.info(UserPathDto.setPartnerData("0", "copyPerformance", "performancesId=" + performancesId, performancePartnerVo.getPerformancesId()));
            return performancePartnerVo.getPerformancesId();
        } catch (Exception e) {
            e.printStackTrace();
            log.info(UserPathDto.setPartnerData("0", "copyPerformance", "performancesId=" + performancesId, e));
            return null;
        }
    }

    @Override
    public ResponseDto<PageInfo<PerformancePartnerListDao>> getList(PerformancePartnerListParam performancePartnerListParam) {
        performancePartnerListParam.setMerchantId(CurrentUtil.getCurrentUid());
        int status = performancePartnerListParam.getStatus();
        int page = performancePartnerListParam.getPage() - 1;
        int size = performancePartnerListParam.getSize();
        PageInfo<PerformancePartnerListDao> pageInfoTmp;
        if (status == 0) {//未发布演出
            // 排序 分页
            Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
            //条件
            Criteria criteria = Criteria.where("status").is(status).and("isCreateSave").is(1).and("merchantId").is(performancePartnerListParam.getMerchantId());
            if (!performancePartnerListParam.getTitle().isEmpty()) {
                criteria.and("title").regex(".*?\\" + performancePartnerListParam.getTitle());
            }
            Query query = Query.query(criteria);
            // 查询总数
            long count = mongoMerchantUtils.getPerformancePartnerCount(query);
            List<PerformancePartnerVo> performancePartnerVo = mongoMerchantUtils.getPerformancePartnerList(query);
            query.with(pageable);
            //处理Vo
            List<KylinPerformancePartnerListVo> voList = ObjectUtil.getKylinPerformancePartnerListVo();
            for (PerformancePartnerVo item : performancePartnerVo) {
                KylinPerformancePartnerListVo voData = KylinPerformancePartnerListVo.getNew();
                voData.setStatus0Data(item);
                voList.add(voData);
            }
            pageInfoTmp = new PageInfo(voList);
            pageInfoTmp.setTotal(count);
        } else {//演出列表
            try {
                PageHelper.startPage(performancePartnerListParam.getPage(), performancePartnerListParam.getSize());
                List<PerformancePartnerListDao> voList = mongoMerchantUtils.getPerformanceList(performancePartnerListParam);
                for (int i = 0; i < voList.size(); i++) {
                    PerformancePartnerListDao vo = voList.get(i);
                    vo.setSaleGeneral(vo.getNumber() - vo.getRefundNumber());
                    vo.setTotalSalePrice(vo.getPriceActual().subtract(vo.getPriceRefund()));
                    vo.setSurplusGeneral(vo.getTotalGeneral() - vo.getSaleGeneral());
                    if (vo.getStatus() >= 6 && vo.getStatus() != 7) {
                        if (DateUtil.compareStrDay(vo.getTimeSell(), DateUtil.getNowTime()) > 0) {//未开始
                            vo.setStatus(9);
                        } else if (DateUtil.compareStrDay(vo.getTimeStop(), DateUtil.getNowTime()) < 0) {//已结束
                            vo.setStatus(10);
                        } else {
                            vo.setStatus(6);
                        }
                    }
                }
                pageInfoTmp = new PageInfo(voList);
            } catch (Exception e) {
                e.printStackTrace();
                return ResponseDto.failure(ErrorMapping.get(20104));
            }
        }
        return ResponseDto.success(pageInfoTmp);
    }

    @Override
    public ResponseDto<String> withdraw(String performancesId) {
        try {
            String merchantId = CurrentUtil.getCurrentUid();
            LocalDateTime now = LocalDateTime.now();
            KylinPerformanceVo vo = redisMerchantUtils.getPerformanceVo(performancesId);
            if (!mongoMerchantUtils.judgeIsPermission(performancesId, merchantId, new String[]{
                    MerchantAuthorizationConst.PerformancePermission.EDIT.getId(),
            })) {
                if (!vo.getMerchantId().equals(merchantId)) {
                    return ResponseDto.failure(ErrorMapping.get(29999));
                }
            }
            if (vo != null && vo.getAuditStatus() == 0) {
                PerformancePartnerVo performancePartnerVo = PerformancePartnerVo.getNew();
                performancePartnerVo.setPerformancesId(performancesId);
                if (vo.getAppStatus() >= 3) {//通过审核
                    performancePartnerVo.setAuditStatus(1);
                    queueUtil.sendMsgByRedis(MQConst.MerchantQueue.SQL_MERCHANT_PERFORMANCE_UPDATE.getKey(),
                            SqlMapping.get("kylin_performances_status.withdraw",
                                    1, performancesId, now, now
                            ));
                } else if (vo.getAppStatus() == 4 || vo.getAppStatus() == 1) {//未通过审核
                    performancePartnerVo.setAuditStatus(-1);
                    performancePartnerVo.setStatus(0);
                    queueUtil.sendMsgByRedis(MQConst.MerchantQueue.SQL_MERCHANT_PERFORMANCE_UPDATE.getKey(),
                            SqlMapping.get("kylin_performances_status.withdraw2",
                                    -1, 0, performancesId, now, now
                            ));
                } else {
                    performancePartnerVo.setAuditStatus(2);
                    queueUtil.sendMsgByRedis(MQConst.MerchantQueue.SQL_MERCHANT_PERFORMANCE_UPDATE.getKey(),
                            SqlMapping.get("kylin_performances_status.withdraw",
                                    2, performancesId, now, now
                            ));
                }
                mongoMerchantUtils.updatePerformancePartnerVoById(performancePartnerVo);
                log.info(UserPathDto.setPartnerData("0", "withdraw", "performancesId=" + performancesId, "撤回成功"));
                return ResponseDto.success("撤回成功");
            } else {
                return ResponseDto.failure(ErrorMapping.get(20116));
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info(UserPathDto.setPartnerData("0", "withdraw", performancesId, e));
            return ResponseDto.failure(ErrorMapping.get(20117));
        }
    }

    @Override
    public List<PerformanceOrderStatisticalVo> getPerformanceOrderStatisticalList(String performancesId) {
//        PerformanceOrderStatisticalDao countBean = PerformanceOrderStatisticalDao.getNew();
//        countBean.setTitle("总计：");
//
//        List<PerformanceOrderStatisticalVo> voList = new ArrayList<>();
//        List<PerformanceOrderStatisticalDao> dtoList = performancesMapper.getPerformanceOrderStatisticalList(performancesId);
//        dtoList.forEach(dto -> {
//            PerformanceOrderStatisticalVo vo = PerformanceOrderStatisticalVo.getNew();
//            BeanUtil.copy(dto, vo);
//            voList.add(vo);
//
//            countBean.setTotalGeneral(countBean.getTotalGeneral().add(dto.getTotalGeneral()));
//            countBean.setSaleGeneral(countBean.getSaleGeneral().add(dto.getSaleGeneral()));
//            countBean.setSurplusGeneral(countBean.getSurplusGeneral().add(dto.getSurplusGeneral()));
//            countBean.setTotalSalePrice(countBean.getTotalSalePrice().add(dto.getTotalSalePrice()));
//            countBean.setTotalExchange(countBean.getTotalExchange().add(dto.getTotalExchange()));
//            countBean.setTotalRefundGeneral(countBean.getTotalRefundGeneral().add(dto.getTotalRefundGeneral()));
//            countBean.setTotalRefundPrice(countBean.getTotalRefundPrice().add(dto.getTotalRefundPrice()));
//            countBean.setTotalMemberNumber(countBean.getTotalMemberNumber().add(dto.getTotalMemberNumber()));
//            countBean.setTotalPayingNumber(countBean.getTotalPayingNumber().add(dto.getTotalPayingNumber()));
//            countBean.setTotalBuyUsers(dto.getTotalBuyUsers());
//        });
//        PerformanceOrderStatisticalVo vo = PerformanceOrderStatisticalVo.getNew();
//        BeanUtil.copy(countBean, vo);
//        voList.add(vo);
        return null;
    }
}
