package cn.ey.biz.module.weaver.common;

import cn.ey.biz.common.exception.ErrorCode;
import cn.ey.biz.framework.security.core.util.SecurityFrameworkUtils;
import cn.ey.biz.framework.web.core.util.WebFrameworkUtils;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import jodd.util.StringUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.List;

import static cn.ey.biz.common.exception.util.ServiceExceptionUtil.exception;

@Slf4j
public class HrmGetter {

    @Value("${weaver.service.url}")
    String url;
    @Resource
    TokenGetter tokenGetter;
    @Resource
    StringRedisTemplate stringRedisTemplate;

    public final static String USER_ID = "__user_id__";

    public String getCurrentUserId(String app){
        // 如果已经传递直接返回(泛微userId)
        if(UserContextHolder.get(USER_ID) != null){
            return (String)UserContextHolder.get(USER_ID);
        }
        //获取当前登录用户编码
        String userCode = WebFrameworkUtils.getLoginUserCode();
        if(StringUtil.isBlank(userCode)){
            userCode = SecurityFrameworkUtils.getLoginUser().getUserCode();
        }
        log.info("Get user gpn:{}.", userCode);
        //获取人员信息
        HrmUserInfoRequest params = new HrmUserInfoRequest();
        Param param = new Param();
        param.setWorkcode(userCode);
        params.setParams(param);

        //获取人员信息
        String spk = stringRedisTemplate.opsForValue().get(Constants.SERVER_PUBLIC_KEY+app);
        RSA rsa = new RSA(null, spk);
        //对用户信息进行加密传输,暂仅支持传输OA用户ID
        String encryptUserid = rsa.encryptBase64("1", CharsetUtil.CHARSET_UTF_8, KeyType.PublicKey);

        //调用接口获取数据
        HttpRequest.closeCookie();
        String data = HttpRequest.post(url + "/api/hrm/resful/getHrmUserInfoWithPage")
                .header("Content-Type", "application/json; charset=utf-8")
                .header("appid", app)
//                .header("skipsession", "1")
                .header("token", tokenGetter.token(app))
                .header("userid", encryptUserid)
                .body(JSON.toJSONString(params))
                .execute().body();
        Response rsp = JSON.parseObject(data, Response.class);
        if(rsp.isSuccess()){
            Item item = rsp.getData()
                    .dataList
                    .stream()
                    .findFirst()
                    .orElseThrow(()->exception(new ErrorCode(-1, "获取不到用户信息")));
            if(item != null){
                return item.getId();
            }
        }else{
            log.error("Get hrm error:{}.", rsp);
        }
        return null;
    }

    @Data
    class HrmUserInfoRequest{
        Param params;
    }
    @Data
    class Param{
        String workcode;
    }
    @Data
    class Response{
        String code;
        HrmUserInfoResponse data;
        public boolean isSuccess(){
            return "1".equals(this.code);
        }
    }
    @Data
    class HrmUserInfoResponse{
        List<Item> dataList;
    }
    @Data
    class Item{
        String id;
    }

}
