package com.weaver.seconddev.chapanda.feishu.util;

import com.alibaba.fastjson.JSONObject;
import com.weaver.seconddev.chapanda.feishu.constant.Constants;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Component
public class Esb2FeishuHrmAvatarUtil {
    private final static Logger log = LoggerFactory.getLogger(Esb2FeishuHrmAvatarUtil.class);

    @Autowired
    Esb2FeishuUploadImageUtil esb2FeishuUploadImageUtil;

    @Autowired
    Esb2FeishuTokenUtil esb2FeishuTokenUtil;

    public Map<String, Object> syncHrmAvatarByEmployee(String open_id,Long avatar ) {

        Map<String,Object> dataMap = new HashMap<String,Object>();
        String avatarKey = esb2FeishuUploadImageUtil.uploadImage(avatar);

        log.error("avatarKeyr:{}",avatarKey);

        String avatar_origin = "";
        if(StringUtils.isNotBlank(avatarKey)){
            String token = esb2FeishuTokenUtil.getToken();
            log.error("token:"+token);
            if(StringUtils.isNotBlank(token)){
                String message = doHttpPostByToken(avatarKey,open_id,token);
                if(StringUtils.isNotBlank(message)){
                    JSONObject returnData = JSONObject.parseObject(message);
                    if(returnData.containsKey("code")){
                        String code = returnData.getString("code");
                        if("0".equals(code)){
                            JSONObject dataJson = returnData.getJSONObject("data");
                            if(dataJson.containsKey("user")){
                                JSONObject userJson = dataJson.getJSONObject("user");
                                log.error("userJson:{}",userJson.toJSONString());
                                if(userJson.containsKey("avatar")){
                                    JSONObject avatarJson = userJson.getJSONObject("avatar");
                                    if(avatarJson.containsKey("avatar_origin")){
                                        avatar_origin = avatarJson.getString("avatar_origin");
                                        log.error("avatar_origin:{}",avatar_origin);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        dataMap.put("avatarOrigin",avatar_origin);
        dataMap.put("avatarKey",avatarKey);
        return dataMap;
    }

    /**
     *
     * @param token
     * @return
     */
    public String doHttpPostByToken(String avatar_key,String open_id,String token){
        String msg = "";
        log.error("avatar_key:{}",avatar_key);
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        JSONObject bodyData = new JSONObject();
        bodyData.put("avatar_key",avatar_key);
        RequestBody body = RequestBody.create(mediaType, bodyData.toJSONString());
        log.error("update-avatar:{}",bodyData.toJSONString());
        try {
            Request request = new Request.Builder()
                    .url(Constants.feishuHost+Constants.profileUrl+"/"+open_id+"?user_id_type=open_id")
                    .method("PATCH", body)
                    .addHeader("Authorization", "Bearer "+token)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            int code = response.code();
            log.error("code:{}",code);
            msg = response.body().string();
            log.error("msg:"+msg);
        } catch (IOException e) {
            log.error("e:"+e);
            throw new RuntimeException(e);
        }
        return msg;
    }

}
