package com.liquidnet.service.platform.service.impl.goblin;

import com.liquidnet.commons.lang.util.IDGenerator;
import com.liquidnet.commons.lang.util.StringUtil;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.goblin.dto.vo.GoblinNftExCodeVo;
import com.liquidnet.service.goblin.dto.vo.GoblinNftExSkuVo;
import com.liquidnet.service.goblin.entity.GoblinNftExCode;
import com.liquidnet.service.goblin.entity.GoblinNftExCodeTask;
import com.liquidnet.service.goblin.entity.GoblinNftExCodeTaskRelation;
import com.liquidnet.service.goblin.entity.GoblinNftExSku;
import com.liquidnet.service.goblin.mapper.*;
import com.liquidnet.service.goblin.service.IGoblinNftExCodeTaskService;
import com.liquidnet.service.platform.utils.GoblinRedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class GoblinNftExCodeTaskServiceImpl implements IGoblinNftExCodeTaskService {

    @Autowired
    private GoblinNftExCodeMapper goblinNftExCodeMapper;
    @Autowired
    GoblinNftExCodeTaskMapper goblinNftExCodeTaskMapper;
    @Autowired
    private GoblinRedisUtils goblinRedisUtils;
    @Autowired
    private GoblinNftExCodeTaskRelationMapper goblinNftExCodeTaskRelationMapper;
    @Autowired
    private GoblinNftExSkuMapper goblinNftExSkuMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseDto<String> generateCode() {

        /**
         * 获取所有定时任务列表
         */
        List<GoblinNftExCodeTask> goblinNftExCodeTasks = goblinNftExCodeTaskMapper.selectByActivity();

        if (goblinNftExCodeTasks == null || goblinNftExCodeTasks.size() <= 0) {
            return ResponseDto.success("0");
        }


        StringBuffer taskIds = new StringBuffer();
        for (GoblinNftExCodeTask goblinNftExCodeTask : goblinNftExCodeTasks) {
            if (goblinNftExCodeTask.getUnbox().equals("1")) {
                taskIds.append(goblinNftExCodeTask.getTaskId()).append(",");
            }
        }

        List<GoblinNftExCodeTaskRelation> goblinNftExCodeTaskRelations = null;
        if (StringUtil.isNotBlank(taskIds)) {
            taskIds.deleteCharAt(taskIds.length() - 1);
            goblinNftExCodeTaskRelations = goblinNftExCodeTaskRelationMapper.selectByTaskIds(taskIds.toString());
        }

        // sku ---> 兑换码关联
        Map<String, GoblinNftExCodeTask> goblinNftExCodeTaskHashMap = new HashMap<>();

        // 当前时间
        LocalDateTime now = LocalDateTime.now();

        // 构建对象
        List<GoblinNftExCode> goblinNftExCodes = new ArrayList<>();
        List<GoblinNftExSku> goblinNftExSkus = new ArrayList<>();

        StringBuffer updTaskIds = new StringBuffer();

        for (GoblinNftExCodeTask goblinNftExCodeTask : goblinNftExCodeTasks) {

            GoblinNftExSku goblinNftExSku = new GoblinNftExSku();
            goblinNftExSku.setActivityId(goblinNftExCodeTask.getActivityId());
            goblinNftExSku.setSpuId(goblinNftExCodeTask.getSpuId());
            goblinNftExSku.setSkuId(goblinNftExCodeTask.getSkuId());
            goblinNftExSku.setStoreId(goblinNftExCodeTask.getStoreId());
            goblinNftExSku.setExStock(goblinNftExCodeTask.getExStock());
            goblinNftExSku.setUnbox(goblinNftExCodeTask.getUnbox());
            goblinNftExSku.setExLimit(goblinNftExCodeTask.getExLimit());
            goblinNftExSku.setExStartTime(goblinNftExCodeTask.getExStartTime());
            goblinNftExSku.setExStopTime(goblinNftExCodeTask.getExStopTime());
            goblinNftExSku.setCreatedAt(now);
            goblinNftExSkus.add(goblinNftExSku);
            updTaskIds.append(goblinNftExCodeTask.getTaskId()).append(",");

            switch (goblinNftExCodeTask.getUnbox()) {
                case "1":
                    // 获取盲盒  sku-->库存
                    for (GoblinNftExCodeTaskRelation goblinNftExCodeTaskRelation : goblinNftExCodeTaskRelations) {
                        if (goblinNftExCodeTaskRelation.getTaskId().equals(goblinNftExCodeTask.getTaskId()) && goblinNftExCodeTaskRelation.getStock() > 0) {
                            for (int j = 0; j < goblinNftExCodeTaskRelation.getStock(); j++) {
                                GoblinNftExCode goblinNftExCode = GoblinNftExCode.getNew();
                                goblinNftExCode.setCodeId(IDGenerator.nextSnowId());
                                goblinNftExCode.setActivityId(goblinNftExCodeTask.getActivityId());
                                // 兑换码
                                // 样例 2978-6496-9269-0694-XX
                                String code = IDGenerator.createCode(3, 4, true);
                                goblinNftExCode.setCode(code);
                                goblinNftExCode.setBoxSkuId(goblinNftExCodeTaskRelation.getSkuId());
                                goblinNftExCode.setState(1);
                                goblinNftExCode.setCreatedAt(now);
                                goblinNftExCode.setSkuId(goblinNftExCodeTask.getSkuId());

                                // 赋值额外属性
                                GoblinNftExCodeVo goblinNftExCodeVo = GoblinNftExCodeVo.getNew().copy(goblinNftExCode);
                                goblinNftExCodeVo.setExLimit(goblinNftExCodeTask.getExLimit());
                                goblinNftExCodeVo.setExStartTime(goblinNftExCodeTask.getExStartTime());
                                goblinNftExCodeVo.setExStopTime(goblinNftExCodeTask.getExStopTime());
                                goblinNftExCodeVo.setStoreId(goblinNftExCodeTask.getStoreId());
                                goblinNftExCodeVo.setSpuId(goblinNftExCodeTask.getSpuId());
                                goblinNftExCodeVo.setUnBox(goblinNftExCodeTask.getUnbox());


                                LocalDateTime exStopTime = goblinNftExCodeTask.getExStopTime();
                                // 时间差  以秒表示
                                long millisNum = Duration.between(LocalDateTime.now(), exStopTime).toMillis();
                                // redis 存储
                                goblinRedisUtils.addCode(code, goblinNftExCodeVo, millisNum);

                                goblinNftExCodes.add(goblinNftExCode);
                            }
                        }
                    }
                    break;

                default:

                    for (int i = 0; i < goblinNftExCodeTask.getExStock(); i++) {
                        GoblinNftExCode goblinNftExCode = GoblinNftExCode.getNew();
                        goblinNftExCode.setCodeId(IDGenerator.nextSnowId());
                        goblinNftExCode.setActivityId(goblinNftExCodeTask.getActivityId());


                        // 获取兑换码ZA
                        // 样例 2978-6496-9269-0694-XX
                        String code = IDGenerator.createCode(3, 4, true);
                        goblinNftExCode.setCode(code);
                        goblinNftExCode.setSkuId(goblinNftExCodeTask.getSkuId());
                        goblinNftExCode.setState(1);
                        goblinNftExCode.setCreatedAt(now);
                        goblinNftExCodes.add(goblinNftExCode);

                        // 赋值额外属性
                        GoblinNftExCodeVo goblinNftExCodeVo = GoblinNftExCodeVo.getNew().copy(goblinNftExCode);
                        goblinNftExCodeVo.setExLimit(goblinNftExCodeTask.getExLimit());
                        goblinNftExCodeVo.setExStartTime(goblinNftExCodeTask.getExStartTime());
                        goblinNftExCodeVo.setExStopTime(goblinNftExCodeTask.getExStopTime());
                        goblinNftExCodeVo.setStoreId(goblinNftExCodeTask.getStoreId());
                        goblinNftExCodeVo.setSpuId(goblinNftExCodeTask.getSpuId());
                        goblinNftExCodeVo.setUnBox(goblinNftExCodeTask.getUnbox());

                        LocalDateTime exStopTime = goblinNftExCodeTask.getExStopTime();
                        // 时间差  以秒表示
                        long millisNum = Duration.between(LocalDateTime.now(), exStopTime).toMillis();

                        // redis 存储
                        goblinRedisUtils.addCode(code, goblinNftExCodeVo, millisNum);
                    }
            }

            GoblinNftExCodeTask nftExCodeTask = goblinNftExCodeTaskHashMap.get(goblinNftExCodeTask.getSkuId());
            if (nftExCodeTask == null) {
                goblinNftExCodeTaskHashMap.put(goblinNftExCodeTask.getSkuId(), goblinNftExCodeTask);
            }
        }


        // sku ---> 时间存储
        for (String key : goblinNftExCodeTaskHashMap.keySet()) {


            GoblinNftExCodeTask goblinNftExCodeTask = goblinNftExCodeTaskHashMap.get(key);
            LocalDateTime exStartTime = goblinNftExCodeTask.getExStartTime();
            LocalDateTime exStopTime = goblinNftExCodeTask.getExStopTime();
            GoblinNftExSkuVo goblinNftExSkuVo = goblinRedisUtils.getSkuTime(key);

            GoblinNftExSkuVo goblinNftExSku = GoblinNftExSkuVo.getNew();

            Boolean bolTime = false;
            if (!StringUtil.isEmpty(goblinNftExSkuVo)) {

                // 时间比对
                if (goblinNftExSkuVo.getExStartTime() != null && exStartTime.isBefore(goblinNftExSkuVo.getExStartTime())) { // 当操作时间小于red存储时间时为true
                    goblinNftExSku.setExStartTime(exStartTime);
                    goblinNftExSku.setRdStartTime(exStartTime.toString());
                    bolTime = true;
                }else {
                    goblinNftExSku.setExStartTime(goblinNftExSkuVo.getExStartTime());
                    goblinNftExSku.setRdStartTime(goblinNftExSkuVo.getExStartTime().toString());
                }

                if (goblinNftExSkuVo.getExStopTime() != null && exStopTime.isAfter(goblinNftExSkuVo.getExStopTime())) {  // 当操作时间大于red存储时间为true
                    goblinNftExSku.setExStopTime(exStopTime);
                    goblinNftExSku.setRdStopTime(exStopTime.toString());
                    bolTime = true;
                }else {
                    goblinNftExSku.setExStopTime(goblinNftExSkuVo.getExStopTime());
                    goblinNftExSku.setRdStopTime(goblinNftExSkuVo.getExStopTime().toString());
                }
            } else {
                bolTime = true;
                goblinNftExSku.setExStartTime(exStartTime);
                goblinNftExSku.setRdStartTime(exStartTime.toString());
                goblinNftExSku.setExStopTime(exStopTime);
                goblinNftExSku.setRdStopTime(exStopTime.toString());
            }


            if (bolTime) {
                goblinRedisUtils.addSkuTime(key, goblinNftExSku);
            }
        }


        goblinNftExSkuMapper.addGoblinNftExSkus(goblinNftExSkus);

        long startm = System.currentTimeMillis();
        goblinNftExCodeMapper.addGoblinNftExCodes(goblinNftExCodes);
        // 修改定时
        goblinNftExCodeTaskMapper.updateByTaskIds(updTaskIds.toString());
        log.debug("MSQ耗时：ms", System.currentTimeMillis() - startm);

        return ResponseDto.success("操作成功!");
    }

    public static void main(String[] args) {
        String time1 = "2029-06-26 19:00:00";  // 我的时间1
        String time2 = "2019-06-26 19:00:00";  // 我的时间2
        DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime localDateTime1 = LocalDateTime.parse(time1, dtf2);
        System.out.println(localDateTime1.isBefore(LocalDateTime.now()));//你的时间大于当前时间是false
        System.out.println(localDateTime1.isAfter(LocalDateTime.now()));//你的时间大于在当前时间是true
        System.out.println("******************************************************************");
        LocalDateTime localDateTime2 = LocalDateTime.parse(time2, dtf2);
        System.out.println(localDateTime2.isBefore(LocalDateTime.now()));//你的时间小于当前时间是true
        System.out.println(localDateTime2.isAfter(LocalDateTime.now()));//你的时间小于在当前时间是false
    }


}
