using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text.RegularExpressions;
using MySystem.Models;
using Library;
using Aop.Api.Util;

namespace MySystem
{
    public class PublicFunction
    {
        public static decimal NumberFormat(decimal number, int floatCount = 2)
        {
            string str = number.ToString();
            if (str.Contains("."))
            {
                string[] list = str.Split('.');
                if (list[1].Length > floatCount)
                {
                    str = list[0] + "." + list[1].Substring(0, floatCount);
                }
            }
            else
            {
                str += ".00";
            }
            return decimal.Parse(str);
        }

        public static string GetPublicParam(WebCMSEntities db, string Key)
        {
            CustomTagSet set = db.CustomTagSet.FirstOrDefault(m => m.Tags == Key);
            if(set != null)
            {
                return set.Contents;
            }
            return "";
        }



        #region 获取网络文件内容

        public static string GetNetFileContent(string url)
        {
            string textContent = "";     
            using (var client = new System.Net.WebClient())
            {
                try
                {
                    textContent = client.DownloadString(url); // 通过 DownloadString 方法获取网页内容
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "获取网络文件内容异常");
                }
            }
            return textContent;
        }

        public static byte[] GetNetFileData(string url)
        {
            byte[] textContent = new byte[] { };
            using (var client = new System.Net.WebClient())
            {
                try
                {
                    textContent = client.DownloadData(url); // 通过 DownloadString 方法获取网页内容
                }
                catch (Exception ex)
                {
                    function.WriteLog(DateTime.Now.ToString() + "\n" + ex.ToString() + "\n\n", "获取网络文件流异常");
                }
            }
            return textContent;
        }

        public static FileItem GetNetFileItem(string url)
        {
            string fileName = url;
            if(fileName.Contains("/"))
            {
                fileName = fileName.Substring(fileName.LastIndexOf("/") + 1);
            }
            FileItem item = new FileItem(fileName, GetNetFileData(url));
            return item;
        }

        #endregion
    }
}
