using Aspose.Cells;
using Aspose.Words;
using Aspose.Words.Tables;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web;
using Ubiety.Dns.Core;

namespace OASystem.API.OAMethodLib.File
{
    /// <summary>
    /// asponse 文档操作
    /// </summary>
    public class AsposeHelper
    {

        #region DownWordToModel

        /// <summary>
        /// 根据Word模板进行数据的导出Word操作
        /// </summary>
        /// <param name="tempFileName">模板文件名称</param>
        /// <param name="saveFolderName">保存文件夹名称</param>
        /// <param name="dic">数据源 key 对应 value</param>
        /// <param name="listDt">需要循环的数据DataTable  多个注意DataTableName </param>
        /// <returns>返回的文档路径</returns>
        public static string ExpertWordToModel(string tempFileName, string saveFolderName, string saveFilName, Dictionary<string, object> dic,
            List<DataTable>? listDt)
        {
            try
            {
                removeWatermark();//加载监听,用于去除水印

                List<string> fieldNames = new List<string>();  //字段名字符串数组
                List<object> fieldValues = new List<object>(); //字段值数组

                foreach (string key in dic.Keys)
                {
                    fieldNames.Add(key);
                    fieldValues.Add(dic[key]);
                }

                string tempPath = string.Format("{0}/Word/Template/{1}", AppSettingsHelper.Get("OfficeTempBasePath"), tempFileName);
                //载入模板
                Document doc = new Document(tempPath);
                doc.MailMerge.Execute(fieldNames.ToArray(), fieldValues.ToArray());
                //将我们获得的DataTable类型的数据：EduDataTable放入doc方法中做处理
                if (listDt != null && listDt.Count > 0)
                {
                    foreach (DataTable dt in listDt)
                    {
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            doc.MailMerge.ExecuteWithRegions(dt);
                        }
                    }
                }

                //合并模版，相当于页面的渲染
                doc.MailMerge.Execute(new[] { "PageCount" }, new object[] { doc.PageCount });
                //"OfficeTempBasePath": "C:/Server/File/OA2023/Office/"
                //saveFolderName:TencentOCR
                string path = string.Format("{0}/Word/{1}", AppSettingsHelper.Get("OfficeTempBasePath"), saveFolderName);

                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);//不存在就创建文件夹
                }

                string saveFilePath = string.Format("{0}/{1}", path, saveFilName);

                //保存合并后的文档
                doc.Save(saveFilePath);
                saveFilePath = saveFilePath.Replace("C:/Server/File/OA2023/", AppSettingsHelper.Get("OfficeBaseUrl")); //返回下载地址
                return saveFilePath; //返回下载地址
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        /// <summary>
        /// 加载监听,用于去除水印
        /// </summary>
        public static void removeWatermark()
        {
            new Aspose.Words.License().SetLicense(new MemoryStream(Convert.FromBase64String("PExpY2Vuc2U+CiAgPERhdGE+CiAgICA8TGljZW5zZWRUbz5TdXpob3UgQXVuYm94IFNvZnR3YXJlIENvLiwgTHRkLjwvTGljZW5zZWRUbz4KICAgIDxFbWFpbFRvPnNhbGVzQGF1bnRlYy5jb208L0VtYWlsVG8+CiAgICA8TGljZW5zZVR5cGU+RGV2ZWxvcGVyIE9FTTwvTGljZW5zZVR5cGU+CiAgICA8TGljZW5zZU5vdGU+TGltaXRlZCB0byAxIGRldmVsb3BlciwgdW5saW1pdGVkIHBoeXNpY2FsIGxvY2F0aW9uczwvTGljZW5zZU5vdGU+CiAgICA8T3JkZXJJRD4yMDA2MDIwMTI2MzM8L09yZGVySUQ+CiAgICA8VXNlcklEPjEzNDk3NjAwNjwvVXNlcklEPgogICAgPE9FTT5UaGlzIGlzIGEgcmVkaXN0cmlidXRhYmxlIGxpY2Vuc2U8L09FTT4KICAgIDxQcm9kdWN0cz4KICAgICAgPFByb2R1Y3Q+QXNwb3NlLlRvdGFsIGZvciAuTkVUPC9Qcm9kdWN0PgogICAgPC9Qcm9kdWN0cz4KICAgIDxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT4KICAgIDxTZXJpYWxOdW1iZXI+OTM2ZTVmZDEtODY2Mi00YWJmLTk1YmQtYzhkYzBmNTNhZmE2PC9TZXJpYWxOdW1iZXI+CiAgICA8U3Vic2NyaXB0aW9uRXhwaXJ5PjIwMjEwODI3PC9TdWJzY3JpcHRpb25FeHBpcnk+CiAgICA8TGljZW5zZVZlcnNpb24+My4wPC9MaWNlbnNlVmVyc2lvbj4KICAgIDxMaWNlbnNlSW5zdHJ1Y3Rpb25zPmh0dHBzOi8vcHVyY2hhc2UuYXNwb3NlLmNvbS9wb2xpY2llcy91c2UtbGljZW5zZTwvTGljZW5zZUluc3RydWN0aW9ucz4KICA8L0RhdGE+CiAgPFNpZ25hdHVyZT5wSkpjQndRdnYxV1NxZ1kyOHFJYUFKSysvTFFVWWRrQ2x5THE2RUNLU0xDQ3dMNkEwMkJFTnh5L3JzQ1V3UExXbjV2bTl0TDRQRXE1aFAzY2s0WnhEejFiK1JIWTBuQkh1SEhBY01TL1BSeEJES0NGbWg1QVFZRTlrT0FxSzM5NVBSWmJRSGowOUNGTElVUzBMdnRmVkp5cUhjblJvU3dPQnVqT1oyeDc4WFE9PC9TaWduYXR1cmU+CjwvTGljZW5zZT4=")));
        }
        #endregion

        #region DownExcelToModel
        /// <summary>
        /// 根据Word模板进行数据的导出Word操作
        /// </summary>
        /// <param name="tempFileName">Excel模板文件名称</param>
        /// <param name="saveFolderName">保存文件夹名称</param>
        /// <param name="saveFilName">保存文件名称</param>
        /// <param name="dic">数据源 key 对应 value</param>
        /// <param name="listDt">需要循环的数据DataTable  多个注意DataTableName </param>
        /// <returns>返回的文档路径</returns>
        public static string ExpertExcelToModel(string tempFileName, string saveFolderName, string saveFilName, Dictionary<string, object> dic,
            List<DataTable>? listDt)
        {
            try
            {
                string tempPath = string.Format("{0}/Excel/Template/{1}", AppSettingsHelper.Get("OfficeTempBasePath"), tempFileName);

                //载入模板
                Workbook wbook = new Workbook(tempPath);
                //默认第一个工作表
                Worksheet wSheet = wbook.Worksheets[0];
                WorkbookDesigner designer = new WorkbookDesigner(wbook);

                //数据源 多个
                if (listDt != null && listDt.Count > 0)
                {
                    foreach (var item in listDt)
                    {
                        if (item.Rows.Count > 0)
                        {
                            //designer.SetDataSource(item.TableName, item);
                            designer.SetDataSource(item);
                        }
                    }
                }

                //报表单位
                if (dic.Count > 0)
                {
                    foreach (var item in dic)
                    {
                        designer.SetDataSource(item.Key, item.Value);
                    }
                }

                designer.Process();

                string path = string.Format("{0}/Excel/{1}", AppSettingsHelper.Get("OfficeTempBasePath"), saveFolderName);

                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);//不存在就创建文件夹
                }
                string saveFilePath = string.Format("{0}/{1}", path, saveFilName);

                //保存合并后的文档
                wbook.Save(saveFilePath);
                //saveFilePath = saveFilePath.Replace("C:/Server/File/0A2023/", AppSettingsHelper.Get("OfficeBaseUrl")); //返回下载地址
                saveFilePath = AppSettingsHelper.Get("OfficeBaseUrl") + "/Office/Excel/" + saveFolderName + "/" + saveFilName;
                return saveFilePath; //返回下载地址
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        #endregion

        #region List<T> 转 Datatbale

        /// <summary>
        /// 将List转换为DataTable
        /// </summary>
        /// <param name="newTableName">newTableName</param>
        /// <param name="list">请求数据</param>
        /// <returns></returns>
        public static DataTable ListToDataTable<T>(string newTableName, List<T> list)
        {
            //创建一个名为"tableName"的空表
            DataTable dt = new DataTable(newTableName);

            //创建传入对象名称的列
            foreach (var item in list.FirstOrDefault().GetType().GetProperties())
            {
                dt.Columns.Add(item.Name);
            }
            //循环存储
            foreach (var item in list)
            {
                //新加行
                DataRow value = dt.NewRow();
                //根据DataTable中的值，进行对应的赋值
                foreach (DataColumn dtColumn in dt.Columns)
                {
                    int i = dt.Columns.IndexOf(dtColumn);
                    //基元元素，直接复制，对象类型等，进行序列化
                    if (value.GetType().IsPrimitive)
                    {
                        value[i] = item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item);
                    }
                    else
                    {
                        value[i] = JsonConvert.SerializeObject(item.GetType().GetProperty(dtColumn.ColumnName).GetValue(item));
                    }
                }
                dt.Rows.Add(value);
            }
            return dt;
        }

        #endregion

    }
}
