package com.storlead.wx.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.storlead.wx.pojo.vo.CorpWeChatDeptVO;
import com.storlead.wx.pojo.vo.CorpWeChatUserVO;
import com.storlead.wx.properties.CorpWeChatConstants;
import com.storlead.wx.service.WechatOrganizSyncService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.List;

/**
 * @program: sp-sales
 * @description:
 * @author: chenkq
 * @create: 2022-07-15 15:02
 */
@Slf4j
@Service
public class WechatOrganizSyncServiceImpl implements WechatOrganizSyncService {

    /**
     * 获取部门 如果不需要获取指定部门下的用户 而是获取全部用户 可以 直接调用 获取部门成员详情接口并将参数 DEPARTMENT_ID=1
     *
     * @param url         https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=ACCESS_TOKEN&id=ID
     * @param accessToken accessToken
     * @param deptId      不传的话查询所有部门
     * @return java.util.List<com.storlead.web.model.vo.CorpWeChatDeptVO>
     * @author blank
     * @date 2021-3-9 下午 12:03
     */
    @Override
    public List<CorpWeChatDeptVO> getDeptListFormTencent(@NotNull String url, @NotNull String accessToken, Long deptId) {
        if (deptId != null && deptId > 0) {
            url = url.replace("ID", deptId.toString());
        }
        String resultStr = HttpUtil.get(url.replace("ACCESS_TOKEN", accessToken));
        if (StringUtils.isNotEmpty(resultStr)) {
            log.debug("查询所有部门---> {}", resultStr);
            JSONObject jsonResult = new JSONObject(resultStr);
            int errCode = jsonResult.getInt("errcode");
            String errMsg = jsonResult.getStr("errmsg");
            if (CorpWeChatConstants.RETURN_SUCCESS_CODE == errCode) {
                log.info("部门 获取成功: {} ", jsonResult.getJSONArray("department").toString());
                return jsonResult.getJSONArray("department").toList(CorpWeChatDeptVO.class);
            }
        }
        return null;
    }

    /**
     * 获取部门成员详情
     *
     * @param url         https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=ACCESS_TOKEN&department_id=DEPARTMENT_ID&fetch_child=FETCH_CHILD
     *                    参数	        必须	说明
     *                    access_token	是	调用接口凭证
     *                    department_id	是	获取的部门id
     *                    fetch_child	否	1/0：是否递归获取子部门下面的成员
     * @param accessToken accessToken
     * @param deptId      企业微信部门ID
     * @return java.util.List<com.storlead.web.model.vo.CorpWeChatUserVO>
     * @author blank
     * @date 2021-3-9 下午 12:19
     */
    @Override
    public List<CorpWeChatDeptVO> getUserListUnderDeptFormTencent(@NotNull String url, @NotNull String accessToken, Long deptId) {
        if (deptId != null && deptId > 0) {
            url = url.replace("DEPARTMENT_ID", deptId.toString());
        }
        String resultStr = HttpUtil.get(url.replace("ACCESS_TOKEN", accessToken).replace("FETCH_CHILD", "1"));
        if (StringUtils.isNotEmpty(resultStr)) {
            log.debug("查询所有用户---> {}", resultStr);
            JSONObject jsonResult = new JSONObject(resultStr);
            int errCode = jsonResult.getInt("errcode");
            String errMsg = jsonResult.getStr("errmsg");
            if (CorpWeChatConstants.RETURN_SUCCESS_CODE == errCode) {
                log.info("用户 获取成功: {} ", jsonResult.getJSONArray("userlist").toString());
                return jsonResult.getJSONArray("userlist").toList(CorpWeChatDeptVO.class);
            }
        }
        return null;
    }

    /**  new *
    //https://qyapi.weixin.qq.com/cgi-bin/department/simplelist?access_token=ACCESS_TOKEN&id=ID
     ****/
    @Override
    public List<CorpWeChatDeptVO> getOrgDeptIdList(@NotNull String url, @NotNull String accessToken, Long deptId) {
        if (deptId != null && deptId > 0) {
            url = url.replace("id", deptId.toString());
        }
        String resultStr = HttpUtil.get(url.replace("ACCESS_TOKEN", accessToken).replace("FETCH_CHILD", "1"));
        if (StringUtils.isNotEmpty(resultStr)) {
            log.debug("查询所有组织架构id---> {}", resultStr);
            JSONObject jsonResult = new JSONObject(resultStr);
            int errCode = jsonResult.getInt("errcode");
            String errMsg = jsonResult.getStr("errmsg");
            if (CorpWeChatConstants.RETURN_SUCCESS_CODE == errCode) {
                log.info("用户 获取成功: {} ", jsonResult.getJSONArray("department_id").toString());
                return jsonResult.getJSONArray("department_id").toList(CorpWeChatDeptVO.class);
            }
        }
        return null;
    }

    @Override
    public List<CorpWeChatUserVO> getUserIdList(String url, String accessToken) {
        String resultStr = HttpUtil.get(url.replace("ACCESS_TOKEN", accessToken).replace("FETCH_CHILD", "1"));
        if (StringUtils.isNotEmpty(resultStr)) {
            log.debug("查询所有用户---> {}", resultStr);
            JSONObject jsonResult = new JSONObject(resultStr);
            int errCode = jsonResult.getInt("errcode");
            String errMsg = jsonResult.getStr("errmsg");
            if (CorpWeChatConstants.RETURN_SUCCESS_CODE == errCode) {
                log.info("用户 获取成功: {} ", jsonResult.getJSONArray("dept_user").toString());
                return jsonResult.getJSONArray("dept_user").toList(CorpWeChatUserVO.class);
            }
        }
        return null;
    }

    /**  new *
     //https://qyapi.weixin.qq.com/cgi-bin/department/get?access_token=ACCESS_TOKEN&id=ID
     ****/
    @Override
    public CorpWeChatDeptVO getDeptDetail(@NotNull String url, @NotNull String accessToken, Long deptId) {

        String resultStr = HttpUtil.get(url.replace("ACCESS_TOKEN", accessToken).replace("FETCH_CHILD", "1"));
        if (StringUtils.isNotEmpty(resultStr)) {
            log.debug("查询所有组织架构id---> {}", resultStr);
            JSONObject jsonResult = new JSONObject(resultStr);
            int errCode = jsonResult.getInt("errcode");
            String errMsg = jsonResult.getStr("errmsg");
            if (CorpWeChatConstants.RETURN_SUCCESS_CODE == errCode) {
                log.info("用户 获取成功: {} ", jsonResult.getJSONArray("department_id").toString());
                return jsonResult.getBean(("department_id"),CorpWeChatDeptVO.class);
            }
        }
        return null;
    }

    /**  new *
     //https://qyapi.weixin.qq.com/cgi-bin/department/get?access_token=ACCESS_TOKEN&id=ID
     ****/
    @Override
    public CorpWeChatUserVO getUserDetail(@NotNull String url, @NotNull String accessToken,String userid) {
//        if (StrUtil.isNotBlank(userid)) {
//            url = url + "&user_ticket="+userid;
//        }
//        url = url.replace("ACCESS_TOKEN","7tQMlzv8X0u96WRACIvADIv-hhCYl88UzjXEh07k-rhCY2oQyQa2oTS-sc5fNPyGTiQUNq3N5RCR0Bu7h6CxiqD-ycFki9nYyNgV9hEzzifpxOw_FVToytuuZ6pVaRG79uELKAdkdm96f8kFIyEce3BnF3R0BtYXzQ1U2Wcjjnn3Ik62fYKy1iNz-G8FaESG6wxNsr0gQzjpeovdQ9jL1g");
//        com.alibaba.fastjson.JSONObject parammap = new com.alibaba.fastjson.JSONObject();
//        parammap.put("user_ticket", "OXeMQL5TeJlkEODQSyFYoW-VqEH0StbrtaqEeP2TH3SMoN_ljz2JXGV-y8Ho8qFgOL-9CGBeVhjKhyTzJGkJBnhxZWErwogcedLo-elT_Fo");
//        String resultStr = doPost(url,parammap.toJSONString());

        String urlOld = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserdetail?access_token=ACCESSTOKEN";
        String url1 = urlOld.replace("ACCESSTOKEN",accessToken);

        com.alibaba.fastjson.JSONObject parammap = new com.alibaba.fastjson.JSONObject();
        parammap.put("user_ticket", "nMQ_v2cqPywAZJdxPzKNE4fuxxL_KJm62ztgsvhfHLuS9b3BiDU2NKnHyY2_lj9yxYrWDiZ5HQmU-l-QaqUD1_xmSCAElDfNruCLw-a1w3w");
        String resultStr = HttpUtil.post(url1, parammap.toJSONString());
        if (StringUtils.isNotEmpty(resultStr)) {
            log.debug("查询所有组织架构id---> {}", resultStr);
            JSONObject jsonResult = new JSONObject(resultStr);
            int errCode = jsonResult.getInt("errcode");
            String errMsg = jsonResult.getStr("errmsg");
            if (CorpWeChatConstants.RETURN_SUCCESS_CODE == errCode) {
                log.info("用户 获取成功: {} ", jsonResult.getJSONArray("department_id").toString());
                return jsonResult.getBean(("department_id"),CorpWeChatUserVO.class);
            }
        }
        return null;
    }

    @Override
    public CorpWeChatUserVO getLoginUserInfo(@NotNull String oldUrl, @NotNull String accessToken,String code) {

        String url = oldUrl.replace("ACCESSTOKEN",accessToken);
        if (StrUtil.isNotBlank(code)) {
            url = url +"&auth_code="+code;
        }
        String resultStr = HttpUtil.get(url);
        if (StringUtils.isNotEmpty(resultStr)) {
            log.debug("查询所有组织架构id---> {}", resultStr);
            JSONObject jsonResult = new JSONObject(resultStr);
            int errCode = jsonResult.getInt("errcode");
            String errMsg = jsonResult.getStr("errmsg");
            if (CorpWeChatConstants.RETURN_SUCCESS_CODE == errCode) {
                log.info("用户 获取成功: {} ", jsonResult.getJSONArray("department_id").toString());
                return jsonResult.getBean(("department_id"),CorpWeChatUserVO.class);
            }
        }
        return null;
    }



    public String doPost(String url ,String json) {
        // 建立Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String res = "";

        try {
            // 建立Http Post请求
            HttpPost post = new HttpPost(url);
            // 建立请求内容 ContentType：请求格式设置
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            post.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(post);

            res = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return res;
    }
}
