package com.zm.order.tool.server.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Throwables;
import com.zm.order.tool.server.component.ShardingKeyGenerator;
import com.zm.order.tool.server.dao.ItemRecommendDao;
import com.zm.order.tool.server.manager.InnerApiManager;
import com.zm.order.tool.server.model.ItemRecommend;
import com.zm.order.tool.server.model.OrderData;
import com.zm.order.tool.server.query.ItemRecommendQuery;
import com.zm.order.tool.server.service.ItemRecommendService;
import com.zm.order.tool.server.tb.TbItemRecommendDao;
import com.zm.order.tool.server.tempdb.OrderDataDao;
import com.zm.util.dto.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zhuxiaofeng
 * @packageName: com.zm.order.tool.server.service.impl
 * @className: ItemRandomServiceImpl
 * @date 2022/8/9 10:53
 */

@Service
public class ItemRandomServiceImpl implements ItemRecommendService {

    private static final Logger logger = LoggerFactory.getLogger(ItemRandomServiceImpl.class);

    @Autowired
    private ItemRecommendDao recommendDao;

    @Autowired
    private TbItemRecommendDao TbRecommendDao;

    @Autowired
    private ShardingKeyGenerator shardingKeyGenerator;

    @Autowired
    private InnerApiManager innerApiManager;

    @Autowired
    private OrderDataDao orderDataDao;

    private static final Long oneHourTime = 3600000L;

    @Override
    public void randomInsert() {
        try {
            Random random = new Random();
            for (int i = 0; i < 5000; i++) {
                List<ItemRecommend> itemList = new ArrayList<>(200);
                for (int j = 0; j < 100; j++) {
                    ItemRecommend item = new ItemRecommend();
                    item.setId(shardingKeyGenerator.generateSnowflakeNumKey());
                    item.setItemName("test");
                    item.setIsDeleted(-1);
                    item.setSellerId(123L);
                    item.setOrderNo("qimaimaimai");
                    item.setSkuId("121212");
                    item.setSpuId(34343434L);
                    item.setUserId(7634343434L);
                    int i1 = random.nextInt(20) + 1;
                    item.setSellerId(Long.valueOf(i1));
                    item.setStoreId(777L);
                    long random1 = random(1659888000000L, 1659974399000L);
                    item.setOrderAt(new Date(random1));
                    itemList.add(item);
                }
                int inserts = recommendDao.inserts(itemList);
                logger.info("randomInsert, i:{}", i);
            }
        } catch (Throwable e) {
            logger.error("ItemRandomServiceImpl[randomInsert] failed!, cause by:{}", e);
        }
    }

    public static long random(long begin, long end) {
        long rtn = begin + (long) (Math.random() * (end - begin));
        if (rtn == begin || rtn == end) {
            return random(begin, end);
        }
        return rtn;
    }

    @Override
    public void realDelete() {
        logger.info("ItemRandomServiceImpl[realDeleteStart]");
        try {
            int count = 0;
            int size = 200;
            ItemRecommendQuery query = new ItemRecommendQuery();
            query.setIsDeleted(-1);
            query.setSize(size);
            Long lastId = null;
            Long yesterdayStart = getYesterdayStart();
            // 分时段处理，每小时一个时间段
            for (int i = 0; i < 24; i++) {
                Date start = new Date(yesterdayStart);
                Date end = new Date(yesterdayStart + oneHourTime);
                query.setOrderAtStart(start);
                query.setOrderAtEnd(end);
                // 递增一小时
                yesterdayStart += oneHourTime;
                for (; ; ) {
                    query.setLastId(lastId);
                    List<ItemRecommend> recommends = TbRecommendDao.selectIdList(query);
                    List<Long> idList = new ArrayList<>(size);
                    List<Long> sellerIdList = new ArrayList<>(size);
                    for (ItemRecommend recommend : recommends) {
                        idList.add(recommend.getId());
                        sellerIdList.add(recommend.getSellerId());
                    }
                    if (CollectionUtils.isEmpty(idList)) {
                        break;
                    }
                    count += idList.size();
                    recommendDao.realDeleteByIdList(idList, sellerIdList);
                    lastId = idList.get(idList.size() - 1);
                    if (idList.size() < size) {
                        break;
                    }
                }
                logger.info("ItemRandomServiceImpl[realDeleteRun], i:{}, count:{}", i, count);
            }
            logger.info("ItemRandomServiceImpl[realDeleteEnd]");
        } catch (Throwable e) {
            logger.error("ItemRandomServiceImpl[realDelete] failed!, cause by:{}", e);
        }
    }

    /**
     * 获取昨天开始时间戳
     * @return
     * @throws ParseException
     */
    private Long getYesterdayStart() throws ParseException {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        String yesterdayStart = new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(cal.getTime());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date start = simpleDateFormat.parse(yesterdayStart);
        long startTime = start.getTime();
        return startTime;
    }

    public static void main(String[] args) throws ParseException {
    }

    @Override
    public void orderCenterApi() {

        Result<Long> result = new Result();
        try {
            int error = 0;
            int count = 0;
            Long lastId = 0L;
            for (;;) {
                List<OrderData> orderDataList = orderDataDao.selectList(lastId);
                if (CollectionUtils.isEmpty(orderDataList)) {
                    break;
                }
                for (OrderData orderData : orderDataList) {
                    orderData.getBody();
                    try{
                        Map orderMap = JSONObject.parseObject(orderData.getBody());
                        Boolean aBoolean = innerApiManager.orderCreate(orderMap);
                        if (aBoolean) {
                            count++;
                            orderDataDao.update(orderData.getId(), 1);
                        } else {
                            error++;
                            orderDataDao.update(orderData.getId(), 2);
                        }
                    } catch (Throwable e){
                        error++;
                        orderDataDao.update(orderData.getId(), 2);
                        System.out.println(orderData.getId());
                    }
                }
                logger.info("orderCreate; successCount:{}, errorCount:{}", count, error);
                lastId = orderDataList.get( orderDataList.size() - 1 ).getId();
                if (orderDataList.size() < 100) {
                    break;
                }
            }
            System.out.println(error);

        } catch (Throwable throwable) {
            logger.error("InnerApiManager[noticeDownloadTaskStart] failed, cause by:{}",
                    Throwables.getStackTraceAsString(throwable));
        }
    }
}
