package com.connor.bhdz.pdm.partToCapp;

import java.awt.Frame;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.connor.bhdz.pdm.assets.Constants;
import com.connor.bhdz.pdm.drawingToCapp.ConnOra;
import com.connor.bhdz.pdm.drawingToCapp.ProgressBarThread;
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.TCComponentForm;
import com.teamcenter.rac.kernel.TCComponentItem;
import com.teamcenter.rac.kernel.TCComponentItemRevision;
import com.teamcenter.rac.kernel.TCComponentUser;
import com.teamcenter.rac.kernel.TCException;
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 SendPartToCappAction extends AbstractAIFAction {
	private AbstractAIFApplication application;
	private TCSession session;

	protected SendPartToCappAction(AbstractAIFApplication application, Frame frame, String param) {
		super(application, frame, param);
		this.application = application;
		this.session = (TCSession) application.getSession();
	}
	
	/**
	 * 获取当前时间，格式为"yyyy-MM-dd HH-mm-ss"
	 * @return String
	 */
	private String getCurrentTime() {
		System.out.println("getCurrentTime方法开始执行");
		// 获取当前时间
        LocalDateTime now = LocalDateTime.now();
 
        // 定义自定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH-mm-ss");
 
        // 格式化当前时间
        String formattedDate = now.format(formatter);
 
		return formattedDate;
		
	}
	
	
	/**
	 * 遍历BOM行，组织BOM属性存储到数据库BOM	表中
	 * @param bomLine 父项bom行
	 * @throws TCException 
	 * @throws SQLException 
	 */
//	private void throwBom(TCComponentBOMLine bomLine) throws TCException, SQLException {
//		// TODO Auto-generated method stub
//		//获取父项BOM信息
//		TCComponentItem item = bomLine.getItem();
//		TCComponentItemRevision itemRevision = bomLine.getItemRevision();
//		String parent = item.getProperty("item_id");//父项物料图号
//		String parentversion = itemRevision.getProperty("item_revision_id");//父项物料版本
//		String parentname = item.getProperty("object_name");//父项物料名称
//		
//		//遍历子项BOM，获取子项信息并保存
//		if (bomLine.hasChildren()) {
//			AIFComponentContext[] childrens = bomLine.getChildren();
//			for (AIFComponentContext children : childrens) {
//				TCComponentBOMLine bomLineChild = (TCComponentBOMLine) children.getComponent();
//				TCComponentItem childItem = bomLineChild.getItem();
//				TCComponentItemRevision childItemRevision = bomLineChild.getItemRevision();
//				//保存子项的物料信息到数据库表中
////				savePart(childItemRevision);
//				//组织子项属性信息，并和父项信息一起保存为一条数据
//				String sub = childItem.getProperty("item_id");//子项物料编码
//				String subversion = childItemRevision.getProperty("item_revision_id");//子项版本号
//				String subname = childItem.getProperty("object_name");//子项名称
//				bomLineChild.lock();
//				String lineno = bomLineChild.getProperty("bl_sequence_no");//子项行号
//				String quantity = bomLineChild.getProperty("bl_quantity");//子项数量
//				bomLineChild.unlock();
//				String user = session.getUser().getUserName();//下发人员
//				//TODO 根据父子项版本和物料ID确定唯一性，查询是否已经存在该条BOM数据（若已存在则只保存”更新时间”为当前时间；若不存在则保存“下发时间”和“更新时间”为当前时间）
//				if (true/*不存在*/) {
//					String issuedtime = getCurrentTime();
//					String updatetime = getCurrentTime();
//					//TODO 插入数据到BOM数据库表中
//					
//				}else {
//					String updatetime = getCurrentTime();
//					//TODO 更新数据到BOM数据库表中
//					
//				}
//				throwBom(bomLineChild);
//			}
//		}
//	}

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

	

	@Override
	public void run() {
		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
				if (selectComponent instanceof TCComponentItem) {
					//如果选中对象是物料对象H8_wuliao
					TCComponentItem item = (TCComponentItem) selectComponent;
					//获取最新已发布版本对象-latestReleasedRev
					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_PartRevision
					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);
					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+"/part/"+way;
        try {//测试机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;
	}

}
