using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.knowledge
{
    public class KnowledgeController : BaseController
    {
        // 获取知识库列表
        public ActionResult GetList()
        {
            ActionResult res = NoToken("未知错误，请重新登录");

                DataTable dt = new DataTable();
                string pid = HttpUtility.UrlDecode(RequestString.GetQueryString("pid"));
                string keywords = HttpUtility.UrlDecode(RequestString.GetQueryString("keywords"));
                string strpageindex = RequestString.GetQueryString("page");
                int pageindex = 1;
                string strpagesize = RequestString.GetQueryString("pagesize");
                int pagesize = 10;

                string sql = " and F_DeleteFlag=0";
                if (pid.Trim() != "")
                {
                DataTable dr = new DataTable();
                dr = new BLL.T_RepositoryCategory().GetList(" 1=1 " + "and F_CategoryId="+ pid).Tables[0];
                string modelList = BindTree(dr, pid);
                sql += " and F_CategoryId in(" + modelList.Trim()+")";
                }
                if (keywords.Trim() != "")
                {
                    sql += " and (F_Content like '%" + keywords.Trim() + "%' or F_Title like '%"
                        + keywords.Trim() + "%' or F_KeyWords like '%" + keywords.Trim() + "%')";
                }
                if (strpageindex.Trim() != "")
                {
                    pageindex = Convert.ToInt32(strpageindex);
                }

                if (strpagesize.Trim() != "")
                {
                    pagesize = Convert.ToInt32(strpagesize);
                }
                int recordCount = 0;
                dt = BLL.PagerBLL.GetListPager(
                    "T_RepositoryInformation a",
                    "F_RepositoryId",
                   "F_CreateName=(select F_UserName+'('+F_UserCode+')'  from  T_Sys_UserAccount where F_UserId=a.F_CreateBy),*",
                    sql,
                    "ORDER BY F_RepositoryId desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);
          //  List<Model.TreeModel> modelList = BindTree(dt, "0");
            //System.Collections.Generic.List<Model.T_RepositoryInformation> modelList = new BLL.T_RepositoryInformation().DataTableToList(dt);

            //if (modelList.Count > 0)
            //{
            //    res = Success("加载成功", modelList);
            //}
            //else
            //    res = Error("加载失败");

            var obj = new
                {
                    rows = dt,
                    total = recordCount
                };

                res = Content(obj.ToJson());

            return res;
        }
       
        private string  BindTree(DataTable tab, string parentid)
        {

            DataTable tab2 = new DataTable();
            string modelList = parentid;
            var iv = new BLL.T_RepositoryCategory().GetModelList("F_ParentId=" + parentid + " and F_DeleteFlag=0 and F_CategoryType is null order by F_Sort");
           if (iv != null )
            {
                foreach (var it in  iv)
                {
                    modelList += "," + it.F_CategoryId;
                }
            }
            return modelList;
        }
        //private List<Model.TreeModel> BindTree(DataTable tab, string parentid)
        //{
        //    DataTable tab2 = new DataTable();

        //    if (tab != null && tab.Rows.Count > 0)
        //    {
        //        List<Model.T_RepositoryInformation> categorylist = new BLL.T_RepositoryInformation().DataTableToList(tab);
        //        List<Model.TreeModel> modelList = new List<Model.TreeModel>(categorylist.Count);
        //        for (int i = 0; i < categorylist.Count; i++)
        //        {
        //            Model.TreeModel model = new Model.TreeModel();
        //            string currentID = categorylist[i].F_CategoryId.ToString();//当前功能ID
        //            model.id = currentID;
        //            model.IconCls = "";//图标
        //            model.text = categorylist[i].F_CategoryName;
        //            tab2 = new BLL.T_RepositoryInformation().GetList("F_ParentId=" + currentID + " and F_DeleteFlag=0 and F_CategoryType is null order by F_Sort").Tables[0];
        //            if (tab2 != null && tab2.Rows.Count > 0)
        //            {
        //                model.children = BindTree(tab2, currentID);
        //            }
        //            modelList.Add(model);
        //        }
        //        return modelList;

        //    }
        //    else
        //    {
        //        return null;
        //    }

        //}
        //获取知识库
        public ActionResult GetInfo(string infoid)
        {
            ActionResult res = NoToken("未知错误，请重新登录");

            if (infoid != null && infoid.Trim() != "")
            {
                BLL.T_RepositoryInformation dBLL = new BLL.T_RepositoryInformation();
                Model.T_RepositoryInformation dModel = dBLL.GetModel(int.Parse(infoid.Trim()));
                if (dModel != null)
                {
                    DataTable FileUrl = new DataTable();
                    var configfj = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();
                    DataTable dt = new DataTable();
                    //if (!string.IsNullOrEmpty(dModel.F_Expand2)) {
                    //    dt = DbHelperSQL.Query("select * from T_Sys_Accessories where F_FileId in (" + dModel.F_Expand2 + ")").Tables[0];
                    //}
                    //if (configfj != null)
                    //{
                    //    foreach (DataRow dr in dt.Rows)
                    //    {
                    //        FileUrl += configfj.F_ParamValue + dr["F_FileUrl"].ToString() + ",";
                    //    }
                    //}

                    FileUrl = GetFileData(dModel.F_Expand2, configfj.F_ParamValue);
                    var obj = new
                    {
                        F_RepositoryId = dModel.F_RepositoryId,
                        F_CategoryId = dModel.F_CategoryId,
                        F_CustomerId = dModel.F_CustomerId,
                        F_CustomerName = dModel.F_CustomerName,
                        F_ManId = dModel.F_ManId,
                        F_ManName = dModel.F_ManName,
                        F_Title = dModel.F_Title,
                        F_Content = dModel.F_Content,
                        F_Description = dModel.F_Description,
                        F_Comments = dModel.F_Comments,
                        F_Url = dModel.F_Url,
                        F_KeyWords = dModel.F_KeyWords,
                        F_Expand1 = dModel.F_Expand1,
                        F_Expand2 = dModel.F_Expand2,
                        F_IntExpand1 = dModel.F_IntExpand1,
                        F_CreateOn = dModel.F_CreateOn,
                        F_CreateBy = dModel.F_CreateBy,
                        F_CreateName = dModel.F_CreateName,
                        F_ModifyOn = dModel.F_ModifyOn,
                        F_ModifyBy = dModel.F_ModifyBy,
                        F_ModifyName = dModel.F_ModifyName,
                        F_DeleteFlag = dModel.F_DeleteFlag,
                        FileUrls = FileUrl
                    };
                    res = Success("获取知识库信息成功", obj);
                }
                else
                {
                    res = Error("获取知识库信息失败");
                }
            }
            else
            {
                res = Error("获取参数失败");
            }

            return res;
        }

        //[Authority]
        //添加知识库
        public ActionResult AddInfo(string title, string key, string con, string pid,string fileids)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                    Model.T_RepositoryInformation dModel = new Model.T_RepositoryInformation();
                    if (pid.Trim() != "")
                    {
                        Model.T_RepositoryCategory pModel = new BLL.T_RepositoryCategory().GetModel(int.Parse(pid.Trim()));
                        dModel.F_CategoryId = int.Parse(pid.Trim());
                        if (pModel != null)
                            dModel.F_Expand1 = pModel.F_CategoryName;
                    }
                    else
                        dModel.F_CategoryId = 0;

                    dModel.F_Title = title.Trim();
                    dModel.F_KeyWords = key.Trim();
                    dModel.F_Content = WebHelper.UrlDecode(con.Trim());
                    dModel.F_Description = WebHelper.NoHtml(WebHelper.UrlDecode(con.Trim()));
                    dModel.F_Expand2 = fileids.Trim();

                    dModel.F_CreateOn = DateTime.Now;
                    dModel.F_ModifyOn = DateTime.Now;
                    dModel.F_CreateBy = CurrentUser.UserData.F_UserId;
                    dModel.F_DeleteFlag = 0;
                    int b = new BLL.T_RepositoryInformation().Add(dModel);
                    if (b > 0)
                    {
                        res = Success("添加成功");
                    }
                    else
                    {
                        res = Success("添加失败");
                    }

            }
            return res;
        }
        //[Authority]
        //编辑知识库
        public ActionResult EditInfo(string infoid, string title, string key, string con, string pid, string fileids)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                if (infoid != null && infoid.Trim() != "")
                {
                    BLL.T_RepositoryInformation dBLL = new BLL.T_RepositoryInformation();
                    Model.T_RepositoryInformation dModel = dBLL.GetModel(int.Parse(infoid.Trim()));
                    if (dModel != null)
                    {
                        if (pid.Trim() != "")
                        {
                            Model.T_RepositoryCategory pModel = new BLL.T_RepositoryCategory().GetModel(int.Parse(pid.Trim()));
                            dModel.F_CategoryId = int.Parse(pid.Trim());
                            if (pModel != null)
                                dModel.F_Expand1 = pModel.F_CategoryName;
                        }
                        dModel.F_Title = title.Trim();
                        dModel.F_KeyWords = key.Trim();
                        dModel.F_Content = WebHelper.UrlDecode(con.Trim());
                        dModel.F_Description = WebHelper.NoHtml(WebHelper.UrlDecode(con.Trim()));
                        dModel.F_Expand2 = fileids.Trim();

                        dModel.F_ModifyBy = CurrentUser.UserData.F_UserId;
                        dModel.F_ModifyOn = DateTime.Now;
                        bool b = dBLL.Update(dModel);
                        if (b)
                        {
                            res = Success("编辑成功");
                        }
                        else
                        {
                            res = Success("编辑失败");
                        }
                    }
                    else
                        res = Error("获取信息失败");
                }
                else
                {
                    res = Error("请选择要编辑的知识库");
                }

            }
            return res;
        }
        //[Authority]
        //删除知识库
        public ActionResult DelInfos(string[] ids)
        {
            ActionResult res = NoToken("未知错误，请重新登录");

                //string ids = RequestString.GetQueryString("ids");
                if (ids != null && ids.Length > 0)
                {
                    string idd = " ";
                    foreach (string str in ids)
                    {
                        idd += str + ",";
                    }
                    if (new BLL.T_RepositoryInformation().DeleteList(idd.TrimEnd(',')))
                    {
                        res = Success("删除成功");
                    }
                    else
                        res = Error("删除失败");
                }
                else
                {
                    res = Error("获取参数失败");
                }

            return res;
        }

        /// <summary>
        /// 导入excel
        /// </summary>
        /// <returns></returns>
        public ActionResult ImportExcel(string pid)
        {
            int userId = CurrentUser.UserData.F_UserId;
            HttpPostedFile _upFile = RequestString.GetFile("upFile");
            if (_upFile != null)
            {
                int headrow = 0;
                string filepath = "";
                string datepath = DateTime.Now.ToString("yyyyMMddHHMMss");
                string aLastName = _upFile.FileName.Substring(_upFile.FileName.LastIndexOf(".") + 1, (_upFile.FileName.Length - _upFile.FileName.LastIndexOf(".") - 1)); //扩展名
                if (aLastName != "xls" && aLastName != "xlsx")
                {
                    return Error("文件类型错误，请选择Excel文件");
                }
                string newpath = datepath + "_" + _upFile.FileName;
                if (!Directory.Exists(Server.MapPath(this.Request.ApplicationPath + "\\ExcelData")))
                {
                    Directory.CreateDirectory(Server.MapPath(this.Request.ApplicationPath + "\\ExcelData"));
                }
                filepath = this.Request.ApplicationPath + "/ExcelData/" + newpath;
                string PhysicalPath = Server.MapPath(filepath);
                _upFile.SaveAs(PhysicalPath);
                DataTable dt = new DataTable();
                IWorkbook workbook = null;
                using (FileStream file = new FileStream(PhysicalPath, FileMode.Open, FileAccess.Read))
                {
                    if (aLastName == "xlsx") // 2007版本
                    {
                        workbook = new XSSFWorkbook(file);
                    }
                    else if (aLastName == "xls") // 2003版本
                    {
                        workbook = new HSSFWorkbook(file);
                    }
                }
                ISheet sheet = workbook.GetSheetAt(0);
                System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
                //获取sheet的第一行
                IRow headerRow = sheet.GetRow(headrow);
                int cellCount = headerRow.LastCellNum;
                if (cellCount < 1)
                    return Error("文件标题没有数据");
                for (int j = 0; j < cellCount; j++)
                {
                    ICell cell = headerRow.GetCell(j);
                    dt.Columns.Add(cell.ToString());
                }
                BLL.T_RepositoryInformation bll = new BLL.T_RepositoryInformation();
                var pbll = new BLL.T_RepositoryCategory();
                var list = pbll.DataTableToList(pbll.GetList(" F_DeleteFlag=0 ").Tables[0]);
                int count = 0;
                ////客户名称加入来电单位
                for (int i = (sheet.FirstRowNum + headrow + 1); i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i);
                    DataRow dataRow = dt.NewRow();

                    for (int j = row.FirstCellNum; j < cellCount; j++)
                    {
                        if (row.GetCell(j) != null)
                            dataRow[j] = row.GetCell(j).ToString();
                    }
                    dt.Rows.Add(dataRow);
                    if (dt.Rows.Count < 1)
                        return Error("文件内容没有数据");
                    //导入后要插入数据库
                    var model = new Model.T_RepositoryInformation();
                    if (pid.Trim() != "")
                    {
                        //Model.T_RepositoryCategory pModel = new BLL.T_RepositoryCategory().GetModel(int.Parse(pid.Trim()));
                        var pmodel = list.FirstOrDefault(x => x.F_CategoryId == int.Parse(pid.Trim()));
                        model.F_CategoryId = int.Parse(pid.Trim());
                        if (pmodel != null)
                            model.F_Expand1 = pmodel.F_CategoryName;
                    }
                    else
                    {
                        model.F_CategoryId = 0;
                    }
                    model.F_Title = dataRow[0].ToString();
                    model.F_KeyWords = dataRow[1].ToString();
                    model.F_Content = WebHelper.UrlDecode(dataRow[2].ToString());
                    model.F_Description = WebHelper.NoHtml(WebHelper.UrlDecode(dataRow[0].ToString()));
                    model.F_CreateOn = DateTime.Now;
                    model.F_DeleteFlag = 0;
                    model.F_CreateBy = userId;
                    int n = bll.Add(model);
                    if (n > 0)
                    {
                        count++;
                    }
                }
                if (dt == null || dt.Rows.Count == 0)
                    return Error("文件没有数据");
                else
                {
                    var jstr = DataTableToJson(dt);
                    return Success("导入成功 " + count + "条信息", jstr);
                }

            }
            return Error("文件不能为空");
        }

        /// <summary>
        /// 导出excel
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportExcel()
        {
            #region 获取数据
        DataTable dt = new DataTable();
            int userId = CurrentUser.UserData.F_UserId;
            Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
            if (ua != null)
            {
                string pid = HttpUtility.UrlDecode(RequestString.GetQueryString("pid"));
                string keywords = HttpUtility.UrlDecode(RequestString.GetQueryString("keywords"));
                string sql = " and F_DeleteFlag=0";
                if (pid.Trim() != "")
                {
                    sql += " and F_CategoryId=" + pid.Trim();
                }
                if (keywords.Trim() != "")
                {
                    sql += " and (F_Content like '%" + keywords.Trim() + "%' or F_Title like '%"
                        + keywords.Trim() + "%' or F_KeyWords like '%" + keywords.Trim() + "%')";
                }
                string str = "SELECT  F_Expand1 AS '所属分类',F_Title AS '标题',F_KeyWords AS '关键字',F_Content AS '内容' FROM dbo.T_RepositoryInformation where 1=1 " + sql + " ORDER BY F_RepositoryId desc";
                dt = DbHelperSQL.Query(str).Tables[0];
                foreach (DataRow dr in dt.Rows)
                {
                    dr["内容"] = Utils.DropHTML(dr["内容"].ToString());
                }
            }
            #endregion
            NPOIHelper npoi = new NPOIHelper();
            if (npoi.ExportToExcel("知识库", dt) == "")
            {
                return Success("导出成功");
            }
            else
            {
                return Error("导出失败");
            }
        }

        public string DataTableToJson(DataTable dt)
        {
            string JsonString = string.Empty;
            JsonString = JsonConvert.SerializeObject(dt);
            return JsonString;
        }

        #region 上传附件
        public DataTable GetFileData(string ids, string prefix)
        {
            DataTable dt = new DataTable();
            if (!string.IsNullOrEmpty(ids))
            {
                dt = DbHelperSQL.Query("select * from T_Sys_Accessories where F_FileId in (" + ids + ")").Tables[0];
                foreach (DataRow dr in dt.Rows)
                {
                    dr["F_FileUrl"] = prefix + dr["F_FileUrl"].ToString();
                }
            }
            return dt;
        }
        /// <summary>
        /// 上传base64图片
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadBase64(string[] dataurl)
        {

            string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));
            #region 保存文件到本地路径
            DataTable FileUrl = new DataTable();
            var configfj = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();

            //string dataurl = HttpUtility.UrlDecode(RequestString.GetFormString("dataurl"));
            //  string dataurl = RequestString.GetFormString("dataurl");
            List<Model.T_Sys_Accessories> acs = new List<Model.T_Sys_Accessories>();
            if (dataurl != null)
            {
                for (int i = 0; i < dataurl.Length; i++)
                {
                    string path = "/Upload/APP/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";
                    Random Rdm = new Random();
                    string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + i + ".jpg";
                    ImageUpload iu = new ImageUpload();
                    iu.SavePath = path;
                    iu.DataUrl = dataurl[i];
                    //   iu.IsCreateImg = false;

                    if (!string.IsNullOrEmpty(filename))
                    {
                        iu.SaveType = 1;
                        iu.InFileName = filename;
                    }
                    iu.Upload64();

                    if (!string.IsNullOrEmpty(iu.SavePath))
                    {
                        uploadFile upfile = new uploadFile();
                        //通过读取配置文件，获取数据库
                        string _ftp = Configs.GetValue("ftp");
                        string _acc = Configs.GetValue("account");
                        string _pwd = Configs.GetValue("password");
                        upfile.ftpPath = _ftp;
                        upfile.ftpUserID = _acc;
                        upfile.ftpPassword = _pwd;
                        //20180207 原文件同时保存
                        string uploadBeforres = upfile.UploadLocalToFtp(iu.SavePath + filename);
                        int n = iu.Error;
                        if (n == 0)
                        {
                            path = path + iu.OutFileName;
                            Model.T_Sys_Accessories model_T_Sys_Accessories = new Model.T_Sys_Accessories();
                            model_T_Sys_Accessories.F_AddTime = DateTime.Now;//上传时间
                            model_T_Sys_Accessories.F_FileName = filename;//附件名称
                            model_T_Sys_Accessories.F_FileType = ".jpg";//附件类型
                            model_T_Sys_Accessories.F_FileUrl = (filename).Replace('\\', '/');//附件地址
                            model_T_Sys_Accessories.F_Size = iu.FileSize;
                            model_T_Sys_Accessories.F_UserCode = stropenid;//上传人  
                            model_T_Sys_Accessories.F_OriName = filename;
                            int fid = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                            #endregion
                            model_T_Sys_Accessories.F_FileId = fid;//修改为返回对象以便查看图片
                            acs.Add(model_T_Sys_Accessories);
                        }
                        else
                        {
                            string msg = string.Empty;
                            switch (n)
                            {
                                case 1: msg = "请选择要上传的文件"; break;
                                case 2: msg = "上传的文件类型不支持"; break;
                                case 3: msg = "上传的文件过大"; break;
                                case 4: msg = "未知错误"; break;

                            }
                            return Error(msg);
                        }
                    }
                    else
                        return Error("格式修改出错，请重新上传");
                }
                string mag = "";
                if (acs != null)
                {
                    foreach (var it in acs)
                    {
                        if (mag == "")
                        {
                            mag = it.F_FileId + "";
                        }
                        else
                        {
                            mag = mag + "," + it.F_FileId;
                        }
                    }
                }
                if (mag != "")
                {
                    FileUrl = GetFileData(mag, configfj.F_ParamValue);
                }
                var obj = new
                {
                    state = "success",
                    message = "成功",
                    acs,
                    FileUrl,
                };
                return Content(obj.ToJson());



            }

            return Error("请选择要上传的文件");

        }

        /// <summary>
        /// 上传base64图片
        /// </summary>
        /// <returns></returns>
        public ActionResult Upload64()
        {
 
           
            //string dataurl = HttpUtility.UrlDecode(RequestString.GetFormString("dataurl"));
            string dataurl = RequestString.GetFormString("dataurl");
            string filename = DateTime.Now.ToString("yyyyMMddHHmmssfff")+ ".jpg";
            if (!string.IsNullOrEmpty(dataurl))
            {
                string stropenid = HttpUtility.UrlDecode(RequestString.GetFormString("openid"));
                #region 保存文件到本地路径
                string path = "/Upload/APP/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MM") + "/" + DateTime.Now.ToString("dd") + "/";

                ImageUpload iu = new ImageUpload();
                iu.SavePath = path;
                iu.DataUrl = dataurl;
                if (!string.IsNullOrEmpty(filename))
                {
                    iu.SaveType = 1;
                    iu.InFileName = filename;
                }
                iu.Upload64();

                if (!string.IsNullOrEmpty(iu.SavePath))
                {
                    uploadFile upfile = new uploadFile();
                    //通过读取配置文件，获取数据库
                    string _ftp = Configs.GetValue("ftp");
                    string _acc = Configs.GetValue("account");
                    string _pwd = Configs.GetValue("password");
                    upfile.ftpPath = _ftp;
                    upfile.ftpUserID = _acc;
                    upfile.ftpPassword = _pwd;
                    //20180207 原文件同时保存
                    string uploadBeforres = upfile.UploadLocalToFtp(iu.SavePath+ filename);
                    int n = iu.Error;
                    if (n == 0)
                    {
                        path = path + iu.OutFileName;
                        Model.T_Sys_Accessories model_T_Sys_Accessories = new Model.T_Sys_Accessories();
                        model_T_Sys_Accessories.F_AddTime = DateTime.Now;//上传时间
                        model_T_Sys_Accessories.F_FileName = filename;//附件名称
                        model_T_Sys_Accessories.F_FileType = ".jpg";//附件类型
                        model_T_Sys_Accessories.F_FileUrl = (filename).Replace('\\', '/');//附件地址
                        model_T_Sys_Accessories.F_Size = iu.FileSize;
                        model_T_Sys_Accessories.F_UserCode = stropenid;//上传人  
                        model_T_Sys_Accessories.F_OriName = filename;
                        int fid = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                        #endregion
                        if (fid > 0)
                        {
                            //返回附件的ID
                            model_T_Sys_Accessories.F_FileId = fid;//修改为返回对象以便查看图片
                            return Success("文件上传成功", model_T_Sys_Accessories);
                        }
                        else
                            return Success("文件上传成功，日志记录失败");

                    }
                    else
                    {
                        string msg = string.Empty;
                        switch (n)
                        {
                            case 1: msg = "请选择要上传的文件"; break;
                            case 2: msg = "上传的文件类型不支持"; break;
                            case 3: msg = "上传的文件过大"; break;
                            case 4: msg = "未知错误"; break;
                         
                        }
                        return Error(msg);
                    }
                }
                else
                    return Error("格式修改出错，请重新上传");
            }
            else
            {
                return Error("请选择要上传的文件");
            }
        }
           
        
        /// <summary>
        /// 上传附件
        /// </summary>
        /// <returns></returns>
      //  [Authority]
        public ActionResult UpLoadProcess(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file)
        {
            try
            {
                if (file == null) return Error("参数传入失败");
                if (Request.Files.Count == 0) return Error("保存失败");
                string userCode = CurrentUser.UserData.F_UserCode;
                string filePathName = string.Empty;
                #region 保存文件到本地路径
                string path = "/Upload/Files/" + DateTime.Now.ToString("yyyy/MM/dd") + "/";
                string localPath = Server.MapPath(Path.Combine(HttpRuntime.AppDomainAppPath, path));                
                string ex = Path.GetExtension(file.FileName);
                string oriname = Path.GetFileNameWithoutExtension(file.FileName);
                filePathName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + Guid.NewGuid().ToString("N") + ex;
                if (!System.IO.Directory.Exists(localPath))
                {
                    System.IO.Directory.CreateDirectory(localPath);
                }
                string physicalpath = Path.Combine(localPath, filePathName);
                file.SaveAs(physicalpath);
                #endregion
                #region 读取配置的上传路径-原文件和修改过格式的文件均上传至此
                string savedir = Configs.GetValue("saveloc");
                if (!System.IO.Directory.Exists(savedir))
                {
                    System.IO.Directory.CreateDirectory(savedir);
                }
                #endregion
                if (!string.IsNullOrEmpty(physicalpath))
                {
                    #region 上传到ftp
                    uploadFile upfile = new uploadFile();
                    //通过读取配置文件，获取数据库
                    string _ftp = Configs.GetValue("ftp");
                    string _acc = Configs.GetValue("account");
                    string _pwd = Configs.GetValue("password");

                    upfile.ftpPath = _ftp;
                    upfile.ftpUserID = _acc;
                    upfile.ftpPassword = _pwd;
                    //20180207 原文件同时保存
                    string uploadBeforres = upfile.UploadLocalToFtp(physicalpath);
                    #endregion
                    if (uploadBeforres.Equals("上传成功！"))
                    {
                        #region 添加日志
                        Model.T_Sys_Accessories model_T_Sys_Accessories = new Model.T_Sys_Accessories();
                        model_T_Sys_Accessories.F_AddTime = DateTime.Now;//上传时间
                        model_T_Sys_Accessories.F_FileName = filePathName;//附件名称
                        model_T_Sys_Accessories.F_FileType = type;//附件类型
                        model_T_Sys_Accessories.F_FileUrl = (filePathName).Replace('\\', '/');//附件地址
                        model_T_Sys_Accessories.F_Size = size;
                        //     model_T_Sys_Accessories.F_UserCode = userCode;//上传人  
                        model_T_Sys_Accessories.F_OriName = oriname;
                        int fid = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                        #endregion
                        if (fid > 0)
                        {
                            //返回附件的ID
                            model_T_Sys_Accessories.F_FileId = fid;//修改为返回对象以便查看图片
                            return Success("文件上传成功", model_T_Sys_Accessories);
                        }
                        else
                            return Success("文件上传成功，日志记录失败");
                    }
                    else
                        return Error("文件上传失败，请重新上传，失败原因：" + uploadBeforres);
                    #region 添加日志 本地测试
                    //Model.T_Sys_Accessories model_T_Sys_Accessories = new Model.T_Sys_Accessories();
                    //model_T_Sys_Accessories.F_AddTime = DateTime.Now;//上传时间
                    //model_T_Sys_Accessories.F_FileName = filePathName;//附件名称
                    //model_T_Sys_Accessories.F_FileType = type;//附件类型
                    //model_T_Sys_Accessories.F_FileUrl = (filePathName).Replace('\\', '/');//附件地址
                    //model_T_Sys_Accessories.F_Size = size;
                    ////     model_T_Sys_Accessories.F_UserCode = userCode;//上传人  
                    //model_T_Sys_Accessories.F_OriName = oriname;
                    //int fid = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                    //#endregion
                    //if (fid > 0)
                    //{
                    //    //返回附件的ID
                    //    model_T_Sys_Accessories.F_FileId = fid;//修改为返回对象以便查看图片
                    //    return Success("文件上传成功", model_T_Sys_Accessories);
                    //}
                    //else
                    //    return Success("文件上传成功，日志记录失败");
                    #endregion
                }
                else
                    return Error("格式修改出错，请重新上传");
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }



        /// <summary>
        /// 上传视频
        /// </summary>
        /// <returns></returns>
        //  [Authority]
        public ActionResult UpLoadVideo(string type, HttpPostedFileBase file)
        {
            try
            {
                if (file == null) return Error("参数传入失败");
                if (Request.Files.Count == 0) return Error("保存失败");
                //   string userCode = CurrentUser.UserData.F_UserCode;
                Stream stream = file.InputStream;    //将文件转为流 
                int size = file.ContentLength / 1024;
                if (size > 102400)
                {
                   return  Error("视频大于100M,请重新选择");
                }
                string filePathName = string.Empty;
                #region 保存文件到本地路径
                string path = "/Upload/Video/" + DateTime.Now.ToString("yyyy/MM/dd") + "/";
                string localPath = Server.MapPath(Path.Combine(HttpRuntime.AppDomainAppPath, path));
                string ex = Path.GetExtension(file.FileName);
                string oriname = Path.GetFileNameWithoutExtension(file.FileName);
                filePathName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + Guid.NewGuid().ToString("N") + ex;
                if (!System.IO.Directory.Exists(localPath))
                {
                    System.IO.Directory.CreateDirectory(localPath);
                }
                string physicalpath = Path.Combine(localPath, filePathName);
                file.SaveAs(physicalpath);
                #endregion
                #region 读取配置的上传路径-原文件和修改过格式的文件均上传至此
                string savedir = Configs.GetValue("saveloc");
                if (!System.IO.Directory.Exists(savedir))
                {
                    System.IO.Directory.CreateDirectory(savedir);
                }
                #endregion
                if (!string.IsNullOrEmpty(physicalpath))
                {
                    #region 上传到ftp
                    uploadFile upfile = new uploadFile();
                    //通过读取配置文件，获取数据库
                    string _ftp = Configs.GetValue("ftp");
                    string _acc = Configs.GetValue("account");
                    string _pwd = Configs.GetValue("password");

                    upfile.ftpPath = _ftp;
                    upfile.ftpUserID = _acc;
                    upfile.ftpPassword = _pwd;
                    //20180207 原文件同时保存
                    string uploadBeforres = upfile.UploadLocalToFtp(physicalpath);
                    #endregion
                    if (uploadBeforres.Equals("上传成功！"))
                    {
                        #region 添加日志
                        Model.T_Sys_Accessories model_T_Sys_Accessories = new Model.T_Sys_Accessories();
                        model_T_Sys_Accessories.F_AddTime = DateTime.Now;//上传时间
                        model_T_Sys_Accessories.F_FileName = filePathName;//附件名称
                        model_T_Sys_Accessories.F_FileType = type;//附件类型
                        model_T_Sys_Accessories.F_FileUrl = (filePathName).Replace('\\', '/');//附件地址
                        model_T_Sys_Accessories.F_Size = size;
                        //     model_T_Sys_Accessories.F_UserCode = userCode;//上传人  
                        model_T_Sys_Accessories.F_OriName = oriname;
                        int fid = new BLL.T_Sys_Accessories().Add(model_T_Sys_Accessories);
                        #endregion
                        if (fid > 0)
                        {
                            //返回附件的ID
                            model_T_Sys_Accessories.F_FileId = fid;//修改为返回对象以便查看图片
                            return Success("文件上传成功", model_T_Sys_Accessories);
                        }
                        else
                            return Success("文件上传成功，日志记录失败");
                    }
                    else
                        return Error("文件上传失败，请重新上传，失败原因：" + uploadBeforres);
                }
                else
                    return Error("格式修改出错，请重新上传");
            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }
        #endregion
    }
}