using RMYY_CallCenter_Api.DB;
using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace RMYY_CallCenter_Api.Controllers.System
{
    public class KnowledgeController : BaseController
    {
        Bll.T_Sys_Knowledge knbll = new Bll.T_Sys_Knowledge();
        Bll.T_Sys_GongDan gdbll = new Bll.T_Sys_GongDan();


        /// <summary>
        /// 获取知识库列表
        /// </summary>
        /// <param name="keywords"></param>
        /// <param name="typeid"></param>
        /// <param name="pagesize"></param>
        /// <param name="pageindex"></param>
        /// <returns></returns>
        public ActionResult GetList(string keywords, int typeid=0, int pagesize = 10, int pageindex = 1)
        {
            string sql = "and F_IsDel=0";
            DataTable dt = new DataTable();
            if (!string.IsNullOrEmpty(keywords))
                sql += $" and (F_KeyWords like'%" + keywords.Trim() + "%' or F_Title like '%" + keywords.Trim() + "%' or F_Content like '%" + keywords.Trim() + "%')";
            if (typeid != 0)
            {
                if(GetKnType(typeid)!="")
                sql += $" and F_TypeId in (" + GetKnType(typeid) + ")";
            }
            int recordCount = 0;
            dt = Bll.PagerBll.GetListPager
                (
                "T_Sys_Knowledge",
                "F_Id",
                "*",
                sql,
                "ORDER BY F_Id desc",
                pagesize,
                pageindex,
                true,
                out recordCount
                );
            var modelist = knbll.DataTableToList(dt);
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = modelist
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取工单类别
        /// </summary>
        /// <param name="typeid"></param>
        /// <returns></returns>
        public string GetKnType(int typeid)
        {
            string tsql = typeid.ToString();
            string tsql1 = "";
            string tsql2 = "";
            var model = gdbll.GetModel(typeid);
            if (model != null)
            {
                var glist = gdbll.GetModelList("F_ParentID=" + typeid).Select(p => p.F_GDId).ToList();
                if (glist.Count > 0)
                {
                    tsql1 = string.Join(",", glist);
                    if (model.F_TypeId == 1)
                    {
                        var glist1 = gdbll.GetModelList("F_ParentID in (" + tsql1 + ")").Select(p => p.F_GDId).ToList();
                        if (glist1.Count > 0)
                        {
                            tsql2 = string.Join(",", glist1);
                            tsql += "," + tsql1 + "," + tsql2;
                        }
                        else
                        {
                            tsql += "," + tsql1;
                        }
                    }
                    else
                    {
                        tsql += "," + tsql1;
                    }
                }
                return tsql;
            }
            else return "";
        }

        /// <summary>
        /// 获取知识库
        /// </summary>
        /// <param name="kid"></param>
        /// <returns></returns>
        public ActionResult GetModel(int kid)
        {
            if (kid <= 0)
                return Error("获取参数失败");
            var model = knbll.GetModel(kid);
            if (model != null)
                return Success("获取成功", model);
            else return Error("获取知识库信息失败");

        }
            
        //添加知识库
        public ActionResult AddInfo(string title, string key, string con, string tid, string fileids="")
        {


            Model.T_Sys_Knowledge kmodel = new Model.T_Sys_Knowledge();
            if (tid.Trim() != "")
            {
                Model.T_Sys_GongDan tmodel = new Bll.T_Sys_GongDan().GetModel(int.Parse(tid.Trim()));
                kmodel.F_TypeId = int.Parse(tid.Trim());
                if (tmodel != null)
                    kmodel.F_TypeName = tmodel.F_Name;//工单名称
            }
            else
                kmodel.F_TypeId = 0;

            kmodel.F_Title = title.Trim();
            kmodel.F_KeyWords = key.Trim();
            kmodel.F_Content = WebHelper.UrlDecode(con.Trim());
            kmodel.F_Description = WebHelper.NoHtml(WebHelper.UrlDecode(con.Trim()));
            kmodel.F_Files = fileids.Trim();
            kmodel.F_CreateCode = User.F_UserCode;
            kmodel.F_CreateTime = DateTime.Now;
            kmodel.F_CreateName = User.F_UserName;
            kmodel.F_IsDel = 0;
            int b = new Bll.T_Sys_Knowledge().Add(kmodel);
            if (b > 0)
            {
                return Success("添加成功");
            }
            else
            {
                return Success("添加失败");
            }

        }

        //编辑知识库
        public ActionResult EditInfo(int kid,string title, string key, string con, string tid, string fileids="")
        {
            if (kid > 0)
            {
                Model.T_Sys_Knowledge kmodel = knbll.GetModel(kid);
                if (kmodel == null)
                    return Error("获取信息失败！");
                if (tid.Trim() != "")
                {
                    Model.T_Sys_GongDan tmodel = new Bll.T_Sys_GongDan().GetModel(int.Parse(tid.Trim()));
                    kmodel.F_TypeId = int.Parse(tid.Trim());
                    if (tmodel != null)
                        kmodel.F_TypeName = tmodel.F_Name;//工单名称
                }
                kmodel.F_Title = title.Trim();
                kmodel.F_KeyWords = key.Trim();
                kmodel.F_Content = WebHelper.UrlDecode(con.Trim());
                kmodel.F_Description = WebHelper.NoHtml(WebHelper.UrlDecode(con.Trim()));
                kmodel.F_Files = fileids.Trim();
                kmodel.F_ModifyCode = User.F_UserCode;
                kmodel.F_ModifyName = User.F_UserName;
                kmodel.F_ModifyTime = DateTime.Now;
                bool b = new Bll.T_Sys_Knowledge().Update(kmodel);
                if (b)
                {
                    return Success("编辑成功");
                }
                else
                {
                    return Success("编辑失败");
                }
            }
            else
                return Error("请选择要编辑的知识库！");
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelInfos(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idstr = string.Join(",", ids);
                string sql = "update T_Sys_Knowledge set F_IsDel=1 where F_Id in(" + idstr + ")";
                if (DbHelperSQL.ExecuteSql(sql) > 0)
                    return Success("删除成功！");
                else return Error("删除失败！");

            }
            else return Error("获取参数失败！");

        }

        /// <summary>
        /// 获取工单类型树
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTypeTree()
        {
            var tmodel = gdbll.GetModelList("");
            tmodel.Sort((x, y) => x.F_Sort- y.F_Sort);//排序
            var treeList = new List<TreeModel>();
            foreach (var item in tmodel.Where(p => p.F_ParentID == 0).ToList())
            {
                TreeModel treeModel = new TreeModel();
                treeModel.id = item.F_GDId.ToString();
                treeModel.IconCls = item.F_ImgUrl; 
                treeModel.text = item.F_Name;
                treeModel.parentid = item.F_ParentID.ToString();
                treeModel.children = TreeRecursion(tmodel, item.F_GDId.ToString());
                treeList.Add(treeModel);
            }
            //return Content(treeList.ToJson());
            return Success("获取菜单树成功", treeList);
        }

        public List<TreeModel> TreeRecursion(List<Model.T_Sys_GongDan> dt, string parentid="0")
        {
            List<TreeModel> treelist = new List<TreeModel>();
            if (parentid != "0")
            {
                foreach (var item in dt.Where(p => p.F_ParentID == Convert.ToInt32(parentid)).ToList())
                {
                    TreeModel treeModel = new TreeModel();
                    treeModel.id = item.F_GDId.ToString();
                    treeModel.IconCls = item.F_ImgUrl;
                    treeModel.text = item.F_Name;
                    treeModel.parentid = item.F_ParentID.ToString();
                    treeModel.children = TreeRecursion(dt, item.F_GDId.ToString());
                    treelist.Add(treeModel);
                }
            }  
            return treelist;
        }
        /// <summary>
        /// 导入知识库
        /// </summary>
        /// <returns></returns>
        public ActionResult Excelmodelinfo()
        {
            NPOIHelper npoi = new NPOIHelper();
            if (Request.Files.Count <= 0)
                throw new Exception("请选中的Excel文件！");
            var a = Request.Files[0];
            var dtExcel = npoi.ExcelToTable(Request.Files[0], 0);
            foreach (DataRow item in dtExcel.Rows)
            {
                Model.T_Sys_Knowledge kmodel = new Model.T_Sys_Knowledge();
                if (item["知识库类型"].ToString() != "")
                {
                    //根据工单类型名称获取工单类型编号
                    var getmodelbyname = new Bll.T_Sys_GongDan().GetModelbyname(item["知识库类型"].ToString());
                    var tid = getmodelbyname.F_TypeId;
                    Model.T_Sys_GongDan tmodel = new Bll.T_Sys_GongDan().GetModel(Convert.ToInt32(tid));
                    kmodel.F_TypeId = Convert.ToInt32(tid);// int.Parse(item["工单类型"].ToString().Trim());
                     kmodel.F_TypeName = item["知识库类型"].ToString();//工单类型名称
                }
                else
                    kmodel.F_TypeId = 0;

                kmodel.F_Title = item["标题"].ToString();
                kmodel.F_KeyWords = item["关键字"].ToString();
                kmodel.F_Content = item["内容"].ToString();
                kmodel.F_Description = item["描述"].ToString();
                kmodel.F_Files ="";
                kmodel.F_CreateCode = User.F_UserCode;
                kmodel.F_CreateTime = DateTime.Now;
                kmodel.F_CreateName = User.F_UserName;
                kmodel.F_IsDel = 0;
                int b = new Bll.T_Sys_Knowledge().Add(kmodel);
            }
            return Success("导入成功");
        }
    }
}