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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yifu.cloud.plus.v1.ekp.config.WxConfig;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

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

/**
 * 企业微信智能表格SheetId获取工具类
 * 用于通过文档ID获取表格ID
 */
@Data
@Component
public class WeComSheetIdFetcher {
    /**
     * 企业微信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_SHEET_PATH = "/wedoc/smartsheet/get_sheet";

    /**
     * 通过文档ID获取表格ID列表
     *
     * @param docId      文档ID
     * @return 表格ID列表
     */
    public List<String> getSheetIds(WxConfig wxConfig,String docId) {
        List<String> sheetIds = new ArrayList<>();
        try {
			RestTemplate restTemplate = new RestTemplate();
            // 1. 获取access_token
            String accessToken = wxConfig.getAccessToken(restTemplate);
			//getAccessToken(corpId, corpSecret);
            if (accessToken == null || accessToken.isEmpty()) {
                System.err.println("获取access_token失败");
                return sheetIds;
            }

            // 2. 查询子表信息
            List<SheetInfo> sheetInfos = getSheetInfo(accessToken, docId);
            for (SheetInfo sheetInfo : sheetInfos) {
                // 只返回智能表类型的sheet_id
                if ("smartsheet".equals(sheetInfo.getType())) {
                    sheetIds.add(sheetInfo.getSheetId());
                }
            }
        } catch (Exception e) {
            System.err.println("获取表格ID时发生异常: " + e.getMessage());
            e.printStackTrace();
        }
        return sheetIds;
    }

    /**
     * 获取企业微信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
     * @return 子表信息列表
     */
    private List<SheetInfo> getSheetInfo(String accessToken, String docId) {
        List<SheetInfo> sheetInfos = new ArrayList<>();
        try {
            String url = WE_COM_API_BASE_URL + GET_SHEET_PATH + "?access_token=" + accessToken;

            RestTemplate restTemplate = new RestTemplate();

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

            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 sheets = jsonObject.getJSONArray("sheet_list");
                    if (sheets != null && !sheets.isEmpty()) {
                        for (int i = 0; i < sheets.size(); i++) {
                            JSONObject sheet = sheets.getJSONObject(i);
                            SheetInfo sheetInfo = new SheetInfo();
                            sheetInfo.setSheetId(sheet.getString("sheet_id"));
                            sheetInfo.setTitle(sheet.getString("title"));
                            sheetInfo.setType(sheet.getString("type"));
                            sheetInfos.add(sheetInfo);
                        }
                    }
                } else {
                    System.err.println("查询子表信息失败，错误代码：" + jsonObject.getInteger("errcode")
                            + "，错误信息：" + jsonObject.getString("errmsg"));
                }
            }
        } catch (Exception e) {
            System.err.println("查询子表信息时发生异常: " + e.getMessage());
            e.printStackTrace();
        }
        return sheetInfos;
    }

    /**
     * 子表信息内部类
     */
    public static class SheetInfo {
        private String sheetId;
        private String title;
        private String type; // smartsheet: 智能表, dashboard: 仪表盘, external: 说明页

        public String getSheetId() {
            return sheetId;
        }

        public void setSheetId(String sheetId) {
            this.sheetId = sheetId;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        @Override
        public String toString() {
            return "SheetInfo{" +
                    "sheetId='" + sheetId + '\'' +
                    ", title='" + title + '\'' +
                    ", type='" + type + '\'' +
                    '}';
        }
    }

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

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

        // 获取表格ID列表
      /*  List<String> sheetIds = fetcher.getSheetIds(docId);
        System.out.println("获取到的表格ID列表: " + sheetIds);*/
    }
}