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

namespace CallCenterApi.Interface.Controllers.knowledge
{
    [Authority]
    public class KnowledgeController : BaseController
    {
        BLL.T_RepositoryInformation infoBLL = new BLL.T_RepositoryInformation();
        // 获取知识库列表
        public ActionResult GetList(string keywords, string pid, int? issub, int? ispass)
        {
            DataTable dt = new DataTable();
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            string sql = "";
            if (issub != null)
            {//是否提交审核 0否，1是
                sql += " and isnull(F_ISSubmitAudit,0)=" + issub;
            }
            //else
            //{
            //    sql += " and isnull(F_ISSubmitAudit,0)=1 ";
            //}
            if (ispass != null)
            {//是否审核通过 -1否，0未审核，1是
                sql += " and isnull(F_ISPass,0)=" + ispass;
            }
            //else
            //{
            //    sql += " and isnull(F_ISPass,0)=0 ";
            //}
            if (pid != null && pid.Trim() != "")
            {
                sql += " and F_CategoryId=" + pid.Trim();
            }
            if (keywords != null && keywords.Trim() != "")
            {
                sql = "";
                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);

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

            return Content(obj.ToJson());

        }

        //获取知识库
        public ActionResult GetInfo(string infoid)
        {
            Model.T_RepositoryInformation dModel = infoBLL.GetModel(int.Parse(infoid.Trim()));
            BLL.T_Sys_UserAccount userBLL = new BLL.T_Sys_UserAccount();
            Model.T_Sys_UserAccount userModel = new Model.T_Sys_UserAccount();
            if (dModel != null)
            {
                //获取信息更新点击量
                infoBLL.UpdateClick(int.Parse(infoid.Trim()));
                string cname = "";
                #region 类别
                if (dModel.F_CategoryId != null)
                {
                    Model.T_RepositoryCategory cModel = new BLL.T_RepositoryCategory().GetModel(dModel.F_CategoryId.Value);
                    if (cModel != null)
                        cname = cModel.F_CategoryName;
                }
                #endregion
                string auditu = "";
                #region 审核人
                if (dModel.F_AuditID != null)
                {
                    Model.T_RepositoryAudit auM = new BLL.T_RepositoryAudit().GetModel(dModel.F_AuditID.Value);
                    if (auM != null && auM.F_AuditBy != null)
                    {
                        userModel = userBLL.GetModel(auM.F_AuditBy.Value);
                        if (userModel != null)
                        {
                            auditu = userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                        }
                    }
                }
                #endregion
                string creatu = "";
                #region 添加人
                if (dModel.F_CreateBy != null)
                {
                    userModel = userBLL.GetModel(dModel.F_CreateBy.Value);
                    if (userModel != null)
                    {
                        creatu = userModel.F_UserName + "(" + userModel.F_UserCode + ")";
                    }
                }
                #endregion

                var obj = new
                {
                    F_RepositoryId = dModel.F_RepositoryId,
                    F_Title = dModel.F_Title,
                    F_Content = dModel.F_Content,
                    F_Description = dModel.F_Description,
                    F_ISSubmitAudit = dModel.F_ISSubmitAudit,
                    F_CreateOn = dModel.F_CreateOn,
                    F_Category = cname,
                    F_CategoryId = dModel.F_CategoryId,
                    F_CreateBy = creatu,
                    F_AuditBy = auditu,
                };
                return Success("获取知识库信息成功", obj);
            }
            else
            {
                return Error("获取知识库信息失败");
            }

        }

        //获取审核列表
        public ActionResult GetAuditList(int? action, int? ispass)
        {
            DataTable dt = new DataTable();
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            string sql = ""; string sqlLog = "";
            if (ispass != null)
            {
                sql += " and isnull(F_ISPass,0)=" + ispass;
                if (ispass == 0)
                    sql += " and F_RepositoryId in (select F_RepositoryId from T_RepositoryInformation where F_ISSubmitAudit=1)";
            }
            //else
            //{
            //    sql += " and isnull(F_ISPass,0)=0 ";
            //}
            if (action != null)
            {
                sql += " and F_Action=" + action;
                sqlLog += " and F_Action=" + action;
            }

            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_RepositoryAudit",
                "F_AuditId",
                "*",
                sql,
                "ORDER BY F_AuditId desc",
                pagesize,
                pageindex,
                true,
                out recordCount);
            List<Model.T_RepositoryAudit> auditList = new BLL.T_RepositoryAudit().DataTableToList(dt);
            List<Model.T_RepositoryLog> logList = new BLL.T_RepositoryLog().GetModelList(" 1=1 " + sqlLog);
            var obj = new
            {
                rows = auditList.Select(x =>
                {
                    var preContent = ""; var afterContent = "";
                    var predis = ""; var afterdis = "";
                    var title = ""; var ptitle = ""; var atitle = "";
                    if (x.F_PreLogID != null)
                    {
                        Model.T_RepositoryLog logModel = logList.Where(y => y.F_LogId == x.F_PreLogID.Value).FirstOrDefault();
                        if (logModel != null)
                        {
                            preContent = logModel.F_Content;
                            predis = logModel.F_Description;
                            ptitle = logModel.F_Title;
                        }
                    }
                    if (x.F_AfterLogID != null)
                    {
                        Model.T_RepositoryLog logModel = logList.Where(y => y.F_LogId == x.F_AfterLogID.Value).FirstOrDefault();
                        if (logModel != null)
                        {
                            afterContent = logModel.F_Content;
                            afterdis = logModel.F_Description;
                            atitle = logModel.F_Title;
                        }
                    }
                    if (ptitle != "")
                    { title = ptitle; }
                    else { title = atitle; }
                    return new
                    {
                        F_AuditId = x.F_AuditId,
                        F_Action = x.F_Action,
                        F_Title = title,
                        F_PreContent = preContent,
                        F_PreDescription = predis,
                        F_AfterContent = afterContent,
                        F_AfterDescription = afterdis,
                        F_ISPass = x.F_ISPass,
                        F_AuditRemark = x.F_AuditRemark,
                    };
                }),
                total = recordCount
            };

            return Content(obj.ToJson());
        }

        [Authority]
        //添加知识库
        public ActionResult AddInfo(string title, string con, string pid, int issub)
        {
            Model.T_RepositoryInformation dModel = new Model.T_RepositoryInformation();


            dModel.F_Title = title.Trim();
            dModel.F_Content = WebHelper.UrlDecode(con.Trim());
            dModel.F_CategoryId = int.Parse(pid);
            dModel.F_Description = WebHelper.NoHtml(WebHelper.UrlDecode(con.Trim()));
            dModel.F_ISPass = 0;
            dModel.F_ISSubmitAudit = issub;
            dModel.F_CreateOn = DateTime.Now;
            dModel.F_CreateBy = int.Parse(User.UserData["F_UserID"]);

            int b = infoBLL.Add(dModel);
            if (b > 0)
            {
                dModel.F_RepositoryId = b;
                int logid = addLog(dModel, 1);
                int auditid = addaudit(b, 1, null, logid);
                new BLL.T_RepositoryInformation().UpdateAuditID(b, auditid);
                return Success("添加成功");
            }
            else
            {
                return Success("添加失败");
            }

        }
        [Authority]
        //编辑知识库
        public ActionResult EditInfo(string infoid, string title, string con, string pid, int? issub)
        {
            Model.T_RepositoryInformation dModel = infoBLL.GetModel(int.Parse(infoid.Trim()));
            if (dModel != null)
            {
                if (title.Trim() != "")
                {
                    dModel.F_Title = title.Trim();
                }
                if (con.Trim() != "")
                {
                    dModel.F_Content = WebHelper.UrlDecode(con.Trim());
                    dModel.F_Description = WebHelper.NoHtml(WebHelper.UrlDecode(con.Trim()));
                }
                if (pid != null)
                {
                    dModel.F_CategoryId = int.Parse(pid);
                }
                if (issub != null)
                {
                    dModel.F_ISSubmitAudit = issub;
                }

                Model.T_RepositoryAudit audModel = new Model.T_RepositoryAudit();
                if (dModel.F_AuditID != null)
                    audModel = new BLL.T_RepositoryAudit().GetModel(dModel.F_AuditID.Value);

                int logid = addLog(dModel, 2);
                if (logid > 0)
                {
                    int auditid = addaudit(int.Parse(infoid.Trim()), 2, audModel.F_AfterLogID, logid);
                    new BLL.T_RepositoryInformation().UpdateAuditID(int.Parse(infoid.Trim()), auditid);
                    infoBLL.UpdateSubAudit(int.Parse(infoid.Trim()), 1);
                    return Success("保存成功");
                }
                else
                {
                    return Success("保存失败");
                }
            }
            else
            {
                return Error("请选择要编辑的知识库");
            }
        }
        [Authority]
        //删除知识库
        public ActionResult DelInfos(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                int c = 0;
                foreach (string str in ids)
                {
                    Model.T_RepositoryInformation dModel = infoBLL.GetModel(int.Parse(str.Trim()));
                    if (dModel != null)
                    {
                        Model.T_RepositoryAudit audModel = new Model.T_RepositoryAudit();
                        if (dModel.F_AuditID != null)
                            audModel = new BLL.T_RepositoryAudit().GetModel(dModel.F_AuditID.Value);

                        int logid = addLog(dModel, 3);
                        if (logid > 0)
                        {
                            int auditid = addaudit(int.Parse(str.Trim()), 3, audModel.F_AfterLogID, logid);
                            infoBLL.UpdateSubAudit(int.Parse(str.Trim()), 1);
                            infoBLL.UpdateAuditID(int.Parse(str.Trim()), auditid);
                            c++;
                        }
                    }
                }
                if (c == ids.Length)
                    return Success("已提交审核");
                else if (c < ids.Length && c > 0)
                    return Success("部分审核完成，请查看未审核的内容！");
                else
                    return Error("审核失败！");
            }
            else
            {
                return Error("获取参数失败");
            }
        }
        [Authority]
        //审核
        public ActionResult AuditR(int[] ids, string auditremark, int ispass)
        {
            int c = 0;
            foreach (int str in ids)
            {
                if (audit(str, auditremark, ispass))
                    c++;
            }
            if (c >= ids.Length)
                return Success("审核完成！");
            else if (c < ids.Length && c > 0)
                return Success("部分审核完成，请查看未审核的内容！");
            else
                return Error("审核失败！");
        }
        [Authority]
        //提交审核
        public ActionResult SubAudit(int[] ids)
        {
            int c = 0;
            foreach (int str in ids)
            {
                if (infoBLL.UpdateSubAudit(str, 1))
                    c++;
            }
            if (c >= ids.Length)
                return Success("提交成功！");
            else if (c < ids.Length && c > 0)
                return Success("部分提交完成，请查看未提交的内容！");
            else
                return Error("提交失败！");

        }


        //添加审核
        private int addaudit(int rid, int action, int? preid, int? afterid)
        {
            int auditid = 0;
            Model.T_RepositoryAudit auditModel = new Model.T_RepositoryAudit();
            auditModel.F_Action = action;
            auditModel.F_RepositoryId = rid;
            if (preid != null)
            {
                auditModel.F_PreLogID = preid;
            }
            if (afterid != null)
            {
                auditModel.F_AfterLogID = afterid;
            }
            auditModel.F_ISPass = 0;
            auditModel.F_CreateBy = int.Parse(User.UserData["F_UserID"]);
            auditModel.F_CreateOn = DateTime.Now;
            auditid = new BLL.T_RepositoryAudit().Add(auditModel);
            return auditid;
        }
        //审核
        private bool audit(int? auditid, string auditremark, int ispass)
        {
            BLL.T_RepositoryAudit auditBLL = new BLL.T_RepositoryAudit();
            if (auditid != null)
            {
                Model.T_RepositoryAudit auditModel = auditBLL.GetModel(auditid.Value);
                if (auditModel != null)
                {
                    auditModel.F_AuditBy = int.Parse(User.UserData["F_UserID"]);
                    auditModel.F_AuditOn = DateTime.Now;
                    auditModel.F_AuditRemark = auditremark;
                    auditModel.F_ISPass = ispass;
                    bool r = auditBLL.Update(auditModel);
                    if (r)
                    {
                        if (ispass == 1)
                        {
                            bool dd = infoBLL.UpdateAudit(auditModel.F_RepositoryId.Value, 1);
                            if (auditModel.F_Action == 2)
                            {
                                Model.T_RepositoryLog logModel = new BLL.T_RepositoryLog().GetModel(auditModel.F_AfterLogID.Value);
                                Model.T_RepositoryInformation infoModel = infoBLL.GetModel(auditModel.F_RepositoryId.Value);
                                infoModel.F_Title = logModel.F_Title;
                                infoModel.F_CategoryId = logModel.F_IntExpand1;
                                infoModel.F_Description = logModel.F_Description;
                                infoModel.F_Content = logModel.F_Content;
                                return infoBLL.Update(infoModel);
                            }
                            if (auditModel.F_Action == 3)
                            {
                                return infoBLL.Delete(auditModel.F_RepositoryId.Value);
                            }
                            return dd;
                        }
                        else
                        {
                            return r;
                        }
                    }
                }
            }
            return false;
        }
        //添加日志
        private int addLog(Model.T_RepositoryInformation rmodel, int action)
        {
            int logid = 0;
            Model.T_RepositoryLog logModel = new Model.T_RepositoryLog();
            logModel.F_Action = action;
            logModel.F_Description = rmodel.F_Description;
            logModel.F_IntExpand1 = rmodel.F_CategoryId;
            logModel.F_Content = rmodel.F_Content;
            logModel.F_KeyWords = rmodel.F_KeyWords;
            logModel.F_RepositoryId = rmodel.F_RepositoryId;
            logModel.F_Title = rmodel.F_Title;
            logModel.F_Url = rmodel.F_Url;

            logModel.F_CreateBy = int.Parse(User.UserData["F_UserID"]);
            logModel.F_CreateOn = DateTime.Now;

            logid = new BLL.T_RepositoryLog().Add(logModel);
            return logid;
        }

    }
}