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

import com.alibaba.fastjson.JSONObject;
import com.weaver.file.ud.api.FileDownloadService;
import com.weaver.seconddev.chapanda.feishu.constant.Constants;
import com.weaver.seconddev.chapanda.feishu.dao.HrmUserAvatarDao;
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.List;
import java.util.Map;


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

    @Autowired
    Esb2FeishuUploadImageUtil esb2FeishuUploadImageUtil;

    @Autowired
    HrmUserAvatarDao hrmUserAvatarDao;
    @Autowired
    Esb2FeishuTokenUtil esb2FeishuTokenUtil;

    @Autowired
    Esb2FeishuOpenIdUtil esb2FeishuOpenIdUtil;

    @Autowired
    private FileDownloadService fileDownloadService;

    public Map<String, Object> syncHrmAvatarByFull() {

        List<Map<String,Object>> avatarList = hrmUserAvatarDao.queryHrmAvatarList();
        log.error("avatarList:{}",avatarList.size());
        Map<String, Object> messageMap = new HashMap<String, Object>();

        int successTotal = 0;
        for(int i=0;i<avatarList.size();i++){

            Map<String,Object> avatarMap = avatarList.get(i);
            String open_id = String.valueOf(avatarMap.get("open_id"));
            String mobile = String.valueOf(avatarMap.get("mobile"));
            log.error("open_id1:{}",open_id);
            log.error("mobile:{}",mobile);
            if(StringUtils.isBlank(open_id)){
                if(StringUtils.isNotBlank(mobile)){
                    open_id = esb2FeishuOpenIdUtil.queryFeishuOpenId(mobile);
                }
            }
            log.error("open_id2:{}",open_id);

            Long p1 = Long.valueOf(String.valueOf(avatarMap.get("p1")));
            Long p2 = Long.valueOf(String.valueOf(avatarMap.get("p2")));
            Long p3 = Long.valueOf(String.valueOf(avatarMap.get("p3")));
            log.error("p1:{}",p1);
            log.error("p2:{}",p2);
            log.error("open_id:{}",open_id);

            String avatarKey = "";
            if(p1 > 0){
                avatarKey = esb2FeishuUploadImageUtil.uploadImage(p1);
            }else if(p2 > 0){
                avatarKey = esb2FeishuUploadImageUtil.uploadImage(p2);
            }else if(p3 > 0){
                avatarKey = esb2FeishuUploadImageUtil.uploadImage(p3);
            }

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

            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)){
                                successTotal++;
                                JSONObject dataJson = returnData.getJSONObject("data");
                                if(dataJson.containsKey("user")){
                                    JSONObject userJson = dataJson.getJSONObject("user");
                                    log.error("userJson:{}",userJson.toJSONString());
                                }
                            }
                        }
                    }
                }
            }
        }

        messageMap.put("total",avatarList.size());
        messageMap.put("success",successTotal);
        return messageMap;
    }

    /**
     *
     * @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;
    }


    public Map<String, Object> syncHrmAvatarByDate(int days) {

        List<Map<String,Object>> avatarList = hrmUserAvatarDao.queryHrmAvatarByDate(days);
        log.error("avatarList:{}",avatarList.size());
        Map<String, Object> messageMap = new HashMap<String, Object>();
        int successTotal = 0;
        for(int i=0;i<avatarList.size();i++){

            Map<String,Object> avatarMap = avatarList.get(i);
            String open_id = String.valueOf(avatarMap.get("open_id"));
            log.error("open_id1:{}",open_id);
            String mobile = String.valueOf(avatarMap.get("mobile"));
            log.error("mobile:{}",mobile);

            if(StringUtils.isBlank(open_id)){
                if(StringUtils.isNotBlank(mobile)){
                    open_id = esb2FeishuOpenIdUtil.queryFeishuOpenId(mobile);
                }
            }
            log.error("open_id2:{}",open_id);

            Long p1 = Long.valueOf(String.valueOf(avatarMap.get("p1")));
            Long p2 = Long.valueOf(String.valueOf(avatarMap.get("p2")));
            Long p3 = Long.valueOf(String.valueOf(avatarMap.get("p3")));
            log.error("p1:{}",p1);
            log.error("p2:{}",p2);
            log.error("open_id:{}",open_id);

            String avatarKey = "";
            if(p1 > 0){
                avatarKey = esb2FeishuUploadImageUtil.uploadImage(p1);
            }else if(p2 > 0){
                avatarKey = esb2FeishuUploadImageUtil.uploadImage(p2);
            }else if(p3 > 0){
                avatarKey = esb2FeishuUploadImageUtil.uploadImage(p3);
            }

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

            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)){
                                successTotal++;
                                JSONObject dataJson = returnData.getJSONObject("data");
                                if(dataJson.containsKey("user")){
                                    JSONObject userJson = dataJson.getJSONObject("user");
                                    log.error("userJson:{}",userJson.toJSONString());
                                }
                            }
                        }
                    }
                }
            }
        }

        messageMap.put("total",avatarList.size());
        messageMap.put("success",successTotal);
        return messageMap;
    }



    public Map<String, Object> syncHrmAvatarByAvatarList(List<Map<String,Object>> avatarList) {

        log.error("avatarList:{}",avatarList.size());
        Map<String, Object> messageMap = new HashMap<String, Object>();
        int successTotal = 0;
        for(int i=0;i<avatarList.size();i++){

            Map<String,Object> avatarMap = avatarList.get(i);
            String open_id = String.valueOf(avatarMap.get("open_id"));
            log.error("open_id1:{}",open_id);
            String mobile = String.valueOf(avatarMap.get("mobile"));
            log.error("mobile:{}",mobile);
            if(StringUtils.isBlank(open_id)){
                if(StringUtils.isNotBlank(mobile)){
                    open_id = esb2FeishuOpenIdUtil.queryFeishuOpenId(mobile);
                }
            }
            log.error("open_id2:{}",open_id);
            Long p1 = Long.valueOf(String.valueOf(avatarMap.get("p1")));
            Long p2 = Long.valueOf(String.valueOf(avatarMap.get("p2")));
            Long p3 = Long.valueOf(String.valueOf(avatarMap.get("p3")));
            log.error("p1:{}",p1);
            log.error("p2:{}",p2);
            log.error("open_id:{}",open_id);

            String avatarKey = "";
            if(p1 > 0){
                avatarKey = esb2FeishuUploadImageUtil.uploadImage(p1);
            }else if(p2 > 0){
                avatarKey = esb2FeishuUploadImageUtil.uploadImage(p2);
            }else if(p3 > 0){
                avatarKey = esb2FeishuUploadImageUtil.uploadImage(p3);
            }

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

            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)){
                                successTotal++;
                                JSONObject dataJson = returnData.getJSONObject("data");
                                if(dataJson.containsKey("user")){
                                    JSONObject userJson = dataJson.getJSONObject("user");
                                    log.error("userJson:{}",userJson.toJSONString());
                                }
                            }
                        }
                    }
                }
            }
        }

        messageMap.put("total",avatarList.size());
        messageMap.put("success",successTotal);
        return messageMap;
    }

}
