
using Furion;
using Furion.FriendlyException;
using Furion.LinqBuilder;
using Newtonsoft.Json.Linq;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using TempTask.WebEntry.ApiController.Dto;

namespace TempTask.WebEntry.Tools
{
    /// <summary>
    /// 
    /// </summary>
    public class NumZjHelper
    {
        /// <summary>
        /// 
        /// </summary>
        public enum ExcelType
        {
            /// <summary>
            /// 总表
            /// </summary>
            [Description("总表（样表）.xls")]
            总表 = 1,
            /// <summary>
            /// 城市更新
            /// </summary>
            [Description("住建系统抓投资情况通报（城市更新）样表.xlsx")]
            城市更新 = 2,
            /// <summary>
            /// 房地产业
            /// </summary>
            [Description("住建系统抓投资情况通报（房地产业+GDP支撑性指标）样表.xlsx")]
            房地产业 = 3,
            /// <summary>
            /// 城市更新0318
            /// </summary>
            [Description("通报表格（城市更新）2022-3-18.xls")]
            城市更新0318 = 4
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="year"></param>
        /// <param name="month"></param>
        /// <param name="week"></param>
        /// <param name="numZjExcel"></param> 
        /// <returns></returns>
        public static string WriteTemplate(int year, int month, int week, NumZjExcel numZjExcel)
        {
            try
            {
                var _month = month.ToString().Length == 1 ? ("0" + month) : month.ToString();
                var week2 = week < 10 ? ("0" + week) : week.ToString();
                int excelTypeInt = (int)numZjExcel.excel_no;
                string template_name = EnumHelper.GetEnumDescription<ExcelType>(numZjExcel.excel_no);
                string excelFilePath = $"{App.WebHostEnvironment.WebRootPath}\\ExcelTemplate\\{template_name}";
                string outputPath = string.Empty;
                if (!string.IsNullOrEmpty(excelFilePath))
                {
                    using (FileStream excelFileStream = System.IO.File.OpenRead(excelFilePath))
                    {
                        bool isCompatible = ExcelHelper.GetIsCompatible(excelFilePath);
                        IWorkbook workbook = ExcelHelper.CreateWorkbook(isCompatible, excelFileStream);
                        foreach (var sheet_item in numZjExcel.sheets)
                        {
                            if (sheet_item.url.IsNullOrEmpty())
                                continue;
                            ISheet sheet = null;
                            //if (int.TryParse(sheet_name.sheet_no, out sheetIndex))
                            //{
                            sheet = workbook.GetSheetAt(sheet_item.sheet_no - 1);
                            //}
                            //else
                            //{
                            //    sheet = workbook.GetSheet(sheet_name.Value);
                            //}
                            Dictionary<string, string> dic_sheet_config = new Dictionary<string, string>();
                            var api_result = HttpHelper.CallUrl(sheet_item.url.Replace("{year}", year.ToString()).Replace("{_month}", _month).Replace("{week}", week.ToString()).Replace("{week2}", week2), "");
                            var obj = JObject.Parse(api_result);
                            var datas = obj["data"] as JArray;
                            //从第几行开始 , 比如 行号是4 , 就写3
                            var startRowIndex = sheet_item.start_row - 1;
                            //当前已经跳了几行
                            int current_skip_count = 0;
                            for (int i = 0; i < sheet_item.null_row_count; i++)
                            {
                                var c_rowindex = startRowIndex + i;
                                if (sheet_item.skip_rows != null && sheet_item.skip_rows.Contains(c_rowindex + 1))
                                {
                                    current_skip_count++;
                                    continue;
                                }
                                int cell_start_index = sheet_item.start_cell.ToExcelColumnIndex();
                                for (int x = cell_start_index; x < cell_start_index + sheet_item.null_cell_count; x++)
                                {
                                    if (i >= datas.Count + (sheet_item.skip_rows?.Count ?? 0))
                                    {
                                        sheet.GetRow(c_rowindex).GetCell(x).SetCellValue("/");
                                    }
                                    else
                                    {
                                        var column_letter = x.ToExcelColumnName();
                                        if (sheet_item.skip_columns != null && sheet_item.skip_columns.Contains(column_letter))
                                            continue;
                                        string api_column_name = string.Empty;
                                        if (numZjExcel.is_excel_config)
                                        {
                                            if (!dic_sheet_config.ContainsKey(column_letter))
                                                dic_sheet_config.Add(column_letter, sheet.GetRow(startRowIndex).GetCell(x).StringCellValue);
                                            api_column_name = dic_sheet_config[column_letter];
                                        }
                                        else
                                            api_column_name = App.Configuration[$"column_name_match_{excelTypeInt}_{sheet_item.sheet_no}:{ x.ToExcelColumnName()}"];
                                        if (string.IsNullOrWhiteSpace(api_column_name))
                                            continue;
                                        var jtoken = datas[i - current_skip_count][api_column_name];
                                        var cellvalue = string.Empty;
                                        if (jtoken.Type == JTokenType.Null)
                                            cellvalue = "/";
                                        else
                                            cellvalue = jtoken.ToString();
                                        sheet.GetRow(c_rowindex).GetCell(x).SetCellValue(cellvalue);
                                    }
                                }
                                //var x = 0;
                                //foreach (var cell in cells)
                                //{
                                //    if (x < sheet_item.skip)
                                //    {
                                //        x++;
                                //        continue;
                                //    }
                                //    //if (cell.Value.ToString().StartsWith("3302"))
                                //    //    continue;
                                //    if (x >= sheet_item.null_cell_count)
                                //        continue;
                                //    sheet.GetRow(c_rowindex).GetCell(sheet_item.start_cell.ToExcelColumnIndex() - 1 + x - sheet_item.skip).SetCellValue(cell.Value.ToString());
                                //    x++;
                                //}
                            }
                        }
                        var file = new FileInfo(excelFilePath);
                        var savePath = file.DirectoryName + "\\OutPut\\";
                        if (!Directory.Exists(savePath))
                            Directory.CreateDirectory(savePath);
                        outputPath = savePath + year + "_" + _month + "_" + week + "_" + template_name;
                        using (var filess = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.Read))
                        {
                            workbook.Write(filess);
                        }
                    }
                }
                return outputPath;
            }
            catch (System.IO.IOException ioex)
            {
                throw Oops.Oh("文件被占用，请检查文件模板");
            }
        }

    }
}
