package nckd.jimin.jyyy.hr.wtc.wtis.util;


import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.util.HttpClientUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 2025-05-22 Tyx
 * 钉钉同步工具类
 */
public class DingTalkSyncUtil {
    private static Log logger = LogFactory.getLog(DingTalkSyncUtil.class);

    private static String mapping_entity = "bas_immapping";
    private static String tokenParamKey = "getTokenUrl";
    private static String punchParamKey = "getPunchUrl";
    private static String appKeyParamKey = "appKey";
    private static String appSecretParamKey = "appSecret";
    private static String KEY_ENTITY_LOG = "nckd_syncdingtalklog";
    private static long l1 = 0L;
    private static long l2 = 0L;
    private static String accessToken = "";
    public static String v_success = "A";
    public static String v_partsuccess = "B";
    public static String v_error = "C";
    public static String SyncPunch = "打卡数据同步";
    public static String SyncTrip = "出差数据同步";
    public static String SyncVa = "休假数据同步";
    public static String SyncFill = "补签数据同步";
    public static String SyncShift = "班次数据同步";
    public final static Map<String, String> typeMap = new HashMap<String, String>();


    /**
     * 获取参数值
     * @param key
     * @return
     */
    public static String getParamValue(String key) {
        QFilter filter = new QFilter("number", QCP.equals, "DingTalk");
        filter.and("nckd_entryentity.nckd_key",QCP.equals, key);
        DynamicObject bill = QueryServiceHelper.queryOne("nckd_commonparams", "nckd_entryentity.nckd_value", new QFilter[]{filter});
        return bill.getString("nckd_entryentity.nckd_value");
    }

    /**
     * 获取参数名
     * @param value
     * @return
     */
    public static String getParamKey(String value) {
        QFilter filter = new QFilter("number", QCP.equals, "DingTalk");
        filter.and("nckd_entryentity.nckd_value",QCP.like, "%" + value + "%");
        DynamicObject bill = QueryServiceHelper.queryOne("nckd_commonparams", "nckd_entryentity.nckd_key", new QFilter[]{filter});
        return bill.getString("nckd_entryentity.nckd_key");
    }

    /**
     * POST请求
     * @param url
     * @param bodyData
     * @return
     * @throws IOException
     */
    public static JSONObject doPostByHttpClient(String url, JSONObject bodyData) throws IOException {
        Map<String, String> headers = new HashMap();
        headers.put("Content-Type", "application/json");
        headers.put("Accept", "*/*");
        logger.info(String.format("url[%s],data[%s]", url, bodyData.toJSONString()));
        System.out.println(String.format("url[%s],data[%s]", url, bodyData.toJSONString()));
        String responseEntify = HttpClientUtils.postjson(url, headers, bodyData.toJSONString(), 10000, 10000);

        logger.info(responseEntify);
        JSONObject result = (JSONObject)JSONObject.parse(responseEntify);
        return result;
    }

    /**
     * get请求
     * @param url
     * @param connectionTimeout
     * @param readTimeout
     * @return
     * @throws Exception
     */
    public static String doGet(String url, int connectionTimeout, int readTimeout) throws Exception {
        return HttpClientUtils.get(url, connectionTimeout, readTimeout);
    }


    /**
     * 获取钉钉AccessToken
     * @return
     * @throws Exception
     */
    public static String getAccessToken() throws Exception {
        String url = DingTalkSyncUtil.getParamValue(tokenParamKey);
        String appKey = DingTalkSyncUtil.getParamValue(appKeyParamKey);
        String appSecret = DingTalkSyncUtil.getParamValue(appSecretParamKey);
        String doGetUrl = url + "appkey=" + appKey + "&appsecret=" + appSecret;
        l2 = System.currentTimeMillis();
        long diff = l2 - l1;
        if(diff % (1000 * 60) > 60) {
            String responseStr = DingTalkSyncUtil.doGet(doGetUrl, 10000, 10000);
            JSONObject ob = JSONObject.parseObject(responseStr);
            if (ob.getInteger("errcode") == 0) {
                l1 = System.currentTimeMillis();
                accessToken = ob.getString("access_token");
            } else {
                return null;
            }
        }
        return accessToken;
    }

    /**
     * 获取钉钉用户集成数据
     * @return
     */
    public static DynamicObjectCollection getMappingInfo() {
        QFilter filter = new QFilter("imtype.id", QCP.equals, 2L);
        //filter.and("user.isforbidden",QCP.equals,false);
        filter.and("user.enable",QCP.equals, "1");
        String selectFields = "user.number,openid";
        return QueryServiceHelper.query(mapping_entity, selectFields, new QFilter[]{filter});
    }

    /**
     * 用户集成数据转换成Map，key = 人员工号, value = openId
     * @return
     */
    public static Map<String, String> convertMappingInfo() {
        DynamicObjectCollection mappingCols = getMappingInfo();
        Map<String, String> openMap = mappingCols.stream().collect(Collectors.toMap((dyx) -> {
            return dyx.getString("user.number");
        }, (dyx) -> {
            return dyx.getString("openid");
        }));
        return openMap;
    }

    /**
     * 创建同步日志
     * @param status 同步状态 A-成功 B-部分成功 C-失败
     * @param request   请求报文
     * @param response  返回报文
     * @param syncType  同步类型
     */
    public static void createLog (String status, String request, String response, String syncType) {
        DynamicObject dynamicObject = BusinessDataServiceHelper.newDynamicObject(KEY_ENTITY_LOG);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        dynamicObject.set("enable", "1");
        dynamicObject.set("status", "C");
        dynamicObject.set("number", uuid.substring(0,29));
        dynamicObject.set("nckd_status", status);
        dynamicObject.set("nckd_synctype", syncType);
        if (request.length() < 200) {
            dynamicObject.set("nckd_request", request);
        } else {
            dynamicObject.set("nckd_request", request.substring(0, 200) + "...");
        }
        dynamicObject.set("nckd_request_tag", request);

        if (response.length() < 200) {
            dynamicObject.set("nckd_response", response);
        } else {
            dynamicObject.set("nckd_response", response.substring(0, 200) + "...");
        }
        dynamicObject.set("nckd_response_tag", response);
        SaveServiceHelper.save(new DynamicObject[]{dynamicObject});
        logger.info("-------- 保存日志 --------");
    }

    /**
     * 创建同步日志
     * @param status 同步状态 A-成功 B-部分成功 C-失败
     * @param request   请求报文
     * @param response  返回报文
     * @param syncType  同步类型
     */
    public static void createLog (String status, String billNo, String request, String response, String syncType) {
        DynamicObject dynamicObject = BusinessDataServiceHelper.newDynamicObject(KEY_ENTITY_LOG);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        dynamicObject.set("enable", "1");
        dynamicObject.set("status", "C");
        dynamicObject.set("number", uuid.substring(0,29));
        dynamicObject.set("nckd_billno", billNo);
        dynamicObject.set("nckd_status", status);
        dynamicObject.set("nckd_synctype", syncType);
        if (request.length() < 200) {
            dynamicObject.set("nckd_request", request);
        } else {
            dynamicObject.set("nckd_request", request.substring(0, 200) + "...");
        }
        dynamicObject.set("nckd_request_tag", request);

        if (response.length() < 200) {
            dynamicObject.set("nckd_response", response);
        } else {
            dynamicObject.set("nckd_response", response.substring(0, 200) + "...");
        }
        dynamicObject.set("nckd_response_tag", response);
        SaveServiceHelper.save(new DynamicObject[]{dynamicObject});
        logger.info("-------- 保存日志 --------");
    }

    static {
        typeMap.put("2",SyncTrip);
        typeMap.put("3",SyncVa);
        typeMap.put("4",SyncFill);
    }


}
