package com.liquidnet.service.platform.controller.A_fskfsfs;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.liquidnet.common.cache.redis.util.RedisDataSourceUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.kylin.constant.KylinRedisConst;
import com.liquidnet.service.kylin.dto.param.PerformancePartnerVo;
import com.liquidnet.service.kylin.dto.vo.mongo.KylinPerformanceVo;
import com.liquidnet.service.kylin.dto.vo.partner.KylinTicketPartnerVo;
import com.liquidnet.service.kylin.dto.vo.partner.KylinTicketTimesPartnerVo;
import com.liquidnet.service.kylin.entity.KylinTicketRelations;
import com.liquidnet.service.kylin.entity.KylinTicketStatus;
import com.liquidnet.service.kylin.entity.KylinTickets;
import com.liquidnet.service.kylin.mapper.KylinTicketRelationsMapper;
import com.liquidnet.service.kylin.mapper.KylinTicketStatusMapper;
import com.liquidnet.service.kylin.mapper.KylinTicketsMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 临时数据处理
 *
 * @author jiangxiulong
 */
@Api(tags = "临时数据处理")
@RestController
@RequestMapping("fskfsfs")
@Slf4j
public class JxlDataKylinPerformancesController {

    @Autowired
    private KylinTicketRelationsMapper ticketRelationsMapper;
    @Autowired
    private KylinTicketStatusMapper ticketStatusMapper;
    @Autowired
    private KylinTicketsMapper ticketsMapper;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisDataSourceUtil redisDataSourceUtil;

    @GetMapping("P001")
    @ApiOperation("演出审核后丢失数据报错")
    @ApiImplicitParams({
            @ApiImplicitParam(type = "query", dataType = "String", name = "performancesId", value = "演出id", required = true),
    })
    public ResponseDto P001(
            @RequestParam("performancesId") String performancesId
    ) {
        try {
            List<KylinTicketTimesPartnerVo> voTimes = mongoTemplate.find(Query.query(Criteria.where("performancesId").is(performancesId)),
                    KylinTicketTimesPartnerVo.class, KylinTicketTimesPartnerVo.class.getSimpleName());
            for (KylinTicketTimesPartnerVo voTime : voTimes) {
                String ticketTimesId = voTime.getTicketTimesId();
                List<KylinTicketPartnerVo> timesIdVo = mongoTemplate.find(Query.query(
                                Criteria.where("timesId").is(ticketTimesId)),
                        KylinTicketPartnerVo.class,
                        KylinTicketPartnerVo.class.getSimpleName());
                for (KylinTicketPartnerVo ticketVo : timesIdVo) {
                    String ticketsId = ticketVo.getTicketsId();
                    PerformancePartnerVo performanceData = mongoTemplate.findOne(Query.query(Criteria.where("performancesId").is(performancesId)), PerformancePartnerVo.class, PerformancePartnerVo.class.getSimpleName());

                    // 票种
                    KylinTickets kylinTickets = ticketsMapper.selectOne(Wrappers.lambdaQuery(KylinTickets.class).eq(KylinTickets::getTicketsId, ticketsId));
                    if (null == kylinTickets) {
                        KylinTickets tickets = new KylinTickets();
                        BeanUtils.copyProperties(ticketVo, tickets);
                        tickets.setPayCountdownMinute(performanceData.getPayCountdownMinute());
                        tickets.setPriceExpress(new BigDecimal("0.00"));
                        tickets.setPriceDiscountMember(new BigDecimal("0.00"));
                        tickets.setPriceDiscount(new BigDecimal("0.00"));
                        tickets.setTimeStart(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketVo.getTimeStart())));
                        tickets.setTimeEnd(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketVo.getTimeEnd())));
                        if (ticketVo.getIsExpress() == 1) {
                            tickets.setTimeEndExpress(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketVo.getTimeEndExpress())));
                            tickets.setDescribeExpress(ticketVo.getDescribeExpress());
                        }
                        if (ticketVo.getIsElectronic() == 1) {
                            tickets.setDescribeElectronic(ticketVo.getDescribeElectronic());
                        }
                        tickets.setUseStart(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(voTime.getUseStart())));
                        tickets.setUseEnd(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(voTime.getUseEnd())));
                        tickets.setSaleRemindMinute(60);
                        tickets.setCreatedAt(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketVo.getCreatedAt())));
                        tickets.setUpdatedAt(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketVo.getUpdatedAt())));
                        ticketsMapper.insert(tickets);
                    }

                    // 库存
                    String surplusGeneralKey = KylinRedisConst.PERFORMANCES_INVENTORY + ticketsId + ":" + KylinRedisConst.SURPLUS_GENERAL;
                    String surplusExchangeKey = KylinRedisConst.PERFORMANCES_INVENTORY + ticketsId + ":" + KylinRedisConst.SURPLUS_EXCHANGE;
                    Object surplusGeneralObj = redisDataSourceUtil.getRedisKylinUtil().get(surplusGeneralKey);
                    Object surplusExchangeObj = redisDataSourceUtil.getRedisKylinUtil().get(surplusExchangeKey);
                    if (null == surplusGeneralObj) {
                        redisDataSourceUtil.getRedisKylinUtil().set(surplusGeneralKey, ticketVo.getSurplusGeneral());
                    }
                    if (null == surplusExchangeObj) {
                        redisDataSourceUtil.getRedisKylinUtil().set(surplusExchangeKey, ticketVo.getSurplusExchange());
                    }

                    // 场次与票种关联表
                    LocalDateTime timeC = null;
                    LocalDateTime timeU = null;
                    KylinTicketRelations kylinTicketRelations = ticketRelationsMapper.selectOne(
                            Wrappers.lambdaQuery(KylinTicketRelations.class)
                                    .eq(KylinTicketRelations::getTicketId, ticketsId)
                                    .eq(KylinTicketRelations::getTimesId, ticketTimesId)
                    );
                    if (null == kylinTicketRelations) {
                        try {
                            timeC = DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketVo.getCreatedAt()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            timeU = DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketVo.getUpdatedAt()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        KylinTicketRelations ticketRelations = new KylinTicketRelations();
                        BeanUtils.copyProperties(ticketVo, ticketRelations);
                        ticketRelations.setCreatedAt(timeC);
                        ticketRelations.setUpdatedAt(timeU);
                        ticketRelations.setTicketRelationsId(IDGenerator.nextSnowId());
                        ticketRelations.setTicketId(ticketsId);
                        ticketRelationsMapper.insert(ticketRelations);
                    }

                    // KylinTicketStatus
                    KylinTicketStatus ticketStatusNew = new KylinTicketStatus();
                    BeanUtils.copyProperties(ticketVo, ticketStatusNew);
                    ticketStatusNew.setTicketId(ticketsId);
                    ticketStatusNew.setStatusExchange(7);
                    if (ticketVo.getExpressType() == null) {
                        ticketStatusNew.setExpressType(0);
                    }
                    ticketStatusNew.setIsTrueName(performanceData.getIsTrueName());
                    ticketStatusNew.setMemberLimitCount(1);
                    ticketStatusNew.setCreatedAt(timeC);
                    ticketStatusNew.setUpdatedAt(timeU);
                    if (ticketVo.getIsShowCode() == 1) {
                        try {
                            ticketStatusNew.setQrCodeShowTime(DateUtil.asLocalDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticketVo.getQrCodeShowTime())));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    KylinTicketStatus ticketStatus = ticketStatusMapper.selectOne(
                            Wrappers.lambdaQuery(KylinTicketStatus.class)
                                    .eq(KylinTicketStatus::getTicketId, ticketsId)
                    );
                    // 添加
                    if (null == ticketStatus) {
                        ticketStatusNew.setTicketStatusId(IDGenerator.nextSnowId());
                        ticketStatusMapper.insert(ticketStatusNew);
                        System.out.println("新增---------------------------------");
                        System.out.println(ticketsId);
                        System.out.println(ticketStatusNew);
                    } else {// 编辑
                        ticketStatusMapper.update(ticketStatusNew,
                                new UpdateWrapper<KylinTicketStatus>().
                                        eq("ticket_id", ticketsId)
                        );
                        System.out.println("编辑---------------------------------");
                        System.out.println(ticketsId);
                        System.out.println(ticketStatusNew);
                    }
                }
            }

            KylinPerformanceVo performanceData = mongoTemplate.findOne(Query.query(Criteria.where("performancesId").is(performancesId)), KylinPerformanceVo.class, KylinPerformanceVo.class.getSimpleName());
            redisDataSourceUtil.getRedisKylinUtil().set(KylinRedisConst.PERFORMANCES + performancesId, performanceData);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        dataUtils.delPerformanceRedis(performancesId);
//        System.out.println(voTimes);
        return ResponseDto.success();
    }

}
