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

import cn.hutool.json.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.seconddev.chapanda.feishu.constant.Constants;
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.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;


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

    @Autowired
    private Esb2FeishuTokenUtil esb2FeishuTokenUtil;

    public String senBotTodoMessage(String requestid,String requestName,String requestmark,
                                 String create_open_id,
                                  String title_open_id,String receiver_open_id,
                                 String mobileurl,String pcurl) {
        String message_ids = "";
        String token = esb2FeishuTokenUtil.getToken();
        log.error("token:"+token);
        if(StringUtils.isNotBlank(token)){

            String bodyData = appendBodyParam(requestid,requestName,create_open_id,
                    receiver_open_id,title_open_id,
                    mobileurl, pcurl);

            log.error("feishu-todo:{}",bodyData);

            String message = doSendPost(bodyData,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");
                        if(dataJson.containsKey("message_id")){
                            String message_id = dataJson.getString("message_id");
                            message_ids += StringUtils.isBlank(message_ids) ? message_id : ","+message_id;
                        }
                    }
                }
            }

        }
        return message_ids;
    }


    public String doSendPost(String bodyData, String token){
        String msg = "";

// "{\n  \"approval_code\": \"5DB33242-4B8B-4D72-A64E-DF030E9D94EA\",\n  \"status\": \"PENDING\",\n  \"extra\": \"{\\\"测试\\\":\\\"泛微\\\"}\",\n  \"instance_id\": \"t024j0gfn0\",\n  \"links\": {\n    \"pc_link\": \"http://10.60.4.124:30609/sp/workflow/flowpage/view/1154324404224876544\",\n    \"mobile_link\": \"http://10.60.4.124:30609/sp/workflow/flowpage/view/1154324404224876544\"\n  },\n  \"title\": \"@i18n@1\",\n  \"form\": [\n    {\n      \"name\": \"@i18n@2\",\n      \"value\": \"@i18n@3\"\n    }\n  ],\n  \"user_id\": \"ggf9e451\",\n  \"user_name\": \"@i18n@9\",\n  \"start_time\": \"1752221889000\",\n  \"end_time\": \"1752221889000\",\n  \"update_time\": \"1752221889000\",\n  \"display_method\": \"BROWSER\",\n  \"update_mode\": \"UPDATE\",\n  \"task_list\": [\n    {\n      \"task_id\": \"1154324404224876544\",\n      \"user_id\": \"ggf9e451\",\n      \"title\": \"@i18n@4\",\n      \"links\": {\n        \"pc_link\": \"http://10.60.4.124:30609/sp/workflow/flowpage/view/1154324404224876544\",\n        \"mobile_link\": \"http://10.60.4.124:30609/sp/workflow/flowpage/view/1154324404224876544\"\n      },\n      \"status\": \"PENDING\",\n      \"extra\": \"{\\\"测试2\\\":\\\"范围2\\\"}\",\n      \"create_time\": \"1752221889000\",\n      \"end_time\": \"1752221889000\",\n      \"update_time\": \"1752221889000\",\n      \"action_context\": \"1154324404224876544\",\n      \"action_configs\": [\n        {\n          \"action_type\": \"APPROVE\",\n          \"action_name\": \"@i18n@5\",\n          \"is_need_reason\": false,\n          \"is_reason_required\": false,\n          \"is_need_attachment\": false\n        }\n      ],\n      \"display_method\": \"BROWSER\",\n      \"exclude_statistics\": false\n     \n    }\n  ],\n  \"i18n_resources\": [\n    {\n      \"locale\": \"zh-CN\",\n      \"texts\": [\n        {\n          \"key\": \"@i18n@1\",\n          \"value\": \"招聘需求申请流程\"\n        },\n        {\n          \"key\": \"@i18n@2\",\n          \"value\": \"创建人\"\n        },\n        {\n          \"key\": \"@i18n@3\",\n          \"value\": \"石磊\"\n        },\n        {\n          \"key\": \"@i18n@4\",\n          \"value\": \"招聘需求申请流程--sysadmin\"\n        },{\n          \"key\": \"@i18n@5\",\n          \"value\": \"批准\"\n        },\n        {\n          \"key\": \"@i18n@9\",\n          \"value\": \"石磊\"\n        },\n        {\n          \"key\": \"@i18n@10\",\n          \"value\": \"运营支持部\"\n        },\n        {\n          \"key\": \"@i18n@name\",\n          \"value\": \"部门经理审批\"\n        }\n      ],\n      \"is_default\": true\n    }\n  ]\n}"
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, bodyData);
// https://open.feishu.cn/open-apis/approval/v1/message/send
//        RequestBody body = RequestBody.create(mediaType, "{\n    \"template_id\":\"1008\",\n    \"open_id\":\"ou_8ff7816cfa8cda57643cac2a06fbdc7e\",\n    \n    \"approval_name\":\"@i18n@1\",\n    \"comment\":\"@i18n@2\",\n    \"title_user_id\":\"ou_22e2ad302f4570359ea371f553648d3b\",\n    \"title_user_id_type\":\"open_id\",\n\n    \"content\":{\n        \"user_id\":\"ou_22e2ad302f4570359ea371f553648d3b\",\n      \t\"user_id_type\": \"open_id\",\n    \n        \"summaries\":[\n            {\n                \"summary\":\"@i18n@3\"\n            }\n        ]\n    },\n    \"note\":\"@i18n@4\",\n    \"actions\":[\n        {\n            \"action_name\":\"DETAIL\",\n            \"url\":\"https://hrtest.chabaidao.com/sp/workflow/flowpage/view/1159530626260205576\",\n            \"android_url\":\"https://hrtest.chabaidao.com/sp/workflow/flowpage/view/1159530626260205576\",\n            \"ios_url\":\"https://hrtest.chabaidao.com/sp/workflow/flowpage/view/1159530626260205576\",\n            \"pc_url\":\"https://hrtest.chabaidao.com/sp/workflow/flowpage/view/1159530626260205576\"\n        }\n    ], \n   \n    \n    \"i18n_resources\":[\n        {\n            \"locale\":\"zh-CN\",\n            \"is_default\":true,\n            \"texts\":{\n                \"@i18n@1\":\"编制测试-sysadmin-2025-07-22\",\n                 \"@i18n@2\":\"测试33\",\n                \"@i18n@3\":\"项目经理审批\",\n                \"@i18n@4\":\"从人力资源系统审批\",\n                 \"@i18n@5\":\"取消\"\n            }\n        }\n    ]\n    \n    \n\n}");

        try {
            Request request = new Request.Builder()
                    .url(Constants.feishuHost+Constants.sendBotUrl)
                    .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;
    }

    public String appendBodyParam(String requestid,
                                 String requestName,
                                 String create_open_id,
                                 String receiver_open_id,
                                 String title_open_id,
                                 String mobileurl,
                                 String pcurl
    ){

        JSONObject bodyJson = new JSONObject();
        bodyJson.put("template_id",Constants.botTemplateId);
        bodyJson.put("open_id",receiver_open_id);
        bodyJson.put("approval_name","@i18n@title");
        bodyJson.put("title_user_id",title_open_id);
        bodyJson.put("title_user_id_type","open_id");

        JSONArray summariesArray = new JSONArray();
        JSONObject summariesObject = new JSONObject();
        summariesObject.put("summary","@i18n@summary");
        summariesArray.add(summariesObject);

        summariesObject = new JSONObject();
        summariesObject.put("summary","@i18n@requestid");
        summariesArray.add(summariesObject);

        JSONObject contentJson = new JSONObject();
        contentJson.put("user_id",create_open_id);
        contentJson.put("user_id_type","open_id");
        contentJson.put("summaries",summariesArray);
        bodyJson.put("content",contentJson);
        JSONArray actionsArray = new JSONArray();
        JSONObject actionsObject = new JSONObject();
        actionsObject.put("action_name","DETAIL");
        actionsObject.put("url",Constants.HrmHost+mobileurl);
        actionsObject.put("android_url",Constants.HrmHost+mobileurl);
        actionsObject.put("ios_url",Constants.HrmHost+mobileurl);
        actionsObject.put("pc_url",Constants.HrmHost+pcurl);
        actionsArray.add(actionsObject);
        bodyJson.put("actions",actionsArray);

        JSONObject i18nResourcesTextsJson = new JSONObject();
        i18nResourcesTextsJson.put("@i18n@title",requestName);
        i18nResourcesTextsJson.put("@i18n@summary",requestName);
        i18nResourcesTextsJson.put("@i18n@requestid",requestid);
        JSONObject i18nResourcesJson = new JSONObject();
        i18nResourcesJson.put("locale","zh-CN");
        i18nResourcesJson.put("texts",i18nResourcesTextsJson);
        i18nResourcesJson.put("is_default",true);

        JSONArray i18nResourcesArray = new JSONArray();
        i18nResourcesArray.add(i18nResourcesJson);
        bodyJson.put("i18n_resources",i18nResourcesArray);

        return bodyJson.toJSONString();
    }

    public long convertTimeStamp(String date) {

        if(StringUtils.isNotBlank(date)){
            if(date.contains("T")){
                date = date.replace("T"," ");
            }
        }
        System.out.println("date:"+date);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long timestamp = 0L;
        try{
            if(StringUtils.isNotBlank(date)){
                System.out.println("date:"+date.length());
                if(date.length() == 10){
                    date = date + " 00:00:00";
                }else if(date.length() == 16){
                    date = date + ":00";
                }
                if(date.length() == 19){
                    try {
                        timestamp = sdf.parse(date).getTime();
                    } catch (ParseException e) {
                        log.error("e:{}",e);
                    }
                }
                log.error("timestamp:{}",timestamp);
                System.out.println(timestamp);
                System.out.println(String.valueOf(System.currentTimeMillis()));
            }
        }catch (Exception e){
            log.error("e:{}",e);
        }
        return timestamp;
    }

}
