package com.hz.pm.api.external;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.hz.pm.api.external.model.dto.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

import static cn.hutool.core.date.DatePattern.NORM_DATETIME_FORMATTER;

/**
 * <p>
 * MhApiClient
 * </p>
 *
 * @author WendyYang
 * @since 20:41 2023/12/20
 */
@Component
public class MhApiClient {

    @Value("${mh.api-host:}")
    private String mhApiHost;

    private static final String UNIT_URL = "/sync/unit";
    private static final String USER_URL = "/sync/user";
    private static final String EXPERT_URL = "/sync/expert";
    private static final String COMPANY_URL = "/sync/company";


    public MhRetDTO<List<MhUnitDTO>> queryUnits() {
        String requestUrl = mhApiHost + UNIT_URL;
        String retBody = HttpUtil.get(requestUrl);
        return JSONUtil.toBean(retBody, new TypeReference<MhRetDTO<List<MhUnitDTO>>>() {
        }, false);
    }

    public MhRetDTO<List<MhCompanyDTO>> queryCompany() {
        String requestUrl = mhApiHost + COMPANY_URL;
        String retBody = HttpUtil.get(requestUrl);
        return JSONUtil.toBean(retBody, new TypeReference<MhRetDTO<List<MhCompanyDTO>>>() {
        }, false);
    }

    public MhRetDTO<List<MhUserDTO>> queryUsers(LocalDateTime syncDateTime) {
        String requestUrl = mhApiHost + USER_URL;
        if (syncDateTime != null) {
            String timeString = LocalDateTimeUtil.format(syncDateTime, NORM_DATETIME_FORMATTER);
            requestUrl += "?syncDateTime=" + timeString;
        }
        String retBody = HttpUtil.get(requestUrl);
        return JSONUtil.toBean(retBody, new TypeReference<MhRetDTO<List<MhUserDTO>>>() {
        }, false);
    }

    public MhRetDTO<MhExpertDTO> queryExperts(LocalDateTime syncDateTime) {
        String requestUrl = mhApiHost + EXPERT_URL;
        if (syncDateTime != null) {
            String timeString = LocalDateTimeUtil.format(syncDateTime, NORM_DATETIME_FORMATTER);
            requestUrl += "?syncDateTime=" + timeString;
        }
        String retBody = HttpUtil.get(requestUrl);
        return JSONUtil.toBean(retBody, new TypeReference<MhRetDTO<MhExpertDTO>>() {
        }, false);
    }

}
