using Common;
using LinqToDB.Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using RestSharp;
using System.Collections;
using static NPOI.HSSF.UserModel.HeaderFooter;
using MySql.Data.MySqlClient;
using System.Data;
using BLW_Log.Models;

namespace BLW_Log.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class HuobanController : ControllerBase
    {
        private readonly string baseUrl = "https://api.huoban.com/";
        private readonly string API_Key = "FIQBLpReK6nAJ0CzYOxmNgKtEpa0cApctanSZyGW";
        private readonly List<string> TblSPHeader = ["审批状态", "报备编号", "项目名称", "客房数量", "所属客户", "负责人", "流程结束时间"];
        /// <summary>
        /// 创建返回结果的辅助方法
        /// </summary>
        /// <param name="isSuccess">是否成功</param>
        /// <param name="message">返回消息</param>
        /// <param name="statusCode">状态码</param>
        /// <param name="data">返回数据</param>
        /// <returns>ReturnInfo对象</returns>
        private ReturnInfo CreateResult(bool isSuccess, string message, int statusCode, object? data = null)
        {
            return new ReturnInfo
            {
                isok = isSuccess,
                message = message,
                status = statusCode,
                response = data
            };
        }

        /// <summary>
        /// 获取工作区ID（内部方法）
        /// </summary>
        /// <returns>工作区ID</returns>
        private string GetHuobanSpaceList()
        {
            try
            {
                // 创建 REST 客户端
                var options = new RestClientOptions(baseUrl);
                var client = new RestClient(options);

                // 创建请求
                var request = new RestRequest("openapi/v1/space/list", Method.Get);

                // 添加授权头
                request.AddHeader("Open-Authorization", $"Bearer {API_Key}");

                // 执行请求
                var response = client.Execute(request);
                string space_id = "";
                if (response.IsSuccessful)
                {
                    // 解析响应内容
                    var responseData = JsonConvert.DeserializeObject<dynamic>(response.Content);
                    foreach (var item in responseData.data.spaces)
                    {
                        if (item.name == "宝来威智能（广东）有限公司")
                        {
                            space_id = item.space_id;
                            break;
                        }
                    }
                }
                return space_id;
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        /// <summary>
        /// 获取"项目报备"表格ID
        /// </summary>
        /// <param name="space_id">工作区ID</param>
        /// <returns>表格ID</returns>
        private string GetProjectReportTableId(string space_id)
        {
            try
            {
                // 创建 REST 客户端
                var options = new RestClientOptions(baseUrl);
                var client = new RestClient(options);

                // 创建请求
                var request = new RestRequest("openapi/v1/table/list", Method.Post);

                // 添加授权头
                request.AddHeader("Open-Authorization", $"Bearer {API_Key}");
                request.AddHeader("Content-Type", "application/json");

                // 添加请求体
                var requestBody = new { space_id };
                request.AddJsonBody(requestBody);

                // 执行请求
                var response = client.Execute(request);

                if (response.IsSuccessful)
                {
                    // 解析响应内容
                    var responseData = JsonConvert.DeserializeObject<dynamic>(response.Content);
                    string table_id = "";
                    foreach (var item in responseData.data.tables)
                    {
                        if (item.name == "项目报备")
                        {
                            table_id = item.table_id;
                            break;
                        }
                    }
                    return table_id;
                }
                else
                {
                    return "";
                }
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        /// <summary>
        /// 获取"项目报备"表格表头
        /// </summary>
        /// <param name="space_id">工作区ID</param>
        /// <returns>表格ID</returns>
        private Dictionary<string, string> GetProjectReportTableHeader(string table_id)
        {
            try
            {
                // 创建 REST 客户端
                var options = new RestClientOptions(baseUrl);
                var client = new RestClient(options);

                // 创建请求
                var request = new RestRequest($"openapi/v1/table/{table_id}", Method.Post);

                // 添加授权头
                request.AddHeader("Open-Authorization", $"Bearer {API_Key}");
                request.AddHeader("Content-Type", "application/json");


                // 执行请求
                var response = client.Execute(request);

                if (response.IsSuccessful)
                {
                    Dictionary<string, string> tabelHeader = [];
                    // 解析响应内容
                    var responseData = JsonConvert.DeserializeObject<TblRoot>(response.Content);
                    var dic = responseData.data.table.fields;
                    foreach (dynamic item in dic)
                    {
                        if (TblSPHeader.Contains(Convert.ToString(item.name)))
                        {
                            tabelHeader.Add(item.field_id.ToString(), item.name.ToString());
                        }
                    }
                    return tabelHeader;
                }
                else
                {
                    return [];
                }
            }
            catch (Exception ex)
            {
                return [];
            }
        }

        /// <summary>
        /// 查询"项目报备"数据列表
        /// </summary>
        /// <param name="table_id">表格ID</param>
        /// <returns>数据列表</returns>
        private dynamic QueryProjectReportData(string table_id, Dictionary<string, string> TblHeader, int limit = 5, int offset = 0)
        {
            try
            {
                // 创建 REST 客户端
                var options = new RestClientOptions(baseUrl);
                var client = new RestClient(options);

                // 创建请求
                var request = new RestRequest("openapi/v1/item/list", Method.Post);

                // 添加授权头
                request.AddHeader("Open-Authorization", $"Bearer {API_Key}");
                request.AddHeader("Content-Type", "application/json");

                // 构建请求体
                var requestBody = new
                {
                    table_id,
                    filter = new
                    {
                        and = new ArrayList
                        {
                            new
                            {
                                field = "2200000565424395",
                                query = new
                                {
                                    eq = new List<string> { "2" }
                                }
                            }
                        }
                    },
                    order = new
                    {
                        field_id = "2200000565427086",
                        type = "desc"
                    },
                    limit = limit,
                    offset = offset,
                    with_field_config = 0
                };
                request.AddJsonBody(requestBody);

                // 执行请求
                var response = client.Execute(request);

                if (response.IsSuccessful)
                {
                    // 解析响应内容
                    TblListRoot resp = JsonConvert.DeserializeObject<TblListRoot>(response.Content);
                    TblListData responseData = resp.data;
                    var rs = new
                    {
                        total = responseData.total,
                        filtered = responseData.filtered,
                        hasMore = responseData.has_more,
                        fields = GetItemsListDic(TblHeader, responseData.items)
                    };
                    return rs;
                }
                else
                {
                    return null;
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        /// <summary>
        /// 获取元素列表
        /// </summary>
        private List<TblProject> GetItemsListDic(Dictionary<string, string> TblHeader, List<TblListItem> itemList)
        {
            List<TblProject> res = [];
            try
            {
                foreach (var item in itemList)
                {
                    TblProject pro = new();
                    var fls = item.fields;
                    bool isPass = true;
                    foreach (var flsitem in fls)
                    {
                        if (!TblHeader.ContainsKey(flsitem.Key))
                        {
                            continue;
                        }
                        if (TblHeader[flsitem.Key].Equals("审批状态"))
                        {
                            try
                            {
                                var t = Convert.ToString(fls[flsitem.Key][0].name);
                                if (t != "已通过")
                                {
                                    isPass = false;
                                }
                            }
                            catch
                            {
                                isPass = false;
                            }
                        }
                        if (TblHeader[flsitem.Key].Equals("报备编号"))
                        {
                            pro.guid = Convert.ToString(fls[flsitem.Key]);
                            pro.report_id = Convert.ToString(fls[flsitem.Key]);
                        }
                        if (TblHeader[flsitem.Key].Equals("项目名称"))
                        {
                            pro.hotel_name = Convert.ToString(fls[flsitem.Key]);
                        }
                        if (TblHeader[flsitem.Key].Equals("客房数量"))
                        {
                            pro.remarks += "_" + Convert.ToString(fls[flsitem.Key]) + "间客房";
                        }
                        if (TblHeader[flsitem.Key].Equals("负责人"))
                        {
                            pro.creator = Convert.ToString(fls[flsitem.Key][0].name);
                        }
                        if (TblHeader[flsitem.Key].Equals("所属客户"))
                        {
                            try
                            {
                                pro.remarks += "_" + Convert.ToString(fls[flsitem.Key][0].title);
                            }
                            catch { }
                        }
                        if (TblHeader[flsitem.Key].Equals("流程结束时间"))
                        {
                            try
                            {
                                pro.created_at = Convert.ToDateTime(fls[flsitem.Key]);
                            }
                            catch { }
                        }
                    }
                    if (isPass && !string.IsNullOrEmpty(pro.hotel_name))
                    {
                        pro.remarks = pro.remarks.StartsWith('_') ? pro.remarks[1..] : pro.remarks;
                        res.Add(pro);
                    }
                }
            }
            catch (Exception ex)
            {
                // 异常处理
                Console.WriteLine(ex.StackTrace + ex.Message);
            }
            return res;
        }
        /// <summary>
        /// 获取"项目报备"表中所有数据
        /// </summary>
        /// <returns>所有数据列表</returns>
        [HttpPost]
        public ReturnInfo GetAllProjectReportData()
        {
            try
            {
                // 1. 获取工作区ID
                string space_id = GetHuobanSpaceList();

                // 参数验证：检查工作区ID是否为空
                if (string.IsNullOrEmpty(space_id))
                {
                    return CreateResult(false, "获取工作区ID失败", 400, null);
                }

                // 2. 获取"项目报备"表格ID
                string table_id = GetProjectReportTableId(space_id);

                // 参数验证：检查表格ID是否为空
                if (string.IsNullOrEmpty(table_id))
                {
                    return CreateResult(false, "获取表格ID失败", 400, null);
                }
                // 3. 获取"项目报备"表格ID
                var tableHeader = GetProjectReportTableHeader(table_id);
                // 参数验证：检查表格表头是否为空
                if (tableHeader.Count <= 0)
                {
                    return CreateResult(false, "获取表格表头失败", 400, null);
                }

                int limit = 20;
                int offset = 0;
                bool stopFetching = false;
                int totalAdded = 0;
                List<TblProject> allItems = new List<TblProject>();

                while (!stopFetching)
                {
                    // 4. 查询"项目报备"数据列表
                    dynamic data = QueryProjectReportData(table_id, tableHeader, limit, offset);

                    // 结果验证：检查数据是否获取成功
                    if (data == null)
                    {
                        return CreateResult(false, "获取数据失败", 500, null);
                    }

                    List<TblProject> items = data.fields;
                    if (items == null || items.Count == 0) break;

                    foreach (var item in items)
                    {
                        if (CheckProjectExists(item.report_id))
                        {
                            stopFetching = true;
                            break;
                        }

                        // Insert
                        WebProjectAdd(item);
                        totalAdded++;
                        //allItems.Add(item);
                    }

                    if (stopFetching) break;

                    if ((bool)data.hasMore == false) break;

                    offset += limit;
                }

                // 4. 返回成功结果
                return CreateResult(true, $"同步完成，新增 {totalAdded} 条记录", 200/*, allItems*/);
            }
            catch (Exception ex)
            {
                // 异常处理：返回包含异常信息的错误结果
                return CreateResult(false, $"发生异常: {ex.Message}", 500, ex.ToString());
            }
        }

        #region 数据库操作

        /// <summary>
        /// 检查项目是否存在
        /// </summary>
        private bool CheckProjectExists(string report_id)
        {
            string sql = "SELECT count(1) as count FROM `cdr_library`.`tbl_web_project` WHERE report_id = @report_id AND is_valid = 1";
            var parameters = new[] { new MySqlParameter("@report_id", report_id) };
            var res = ExecuteQuery(sql, parameters);
            if (res.isok && res.response != null)
            {
                try
                {
                    var json = JArray.Parse(res.response.ToString());
                    if (json.Count > 0 && json[0]["count"] != null)
                    {
                        return Convert.ToInt32(json[0]["count"]) > 0;
                    }
                }
                catch { }
            }
            return false;
        }

        /// <summary>
        /// 添加项目到数据库
        /// </summary>
        private ReturnInfo WebProjectAdd(TblProject project)
        {
            string sql = @"
                INSERT INTO `cdr_library`.`tbl_web_project` 
                (report_id, hotel_name, room_type_count, room_data_json, remarks, creator, created_at, is_valid, guid) 
                VALUES (@report_id, @hotel_name, @room_type_count, @room_data_json, @remarks, @creator, @created_at, 1, @guid)";

            var parameters = new[]
            {
                new MySqlParameter("@report_id", project.report_id ?? (object)DBNull.Value),
                new MySqlParameter("@hotel_name", project.hotel_name ?? (object)DBNull.Value),
                new MySqlParameter("@room_type_count", project.room_type_count),
                new MySqlParameter("@room_data_json", project.room_data_json ?? (object)DBNull.Value),
                new MySqlParameter("@remarks", project.remarks ?? (object)DBNull.Value),
                new MySqlParameter("@creator", project.creator ?? (object)DBNull.Value),
                new MySqlParameter("@created_at", project.created_at),
                new MySqlParameter("@guid", project.guid ?? Guid.NewGuid().ToString("N"))
            };

            return ExecuteNonQueryWithGuid(sql, parameters);
        }

        /// <summary>
        /// 通用查询执行方法（参数化版本）
        /// </summary>
        private ReturnInfo ExecuteQuery(string sql, MySqlParameter[] parameters = null)
        {
            try
            {
                using var conn = new MySqlConnection(ReadConfig.Instance.MySQLConnectionString);
                conn.Open();

                using var cmd = new MySqlCommand(sql, conn);
                if (parameters != null)
                {
                    cmd.Parameters.AddRange(parameters);
                }

                using var adapter = new MySqlDataAdapter(cmd);
                var ds = new DataSet();
                adapter.Fill(ds);

                if (ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
                {
                    return new ReturnInfo
                    {
                        isok = true,
                        message = "查询成功，但未返回数据",
                        status = 200,
                        response = null
                    };
                }

                return new ReturnInfo
                {
                    isok = true,
                    message = "查询成功",
                    status = 200,
                    response = Newtonsoft.Json.JsonConvert.SerializeObject(ds.Tables[0])
                };
            }
            catch (Exception ex)
            {
                return new ReturnInfo
                {
                    isok = false,
                    message = ex.Message,
                    status = 500,
                    response = null
                };
            }
        }

        /// <summary>
        /// 通用增删改执行方法（参数化版本，返回GUID）
        /// </summary>
        private ReturnInfo ExecuteNonQueryWithGuid(string sql, MySqlParameter[] parameters, string guid = null)
        {
            try
            {
                using var conn = new MySqlConnection(ReadConfig.Instance.MySQLConnectionString);
                conn.Open();

                using var cmd = new MySqlCommand(sql, conn);
                if (parameters != null)
                {
                    cmd.Parameters.AddRange(parameters);
                }

                int affectedRows = cmd.ExecuteNonQuery();

                if (affectedRows > 0)
                {
                    return new ReturnInfo
                    {
                        isok = true,
                        message = "操作成功",
                        status = 200,
                        response = guid ?? GetGuidFromParameters(parameters) ?? "操作完成"
                    };
                }

                return new ReturnInfo
                {
                    isok = false,
                    message = "操作未影响任何数据",
                    status = 400,
                    response = null
                };
            }
            catch (Exception ex)
            {
                return new ReturnInfo
                {
                    isok = false,
                    message = ex.Message,
                    status = 500,
                    response = null
                };
            }
        }

        /// <summary>
        /// 从参数中提取GUID值
        /// </summary>
        private string GetGuidFromParameters(MySqlParameter[] parameters)
        {
            if (parameters == null) return null;

            var guidParam = parameters.FirstOrDefault(p => p.ParameterName == "@guid");
            return guidParam?.Value?.ToString();
        }

        #endregion

    }
    public class TblRoot
    {
        public int code { get; set; }
        public string message { get; set; }
        public TblData data { get; set; }
    }
    public class TblData
    {
        public TblHeader table { get; set; }
    }
    public class TblHeader
    {
        public string table_id { get; set; }
        public string name { get; set; }
        public string alias { get; set; }
        public string space_id { get; set; }
        public string created_on { get; set; }
        public List<dynamic> fields { get; set; }
    }

    public class TblListRoot
    {
        public int code { get; set; }
        public string message { get; set; }
        public TblListData data { get; set; }
        public object meta { get; set; }
    }
    public class TblListData
    {
        public int total { get; set; }
        public int filtered { get; set; }
        public bool has_more { get; set; }
        public List<TblListItem> items { get; set; }
    }

    public class TblListItem
    {
        public string item_id { get; set; }
        public string title { get; set; }
        public Dictionary<string, dynamic> fields { get; set; }
        public object created_by { get; set; }
        public string created_on { get; set; }
        public object updated_by { get; set; }
        public string updated_on { get; set; }
    }

    public class TblProject
    {
        public string report_id { get; set; }
        public string hotel_name { get; set; }
        public int room_type_count { get; set; }
        public string room_data_json { get; set; }
        public string? remarks { get; set; }
        public string creator { get; set; }
        public DateTime created_at { get; set; }
        public bool is_valid { get; set; }
        public string? guid { get; set; }
        public TblProject()
        {
            this.is_valid = true;
            this.room_type_count = 1;
            this.room_data_json = "[]";
        }
    }
}
