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 com.weaver.seconddev.chapanda.feishu.dao.WorkflowDegreeLevelDao;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


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

    @Autowired
    private Esb2FeishuTokenUtil esb2FeishuTokenUtil;

    @Autowired
    private WorkflowDegreeLevelDao workflowDegreeLevelDao;

    public String senTodoMessage(String requestid,String requestName,String requestmark,
                                 String creatorName, String createTime,
                                 String nodeId, String nodeName, String archivingTime,
                                 String degree,String mobileurl,String pcurl,
                                 String create_open_id,String operator_open_id,
                                 String recepttime,String status,String cid
                                              ) {
        log.error("senTodoMessage start");
        String code = "";
        String token = esb2FeishuTokenUtil.getToken();
        log.error("token:"+token);
        if(StringUtils.isNotBlank(token)){

            String department_id = "";
            String department_name = "";
            String createTimeStamp = "0";
            if(StringUtils.isNotBlank(createTime)){
                createTimeStamp = String.valueOf(convertTimeStamp(createTime));
            }

            String archivingTimeStamp = "0";
            if(StringUtils.isNotBlank(archivingTime)){
                archivingTimeStamp = String.valueOf(convertTimeStamp(archivingTime));
            }
            String receptTimeStamp = "0";
            if(StringUtils.isNotBlank(recepttime)){
                receptTimeStamp = String.valueOf(convertTimeStamp(recepttime));
            }

            List<Map<String, Object>> formList = new ArrayList<Map<String, Object>>();
            if(StringUtils.isNotBlank(creatorName)){
                Map<String, Object> formMap = new HashMap<String,Object>();
                formMap.put("name","创建人");
                formMap.put("value",creatorName);
                formList.add(formMap);
            }

            if(StringUtils.isNotBlank(degree)){
                Map<String,Object> degreeMap = workflowDegreeLevelDao.queryDegreeLevel();
                if(degreeMap.containsKey(degree)){
                    String degreeName = String.valueOf(degreeMap.get(degree));
                    Map<String, Object> formMap = new HashMap<String,Object>();
                    formMap.put("name","紧急程度");
                    formMap.put("value",degreeName);
                    formList.add(formMap);
                }
            }

            if(StringUtils.isNotBlank(requestmark)){
                Map<String, Object> formMap = new HashMap<String,Object>();
                formMap.put("name","流程编号");
                formMap.put("value",requestmark);
                formList.add(formMap);
            }

            if(StringUtils.isNotBlank(requestid)){
                Map<String, Object> formMap = new HashMap<String,Object>();
                formMap.put("name","流程ID");
                formMap.put("value",requestid);
                formList.add(formMap);
            }

            if(StringUtils.isNotBlank(requestid)){
                Map<String, Object> formMap = new HashMap<String,Object>();
                formMap.put("name","接收时间");
                formMap.put("value",recepttime);
                formList.add(formMap);
            }




            if(StringUtils.isNotBlank(create_open_id)){
                String bodyData = appendBodyParam(requestid,requestName,create_open_id,
                        department_id,department_name,
                        createTimeStamp,archivingTimeStamp,
                        formList,nodeId,nodeName,operator_open_id,
                        mobileurl, pcurl,receptTimeStamp,status,cid);

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

                String message = doPostSendMessage(bodyData,token);
                log.error("feishu-finish-message:{}",message);
                if(StringUtils.isNotBlank(message)){
                    JSONObject returnData = JSONObject.parseObject(message);
                    if(returnData.containsKey("code")){
                        code = returnData.getString("code");
                    }
                }
            }
        }
        return code;
    }


    public String doPostSendMessage(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);
        try {
            Request request = new Request.Builder()
                    .url(Constants.feishuHost+Constants.workflowApproveUrl)
                    .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 department_id,
                                 String department_name,
                                 String createTimeStamp,
                                 String archivingTimeStamp,
                                 List<Map<String, Object>> formList,
                                 String node_id,
                                 String nodeName,
                                  String task_open_id,
                                  String mobileurl,
                                  String pcurl,
                                  String receptTimeStamp,
                                  String status,
                                  String cid
    ){


        JSONObject bodyJson = new JSONObject();
        bodyJson.put("approval_code",Constants.approvalCode);
        bodyJson.put("status",status);
//        JSONObject extraJson = new JSONObject();
//        extraJson.put("测试","测试");
//        bodyJson.put("extra",extraJson.toJSONString());
        bodyJson.put("instance_id",requestid);
        JSONObject linksJson = new JSONObject();
        linksJson.put("pc_link",Constants.HrmHost+pcurl);
        linksJson.put("mobile_link",Constants.HrmHost+mobileurl);
        bodyJson.put("links",linksJson);
        bodyJson.put("title","@i18n@title");


//        bodyJson.put("user_id",Constants.SysUserId);
//        bodyJson.put("user_name","@i18n@9");
        bodyJson.put("open_id",create_open_id);
//        bodyJson.put("department_id",department_id);

        bodyJson.put("start_time",createTimeStamp);
        bodyJson.put("end_time",archivingTimeStamp);
        bodyJson.put("update_time",String.valueOf(System.currentTimeMillis()));

        bodyJson.put("display_method",Constants.browser);
        bodyJson.put("update_mode",Constants.updateMode);

       log.error("update_time:{}",String.valueOf(System.currentTimeMillis()));

        JSONArray taskListArray = new JSONArray();
        log.error("task_open_id:"+task_open_id);
        JSONObject taskListJson = new JSONObject();
        // "weaver_"+requestid+"_"+task_open_id+"_"+cid
        taskListJson.put("task_id","weaver_"+requestid+"_"+cid);
        taskListJson.put("open_id",task_open_id);
        taskListJson.put("title","@i18n@title");
        taskListJson.put("links",linksJson);
        taskListJson.put("status",status);
        taskListJson.put("create_time",receptTimeStamp);

        taskListJson.put("end_time",archivingTimeStamp);
        taskListJson.put("update_time",String.valueOf(System.currentTimeMillis()));
        taskListJson.put("display_method",Constants.browser);
        taskListJson.put("exclude_statistics",Constants.excludeStatistics);

//            JSONArray actionConfigsArray = new JSONArray();
//            JSONObject actionConfigsJson = new JSONObject();
//            actionConfigsJson.put("action_type","APPROVE");
//            actionConfigsJson.put("action_name","@i18n@5");
//            actionConfigsJson.put("is_need_reason",false);
//            actionConfigsJson.put("is_need_approve_reason",false);
//            actionConfigsJson.put("is_need_comment",false);
//            actionConfigsArray.add(actionConfigsJson);
//            taskListJson.put("action_configs",actionConfigsArray);

        taskListJson.put("node_id",node_id);
        taskListJson.put("node_name","@i18n@node");
        taskListArray.add(taskListJson);

        bodyJson.put("task_list",taskListArray);


        JSONArray i18nResourcesTextsArray = new JSONArray();

        JSONObject i18nResourcesTextsJson = new JSONObject();
        i18nResourcesTextsJson.put("key","@i18n@title");
        i18nResourcesTextsJson.put("value",requestName);
        i18nResourcesTextsArray.add(i18nResourcesTextsJson);

        i18nResourcesTextsJson = new JSONObject();
        i18nResourcesTextsJson.put("key","@i18n@node");
        i18nResourcesTextsJson.put("value",nodeName);
        i18nResourcesTextsArray.add(i18nResourcesTextsJson);

        if(StringUtils.isNotBlank(department_id)){
            bodyJson.put("department_id",department_id);
        }else if(StringUtils.isNotBlank(department_name)){
            String key = "@i18n@departmentname";
            bodyJson.put("department_name",key);

            i18nResourcesTextsJson = new JSONObject();
            i18nResourcesTextsJson.put("key",key);
            i18nResourcesTextsJson.put("value",department_name);
            i18nResourcesTextsArray.add(i18nResourcesTextsJson);
        }

        JSONArray formArray = new JSONArray();
        for(int i=0;i<formList.size();i++){
            Map<String,Object> formMap = formList.get(i);
            String name = formMap.get("name").toString();
            String value = formMap.get("value").toString();

            String key_key = "@i18n@k"+i;
            String val_key = "@i18n@v"+i;

            JSONObject formJson = new JSONObject();
            formJson.put("name",key_key);
            formJson.put("value",val_key);
            formArray.add(formJson);

            i18nResourcesTextsJson = new JSONObject();
            i18nResourcesTextsJson.put("key",key_key);
            i18nResourcesTextsJson.put("value",name);
            i18nResourcesTextsArray.add(i18nResourcesTextsJson);

            i18nResourcesTextsJson = new JSONObject();
            i18nResourcesTextsJson.put("key",val_key);
            i18nResourcesTextsJson.put("value",value);
            i18nResourcesTextsArray.add(i18nResourcesTextsJson);
        }
        bodyJson.put("form",formArray);

//        Iterator<Map.Entry<String, Object>> entries = textsMap.entrySet().iterator();
//        while (entries.hasNext()) {
//            Map.Entry<String, Object> entry = entries.next();
//            String key = entry.getKey();
//            String value = String.valueOf(entry.getValue());
//            JSONObject i18nResourcesTextsJson = new JSONObject();
//            i18nResourcesTextsJson.put("key",key);
//            i18nResourcesTextsJson.put("value",value);
//            i18nResourcesTextsArray.add(i18nResourcesTextsJson);
//            System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
//        }

        JSONObject i18nResourcesJson = new JSONObject();
        i18nResourcesJson.put("locale","zh-CN");
        i18nResourcesJson.put("texts",i18nResourcesTextsArray);
        i18nResourcesJson.put("is_default","true");

        JSONArray i18nResourcesArray = new JSONArray();
        i18nResourcesArray.add(i18nResourcesJson);

        bodyJson.put("i18n_resources",i18nResourcesArray);

        return bodyJson.toJSONString();
    }

    public static void main(String[] args) {

        Esb2FeishuSendFinishUtil esb2FeishuSendTodoUtil = new Esb2FeishuSendFinishUtil();

        String requestid = "1154744413522714631";
        String requestName = "督导奖励申请流程-石磊-2025-07-09";

        String create_open_id = "ou_8ff7816cfa8cda57643cac2a06fbdc7e";
        String department_id = "";
        String department_name = "";
        String start_time = String.valueOf(System.currentTimeMillis());
        String end_time = String.valueOf(System.currentTimeMillis());

        Map<String, Object> textsMap = new HashMap<String,Object>();

        List<Map<String, Object>> taskList = new ArrayList<Map<String, Object>>();
        Map<String,Object> taskMap = new HashMap<String,Object>();
        taskMap.put("open_id",create_open_id);
        taskList.add(taskMap);



        List<Map<String, Object>> formList = new ArrayList<Map<String, Object>>();
        Map<String, Object> formMap = new HashMap<String,Object>();
        formMap.put("name","创建人");
        formMap.put("value","石磊");
        formList.add(formMap);
        formMap = new HashMap<String,Object>();
        formMap.put("name","紧急程度");
        formMap.put("value","紧急");
        formList.add(formMap);
        String node_id = "1151724772346716177";
        String nodeName = "1级审批";

//        String data = esb2FeishuSendTodoUtil.appendBodyParam(requestid,
//                requestName,create_open_id,department_id,department_name,start_time,end_time,
//                formList,node_id,nodeName,new ArrayList<String>(),"","","");
//        System.out.println(data);

        String date = "2025-07-17 21:07:48";

        esb2FeishuSendTodoUtil.convertTimeStamp(date);
    }


    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;
    }

}
