package com.ms.biz.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.doudian.open.api.token_refresh.TokenRefreshRequest;
import com.doudian.open.api.token_refresh.TokenRefreshResponse;
import com.doudian.open.api.token_refresh.param.TokenRefreshParam;
import com.ms.biz.common.E;
import com.ms.biz.common.TaskBaseService;
import com.ms.biz.service.ShopService;
import com.ms.biz.tool.SecurityTool;
import com.ms.biz.tool.TimeTool;
import com.ms.dal.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.Executor;

/**
 * 刷新抖店token
 */

@Configuration
@Component
@Slf4j
public class RefreshTokenTaskService extends TaskBaseService {
    @Autowired
    ShopService shopService;

    /**
     * 同时开启任务处理数量
     */
    public int getCorePoolSiz() {
        return 3;
    }

    /**
     * 任务管理器名称
     */
    public String getTaskExecutorName() {
        return "RefreshTokenTimerTaskPool";
    }

    @Bean(name = "RefreshTokenTimerTaskPool")
    @Override
    public Executor getAsyncExecutor() {
        return super.getAsyncExecutor();
    }

    @Resource(name = "RefreshTokenTimerTaskPool")
    protected Executor taskPool;

    @Override
    protected Executor getTaskPool() {
        return taskPool;
    }

    @Override
    public void runTask() {
        super.runTask();
    }

    /**
     * 获取任务
     */
    @Override
    public Object getTask() {
        String gmtExpireStart = TimeTool.getDateTimeBySeconds(3600);
        String gmtExpireEnd = TimeTool.getDateTimeBySeconds(-3600);
        List<Shop> shops = shopService.getExpiresTokenShops(gmtExpireStart, gmtExpireEnd);
        return shops;
    }

    /**
     * 处理任务
     *
     * @param params
     * @return
     */
    @Override
    public Object processTask(Object params) {
        List<Shop> shops = (List<Shop>) params;
        for (int i=0; i < shops.size(); i++) {
            Shop shop = shops.get(i);
            String oldAccessToken = SecurityTool.decodeByAES(shop.getAccessToken());
            String oldRefreshToken = SecurityTool.decodeByAES(shop.getRefreshToken());
            TokenRefreshRequest request = new TokenRefreshRequest();
            TokenRefreshParam param = request.getParam();
            param.setRefreshToken(oldRefreshToken);
            param.setGrantType("refresh_token");
            log.info("TokenRefreshParam: " + JSONObject.toJSONString(param));
            TokenRefreshResponse response = request.execute();
            String newAccessToken = response.getData().getAccessToken();
            String newRefreshToken = response.getData().getRefreshToken();
            Long newExpires = response.getData().getExpiresIn();
            if (ObjectUtil.isEmpty(newAccessToken)) {
                E.throwMSException("获取accessToken失败");
            }
            if (newAccessToken.equals(oldAccessToken)) {
                log.info("accessToken无需更新");
                return true;
            }
            shop.setExpiresIn(newExpires.toString());
            shop.setRefreshToken(SecurityTool.encodeByAES(newRefreshToken));
            shop.setAccessToken(SecurityTool.encodeByAES(newAccessToken));
            log.info("oldAccessToken:"+oldAccessToken);
            log.info("newAccessToken"+newAccessToken);
            shop.setGmtExpire(DateUtil.parseDateTime(TimeTool.getDateTimeBySeconds(newExpires.intValue())));
            shop.setGmtModified(DateUtil.parseDateTime(TimeTool.getDateTimeBySeconds(0)));
            shopService.updateByPrimaryKey(shop);
        }
        return true;
    }

    /**
     * 清理任务
     *
     * @param params
     */
    @Override
    public void clearTask(Object params) {
    }
}
