using CallCenter.Utility;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Dto;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.knowledge
{
    public class KnowledgeController : BaseController
    {
        private readonly BLL.T_Sys_UserAccount userAccountBLL = new BLL.T_Sys_UserAccount();
        private readonly BLL.T_Sys_Department deptBLL = new BLL.T_Sys_Department();
        // 获取知识库列表
        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() != "")
            {
                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() + "%')";
            }


            var depts = deptBLL.DataTableToListForLevel(DbHelperSQL.Query($"with cte(F_DeptId,F_DeptName,F_ParentId,F_DeptCode,F_Layer,lvl) as( select F_DeptId,F_DeptName,F_ParentId,F_DeptCode,F_Layer,0 lvl from T_Sys_Department where F_DeptId={CurrentUser.UserData.F_UserId} union all select dept.F_DeptId,dept.F_DeptName,dept.F_ParentId,dept.F_DeptCode,dept.F_Layer,lvl+1 from T_Sys_Department dept inner join cte on dept.F_DeptId = cte.F_ParentId) select F_DeptId,F_ParentId,F_DeptName,F_DeptCode,F_Layer,lvl from  cte ").Tables[0]);
            var deptCompany = depts.Where(x => x.Layer == 1).OrderBy(x => x.Level).FirstOrDefault();

            sql += $" and F_CreateBy in (select F_UserId From T_Sys_UserAccount where F_DeptId in(select F_DeptId from T_Sys_Department where F_DeptCode like '{deptCompany?.DeptCode ?? CurrentUser.UserData.F_DeptCode}%'))";


            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);

            var userList = userAccountBLL.DataTableToList(userAccountBLL.GetList("").Tables[0]);
            List<KnowledegDto> list = new List<KnowledegDto>();
            modelList.ForEach(x =>
            {
                var time = "<span style='color:red;'>已失效</span>";
                if (x.F_CanLastLong > 0)
                {
                    time = "永久有效";
                }
                else
                {
                    if (x.F_StartTime == null || x.F_EndTime == null)
                    {
                        time = "<span style='color:red;'>已失效</span>";
                    }
                    else if (DateTime.Now > x.F_StartTime && DateTime.Now < x.F_EndTime)
                    {
                        time = $"{x.F_StartTime?.ToString("yyyy-MM-dd HH:mm:ss") ?? ""} 至 {x.F_EndTime?.ToString("yyyy-MM-dd HH:mm:ss")}";
                    }
                }

                list.Add(new Models.Dto.KnowledegDto
                {
                    F_RepositoryId = x.F_RepositoryId.ToString(),
                    F_CustomerName = userList.SingleOrDefault(m => m.F_UserId == x.F_CreateBy)?.F_UserName ?? "",
                    F_Title = x.F_Title,
                    F_KeyWords = x.F_KeyWords,
                    F_CreateOn = x.F_CreateOn?.ToString("yyyy-MM-dd HH:mm:ss") ?? "",
                    F_CreateName = userList.SingleOrDefault(m => m.F_UserId == x.F_CreateBy)?.F_UserName ?? "",
                    F_CanLastLong = x.F_CanLastLong.ToString(),
                    F_Time = time
                });
            });
            var obj = new
            {
                rows = list,
                total = recordCount
            };

            res = Content(obj.ToJson());

            return res;
        }

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

            return res;
        }

        //[Authority]
        //添加知识库
        public ActionResult AddInfo(string title, string key, string con, string pid, DateTime? start, DateTime? end, int canlastlong = 1)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                if (canlastlong <= 0)
                {
                    if (start == null || end == null)
                        return Error("非永久有效的知识库必须填写有效时间段");
                }


                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;
                dModel.F_CanLastLong = canlastlong;
                dModel.F_StartTime = start;
                dModel.F_EndTime = end;

                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, DateTime? start, DateTime? end, int canlastlong = 1)
        {
            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;
                        }
                        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;
                        if (canlastlong <= 0)
                        {
                            if (start == null || end == null)
                                return Error("非永久有效的知识库必须填写有效时间段");
                        }
                        dModel.F_CanLastLong = canlastlong;
                        dModel.F_StartTime = start;
                        dModel.F_EndTime = end;
                        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;
        }
    }
}