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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.common.hrm.util.HrmCommonUtil;
import com.weaver.seconddev.chapanda.feishu.constant.Constants;
import com.weaver.seconddev.chapanda.feishu.dao.HrmQueryOpenIdDao;
import com.weaver.teams.domain.user.SimpleEmployee;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


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

    @Autowired
    Esb2FeishuTokenUtil esb2FeishuTokenUtil;


    @Autowired
    HrmQueryOpenIdDao hrmQueryOpenIdDao;

    @Autowired
    CommonUtil commonUtil;

    @Autowired
    private HrmCommonUtil hrmCommonUtil;
    public String queryFeishuOpenId(String employeeid) {
        log.error("employeeid:{}",employeeid);
        String openId = "";
        try {
            if(StringUtils.isNotBlank(employeeid)){
                openId = hrmQueryOpenIdDao.queryHrmOpenId(employeeid);
                log.error("openId1:{}",openId);
                if(StringUtils.isBlank(openId)){
                    Long employeeId = commonUtil.convertStringToLong(employeeid);
                    if(employeeId > 0L){
                        SimpleEmployee creatorEmployee = hrmCommonUtil.getSimpleEmployee(employeeId);
                        String creatorMobile = creatorEmployee.getMobile();

                        if(StringUtils.isNotBlank(creatorMobile)) {
                            Map<String, Object> creatorMap = queryFeishuOpenIdByMobiles(creatorMobile);
                            openId = String.valueOf(creatorMap.get(creatorMobile));
                            log.error("openId2:{}",openId);
                        }
                    }
                }
            }
        }catch (Exception e){
            log.error("e:{}",e);
        }

        return openId;
    }

    public Map<String, Object> queryFeishuOpenIdByMobiles(String mobile) {
        Map<String, Object> userMap = new HashMap<String, Object>();
        String searchType = "mobiles";
        String token = esb2FeishuTokenUtil.getToken();
        if(StringUtils.isNotBlank(token)){
            List<String> mobiles = new ArrayList<String>();
            mobiles.add(mobile);
            String message = doHttpPost(mobiles,searchType,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");

                        JSONArray userList = dataJson.getJSONArray("user_list");
                        for(int i=0;i<userList.size();i++){
                            JSONObject userJson = userList.getJSONObject(i);
                            String user_id = "";
                            if(userJson.containsKey("user_id")){
                                user_id = userJson.getString("user_id");
                            }
                            userMap.put(mobile,user_id);
                        }
                    }
                }
            }
        }
        return userMap;
    }


    /**
     *
     * @param email
     * @param calendar_id
     * @param event_id
     * @return
     */
    public Map<String, Object> queryFeishuOpenIdByEmails(String email,String calendar_id,String event_id) {
        log.error("queryFeishuOpenIdByEmails start");
        String searchType = "emails";
        Map<String, Object> userMap = new HashMap<String, Object>();
        String token = esb2FeishuTokenUtil.getToken();
        log.error("token:"+token);
        if(StringUtils.isNotBlank(token)){
            List<String> emails = new ArrayList<String>();
            emails.add(email);
            String message = doHttpPost(emails,searchType,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");

                        JSONArray userList = dataJson.getJSONArray("user_list");
                        for(int i=0;i<userList.size();i++){
                            JSONObject userJson = userList.getJSONObject(i);
                            String user_mobile = userJson.getString("mobile");
                            String user_id = userJson.getString("user_id");
                            userMap.put(user_mobile,user_id);
                        }
                    }
                }
            }
        }
        return userMap;
    }


    public String doHttpPost(List<String> dataList, String searchType, String token){
        String msg = "";

        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");

        String[] dataArray = new String[dataList.size()];
        for(int i=0;i<dataList.size();i++){
            dataArray[i] = dataList.get(i);
        }
        JSONObject bodyData = new JSONObject();
        bodyData.put(searchType,dataArray);
        RequestBody body = RequestBody.create(mediaType, bodyData.toJSONString());
        try {
            Request request = new Request.Builder()
                    .url(Constants.feishuHost+Constants.openIdUrl)
                    .method("POST", 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;
    }

}
