using PageAdmin.Common;
using PageAdmin.Utils;
using System;
using System.IO;
using System.Web.Mvc;

namespace PageAdmin.Web.Areas.E.Controllers
{

    /// <summary>
    ///下载服务器文件解压文件
    /// </summary>
    public class DownServerFileController : Controller
    {
        private string _Lincese;

        [HttpPost]
        public void Index(FormCollection form)
        {
            string appId = form["appid"]; //guid位数字，和Desk区别是appId对外，desKey对内，格式：18112014 ，14表示今天第几个生成，appId进行了md5加密
            string downloadPath = form["downUrl"]; //用appId的前8位进行了时间戳加密
            string savePath = form["savePath"];//保存路径。
            string deCompressPath= form["deCompressPath"];//解压路径
            _Lincese= form["lincese"]; //序列号
            string configAppId = ConfigHelper.SystemConfig.AppId;
            if (string.IsNullOrEmpty(configAppId))
            {
                LogHelper.SaveLog(LogTypeEnum.ElseLog, "下载文件失败，AppId未设置！");
                return;
            }
            else if (EncryptHelper.MD5(configAppId) != appId)
            {
                LogHelper.SaveLog(LogTypeEnum.ElseLog, "下载文件失败，请核对AppId是否填写正确！");
            }
            downloadPath = EncryptHelper.DecryptCiphertext(downloadPath, appId);
            if (downloadPath == null)
            {
                LogHelper.SaveLog(LogTypeEnum.ElseLog, "获取下载文件地址失败，请核对AppId是否填写正确！");
                return;
            }
            else
            {
                DownLoad(downloadPath,savePath, deCompressPath);
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="downloadPath"></param>
        /// <param name="plugName"></param>
        private void DownLoad(string downloadPath, string savePath,string deCompressPath)
        {
            try
            {
                HttpRequestHelper.Save(downloadPath, savePath);
                if(!string.IsNullOrEmpty(_Lincese))
                {
                    IOHelper.CreateFile(savePath + "/Lincese.ini", _Lincese);
                }
            }
            catch(Exception ex)
            {
                LogHelper.SaveLog(LogTypeEnum.ElseLog, "下载失败:"+ex.Message);
                return;
            }
            string ext = Path.GetExtension(savePath).ToLower() ;
            if(ext==".rar" || ext == ".zip")
            {
                if (!string.IsNullOrEmpty(deCompressPath))
                {
                    DeCompress(savePath, deCompressPath);
                }
            }
        }

        /// <summary>
        /// 解压文件
        /// </summary>
        /// <param name="downloadPath"></param>
        /// <param name="savePath"></param>
        private void DeCompress(string deCompressPath,string zipPath)
        {
            WinRarHelper.DeCompress(deCompressPath, zipPath);
        }

    }
}