using Common;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
using NLog;
using Org.BouncyCastle.Asn1.Ocsp;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using static Google.Protobuf.Reflection.SourceCodeInfo.Types;

namespace BLW_Log.Models
{
    public class PanelSelectionClass : BackgroundService
    {
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await Task.Factory.StartNew(async () =>
            {
                //return; // 老服务器需要注释此行代码
                while (!stoppingToken.IsCancellationRequested)
                {
                    try
                    {

                        Dictionary<string, string> PicNum = CSRedisCacheHelper.BRPop<Dictionary<string, string>>("PicNumList");

                        _logger.Info("开始执行Redis轮询");
                        if (PicNum != null)
                        {
                            var pair = PicNum.ElementAt(0);
                            _logger.Info($"开始处理{pair.Key}");
                            var RS = CSRedisCacheHelper.Get<string>(pair.Key);
                            if (RS != null)
                            {
                                try
                                {
                                    // 反序列化Redis返回的数据
                                    var rss = JsonConvert.DeserializeObject<TypeNode>(RS);
                                    var redisResult = rss.MsgNode;
                                    if (rss.MsgType == 1)
                                    {
                                        if (redisResult != null)
                                        {
                                            bool isUnitPanel = pair.Key.StartsWith("Unit");
                                            bool updateSuccess = false;

                                            // Process=0: 预览小图 1: CDR
                                            updateSuccess = UpdatePanelThumbnail(
                                                pair.Value,
                                                redisResult.Process == 0 ? redisResult.ImagePath : redisResult.CdrPath,
                                                isUnitPanel,
                                                redisResult.Process
                                            );

                                            if (updateSuccess)
                                            {
                                                CSRedisCacheHelper.Del(pair.Key);
                                                _logger.Info($"成功更新{pair.Value}的thumbnail_large");
                                            }
                                            else
                                            {
                                                Dictionary<string, string> newDic = new()
                                                {
                                                    { pair.Key, pair.Value }
                                                };
                                                CSRedisCacheHelper.LPush("PicNumList", newDic);
                                            }
                                        }
                                    }
                                    else if (rss.MsgType == 2)
                                    {
                                        if (redisResult != null)
                                        {
                                            bool isUnitPanel = pair.Key.StartsWith("Unit");
                                            bool updateSuccess = false;

                                            updateSuccess = UpdatePorjectCdrpath(
                                                pair.Value,
                                                redisResult.CdrPath
                                            );

                                            if (updateSuccess)
                                            {
                                                CSRedisCacheHelper.Del(pair.Key);
                                                _logger.Info($"成功更新{pair.Value}的cdr_filename");
                                            }
                                            else
                                            {
                                                Dictionary<string, string> newDic = new()
                                                {
                                                    { pair.Key, pair.Value }
                                                };
                                                CSRedisCacheHelper.LPush("PicNumList", newDic);
                                            }
                                        }
                                    }

                                }
                                catch (Exception ex)
                                {
                                    _logger.Error($"处理Redis消息失败: {ex.Message}");
                                }
                            }
                            else
                            {
                                Dictionary<string, string> newDic = new()
                                {
                                    { pair.Key, pair.Value }
                                };
                                CSRedisCacheHelper.LPush("PicNumList", newDic);
                            }
                        }
                        await Task.Delay(1145);
                    }
                    catch (Exception ex)
                    {
                        _logger.Info("Redis轮询err：" + ex.StackTrace + " | " + ex.Message);
                    }


                }
            }, TaskCreationOptions.LongRunning);
        }

        private bool UpdatePanelThumbnail(string guid, string imagePathPlt, bool isUnitPanel, int? process)
        {
            try
            {
                string imagePath = Regex.Replace(imagePathPlt, @"\.plt$", ".cdr", RegexOptions.IgnoreCase);
                using var conn = new MySqlConnection(ReadConfig.Instance.MySQLConnectionString);
                conn.Open();

                string sql;
                using var cmd = new MySqlCommand();
                cmd.Connection = conn;
                if (isUnitPanel)
                {
                    sql = $@"UPDATE `cdr_library`.`tbl_web_panel_unit` 
                        SET thumbnail_large = @ImagePath, design_status = '' 
                        WHERE guid = @Guid";
                    cmd.CommandText = sql;
                }
                else
                {
                    if (process == 0)
                    {
                        // Process=0: 更新thumbnail_large，设置design_status为空
                        sql = $@"UPDATE `cdr_library`.`tbl_web_panel_list` 
                        SET thumbnail_large = @ImagePath, design_status = '' 
                        WHERE guid = @Guid";
                        cmd.CommandText = sql;
                    }
                    else
                    {
                        // Process=1: 更新cdr_filename，设置design_status为空
                        sql = $@"UPDATE `cdr_library`.`tbl_web_panel_list` 
                        SET cdr_filename = @ImagePath, carving_filename = @carving_filename, design_status = '' 
                        WHERE guid = @Guid";
                        cmd.CommandText = sql;
                        cmd.Parameters.AddWithValue("@carving_filename", imagePathPlt);
                    }
                }
                cmd.Parameters.AddWithValue("@ImagePath", imagePath);
                cmd.Parameters.AddWithValue("@Guid", guid);
                using var cmdRt = new MySqlCommand("SELECT design_status FROM `cdr_library`.`tbl_web_panel_list` WHERE guid=@Guid;", conn);
                cmdRt.Parameters.AddWithValue("@Guid", guid);

                int affectedRows = cmd.ExecuteNonQuery();
                var affectedRowsRt = cmdRt.ExecuteScalar() != null ? cmdRt.ExecuteScalar().ToString() : "";
                if (string.IsNullOrEmpty(affectedRowsRt))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                // 记录日志
                _logger.Error($"更新面板数据失败: {ex.Message}");
                return false;
            }
        }

        private bool UpdatePorjectCdrpath(string guid, string imagePath)
        {
            try
            {
                using var conn = new MySqlConnection(ReadConfig.Instance.MySQLConnectionString);
                conn.Open();

                string sql;
                using var cmd = new MySqlCommand();
                cmd.Connection = conn;
                sql = $@"UPDATE `cdr_library`.`tbl_web_project` 
                        SET cdr_filename = @ImagePath, edit_status = '' 
                        WHERE guid = @Guid";
                cmd.CommandText = sql;
                cmd.Parameters.AddWithValue("@ImagePath", imagePath);
                cmd.Parameters.AddWithValue("@Guid", guid);
                using var cmdRt = new MySqlCommand("SELECT edit_status FROM `cdr_library`.`tbl_web_project` WHERE guid=@Guid;", conn);
                cmdRt.Parameters.AddWithValue("@Guid", guid);

                int affectedRows = cmd.ExecuteNonQuery();
                var affectedRowsRt = cmdRt.ExecuteScalar() != null ? cmdRt.ExecuteScalar().ToString() : "";
                if (string.IsNullOrEmpty(affectedRowsRt))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                // 记录日志
                _logger.Error($"更新面板数据失败: {ex.Message}");
                return false;
            }
        }
    }
    public class RedisInfo
    {
        /// <summary>
        /// 列表
        /// </summary>
        public object ObjToRedis { get; set; }
        public string Type { get; set; }
    }
    public class RedisInfoNode
    {
        /// <summary>
        /// GUID
        /// </summary>
        public string Guid { get; set; }
        /// <summary>
        /// 用户
        /// </summary>
        public string User { get; set; }

        /// <summary>
        /// 流程 0-预览小图 1-生成文件
        /// </summary>
        public int Process { get; set; }

        /// <summary>
        /// 图号
        /// </summary>
        public string PictureNum { get; set; }

        /// <summary>
        /// 项目名称
        /// </summary>
        public string ProjectName { get; set; }

        /// <summary>
        /// 项目ID
        /// </summary>
        public string ProjectId { get; set; }

        /// <summary>
        /// 素材库名称（返回时代表生成图片路径）默认为空即可
        /// </summary>
        public string MaterialLibraryName { get; set; }

        /// <summary>
        /// 模板名称（返回时代表生成CDR路径）
        /// </summary>
        public string TemplateName { get; set; }

        /// <summary>
        /// logo位置
        /// </summary>
        public string LogoPosition { get; set; }

        /// <summary>
        /// 替换的logo所在文件
        /// </summary>
        public string LogoFileName { get; set; }

        /// <summary>
        /// 替换logo的相对位置
        /// </summary>
        public string LogoIndexNumber { get; set; }

        /// <summary>
        /// 模板名称索引
        /// PageNumber_LayerNumber_Shapenumber =1_2_2
        /// </summary>
        public string TemplateNameIndex { get; set; }

        /// <summary>
        /// 素材集合 
        /// <位置名称, 替换的图像名称>
        /// <Locationnumber, PageNumber_LayerNumber_Shapenumber>
        /// <1, 1_1_1>
        /// </summary>
        public List<Pattern> PatternList { get; set; }
    }

    public class Pattern
    {
        /// <summary>
        /// 文件名称
        /// </summary>
        public string FileName { get; set; }

        /// <summary>
        /// 相对位置
        /// </summary>
        public string IndexNumber { get; set; }

        /// <summary>
        /// 位置
        /// </summary>
        public string ShapeNumber { get; set; }

        /// <summary>
        /// 位置列表
        /// </summary>
        public List<LocationList> LocationList { get; set; }
    }

    public class LocationList
    {
        /// <summary>
        /// 文件名称
        /// </summary>
        public string FileName { get; set; }

        /// <summary>
        /// 素材类型 0自定义 1:图片 2:文字
        /// </summary>
        public int ShapeType { get; set; }

        /// <summary>
        /// 相对位置
        /// </summary>
        public string IndexNumber { get; set; }

        /// <summary>
        /// 素材绝对位置
        /// </summary>
        public string ShapeNumber { get; set; }

        /// <summary>
        /// 颜色
        /// </summary>
        public string ShapeColor { get; set; }

        /// <summary>
        /// 字体
        /// </summary>
        public string ShapeFont { get; set; }

        /// <summary>
        /// 字号
        /// </summary>
        public float ShapeFontSize { get; set; }

        /// <summary>
        /// 备注
        /// </summary>
        public string Remark { get; set; }

        /// <summary>
        /// 对齐行号
        /// </summary>
        public string LineNumber { get; set; }
    }
    public class TypeNode
    {
        public int MsgType { get; set; }
        public RedisSendNode MsgNode { get; set; }
    }
    public class RedisSendNode
    {
        /// <summary>
        /// 状态枚举值
        /// </summary>
        public enum StatusType
        {
            // 成功
            Success = 1,
            // 失败 素材库不存在
            MaterialLibraryNotExist = 2,
            // 失败 模板不存在
            TemplateNotExist = 3,
            // 失败 素材不存在
            MaterialNotExist = 4,
            // 失败 未找到素材放置位置
            MaterialPositionNotExist = 5,
            // 失败 获取数据库素材失败
            GetMaterialFromDBFail = 6,
            // 失败 构建图像失败
            BuildImageFail = 7,
            // 失败 生成文件失败
            SaveFileFail = 8,
            // 失败 未知操作失败
            UnknownFail = 9,
            // 失败 序列化数据错误
            SerializeFail = 10
        }

        /// <summary>
        /// 用户
        /// </summary>
        public string? User { get; set; }

        /// <summary>
        /// 流程 
        /// 0-预览小图 1-生成文件
        /// </summary>
        public int? Process { get; set; } = 0;

        /// <summary>
        /// 图号
        /// </summary>
        public string PictureNum { get; set; }

        /// <summary>
        /// 项目名称
        /// </summary>
        public string? ProjectName { get; set; }

        /// <summary>
        /// 项目ID
        /// </summary>
        public string? ProjectId { get; set; }

        /// <summary>
        /// 状态（使用枚举类型）
        /// </summary>
        public StatusType Status { get; set; }

        /// <summary>
        /// 图片路径
        /// </summary>
        public string? ImagePath { get; set; }

        /// <summary>
        /// CDR路径
        /// </summary>
        public string? CdrPath { get; set; }

        /// <summary>
        /// 返回信息
        /// </summary>
        public string? Msg { get; set; }
    }
    public class CellCorelDRAW
    {
        public int MsgType { get; set; }
        public object MsgNode { get; set; }
    }
}