using Common;
using Common.system;

using Newtonsoft.Json.Linq;

using System;
using System.Collections.Specialized;
using System.Threading;

using XHWK.Model;

namespace XHWK.WKTool.DAL
{
    /// <summary>
    /// 上传相关方法 创建人：赵耀 创建时间：2020年9月4日
    /// </summary>
    public class DAL_Upload
    {
        private string FileRequestAddress = APP.uploadUrl;

        //private string schoolfileRequestAddress = APP.showImageUrl;
        /// <summary>
        /// 文件是否允许上传
        /// </summary>
        /// <param name="MD5">
        /// MD5
        /// </param>
        /// <param name="Message">
        /// 错误消息
        /// </param>
        /// <returns>
        /// </returns>
        public bool IsAllowUploaded(string MD5, out string Message)
        {
            Exception ex = null;
            Message = "";//请求重试5次 共5秒
            for (int num = 0; num < 5; num++)
            {
                try
                {
                    JObject jo = HttpHelper.PostFunction(FileRequestAddress + @"/chunkdb/isexist", @"application/x-www-form-urlencoded", @"md5=" + MD5, "");
                    if (jo == null)
                    {
                        Message = "无法访问文件服务器，请检查网络或文件服务器地址。";
                        return false;
                    }

                    //修改为0为之前上传成功，1为之前未上传成功
                    if (jo["code"].ToString() == "0")
                    {
                        Message = "";

                        Model.ResultVo<Model_ResourceAddTwo> resultObj = JsonHelper.JsonToObj<Model.ResultVo<Model_ResourceAddTwo>>(jo.ToString());

                        APP.ResourceAddTwo = resultObj.obj;
                        //已存在 不允许上传
                        return false;
                        // if (string.IsNullOrWhiteSpace(jo["obj"].ToString())) { //不存在 允许上传 return
                        // true; } else { //已存在 不允许上传 return false; }
                    }
                    else
                    {
                        Message = "";
                        //不存在 允许上传
                        return true;
                    }
                }
                catch (Exception e)
                {
                    Message = "上传失败，无法访问到服务器：" + e.Message;
                    ex = e;
                    Thread.Sleep(1000);
                }
            }
            string ErrMessage = "【文件是否存在】(IsUploaded):请求失败。" + Message;
            LogHelper.WriteErrLog(ErrMessage, ex);
            return false;
        }

        /// <summary>
        /// 上报文件合并指令
        /// </summary>
        /// <param name="Savefolder">
        /// 保存文件位置 学校id/resource
        /// </param>
        /// <param name="FileCode">
        /// 文件唯一编号 Guid
        /// </param>
        /// <param name="Message">
        /// 错误信息
        /// </param>
        /// <returns>
        /// </returns>
        public bool ReportFileMerge(string Savefolder, string FileCode, out string Message)
        {
            Exception ex = null;
            Message = "";//请求重试5次 共5秒
            for (int num = 0; num < 5; num++)
            {
                try
                {
                    JObject jo = HttpHelper.PostFunction(FileRequestAddress + @"/chunkdb/mergechunk", @"application/x-www-form-urlencoded", @"savefolder=" + Savefolder + "&identifier=" + FileCode, "");
                    if (jo == null)
                    {
                        Message = "无法访问文件服务器，请检查网络或文件服务器地址。";
                        return false;
                    }
                    Model.ResultVo<Model_ResourceAddTwo> resultObj = JsonHelper.JsonToObj<Model.ResultVo<Model_ResourceAddTwo>>(jo.ToString());
                    APP.ResourceAddTwo = new Model_ResourceAddTwo();
                    //0成功，1失败
                    if (resultObj.code == 0 && resultObj.obj != null)
                    {
                        APP.ResourceAddTwo = resultObj.obj;
                        //foreach (Model_WKData Vdata in APP.WKDataList)
                        //{
                        //    if (Vdata.VideoList == null)
                        //    {
                        //        continue;
                        //    }
                        //    foreach (Model_Video videoinfo in Vdata.VideoList)
                        //    {
                        //        if (videoinfo.FileGuid == FileCode)
                        //        {
                        //            //videoinfo.IsUpload = true;
                        //            break;
                        //        }
                        //    }
                        //}
                        return true;
                    }
                    else
                    {
                        //Message = "上传失败！";
                        Message = jo["msg"].ToString();
                        return false;
                    }
                }
                catch (Exception e)
                {
                    Message = e.Message;
                    ex = e;
                    Thread.Sleep(1000);
                }
            }
            string ErrMessage = "【上报合并文件】(ReportFileMerge):请求失败。" + Message;
            LogHelper.WriteErrLog(ErrMessage, ex);
            return false;
        }

        /// <summary>
        /// 上传视频
        /// </summary>
        /// <returns>
        /// </returns>
        public bool UploadVideo(string VideoGuid, out string ErrMessage)
        {
            ErrMessage = "";
            try
            {
                Model_Video VideoInfo = null;
                foreach (Model_WKData Vdata in APP.WKDataList)
                {
                    if (Vdata.VideoList == null)
                    {
                        continue;
                    }

                    foreach (Model_Video videoinfo in Vdata.VideoList)
                    {
                        if (videoinfo.FileGuid == VideoGuid)
                        {
                            VideoInfo = videoinfo;
                            break;
                        }
                    }
                    if (VideoInfo != null)
                    {
                        break;
                    }
                }
                if (VideoInfo == null)
                {
                    ErrMessage = "未找到课程！";
                    return false;
                }
                string UploadUrl = FileRequestAddress + "/chunkdb/upchunk";//zxyceshi
                if (VideoInfo.IsUpload)
                {
                    ErrMessage = "视频已上传";
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLog("【视频上传】（UploadVideo）视频上传失败：" + ex.Message, ex);
            }
            return false;
        }

        /// <summary>
        /// 上传视频
        /// </summary>
        /// <returns>
        /// </returns>
        public bool UploadVideoTwo(string VideoGuid, out string ErrMessage)
        {
            ErrMessage = "";
            try
            {
                Model_Video VideoInfo = null;
                foreach (Model_WKData Vdata in APP.WKDataList)
                {
                    if (Vdata.VideoList == null)
                    {
                        continue;
                    }

                    foreach (Model_Video videoinfo in Vdata.VideoList)
                    {
                        if (videoinfo.FileGuid == VideoGuid)
                        {
                            VideoInfo = videoinfo;
                            break;
                        }
                    }
                    if (VideoInfo != null)
                    {
                        break;
                    }
                }
                if (VideoInfo == null)
                {
                    ErrMessage = "未找到课程！";
                    return false;
                }
                string UploadUrl = FileRequestAddress + "/chunkdb/upchunk";//zxyceshi
                if (VideoInfo.IsUpload)
                {
                    ErrMessage = "视频已上传";
                    return false;
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(VideoInfo.FileMD5))
                    {
                        VideoInfo.FileMD5 = AESHelper.AESEncrypt(FileToolsCommon.ReadBigFileStr(VideoInfo.VideoPath, 1024));
                    }

                    //视频长度
                    long filelen = FileToolsCommon.GetFileSize(VideoInfo.VideoPath);
                    //每片的长度
                    double UploadSliceLenMB = double.Parse(FileToolsCommon.GetConfigValue("UploadSliceLen"));
                    string fileName = FileToolsCommon.GetFileName(VideoInfo.VideoPath);
                    //是否续传
                    bool IsSequel = true;
                    //分块数为0时 从未上传过
                    if (VideoInfo.Block > 0)
                    {
                        //是否已上传所有分块
                        if (VideoInfo.Block > VideoInfo.Uploaded)
                        {
                            //已上传，未上传完
                            IsSequel = true;
                        }
                        else
                        {
                            //上传完,未合并
                            IsSequel = false;

                            #region 合并文件

                            //合并文件
                            bool isres = ReportFileMerge(APP.UserInfo.cloudcode + "/" + APP.UserInfo.Schoolid.ToString() + "/resource", VideoInfo.FileGuid, out ErrMessage);
                            if (isres)
                            {
                                VideoInfo.IsUpload = true;
                                return true;
                            }
                            else
                            {
                                return false;
                            }

                            #endregion 合并文件
                        }
                    }
                    else
                    {
                        //是否允许上传
                        if (IsAllowUploaded(VideoInfo.FileMD5, out ErrMessage))
                        {
                            IsSequel = true;
                            if (VideoInfo.SliceLen == 0)
                            {
                                VideoInfo.SliceLen = (long)(UploadSliceLenMB * 1024 * 1024);
                                VideoInfo.Block = (int)(filelen / VideoInfo.SliceLen + (filelen % VideoInfo.SliceLen > 0 ? 1 : 0));
                            }
                        }
                        else
                        {
                            //文件在服务器上已存在  空间是否存在未知 若增加空间是否存在判断在此处添加
                            IsSequel = false;
                            VideoInfo.Block = 1;
                            VideoInfo.Uploaded = 1;

                            VideoInfo.IsUpload = true;
                            return true;
                        }
                    }

                    ////临时修改 没有断点续传，每次上传都重新上传。
                    //VideoInfo.Uploaded = 0;
                    if (IsSequel)
                    {
                        //已上传长度
                        long len = VideoInfo.Uploaded * VideoInfo.SliceLen;

                        #region 废弃

                        ////分块
                        //for (; len + VideoInfo.SliceLen < filelen; VideoInfo.Uploaded++)
                        //{
                        //    len = VideoInfo.Uploaded * VideoInfo.SliceLen;
                        //    //取指定长度的流
                        //    byte[] byteArray = FileToolsCommon.ReadBigFileSpecifyLength(VideoInfo.VideoPath, len, (int)VideoInfo.SliceLen);
                        //    //参数
                        //    NameValueCollection formFields = new NameValueCollection();
                        //    formFields.Add("identifier", VideoInfo.FileGuid);
                        //    formFields.Add("chunkNumber", (VideoInfo.Uploaded + 1).ToString());
                        //    formFields.Add("filename", fileName);
                        //    formFields.Add("totalchunk", VideoInfo.Block.ToString());
                        //    formFields.Add("md5", VideoInfo.FileMD5);
                        //    JObject jo = HttpHelper.UploadRequestflow(UploadUrl, byteArray, fileName, formFields);
                        //    //0成功，1失败
                        //    if (jo["code"].ToString() != "0")
                        //    {
                        //        ErrMessage = jo["msg"].ToString();
                        //        return false;
                        //    }
                        //}

                        #endregion 废弃

                        //分块
                        do
                        {
                            len = VideoInfo.Uploaded * VideoInfo.SliceLen;
                            //取指定长度的流
                            byte[] byteArray = FileToolsCommon.ReadBigFileSpecifyLength(VideoInfo.VideoPath, len, (int)VideoInfo.SliceLen);
                            //参数
                            NameValueCollection formFields = new NameValueCollection
                            {
                                { "identifier", VideoInfo.FileGuid },
                                { "chunkNumber", (VideoInfo.Uploaded + 1).ToString() },
                                { "filename", fileName },
                                { "totalchunk", VideoInfo.Block.ToString() },
                                { "md5", VideoInfo.FileMD5 }
                            };
                            //formFields.Add();///教材
                            //if()//章节若没选不传
                            //{
                            //    formFields.Add();
                            //}

                            JObject jo = HttpHelper.UploadRequestflow(UploadUrl, byteArray, fileName, formFields);
                            //0成功，1失败
                            if (jo["code"].ToString() != "0")
                            {
                                ErrMessage = jo["msg"].ToString();
                                return false;
                            }
                            else
                            {
                                VideoInfo.Uploaded++;
                            }
                        } while (len + VideoInfo.SliceLen < filelen);

                        #region 合并文件

                        //合并文件
                        bool isres = ReportFileMerge(APP.UserInfo.cloudcode + "/" + APP.UserInfo.Schoolid.ToString() + "/resource", VideoInfo.FileGuid, out ErrMessage);
                        if (isres)
                        {
                            //VideoInfo.IsUpload = true;
                            return true;
                        }
                        else
                        {
                            return false;
                        }

                        #endregion 合并文件
                    }
                    else
                    {
                        if (string.IsNullOrWhiteSpace(ErrMessage))
                        {
                            //VideoInfo.IsUpload = true;
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLog("【视频上传】（UploadVideo）视频上传失败：" + ex.Message, ex);
            }
            return false;
        }
    }
}