package com.lutao.cloud.auth.sso.client;

import com.lutao.cloud.auth.sso.domain.SSOOrgInfo;
import com.lutao.cloud.auth.sso.domain.SSOSyncDataResponse;
import com.lutao.cloud.auth.sso.domain.SSOUserInfo;
import com.lutao.cloud.auth.sso.util.SSOSigner;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

@FeignClient(name="sso-sync", url = "${sso.sync-url}", configuration = SSOUserSyncHttpClient.FeignConfiguration.class)
public interface SSOUserSyncHttpClient {
    /**
     * 同步统一认证系统组织信息
     * @param orgNo 机构编号，可选
     * @param orgName 机构名称，可选
     * @param parentId 父机构ID，可选
     * @author xudong
     * @since 2024-06-27
     */
    @GetMapping(value = "/ums/service/V1/res/orgs?startTime=1990-06-21T08:00:00.000Z")
    @ResponseBody
    SSOSyncDataResponse<SSOOrgInfo> queryOrg( @RequestParam("ORG_NO") String orgNo,
            @RequestParam("ORG_NAME") String orgName, @RequestParam("PARENT_ID") String parentId
    );

    /**
     * 同步统一认证系统用户信息
     * @param userName 姓名，可选
     * @param idCardUUID 身份标识，可选
     * @author xudong
     * @since 2024-06-27
     */
    @GetMapping(value = "/ums/service/V1/res/users?startTime=1990-06-21T08:00:00.000Z")
    @ResponseBody
    SSOSyncDataResponse<SSOUserInfo> queryUser(@RequestParam("USER_NAME") String userName,
            @RequestParam("USER_CERTIFICATE_NO") String idCardUUID
    );


    class FeignConfiguration {
        @Bean
        public DynamicHeaderRequestInterceptor dynamicHeaderRequestInterceptor() {
            return new DynamicHeaderRequestInterceptor();
        }
        @Bean
        public feign.Logger.Level feignLoggerLevel() {
            return feign.Logger.Level.FULL;
        }
    }

    @Slf4j
    class DynamicHeaderRequestInterceptor implements RequestInterceptor {
        @Value("${sso.app-key}")
        private String appKey;
        @Value("${sso.app-pwd}")
        private String appPwd;
        @Value("${sso.sign-method}")
        private String signMethod;

        @Override
        public void apply(RequestTemplate template) {
            try {
                // 获取所有已经设置的查询参数名
                Map<String, Collection<String>> queries = template.queries();

                // 遍历查询参数，移除值为空或你觉得应该忽略的参数
                Iterator<Map.Entry<String, Collection<String>>> iterator = queries.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, Collection<String>> entry = iterator.next();
                    if (entry.getValue().isEmpty() || entry.getValue().contains("")) { // 或者使用其他条件判断是否应该忽略
                        iterator.remove();
                    }
                }

                Map<String, Object> headerMap = SSOSigner.buildKiamTokenHeader(template.url(), template.method(), null, appKey, appPwd, signMethod);
                headerMap.forEach((key, value) -> template.header(key, value.toString()));
            } catch (Exception e) {
                log.error("DynamicHeaderRequestInterceptor apply sso Header error", e);
            }
        }
    }
}
