using Microsoft.AspNetCore.Components.Forms;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XPrintServer.Business.Dto;
using XPrintServer.Business.Workflows.Configure;

namespace XPrintServer.Business.Workflows
{
    public class SplitImageWorkflow : Workflow, IDisposable
    {
        public SplitImageWorkflow(ComfyUIInfos infos) : base(infos)
        {
            workflowPath = Path.Combine(workflowFolder, infos.Workflow.SplitImageFileName);
            CheckWorkFlow();
        }

        public void Dispose()
        {
            if (httpClient != null)
            {
                httpClient.Dispose();
            }
        }


        // 调用ComfyUI生成图像
        public async Task<string> GenerateImageAsync(string newImageFileName)
        {
            try
            {
                //CheckWorkFlow();
                // 2. 解析并修改工作流中的提示词，宽，高
                var modifiedWorkflow = ModifyWorkflow(newImageFileName);

                // 3. 构建API请求内容
                string requestJson = "{\"client_id\":\"" + client_id + "\",\"prompt\":" + modifiedWorkflow + "}";
                var content = new StringContent(requestJson, Encoding.UTF8, "application/json");

                // 4. 发送POST请求到ComfyUI API
                //Console.WriteLine("正在发送生成请求...");
                var response = await httpClient!.PostAsync(apiUrl, content);
                response.EnsureSuccessStatusCode();

                var responseContent = await response.Content.ReadAsStringAsync();
                var result = System.Text.Json.JsonSerializer.Deserialize<ComfyUIPromptResult>(responseContent!)!;
                return result.PromptId!;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message} {ex.InnerException}");
            }
            return string.Empty;
        }


        protected string ModifyWorkflow(string newImageFileName)
        {
            try
            {
                // 读取JSON内容
                string json = File.ReadAllText(workflowPath);
                JObject workflow = JObject.Parse(json);

                // 查找class_type为LoadImage的节点
                JProperty? loadImageNode = null;
                foreach (var prop in workflow.Properties())
                {
                    var node = (JObject)prop.Value;
                    if (node["class_type"]?.Value<string>() == "LoadImage")
                    {
                        loadImageNode = prop;
                        break;
                    }
                }

                if (loadImageNode == null)
                {
                    Console.WriteLine("未找到LoadImage节点");
                    return string.Empty;
                }

                // 修改图像文件名
                var inputs = (JObject?)loadImageNode.Value["inputs"]!;
                if (inputs.ContainsKey("image"))
                {
                    inputs["image"] = newImageFileName;
                    //Console.WriteLine($"已将图像文件名修改为: {newImageFileName}");
                }
                else
                {
                    Console.WriteLine("LoadImage节点中未找到image属性");
                    return string.Empty;
                }
                // -------------------------- 5. 保存修改后的工作流 --------------------------
                string modifiedJson = workflow.ToString(Newtonsoft.Json.Formatting.Indented);  // 保持JSON缩进格式
                return modifiedJson;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"处理失败：{ex.Message}");
            }
            return string.Empty;
        }
    }
}
