// See https://aka.ms/new-console-template for more information
using CloudGaming.AppConfigModel;
using CloudGaming.GameModel.Db.Db_Ext;
using CloudGaming.GameModel.Db.Db_Game;
using CloudGaming.Model.DbSqlServer.Db_Phone;
using CloudGaming.Model.DbSqlServer.Db_User;

using HuanMeng.DotNetCore.MultiTenant;

using Microsoft.EntityFrameworkCore;

using OfficeOpenXml;

using StackExchange.Redis;

using System.Drawing;

Console.WriteLine("Hello, World!");
// 设置 ExcelPackage 的许可
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
string directoryPath = "C:\\Users\\Administrator\\Pictures\\车机版\\游戏运营配图\\";
string filePath = $"{directoryPath}游戏列表.xlsx";

// 确保文件存在
if (!File.Exists(filePath))
{
    Console.WriteLine("文件不存在");
    return;
}
var optionsBuilder1 = new DbContextOptionsBuilder<CloudGamingGameContext>();
var option1 = optionsBuilder1.UseSqlServer("Server=192.168.195.8;Database=CloudGamingGame;User Id=sa;Password=Dbt@com@123;TrustServerCertificate=true;").Options;
CloudGamingGameContext gameDao = new CloudGamingGameContext(option1);
var optionsBuilder3 = new DbContextOptionsBuilder<CloudGamingCBTContext>();
var option3 = optionsBuilder3.UseSqlServer("Server=192.168.195.8;Database=CloudGamingCBT;User Id=sa;Password=Dbt@com@123;TrustServerCertificate=true;").Options;
CloudGamingCBTContext cbtDao = new CloudGamingCBTContext(option3);
var imageId = (cbtDao.T_App_Image.Where(it => it.ImageId < 90000).Max(it => (int?)it.ImageId) ?? 0) + 1;
var optionsBuilder11 = new DbContextOptionsBuilder<CloudGamingPhoneContext>();
var option11 = optionsBuilder11.UseSqlServer("Server=192.168.195.8;Database=CloudGamingPhone;User Id=sa;Password=Dbt@com@123;TrustServerCertificate=true;").Options;
CloudGamingPhoneContext appDao = new CloudGamingPhoneContext(new TenantInfo()
{
    Identifier = "default",
    TenantId = Guid.Parse("6fba9c21-0de5-4734-a91e-f4961684d3d1")
}, option11);
//gameDao.T_Game_Tags;
var dir = Directory.GetDirectories(directoryPath);
List<tempGame> tempGames = new List<tempGame>();
using (var package = new ExcelPackage(new FileInfo(filePath)))
{
    // 获取第一个工作表
    var worksheet = package.Workbook.Worksheets[0];

    // 获取总行数和总列数
    int rowCount = worksheet.Dimension.Rows;
    int colCount = worksheet.Dimension.Columns;

    // 遍历单元格
    for (int row = 2; row <= rowCount; row++)
    {

        tempGame tempGame = new tempGame();
        tempGame.GameId = GetExcelCell(worksheet.Cells, row, 2);
        tempGame.GameName = GetExcelCell(worksheet.Cells, row, 3);
        tempGame.GameCloudId = GetExcelCell(worksheet.Cells, row, 4);
        tempGame.GameIntroduce = GetExcelCell(worksheet.Cells, row, 5);
        var gameType = GetExcelCell(worksheet.Cells, row, 6);
        if (!string.IsNullOrEmpty(gameType))
        {
            tempGame.GameType = gameType.Split(',', '，');
        }
        var gameTag = GetExcelCell(worksheet.Cells, row, 7);
        if (!string.IsNullOrEmpty(gameTag))
        {
            tempGame.GameTag = gameTag.Split(',', '，');
        }
        tempGame.Title2 = GetExcelCell(worksheet.Cells, row, 8);
        tempGame.ConsumeDiamondNumHour = GetExcelCellInt(worksheet.Cells, row, 9);
        tempGame.Score = GetExcelCell(worksheet.Cells, row, 10);
        tempGame.GameLoadTime = GetExcelCellInt(worksheet.Cells, row, 11);
        tempGame.fengxiangren = GetExcelCell(worksheet.Cells, row, 12);
        string gameDir = dir.Where(it => it.Contains(tempGame.GameId)).FirstOrDefault();
        //string gameDir = $"{directoryPath}\\{tempGame.GameId}_{tempGame.GameName}";
        //if (!Directory.Exists(gameDir))
        //{

        if (string.IsNullOrEmpty(gameDir))
        {
            Console.WriteLine($"{tempGame.GameId}{tempGame.GameName}==>文件夹不存在===》{gameDir}");
            continue;
        }
        if (!Directory.Exists(gameDir))
        {
            Console.WriteLine($"{tempGame.GameId}{tempGame.GameName}==>文件夹不存在===》{gameDir}");
            continue;
        }
        tempGame.GameDir = gameDir;
        tempGames.Add(tempGame);
    }

}
Console.WriteLine("验证成功，开始导入数据...");
//Console.ReadKey();
//List<string> tags = new List<string>();
//Console.WriteLine("开始验证标签...");
//tempGames.ForEach(it => tags.AddRange(it.GameTag));
//tags = tags.Distinct().ToList();
//var gameTags = gameDao.T_Game_Tags.ToList();
//var notTags = tags.Where(it => !gameTags.Any(item => item.TagName == it)).ToList();
//if (notTags != null && notTags.Count > 0)
//{
//    var orderId = (gameTags.Max(it => (int?)it.OrderId) ?? 0) + 1;
//    var tagId = (gameTags.Max(it => (int?)it.TagId) ?? 0) + 1;
//    notTags.ForEach(t =>
//    {
//        //不在数据库中
//        T_Game_Tags t_Game_Tags = new T_Game_Tags()
//        {
//            CreatTime = DateTime.Now,
//            Desc = "",
//            IsOnline = true,
//            OrderId = orderId,
//            TagId = tagId,
//            TagName = t,
//            UpdateTime = DateTime.Now,
//        };
//        gameDao.Add(t_Game_Tags);
//        tagId++;
//        orderId++;
//        Console.WriteLine($"添加标签{t}==>tagId:{tagId}==>orderId:{orderId}");
//    });
//    gameDao.SaveChanges();
//    gameTags = gameDao.T_Game_Tags.ToList();
//}
//Console.WriteLine("开始验证类型...");
//var gameTypes = gameDao.T_Game_Types.ToList();
//List<string> types = new List<string>();
//tempGames.ForEach(it => types.AddRange(it.GameType));
//types = types.Distinct().ToList();

//var notTypes = types.Where(it => !gameTypes.Any(item => item.TypeName == it)).ToList();
//if (notTypes != null && notTypes.Count > 0)
//{
//    var orderId = (gameTypes.Max(it => (int?)it.OrderId) ?? 0) + 1;
//    var TypeId = (gameTypes.Max(it => (int?)it.TypeId) ?? 0) + 1;
//    notTypes.ForEach(t =>
//    {
//        //不在数据库中
//        T_Game_Types t_Game_Tags = new T_Game_Types()
//        {
//            CreatTime = DateTime.Now,
//            IsOnline = true,
//            OrderId = orderId,
//            TypeId = TypeId,
//            TypeName = t,
//            UpdateTime = DateTime.Now,
//            TypeDetails = ""
//        };
//        gameDao.Add(t_Game_Tags);
//        TypeId++;
//        orderId++;
//        Console.WriteLine($"添加类型{t}==>tagId:{TypeId}==>orderId:{orderId}");
//    });
//    gameDao.SaveChanges();
//    gameTypes = gameDao.T_Game_Types.ToList();
//}

var gameChildList = gameDao.T_Game_ChildList.ToList();

Console.WriteLine($"标签和类型验证通过。。。");
//查询游戏
var gameCbt = appDao.T_GameCBT.ToList();
var gameList = gameDao.T_Game_List.ToList();
var gameOrderId = (gameList.Max(it => (int?)it.OrderId) ?? 0) + 1;
tempGames.ForEach((Action<tempGame>)(game =>
{
    var gamel = gameList.FirstOrDefault(it => it.GameId == game.GameId);
    if (gamel == null)
    {
        gamel = new T_Game_List()
        {
            GameId = game.GameId,
            GameName = game.GameName,
            GamePeopleNum = 1,
            GameIsSaveFile = true,
            GameIsCrack = false,
            GameIsAdapter = true,
            GameIsVersion = false,
            GameCloudId = game.GameCloudId,
            OrderId = gameOrderId,
            UpdateTime = DateTime.Now,
            Desc = "",
            GameIntroduce = game.GameIntroduce,
            ScreenOrientation = 0,
            GameIsEditionNumber = false,
            GameIsEditionMouse = true,
            SteamId = "",
            GameDifficulty = "",
            GameIssuer = "",
            DCompany = "",
            GameOperationModel = "手机虚拟手柄,手柄"
        };
        gameOrderId++;
        gameDao.Add(gamel);
        gameList.Add(gamel);
    }
    //gamel.GameIntroduce = game.GameIntroduce;
    //gamel.GameCloudId = game.GameCloudId;
    //gamel.GameName = game.GameName;
    ////添加游戏标签
    ////if(gameTypes)
    //var tempTypes = gameChildList.Where(it => it.GameId == game.GameId && it.ChildType == 1).ToList();
    ////先删除当前游戏所有的类型
    //if (tempTypes != null && tempTypes.Count > 0)
    //{
    //    gameDao.RemoveRange(tempTypes);
    //}
    //if (game.GameType != null && game.GameType.Length > 0)
    //{
    //    int index = 0;
    //    foreach (var gameTypeName in game.GameType)
    //    {
    //        var g = gameTypes.FirstOrDefault(it => it.TypeName == gameTypeName);
    //        if (g != null)
    //        {
    //            T_Game_ChildList cg = new T_Game_ChildList()
    //            {
    //                ChildId = g.TypeId,
    //                ChildType = 1,
    //                GameId = game.GameId,
    //                OrderId = index,
    //                Desc = ""
    //            };
    //            gameDao.Add(cg);
    //            index++;
    //        }
    //    }
    //}
    ////游戏标签管理
    //var tempTags = gameChildList.Where(it => it.GameId == game.GameId && it.ChildType == 2).ToList();
    ////先删除当前游戏所有的标签
    //if (tempTags != null && tempTags.Count > 0)
    //{
    //    gameDao.RemoveRange(tempTags);
    //}
    //if (game.GameTag != null && game.GameTag.Length > 0)
    //{
    //    int index = 0;
    //    foreach (var gameTagName in game.GameTag)
    //    {
    //        var g = gameTags.FirstOrDefault(it => it.TagName == gameTagName);
    //        if (g != null)
    //        {
    //            T_Game_ChildList cg = new T_Game_ChildList()
    //            {
    //                ChildId = g.TagId,
    //                ChildType = 2,
    //                GameId = game.GameId,
    //                OrderId = index,
    //                Desc = ""
    //            };
    //            gameDao.Add(cg);
    //            index++;
    //        }
    //    }
    //}
    
    
    //添加游戏类型
    //gameDao.SaveChanges();
    //添加配置表
    var gameCbtOrderId = (gameCbt.Max(it => (int?)it.OrderId) ?? 0) + 1;
    var gameCbt1 = gameCbt.FirstOrDefault(it => it.GameId == game.GameId&&it.OnlinePlatform== AppPlatform.car.ToString());
    if (gameCbt1 == null)
    {
        gameCbt1 = new T_GameCBT()
        {
            GameId = gamel.GameId,
            IsOnline = true,
            Score = game.Score,
            OrderId = gameCbtOrderId,
            UpdateTime = DateTime.Now,
            CreateTime = DateTime.Now,
            Desc = "",
            IsTest = false,
            IsLimitToVip = false,
            GameLoadTime = game.GameLoadTime,
            Title2 = game.Title2,
            GameName = gamel.GameName,
            ImageId_Banner = 0,
            ConsumeDiamondNumHour = 60,
            ConsumeDiamondNumHourVip = 0,
            GameGroup = 0,
            VipTypeLimit = 0,
            VipVisible = false,
            IsDiscount = false,
            OnlinePlatform = AppPlatform.car.ToString(),
            FriendlyTips = "",
            TenantId = Guid.Parse("6fba9c21-0de5-4734-a91e-f4961684d3d1"),
            GameLoadBgImageId = 0,
            ImageIconId = 0,
            GameBgImgId = 0,
            ImageId_YXK = 0,
            ImageId_ShouSuo = 0,
            ImageId_RM = 0,
            ImageId_FK = 0,
            ImageId_TJ = 0,
        };
        appDao.Add(gameCbt1);
        gameCbt.Add(gameCbt1);
    }
    //game.
    gameCbt1.GameName = game.GameName;
    gameCbt1.Title2 = game.Title2;
    gameCbt1.GameLoadTime = game.GameLoadTime;
    gameCbt1.ConsumeDiamondNumHour = game.ConsumeDiamondNumHour;
    //cbtDao.T_App_Image
    T_App_Image banner = AddImage(game, "banner.png");
    T_App_Image jiazuo = AddImage(game, "jiazuo.png");
    T_App_Image logo_1 = AddImage(game, "log.png");
    T_App_Image logo_2 = AddImage(game, "log.png");
    T_App_Image logo_3 = AddImage(game, "renmen.png");
    T_App_Image biwan = AddImage(game, "biwan.png");
    //T_App_Image youxiku = AddImage(game, "youxiku.png");
    cbtDao.SaveChanges();
    gameCbt1.ImageId_Banner = banner.ImageId;
    gameCbt1.GameBgImgId = banner.ImageId;
    gameCbt1.ImageIconId = logo_1.ImageId;
    gameCbt1.ImageId_RM = logo_3.ImageId;
    gameCbt1.ImageId_ShouSuo = logo_2.ImageId;
    gameCbt1.ImageId_YXK = logo_3.ImageId;
    gameCbt1.ImageId_FK = biwan.ImageId;
    gameCbt1.ImageId_TJ = jiazuo.ImageId;
    gameCbtOrderId++;
    appDao.SaveChanges();

}));

T_App_Image AddImage(tempGame game, string image)
{
    var t_App_Image = new T_App_Image()
    {
        Type = 1,
        CreateTime = DateTime.Now,
        Language = "zh",
        Name = game.GameName,
        UpdateTime = DateTime.Now,
        Url = $"cloudgame/images/game/car/{game.GameId}/{image}",
        ImageId = imageId
    };
    imageId++;
    cbtDao.T_App_Image.Add(t_App_Image);
    return t_App_Image;
}

string GetExcelCell(ExcelRange excelRange, int row, int col)
{
    return excelRange[row, col]?.Text ?? "";
}
int GetExcelCellInt(ExcelRange excelRange, int row, int col)
{
    if (!int.TryParse(excelRange[row, col]?.Text ?? "0", out var c))
    {
        c = 0;
    }
    return c;
}
class tempGame
{
    /// <summary>
    /// 游戏id
    /// </summary>
    public string GameId { get; set; }
    /// <summary>
    /// 游戏名称
    /// </summary>
    public string GameName { get; set; }

    public string[] GameType { get; set; }

    public string[] GameTag { get; set; }
    /// <summary>
    /// 云游戏Id
    /// </summary>
    public virtual string? GameCloudId { get; set; }
    /// <summary>
    /// 游戏介绍
    /// </summary>
    public virtual string? GameIntroduce { get; set; }
    /// <summary>
    /// 游戏详情背景
    /// </summary>
    public virtual int GameBgImgId { get; set; }
    /// <summary>
    /// 评分
    /// </summary>
    public virtual string? Score { get; set; }

    /// <summary>
    /// 备注
    /// </summary>
    public virtual string? Desc { get; set; }

    /// <summary>
    /// 游戏加载图
    /// </summary>
    public virtual int GameLoadBgImageId { get; set; }

    /// <summary>
    /// 游戏详情logo
    /// </summary>
    public virtual int ImageIconId { get; set; }

    /// <summary>
    /// Loading时间
    /// </summary>
    public virtual int GameLoadTime { get; set; }

    /// <summary>
    /// 推荐大图（首页蘑菇必玩 = 首页热血格斗 = 游戏详情页游戏推荐）
    /// </summary>
    public virtual int ImageId_TJ { get; set; }

    /// <summary>
    /// 副标题
    /// </summary>
    public virtual string? Title2 { get; set; }

    /// <summary>
    /// 顶部图片
    /// </summary>
    public virtual int ImageId_Banner { get; set; }

    /// <summary>
    /// 每小时钻石费用
    /// </summary>
    public virtual int ConsumeDiamondNumHour { get; set; }

    /// <summary>
    /// 启动提示
    /// </summary>
    public virtual string? FriendlyTips { get; set; }

    /// <summary>
    /// 游戏库Icon图
    /// </summary>
    public virtual int ImageId_YXK { get; set; }

    /// <summary>
    /// 搜索icon
    /// </summary>
    public virtual int ImageId_ShouSuo { get; set; }

    /// <summary>
    /// 首页爆款热门
    /// </summary>
    public virtual int ImageId_RM { get; set; }

    /// <summary>
    /// （首页GTA系列）大方块
    /// </summary>
    public virtual int ImageId_FK { get; set; }

    /// <summary>
    /// 分享人
    /// </summary>
    public string fengxiangren { get; set; }

    /// <summary>
    /// 
    /// </summary>
    public string GameDir { get; set; }
}

