package cn.reghao.bnt.web.devops.aliyun.service;

import cn.reghao.bnt.web.devops.aliyun.db.repository.AliyunAccountRepository;
import cn.reghao.bnt.web.devops.aliyun.model.po.AliyunAccount;
import cn.reghao.bnt.web.devops.aliyun.model.vo.RefreshStatus;
import cn.reghao.jutil.jdk.converter.DateTimeConverter;
import com.aliyun.cdn20180510.Client;
import com.aliyun.cdn20180510.models.DescribeRefreshTasksRequest;
import com.aliyun.cdn20180510.models.DescribeRefreshTasksResponse;
import com.aliyun.cdn20180510.models.RefreshObjectCachesRequest;
import com.aliyun.cdn20180510.models.RefreshObjectCachesResponse;
import com.aliyun.tea.TeaModel;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author reghao
 * @date 2025-07-31 09:09:36
 */
@Slf4j
@Component
public class AliyunCdn {
    private Client client;
    private final AliyunAccountRepository aliyunAccountRepository;

    public AliyunCdn(AliyunAccountRepository aliyunAccountRepository) {
        this.aliyunAccountRepository = aliyunAccountRepository;
    }

    @PostConstruct
    public void initClient() throws Exception {
        AliyunAccount aliyunAccount = aliyunAccountRepository.findByType("cdn");
        String endpoint = aliyunAccount.getEndpoint();
        String accessKeyId = aliyunAccount.getAccessKeyId();
        String accessKeySecret = aliyunAccount.getAccessKeySecret();
        Config config = new Config()
                // 必填，您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 必填，您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret)
                .setEndpoint(endpoint);
        this.client = new Client(config);
    }

    public String refreshCdn(String domain) {
        String objectType = "Directory";
        String objectPath = String.format("https://%s/", domain);
        return refreshObjectCaches(objectType, objectPath);
    }

    /**
     * 刷新 aliyun-cdn 缓存
     *
     * @param
     * @return
     * @date 2023-12-18 16:24:01
     */
    private String refreshObjectCaches(String objectType, String objectPath) {
        RefreshObjectCachesRequest req = new RefreshObjectCachesRequest();
        // 此参数为刷新的类型， 其值可以为File或Directory。默认值：File。
        req.objectType = objectType;
        // 加速的文件位置，wdtest.licai.cn为配置的域名,后加加速的文件名
        req.objectPath = objectPath;
        try {
            RefreshObjectCachesResponse resp = client.refreshObjectCaches(req);
            Map<String, Object> map = TeaModel.buildMap(resp);
            Map<String, Object> map1 = (Map<String, Object>)map.get("body");
            String taskId = (String) map1.get("RefreshTaskId");
            return taskId;
        } catch (Exception e) {
            log.error("{}", e.getMessage());
        }

        return null;
    }

    public RefreshStatus getRefreshStatus(String taskId) {
        RefreshStatus refreshStatus = describeRefreshTasks(taskId);
        return refreshStatus;
    }

    /**
     * 获取 aliyun-cdn 缓存缓存刷新任务状态
     *
     * @param
     * @return
     * @date 2023-12-18 16:24:19
     */
    private RefreshStatus describeRefreshTasks(String taskId) {
        DescribeRefreshTasksRequest request = new DescribeRefreshTasksRequest();
        request.taskId = taskId;
        try {
            DescribeRefreshTasksResponse resp = client.describeRefreshTasks(request);
            Map<String, Object> map = TeaModel.buildMap(resp);
            Map<String, Object> bodyMap = (Map)map.get("body");
            List list = (List) ((Map) bodyMap.get("Tasks")).get("CDNTask");
            for (Object item : list) {
                Map itemMap = (Map) item;
                String taskId1 = (String) itemMap.get("TaskId");
                String objectType = (String) itemMap.get("ObjectType");
                String objectPath = (String) itemMap.get("ObjectPath");
                String createTime = (String) itemMap.get("CreationTime");
                LocalDateTime localDateTime = DateTimeConverter.localDateTime(createTime);
                String status = (String) itemMap.get("Status");
                String process = (String) itemMap.get("Process");
                return new RefreshStatus(taskId, objectType, objectPath, localDateTime, status, process);
            }
        } catch (Exception error) {
            log.error("{}", error.getMessage());
        }

        return null;
    }
}
