package com.hzya.frame.dd.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.hzya.frame.dd.IDDInterfaceService;
import com.hzya.frame.seeyon.dao.ISeeYonDao;
import com.hzya.frame.seeyon.entity.SeeyonEntity;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import com.hzya.frame.web.exception.BaseSystemException;
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.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 👻👻👻👻👻👻👻👻👻👻 gjh
 * @version 1.0
 * @content
 * @date 2023-08-29 9:48
 */
@Service(value = "ddInterfaceService")
public class DdInterfaceServiceImpl  implements IDDInterfaceService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    //TODO 此处参数暂时使用变量使用！后续应该使用应用参数动态设置

    private final String appSecret = "DuRw6EEEvhGXfr6Q8wN_x4025qKjrffIGCXF9KeCKKIID-LVSsR6_8KWMei6sug1";
    private final String appKey = "dingxewtjaserj292ggu";
    //TODO 此处参数暂时使用变量使用！后续应该使用应用参数动态设置
    @Autowired
    private ISeeYonDao seeYonDao;
    @Override
    public String  senddd(JSONObject requestJson) {
        JSONObject jsonStrObj = requestJson.getJSONObject("jsonStr");

        if(ObjectUtils.isEmpty(jsonStrObj)){
         throw  new BaseSystemException("请传入jsonStr参数");
        }
        String code = jsonStrObj.getString("code");
        if(StringUtils.isEmpty(code)){
            throw  new BaseSystemException("请传入接口编号参数:code");
        }
        String url = getDdUrlByType(code);
        String accessTokenCode = "0001";
        //如果请求的是token接口，不需要拼接access_token参数
        String result = null;
        //如果是单据接口，需要增加access_token参数，在此处定义变量赋值
        String access_token = getToken();
        if(accessTokenCode.equalsIgnoreCase(code)){
            url+= "?appkey="+appKey+"&appsecret="+appSecret;
            result = HttpUtil.get(url);
            JSONObject jsonObject = analysisDDResult(result);
            access_token = jsonObject.getString("access_token");
        }else{
            url+= "?access_token="+access_token;
            JSONObject data = jsonStrObj.getJSONObject("data");
            if("0004".equals(code) || "0003".equals(code)|| "0005".equals(code)){
                logger.info("调用钉钉请求前参数:{}",data.toString());
                if("0003".equals(code)){
                    String formInstanceId = data.getString("formInstanceId");
                    //如果表单ID不等于空走编辑动作
                    if(StrUtil.isNotEmpty(formInstanceId)){
                        result = HttpRequest.put(url).header("x-acs-dingtalk-access-token",access_token).body(data.toString()).execute().body();
                    }else{
                        result = HttpRequest.post(url).header("x-acs-dingtalk-access-token",access_token).body(data.toString()).execute().body();
                    }
                }

                logger.info("调用钉钉返回参数:{}",result);
            }else{
                result = HttpRequest.post(url).header("access_token",access_token).body(data.toJSONString()).execute().body();
            }

        }
        return  result;
    }



    /*****
     * 暂时写个固定获取token方法
     * @content:
     * @author 👻👻👻👻👻👻👻👻 gjh
     * @date  2023-08-29 14:52
     * @param
     * @return java.lang.String
     **/
    private String getToken(){
        String url = getDdUrlByType("0001");
        url+= "?appkey="+appKey+"&appsecret="+appSecret;
        String result = HttpUtil.get(url);
        JSONObject jsonObject = analysisDDResult(result);
        String access_token = jsonObject.getString("access_token");
        return access_token;
    }
    /****
     * 解析钉钉接口返回的数据，转换成json对象
     * @content:
     * @author 👻👻👻👻👻👻👻👻 gjh
     * @date  2023-08-29 11:55
     * @param
     * @return com.alibaba.fastjson.JSONObject
     **/
    private JSONObject analysisDDResult(String result){
        //解析result
        JSONObject jsonObject = JSON.parseObject(result);
        //定义钉钉返回成功的标记
        String okCode = "0";
        //钉钉返回的接口成功标记
        String errorCode = jsonObject.getString("errcode");
        //钉钉接口返回的提示信息
        String errmsg = jsonObject.getString("errmsg");
        //钉钉Result
        String ddResult = jsonObject.getString("result");
        //如果返回值是0，则表示调用成功了
        if(okCode.equalsIgnoreCase(errorCode)){
            return jsonObject;
        }else{
            throw new BaseSystemException("调用钉钉接口失败！错误代码："+errorCode+"错误信息："+errmsg);
        }
    }


    /*****
     * 把所有做过的钉钉接口在此处做备注，通过给外部系统的编号获取
     * @content:
     * @author 👻👻👻👻👻👻👻👻 gjh
     * @date  2023-08-29 9:54
     * @param
     * @return java.lang.String
     **/
    private String getDdUrlByType(String code){
        StringBuffer urlBuffer = null;
        if("0003".equals(code)|| "0004".equals(code)|| "0005".equals(code)){
            urlBuffer = new StringBuffer("https://api.dingtalk.com");
        }else{
            urlBuffer = new StringBuffer("https://oapi.dingtalk.com");
        }
        switch (code){
            case "0001":
                //获取钉钉tokenURL
                urlBuffer.append("/gettoken") ;
                break;
                //通知审批通过URL
            case "0002":
                urlBuffer.append("/topapi/attendance/approve/finish") ;
                break;
            //销售合同URL,无流程表单统一Url
            case "0003":
                urlBuffer.append("/v1.0/yida/forms/instances") ;
                break;
            case "0004":
                urlBuffer.append("/v1.0/yida/forms/instances/search") ;
                break;
            case "0005":
                urlBuffer.append("/v1.0/yida/forms/instances") ;
//                urlBuffer.append("/v1.0/yida/processes/instances/start") ;
                break;
            default:
                throw new BaseSystemException("获取钉钉URL错误！请确认URL编号");
        }
        return  urlBuffer.toString();
    }

}
