package com.yifu.cloud.plus.v1.ekp.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * 企业微信智能表格字段信息获取工具类
 * 用于获取智能表格的字段信息，帮助诊断"字段不存在"错误
 */
@Component
public class WeComSheetFieldFetcher {

    /**
     * 企业微信API基础URL
     */
    private static final String WE_COM_API_BASE_URL = "https://qyapi.weixin.qq.com/cgi-bin";

    /**
     * 获取access_token的接口路径
     */
    private static final String GET_TOKEN_PATH = "/gettoken";

    /**
     * 获取智能表格字段信息的接口路径
     */
    private static final String GET_FIELDS_PATH = "/wedoc/smartsheet/get_fields";

    /**
     * 获取智能表格字段信息
     *
     * @param corpId     企业ID
     * @param corpSecret 应用的密钥
     * @param docId      文档ID
     * @param sheetId    工作表ID
     * @return 字段信息列表
     */
    public List<FieldInfo> getSheetFields(String corpId, String corpSecret, String docId, String sheetId) {
        List<FieldInfo> fieldInfos = new ArrayList<>();
        try {
            // 1. 获取access_token
            String accessToken = getAccessToken(corpId, corpSecret);
            if (accessToken == null || accessToken.isEmpty()) {
                System.err.println("获取access_token失败");
                return fieldInfos;
            }

            // 2. 获取字段信息
            fieldInfos = fetchFields(accessToken, docId, sheetId);
        } catch (Exception e) {
            System.err.println("获取表格字段信息时发生异常: " + e.getMessage());
            e.printStackTrace();
        }
        return fieldInfos;
    }

    /**
     * 获取企业微信access_token
     *
     * @param corpId     企业ID
     * @param corpSecret 应用密钥
     * @return access_token
     */
    private String getAccessToken(String corpId, String corpSecret) {
        try {
            String url = WE_COM_API_BASE_URL + GET_TOKEN_PATH + "?corpid=" + corpId + "&corpsecret=" + corpSecret;

            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                JSONObject jsonObject = JSON.parseObject(response.getBody());
                if (jsonObject.getInteger("errcode") == 0) {
                    return jsonObject.getString("access_token");
                } else {
                    System.err.println("获取access_token失败，错误代码：" + jsonObject.getInteger("errcode")
                            + "，错误信息：" + jsonObject.getString("errmsg"));
                    return null;
                }
            }
        } catch (Exception e) {
            System.err.println("获取access_token时发生异常: " + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取字段信息
     *
     * @param accessToken 访问令牌
     * @param docId       文档ID
     * @param sheetId     工作表ID
     * @return 字段信息列表
     */
    private List<FieldInfo> fetchFields(String accessToken, String docId, String sheetId) {
        List<FieldInfo> fieldInfos = new ArrayList<>();
        try {
            String url = WE_COM_API_BASE_URL + GET_FIELDS_PATH + "?access_token=" + accessToken;

            RestTemplate restTemplate = new RestTemplate();

            // 构造请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("docid", docId);
            requestBody.put("sheet_id", sheetId);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<String> request = new HttpEntity<>(requestBody.toJSONString(), headers);
            ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);

            if (response.getStatusCode() == HttpStatus.OK) {
                JSONObject jsonObject = JSON.parseObject(response.getBody());
                if (jsonObject.getInteger("errcode") == 0) {
                    JSONArray fields = jsonObject.getJSONArray("fields");
                    if (fields != null && !fields.isEmpty()) {
                        for (int i = 0; i < fields.size(); i++) {
                            JSONObject field = fields.getJSONObject(i);
                            FieldInfo fieldInfo = new FieldInfo();
                            fieldInfo.setFieldId(field.getString("field_id"));
                            fieldInfo.setTitle(field.getString("title"));
                            fieldInfo.setType(field.getString("type"));
                            fieldInfos.add(fieldInfo);
                        }
                    }
                } else {
                    System.err.println("获取字段信息失败，错误代码：" + jsonObject.getInteger("errcode")
                            + "，错误信息：" + jsonObject.getString("errmsg"));
                }
            }
        } catch (Exception e) {
            System.err.println("获取字段信息时发生异常: " + e.getMessage());
            e.printStackTrace();
        }
        return fieldInfos;
    }

    /**
     * 使用示例
     *
     * @param args 命令行参数
     */
    public static void main(String[] args) {
        WeComSheetFieldFetcher fetcher = new WeComSheetFieldFetcher();

        // 示例数据
        String corpId = "your_corp_id";
        String corpSecret = "your_corp_secret";
        String docId = "your_doc_id";
        String sheetId = "your_sheet_id";

        // 获取字段信息列表
        List<FieldInfo> fields = fetcher.getSheetFields(corpId, corpSecret, docId, sheetId);
        System.out.println("获取到的字段信息列表: " + fields);
        
        // 打印每个字段的详细信息
        for (FieldInfo field : fields) {
            System.out.println("字段ID: " + field.getFieldId() + 
                               ", 字段标题: " + field.getTitle() + 
                               ", 字段类型: " + field.getType());
        }
    }
}