using CallCenter.Utility;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
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.Web;
using System.Web.Mvc;
using Newtonsoft.Json;

namespace CallCenterApi.Interface.Controllers.knowledge
{
    public class KnowledgeController : BaseController
    {
        // 获取知识库列表
        public ActionResult GetList()
        {
            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() != "")
            {
                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() + "%')";
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_RepositoryInformation",
                "F_RepositoryId",
                "*",
                sql,
                "ORDER BY F_RepositoryId desc",
                pagesize,
                pageindex,
                true,
                out recordCount);

            //System.Collections.Generic.List<Model.T_RepositoryInformation> modelList = new BLL.T_RepositoryInformation().DataTableToList(dt);

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

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

            return Content(obj.ToJson());

        }

        //获取知识库
        public ActionResult GetInfo(string infoid)
        {
            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)
                {
                    return Success("获取知识库信息成功", dModel);
                }
                else
                {
                    return Error("获取知识库信息失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }

        }

        //
        //添加知识库
        public ActionResult AddInfo(string title, string key, string con, string pid)
        {
            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_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)
            {
                return Success("添加成功");
            }
            else
            {
                return Success("添加失败");
            }

        }
        //
        //编辑知识库
        public ActionResult EditInfo(string infoid, string title, string key, string con, string pid)
        {
            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;
                    }
                    if (title.Trim() != "")
                    {
                        dModel.F_Title = title.Trim();
                    }
                    if (key.Trim() != "")
                    {
                        dModel.F_KeyWords = key.Trim();
                    }
                    if (con.Trim() != "")
                    {
                        dModel.F_Content = WebHelper.UrlDecode(con.Trim());
                        dModel.F_Description = WebHelper.NoHtml(WebHelper.UrlDecode(con.Trim()));
                    }

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

        }
        //
        //删除知识库
        public ActionResult DelInfos(string[] ids)
        {
            //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(',')))
                {
                    return Success("删除成功");
                }
                else
                    return Error("删除失败");
            }
            else
            {
                return Error("获取参数失败");
            }

        }

        #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>
        /// 上传附件
        /// </summary>
        /// <returns></returns>

        public ActionResult UpLoadProcess(string id, string name, string type, string lastModifiedDate, int size, HttpPostedFileBase file)
        {
            try
            {
                string userCode = CurrentUser.UserData.F_UserCode;
                string filePathName = string.Empty;
                string path = "/Upload/Files/" + DateTime.Now.ToString("yyyy/MM/dd") + "/";
                string localPath = Server.MapPath(Path.Combine(HttpRuntime.AppDomainAppPath, path));
                if (Request.Files.Count == 0)
                {
                    return Error("保存失败");
                }
                //string ex = Path.GetExtension(file.FileName);
                //filePathName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + Guid.NewGuid().ToString("N") + ex;

                filePathName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + file.FileName;
                if (!System.IO.Directory.Exists(localPath))
                {
                    System.IO.Directory.CreateDirectory(localPath);
                }
                #region
                //int iLen = file.ContentLength;
                //byte[] bData = new byte[iLen];
                //file.InputStream.Read(bData, 0, iLen);

                //FileStream newFile = new FileStream(path + filePathName, FileMode.Create);
                //newFile.Write(bData, 0, bData.Length);
                //newFile.Flush();
                #endregion
                file.SaveAs(Path.Combine(localPath, filePathName));
                #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 = path + filePathName;//附件地址
                model_T_Sys_Accessories.F_Size = size;
                model_T_Sys_Accessories.F_UserCode = userCode;//上传人  
                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("文件失败");

            }
            catch (Exception ex)
            {
                return Error(ex.Message);
            }
        }

        #endregion

        /// <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("文件不能为空");
        }

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