package com.connor.bhdz.pdm.drawingToCapp;

import java.awt.Frame;
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.StandardCopyOption;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.connor.bhdz.pdm.assets.Constants;
import com.teamcenter.rac.aif.AbstractAIFApplication;
import com.teamcenter.rac.aif.common.actions.AbstractAIFAction;
import com.teamcenter.rac.aif.kernel.AIFComponentContext;
import com.teamcenter.rac.aif.kernel.InterfaceAIFComponent;
import com.teamcenter.rac.kernel.TCComponent;
import com.teamcenter.rac.kernel.TCComponentBOMLine;
import com.teamcenter.rac.kernel.TCComponentBOMWindow;
import com.teamcenter.rac.kernel.TCComponentBOMWindowType;
import com.teamcenter.rac.kernel.TCComponentDataset;
import com.teamcenter.rac.kernel.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentTcFile;
import com.teamcenter.rac.kernel.TCComponentUser;
import com.teamcenter.rac.kernel.TCException;
import com.teamcenter.rac.kernel.TCPreferenceService;
import com.teamcenter.rac.kernel.TCSession;
import com.teamcenter.rac.util.MessageBox;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

public class SendDrawingToCappAction extends AbstractAIFAction {
	private AbstractAIFApplication application;
	private TCSession session;

	public SendDrawingToCappAction(AbstractAIFApplication application, Frame frame, String paramString) {
		super(application, frame, paramString);
		this.application = application;
		this.session = (TCSession) application.getSession();
	}
	
	public static boolean isReleased(TCComponent comp) throws Exception {
		TCComponent[] status = comp.getReferenceListProperty("release_status_list");
		if (status == null || status.length == 0) {
			return false;
		}
		return true;
	}
	
	public static TCComponentItemRevision getLastReleaseRevison(TCComponentItem targetComp) throws Exception {
		System.out.println("Get Last Released Revision: " + targetComp);
		if (targetComp == null) {
			return null;
		}
		List<TCComponentItemRevision> releaseRevisionList = new ArrayList<>();
		TCComponent[] comps = targetComp.getReferenceListProperty("revision_list");
		System.out.println(">> Revisions: " + Arrays.toString(comps));
		for (TCComponent comp : comps) {
			if (isReleased(comp)) {
				releaseRevisionList.add((TCComponentItemRevision) comp);
			}
		}
		System.out.println(">> Released Revisions: " + releaseRevisionList);
		return releaseRevisionList.size() == 0 ? null : releaseRevisionList.get(releaseRevisionList.size() - 1);
	}
	
	/**
	 * 为向springboot发送请求准备携带的信息，包括：
	 *									 url，用户名，密码
	 * @return 
	 */
	public Map<String, Object> readyParamMap() {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		TCPreferenceService preferenceService = session.getPreferenceService();
    	String[] values = preferenceService.getStringValues("BH_CAPP_Oracle");
    	if (values.length != 4) {
			System.out.println("未正确获取到首选项信息！");
		}else {
			paramMap.put("url", "jdbc:oracle:thin:@"+values[0]+":1521/"+values[1]);
			paramMap.put("user", values[2]);
			paramMap.put("password", values[3]);
		}
		
		
		return paramMap;
	}

	@Override
	public void run() {//TODO
		ProgressBarThread thread = new ProgressBarThread("下发中", "下发中..."); 
		thread.start(); 
		
		InterfaceAIFComponent[] components = application.getTargetComponents();

		try {
			for (InterfaceAIFComponent selectComponent : components) {
				String itemID = "";//零组件ID
				String revID = "";//版本
				String sql = "";
			
				
				String toTaskRevId = "";//msg：存放版本信息C语言中调用查询构建器：根据toTaskRevId（"000022-A"）获取具体版本
				
				if (selectComponent instanceof TCComponentItem) {
					//如果选中对象是图纸对象H8_drawing，获取"最新已发布版本"对象
					System.out.println("当前选中对象是 H8_drawing");
					TCComponentItem item = (TCComponentItem) selectComponent;
					//获取最新已发布版本对象
					TCComponentItemRevision latestItemRevision = getLastReleaseRevison(item);
					if (latestItemRevision == null) {
						System.out.println("当前选中对象不存在已发布版本！无法下发···");
						MessageBox.post("当前选中对象不存在已发布版本！无法下发···","提示",MessageBox.INFORMATION);
						thread.setBool(true);
						return;
					}
					revID = latestItemRevision.getProperty("item_revision_id");//C语言中调用查询构建器：根据？？获取具体版本
					itemID = latestItemRevision.getProperty("item_id");
					toTaskRevId = itemID + "-" + revID;
					
				}else if (selectComponent instanceof TCComponentItemRevision) {
					//TODO 如果选中对象是图纸版本对象H8_drawingRevision
					System.out.println("当前选中对象是 H8_drawingRevision");
					TCComponentItemRevision revision = (TCComponentItemRevision)selectComponent;
					String releaseDate = revision.getProperty("date_released");
					System.out.println("===>获取到当前版本对象的发布状态："+releaseDate);
					if (releaseDate == null) {
						System.out.println("当前版本未发布");
						MessageBox.post("当前版本未发布！无法下发···","提示",MessageBox.INFORMATION);
						thread.setBool(true);
						return;
					}
					revID = revision.getProperty("item_revision_id");
					itemID = revision.getProperty("item_id");
					toTaskRevId = itemID + "-" + revID;
					
				}else {
					MessageBox.post("erro select!","tip",MessageBox.INFORMATION);
					thread.setBool(true);
					return;
				}
				//组织除msg外的Task表数据
				String tasksource = "手动下发";
				String userName = session.getUser().getUserName();
				String userId = session.getUser().getUserId();
				String status = "未开始";
				String starttime = getCurrentTime();
				//判断task表中是否已经存在相同数据
				Map<String, Object> paramMap = new HashMap<String, Object>();
				//匹配springboot中的查询方法
				paramMap.put("MSG", toTaskRevId);
				Integer result = sendRequest("getByMSG",paramMap);
				if (result > 0) {//存在重复数据，更新
					System.out.println("TASK表存在重复数据，更新···");
					Map<String, Object> paramMapU = new HashMap<String, Object>();
					paramMapU.put("TASKSOURCE",tasksource);
					paramMapU.put("USERNAME",userName);
					paramMapU.put("USERID",userId);
					paramMapU.put("STATUS",status);
					paramMapU.put("STARTTIME",starttime);
					paramMapU.put("MSG",toTaskRevId);
					Integer resultU = sendRequest("updateTask",paramMapU);
					if (resultU == -1){
						System.out.println("向springboot发送请求失败！updateTask");
					}
					
				}else {//不存在重复数据，插入
					System.out.println("TASK表不存在重复数据，插入···");
					Map<String, Object> paramMapI = new HashMap<String, Object>();
					paramMapI.put("TASKSOURCE",tasksource);
					paramMapI.put("USERNAME",userName);
					paramMapI.put("USERID",userId);
					paramMapI.put("STATUS",status);
					paramMapI.put("MSG",toTaskRevId);
					paramMapI.put("STARTTIME",starttime);
					Integer resultI = sendRequest("insertTask",paramMapI);
					if (resultI == -1){
						System.out.println("向springboot发送请求失败！insertTask");
					}
					System.out.println("1");
				}
				System.out.println("2");
			}
			System.out.println("deal end!");
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("===>下发失败");
			MessageBox.post("下发失败","提示",MessageBox.INFORMATION);
			e.printStackTrace();
		}

		MessageBox.post("下发成功","提示",MessageBox.INFORMATION);
		
		thread.setBool(true);
		
	}
	/**
	 * 向异步服务发送请求
	 * @return 返回-1 表示失败
	 */
	private Integer sendRequest(String way,Map<String, Object> param){
		System.out.println("开始调用方法：向SpringBoot程序发送请求···");
		Integer resultInteger = 0;

		String urlString = "http://"+Constants.SPRING_ADDRESS+"/drawing/"+way;
        try {//正式环境中，spring和curl的ip地址：10.41.72.70。我的测试机ip：192.168.3.125
            String url = StrUtil.format(urlString);//springboot服务所在服务器的ip地址
            System.out.println("发送请求："+urlString);
            // 发送POST请求
            HttpResponse response = HttpRequest.post(url)
                    .header("Content-Type", "application/json") // 设置内容类型为JSON
                    .body(JSONUtil.toJsonStr(param)) // 设置请求体为JSON字符串
					.timeout(20*1000) // 设置超时时间
					.execute();
            System.out.println("调用SpringBoot执行数据库操作后的结果为："+response.body()+"\n 请求携带信息为："+param.toString());
            resultInteger = Integer.parseInt(response.body());
            int statusCode = response.getStatus();
            if (statusCode < 200 && statusCode > 300) {
                System.out.println("响应异常: 获取信息为空!");
                return -1;
            }

        } catch (HttpException e) {
        	 // 检查是否是超时异常
            if (e.getMessage().contains("Read timed out") || e.getMessage().contains("Connect timed out")) {
                System.out.println("请求超时: " + e.getMessage());
                return -2; // 使用不同的返回值标识超时情况
            } else {
                // 其他类型的HttpException
                System.out.println("请求过程中发生HttpException: " + e.getMessage());
                return -1;
            }
        } catch (Exception e) {
            // 捕获其他所有异常
            System.out.println("请求过程中发生异常: " + e.getMessage());
            e.printStackTrace(); // 打印堆栈跟踪信息以便调试
            return -1;
        }

        return resultInteger;
	}

	/**
	 * 保存File文件到String文件路径下
	 * @param file 文件
	 * @param savePath 存放路径
	 */
	 public static void saveFileToFileFolder(File file, String savePath) {
		 System.out.println("开始执行saveFileToFileFolder方法");
		// 将字符串路径转换为 Path 对象
		Path saveFolderPath = Paths.get(savePath);
		
		try {
		    // 检查并创建目标文件夹
		    Files.createDirectories(saveFolderPath);
		
		    // 清空目标文件夹
		    clearDirectory(saveFolderPath);
		
		    // 构建目标文件路径
		    Path targetFilePath = saveFolderPath.resolve(file.getName());
		
		    // 将文件复制到目标文件夹
		    Files.copy(file.toPath(), targetFilePath);
		
		    System.out.println("文件已成功保存到: " + targetFilePath);
		} catch (IOException e) {
		    e.printStackTrace();
		    System.err.println("保存文件时发生错误: " + e.getMessage());
		}
	 }

	 /**
	  * 清空文件夹下所有文件
	  * @param directory
	  * @throws IOException
	  */
	 private static void clearDirectory(Path directory) throws IOException {
	     if (Files.exists(directory)) {
	         File[] files = directory.toFile().listFiles();
	         if (files != null) {
	             for (File file : files) {
	                Files.delete(file.toPath());
	             }
	         }
	     }
	 }


	/**
	 * 获取当前时间，格式为"yyyy-MM-dd HH-mm-ss"
	 * @return String
	 */
	private String getCurrentTime() {
		// 获取当前时间
        LocalDateTime now = LocalDateTime.now();
 
        // 定义自定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss");
 
        // 格式化当前时间
        String formattedDate = now.format(formatter);
 
		return formattedDate;
		
	}

}
