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

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

import java.util.List;
import java.util.Map;

/**
 * 企业微信智能表格数据插入工具类
 * 用于向已有的企业微信智能表格中插入数据
 */
@Component
public class WeComSmartSheetDataInserter {
	@Autowired
	private WxConfig wxConfig;
    /**
     * 企业微信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 ADD_RECORDS_PATH = "/wedoc/smartsheet/add_records";

    /**
     * 向企业微信智能表格中插入数据
     *
     * @param docId      文档ID
     * @param sheetId    表格ID
     * @param records    要插入的记录列表
     * @return 插入结果
     */
    public boolean insertData(String docId, String sheetId, List<Map<String, Object>> records) {
        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 false;
            }

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

            // 构造records数组
            new com.alibaba.fastjson.JSONArray();
            requestBody.put("records", records);

            // 3. 发送请求插入数据
            boolean result = addRecords(accessToken, requestBody);
            if (result) {
                System.out.println("数据插入成功");
            } else {
                System.err.println("数据插入失败");
            }
            return result;
        } catch (Exception e) {
            System.err.println("插入数据时发生异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取企业微信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 requestBody 请求体
     * @return 是否成功
     */
    private boolean addRecords(String accessToken, JSONObject requestBody) {
        try {
            String url = WE_COM_API_BASE_URL + ADD_RECORDS_PATH + "?access_token=" + accessToken;
            
            RestTemplate restTemplate = new RestTemplate();
            
            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) {
                    return true;
                } else {
                    System.err.println("添加记录失败，错误代码：" + jsonObject.getInteger("errcode") 
                        + "，错误信息：" + jsonObject.getString("errmsg"));
                    return false;
                }
            }
        } catch (Exception e) {
            System.err.println("添加记录时发生异常: " + e.getMessage());
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 使用示例
     * 
     * @param args 命令行参数
     */
    public static void main(String[] args) {
        WeComSmartSheetDataInserter inserter = new WeComSmartSheetDataInserter();
        
        // 示例数据
        String corpId = "your_corp_id";
        String corpSecret = "your_corp_secret";
        String docId = "your_doc_id";
        String sheetId = "your_sheet_id";
        
        // 构造要插入的数据
        new java.util.ArrayList<Map<String, Object>>();
        /*
        // 示例记录
        Map<String, Object> record1 = new HashMap<>();
        Map<String, Object> values1 = new HashMap<>();
        values1.put("姓名", "张三");
        values1.put("年龄", 25);
        values1.put("部门", "技术部");
        record1.put("values", values1);
        
        Map<String, Object> record2 = new HashMap<>();
        Map<String, Object> values2 = new HashMap<>();
        values2.put("姓名", "李四");
        values2.put("年龄", 30);
        values2.put("部门", "市场部");
        record2.put("values", values2);
        
        records.add(record1);
        records.add(record2);
        
        // 执行插入
        boolean success = inserter.insertData(corpId, corpSecret, docId, sheetId, records);
        if (success) {
            System.out.println("数据插入成功");
        } else {
            System.out.println("数据插入失败");
        }
        */
    }
}