using CallCenter.Utility;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
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();
        private BLL.T_Sys_RoleInfo rolebll = new BLL.T_Sys_RoleInfo();

        // 获取知识库列表
        public ActionResult GetList(string title, string content,string keywords, string pid,int deptid=0,int deptids=0)
        {
            string issub = RequestString.GetQueryString("issub");
            string ispass = RequestString.GetQueryString("ispass");
            DataTable dt = new DataTable();
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            string sql = "";
            if (!string.IsNullOrEmpty(issub))
            {//是否提交审核 0否，1是
                sql += " and isnull(F_ISSubmitAudit,0)=" + issub;
            }
            //else
            //{
            //    sql += " and isnull(F_ISSubmitAudit,0)=1 ";
            //}
            if (!string.IsNullOrEmpty(ispass))
            {//是否审核通过 -1否，0未审核，1是
                sql += " and isnull(F_ISPass,0)=" + ispass;
            }
            else
            {
                sql += " and F_ISPass !=-1";
            }
            //else
            //{
            //    sql += " and isnull(F_ISPass,0)=0 ";
            //}
            if (title != null && title.Trim() != "")
            {
                sql += " and F_Title like '%" + title.Trim() + "%'";
            }
            if (content != null && content.Trim() != "")
            {
                sql += " and F_Description like '%" + content.Trim() + "%'";
            }
            if (pid != null && pid.Trim() != "")
            {
                sql += " and F_CategoryId=" + pid.Trim();
            }
            if (keywords != null && keywords.Trim() != "")
            {
                sql += " and (F_Description like '%" + keywords.Trim() + "%' or F_Content like '%" + keywords.Trim() + "%' or F_Title like '%"
                                                                                                                                                                                                 + keywords.Trim() + "%' or F_KeyWords like '%" + keywords.Trim() + "%')";
            }

            if (deptid >0)
            {
              sql += "and   F_CreateBy in( select F_UserId from T_Sys_UserAccount where F_DeptId ='" + deptid + "')";
            }
            if (deptids > 0)
            {
                sql += $" and F_DeptId='{deptids}'";
                // sql += "and   F_CreateBy in( select F_UserId from T_Sys_UserAccount where F_DeptId ='" + deptid + "')";
            }
            if (User .F_RoleCode =="WLDW")
            {
                sql += "and   F_CreateBy in( select F_UserId from T_Sys_UserAccount where F_DeptId ='" + User .F_DeptId  + "')";
            }
            if (strpageindex.Trim() != "")
            {                    
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }

            Model.T_Sys_RoleInfo role = rolebll.GetModel("WLDW");
            if ( pid==null&& User.F_RoleId == role.F_RoleId)
            {
                sql += " and F_CategoryId in ( select F_CategoryId from T_RepositoryCategory where F_CategoryName ='知识信息分类')";
            }


            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_RepositoryInformation a",
                "F_RepositoryId",
                "*,(select F_CategoryName   from T_RepositoryCategory  where F_CategoryId =a.F_CategoryId  )as CategoryName" +
                ",dbo.GetDeptName(CONVERT (int ,(select F_DeptId  from T_Sys_UserAccount  where F_UserId = a.F_CreateBy)) ) DeptName,dbo.GetDeptName(F_DeptId) DeptNames ",
                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 User = 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 = "";DateTime ?audittime =null;
                #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)
                    {
                        User = userBLL.GetModel(auM.F_AuditBy.Value);
                        if (User != null)
                        {
                            auditu = User.F_UserName + "(" + User.F_UserCode + ")";
                        }
                        audittime = auM.F_AuditOn;
                    }
                }
                #endregion
                string creatu = "";
                #region 添加人
                if (dModel.F_CreateBy != null)
                {
                    User = userBLL.GetModel(dModel.F_CreateBy.Value);
                    if (User != null)
                    {
                        creatu = User.F_UserName + "(" + User.F_UserCode + ")";
                    }
                }
                #endregion
                string KeyName = ""; int key1 = 0;
                if (dModel.F_Key != null)
                {
                    var keyvalue = new BLL.T_Sys_DictionaryValue().GetModel(dModel.F_Key.Value);
                    if (keyvalue != null)
                    {
                        KeyName = keyvalue.F_Value;
                        if (keyvalue.F_PrentId != null)
                            key1 = keyvalue.F_PrentId.Value;
                    }

                }
                string deptname = "";
                if (dModel.F_DeptId>0)
                {
                    var keyvalue = new BLL.T_Sys_Department ().GetModel(dModel.F_DeptId.Value);
                    if (keyvalue != null)
                    {
                        deptname = keyvalue.F_DeptName ;
                        
                    }

                }
                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,
                    F_KeyWords = dModel.F_KeyWords ,
                    KeyName,
                    DeptName= deptname,
                    F_DeptId = dModel.F_DeptId,
                    key1,
                    F_Key = dModel.F_Key,
                    F_AuditOn = audittime
                };
                return Success("获取知识库信息成功", obj);
            }
            else
            {
                return Error("获取知识库信息失败");
            }

        }

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

            string sql = ""; string sqlLog = "";
            if (!string.IsNullOrEmpty(ispass))
            {
                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 (!string.IsNullOrEmpty(action))
            {
                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 a ",
                "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 and F_Action!=4 " + sqlLog);
            var obj = new
            {
                rows = auditList.Select(x =>
                {
                    var preContent = ""; var afterContent = "";
                    var predis = ""; var afterdis = "";
                    var title = ""; var ptitle = ""; var atitle = "";string deptname = "";
                    string CategoryName = "";
                    
                    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 (logModel.F_DeptId >0)
                            {
                                var dept = new BLL.T_Sys_Department().GetModel(logModel.F_DeptId.Value);
                                if (dept != null)
                                    deptname = dept.F_DeptName;
                            }
                            if (logModel.F_IntExpand1 > 0)
                            {
                                var Category = new BLL.T_RepositoryCategory().GetModel(logModel.F_IntExpand1.Value);
                                if (Category != null)
                                    CategoryName = Category.F_CategoryName ;
                            }

                        }
                    }
                    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 (logModel.F_DeptId > 0)
                            {
                                var dept = new BLL.T_Sys_Department().GetModel(logModel.F_DeptId.Value);
                                if (dept != null)
                                    deptname = dept.F_DeptName;
                            }
                            if (logModel.F_IntExpand1 > 0)
                            {
                                var Category = new BLL.T_RepositoryCategory().GetModel(logModel.F_IntExpand1.Value);
                                if (Category != null)
                                    CategoryName = Category.F_CategoryName;
                            }
                        }
                    }
                    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,
                        DeptName= deptname,
                        CategoryName= CategoryName

                    };
                }),
                total = recordCount
            };

            return Content(obj.ToJson());
        }

        public ActionResult GetDeductLsit(int infoid = 0,int deptid=0)
        {
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string knowledgekey = HttpUtility.UrlDecode(RequestString.GetQueryString("knowledgekey"));
            DataTable dt = new DataTable();
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            string sql = "";
            if (infoid > 0)
            {
                sql += "and F_RepositoryId= '" + infoid + "'";
            }
            if (User.F_RoleCode == "WLDW")
            {
                sql += "and F_Expand1= '" + User.F_DeptId + "'";
            }
            else if (deptid>0)
            {
                sql += "and F_Expand1= '" + deptid + "'";
            }

            sql += "and F_Action= '" + 4 + "'";
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and F_CreateOn >=  '" + strstarttime + "'";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and F_CreateOn <=  '" + strendtime + "'";
            }
            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and F_Title  like '%" + strkey + "%'";
            }
            if (knowledgekey.Trim() != "" && knowledgekey != "undefined")
            {
                sql += " and    F_RepositoryId in (select F_RepositoryId from  T_RepositoryInformation  where  F_Content like '%" + knowledgekey + "%')  ";
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

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

            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
         
        }
        [Authority]
        //扣除分值
        public ActionResult DeductInfo(int infoid = 0, int score = 0, string reason = "")
        {
            if (User.F_RoleCode == "GLY")
            {
                if (infoid <= 0)
                    return Error("请选择知识库");
                if (score > 0)
                    return Error("扣除分值不能大于0");
                if (string.IsNullOrEmpty(reason))
                    return Error("请输入扣分原因");
                Model.T_RepositoryInformation dModel = infoBLL.GetModel(infoid);
                if (dModel.F_Score == null)
                    dModel.F_Score = score;
                else
                    dModel.F_Score = dModel.F_Score + score;
                dModel.F_Reason = reason;
                dModel.F_Description = User.F_UserCode;

                if (infoBLL.Update(dModel))
                {
                    string content = $"{User.F_UserName}({User.F_UserCode })知识库{ dModel.F_Title}扣分{Math.Abs((float)score)}";
                    string Operation = OperationLogController
                        .AddOperationList(content, User.F_UserCode, Common.DTRequest.GetIP(), 3, 4594, dModel.F_RepositoryId );


                    int logid = addLog(dModel, 4);

                    return Success("扣分成功");
                }
                else
                {
                    return Success("扣分失败");
                }
            }
            else
            {
                return Error("权限不足");
            }


        }


        public ActionResult GetExamineScore( int deptid = 0)
        {
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            DataTable dt = new DataTable();
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            string sql = "";
             if (deptid > 0)
            {
                sql += "and F_Deptid= '" + deptid + "'";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and F_CreateTime >=  '" + strstarttime + "'";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and F_CreateTime <=  '" + strendtime + "'";
            }
           
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Sys_ExamineScore  a ",
                "F_ID",
                "*,dbo.GetDeptName(a.F_Deptid) DeptName",
                sql,
                "ORDER BY F_ID desc",
                pagesize,
                pageindex,
                true,
                out recordCount);

            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());

        }

        [Authority]
        //扣除分值
        public ActionResult ExamineScore(string  item,int deptid=0,int score=0,string reason="")
        {
                   if (deptid<=0)
                return Error("请选择部门");
            if (string .IsNullOrEmpty (item))
                    return Error("请选择加减分项");


            string strSql = string.Format(@"INSERT INTO T_Sys_ExamineScore
( [F_Item] ,[F_Score],[F_Reason] ,[F_Deptid],[F_CreateTime],[F_Month]  ,[F_CreateUser]) 
                   values   ('{0}','{1}','{2}','{3}','{4}','{5}','{6}') ;select @@IDENTITY ",
                  item, score, reason, deptid, DateTime .Now , DateTime.Now.ToString ("yyyyMM"), 
                   User .F_UserCode );
            int rows = DbHelperSQL.ExecuteSql (strSql);
            if (rows > 0)
            {
                int logid = 0;
                Model.T_RepositoryLog logModel = new Model.T_RepositoryLog();
                logModel.F_Action = 4;
                logModel.F_Description = item;
                logModel.F_Title = item;
                if (score > 0)
                    logModel.F_Content = User.F_UserCode + "加分" + Math.Abs((float)score) +
                        ",加分原因:" + reason;
                else
                    logModel.F_Content = User.F_UserCode + "扣分" + Math.Abs((float)score) +
                         ",扣分原因:" + reason;
                logModel.F_Expand2 = item;
                var dapt = new BLL.T_Sys_Department().GetModel(deptid);
                if (dapt != null)
                {
                    logModel.F_KeyWords = dapt.F_DeptName;
                    logModel.F_Expand1 = dapt.F_DeptId.ToString();
                }
                logModel.F_CreateBy = User.F_UserId;
                logModel.F_CreateOn = DateTime.Now;
                logid = new BLL.T_RepositoryLog().Add(logModel);
                if (logid >0)
                {
                    string content = "";
                    if (score > 0)
                         content = $"{User.F_UserName}({User.F_UserCode })知识库{ item}加分{Math.Abs((float)score)}";
                    else
                          content = $"{User.F_UserName}({User.F_UserCode })知识库{ item}扣分{Math.Abs((float)score)}";
                    string Operation = OperationLogController
                        .AddOperationList(content, User.F_UserCode, Common.DTRequest.GetIP(), 3, 4594,logid );
                }
                return Success ("添加成功");

            }
            else
                return Error("添加失败");
               
          

        }

        [Authority]
        //添加知识库
        public ActionResult AddInfo(string title, string con, string pid,string key, int deptid = 0, int issub=1, int keyid = 0,int demandsid=0)
        {
            Model.T_RepositoryInformation dModel = new Model.T_RepositoryInformation();
            if (string.IsNullOrEmpty(title))
                return Error("标题不能为空");
            if (string.IsNullOrEmpty(con))
                return Error("内容不能为空");

            dModel.F_Title = title.Trim();
            dModel.F_Content = WebHelper.UrlDecode(con.Trim());
            dModel.F_CategoryId = int.Parse(pid);
            dModel.F_DeptId = deptid;
            
            dModel.F_Description = WebHelper.NoHtml(WebHelper.UrlDecode(con.Trim()));
            if (User.F_RoleCode=="GLY")
            {
                dModel.F_ISPass = 1;
            }
            else 
            dModel.F_ISPass = 0;
            dModel.F_ISSubmitAudit = issub;
            dModel.F_CreateOn = DateTime.Now;
            dModel.F_CreateBy = User.F_UserId;
            dModel.F_KeyWords = key;
            dModel.F_Key = keyid;
            int b = infoBLL.Add(dModel);
            if (b > 0)
            {
                string content=$"{User.F_UserName}({User.F_UserCode })添加知识库{  dModel.F_Title }";
                string Operation = OperationLogController
                    .AddOperationList(content, User.F_UserCode, Common.DTRequest.GetIP(), 0, 4594,b );


                if (demandsid > 0)
                {
                    Model.T_Repository_List_Demands demandsModel = new BLL.T_Repository_List_Demands().GetModel(demandsid);
                    if (demandsModel != null)
                    {
                        demandsModel.F_RepositoryId = b ;
                        demandsModel.F_SubmitTime = DateTime.Now;
                        demandsModel.F_SubmitUser = User.F_UserCode;
                        new BLL.T_Repository_List_Demands().Update(demandsModel);
                    }
                }
                dModel.F_RepositoryId = b;
                int logid = addLog(dModel, 1);
                if (User.F_RoleCode != "GLY")
                {
                    int auditid = addaudit(b, 1, null, logid);
                    new BLL.T_RepositoryInformation().UpdateAuditID(b, auditid);
                   

                }
                else
                {
                    Task.Run(() =>
                    {
                        WebClient web = new WebClient();
                        web.Encoding = Encoding.UTF8;
                        string Dataurl = web.DownloadString(FrontUrl + "Affairs/kinfo_add?id=" + b);

                    }).ContinueWith(p =>
                    {
                        System.Diagnostics.Debug.WriteLine(DateTime.Now);
                    });
                }
                return Success("添加成功");
            }
            else
            {
                return Success("添加失败");
            }

        }
        [Authority]
        //编辑知识库
        public ActionResult EditInfo(string infoid, string title, string con, string pid,string key, int? issub,int deptid=0, int keyid = 0)
        {
            Model.T_RepositoryInformation dModel = infoBLL.GetModel(int.Parse(infoid.Trim()));
            if (dModel != null)
            {
                if (keyid > 0)
                {
                    dModel.F_Key = keyid;
                }
                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;
                }
                if (deptid>0)
                    dModel.F_DeptId  = deptid;
                dModel.F_KeyWords = key;

                    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)
                    {
                        string content = $"{User.F_UserName}({User.F_UserCode })编辑知识库{  dModel.F_Title }";
                        string Operation = OperationLogController
                            .AddOperationList(content, User.F_UserCode, Common.DTRequest.GetIP(), 1, 4594, dModel.F_RepositoryId);

                        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)
                    {
                        if (User .F_RoleCode =="GLY")
                        {
                           if ( infoBLL.Delete(dModel.F_RepositoryId))
                            {
                                string content = $"{User.F_UserName}({User.F_UserCode })删除知识库{  dModel.F_Title }";
                                string Operation = OperationLogController
                                    .AddOperationList(content, User.F_UserCode, Common.DTRequest.GetIP(), 2, 4594, dModel.F_RepositoryId);
                                c++;
                            }

                        }
                        else
                        {
                            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)
                            {
                                string content = $"{User.F_UserName}({User.F_UserCode })删除知识库{  dModel.F_Title }";
                                string Operation = OperationLogController
                                    .AddOperationList(content, User.F_UserCode, Common.DTRequest.GetIP(), 2, 4594, dModel.F_RepositoryId);

                                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 = User.F_UserId;
            auditModel.F_CreateOn = DateTime.Now;
            auditid = new BLL.T_RepositoryAudit().Add(auditModel);
            return auditid;
        }
        string FrontUrl = Configs.GetValue("FrontUrl");      
        //审核
        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 = User.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;
                                infoModel.F_ISPass = ispass;
                                infoModel.F_KeyWords = logModel.F_KeyWords;
                                infoModel.F_DeptId = logModel.F_DeptId;

                                infoModel.F_Key = logModel.F_IntExpand2;
                                string content = $"{User.F_UserName}({User.F_UserCode })审核通过了知识库{  infoModel.F_Title }修改";
                                string Operation = OperationLogController
                                    .AddOperationList(content, User.F_UserCode, Common.DTRequest.GetIP(), 3, 4594,infoModel .F_RepositoryId);
                                return infoBLL.Update(infoModel);
                            }
                            
                            if (auditModel.F_Action == 3)
                            {
                                Model.T_RepositoryInformation infoModel = infoBLL.GetModel(auditModel.F_RepositoryId.Value);
                                string content = $"{User.F_UserName}({User.F_UserCode })审核通过了知识库{  infoModel.F_Title }删除";
                                string Operation = OperationLogController
                                    .AddOperationList(content, User.F_UserCode, Common.DTRequest.GetIP(), 3, 4594, infoModel .F_RepositoryId);
                                return infoBLL.Delete(auditModel.F_RepositoryId.Value);
                            }
                            if (dd)
                            {
                                Task.Run(() =>
                                {
                                    WebClient web = new WebClient();
                                    web.Encoding = Encoding.UTF8;

                                    if (auditModel.F_Action == 1)
                                    {
                                        string Dataurl = web.DownloadString(FrontUrl + "Affairs/kinfo_add?id=" + auditModel.F_RepositoryId.Value);
                                    }
                                    else if (auditModel.F_Action == 2)
                                    {
                                        string Dataurl = web.DownloadString(FrontUrl + "Affairs/kinfo_update?id=" + auditModel.F_RepositoryId.Value);
                                    }
                                    else if (auditModel.F_Action == 3)
                                    {
                                        string Dataurl = web.DownloadString(FrontUrl + "Affairs/kinfo_delete?id=" + auditModel.F_RepositoryId.Value + "&remark=" + auditremark);
                                    }
                                }).ContinueWith(p =>
                                {
                                    System.Diagnostics.Debug.WriteLine(DateTime.Now);
                                });

                            }
                            return dd;
                        }
                        else
                        {
                            if (auditModel.F_Action == 1)
                            {
                                Model.T_RepositoryInformation infoModel = infoBLL.GetModel(auditModel.F_RepositoryId.Value);
                                infoModel.F_ISPass  = ispass;
                                return infoBLL.Update(infoModel);
                            }


                            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_DeptId = rmodel.F_DeptId;
            if (action==4)
            {
                logModel.F_Title = rmodel.F_Title;
                logModel.F_Content = User.F_UserCode +"扣分"+Math .Abs ((float )rmodel.F_Score )+
                    ",扣分原因:"+ rmodel.F_Reason ;
                logModel.F_Expand2  = rmodel.F_Content;
                var demandsModel = new BLL.T_Repository_List_Demands().GetModelList
                     ("F_RepositoryId='" + rmodel.F_RepositoryId + "' and F_IsDelete=0");
                try
                {
                    if (demandsModel != null && demandsModel.Count > 0)
                    {
                        if (demandsModel.LastOrDefault().F_Deptid > 0)
                        {
                            var dapt = new BLL.T_Sys_Department().GetModel((int)demandsModel.LastOrDefault().F_Deptid);
                            if (dapt != null)
                            {
                                logModel.F_KeyWords = dapt.F_DeptName;
                                logModel.F_Expand1 = dapt.F_DeptId.ToString ();
                            }
                               
                        }

                    }
                    else if (rmodel.F_CreateBy!=null&&rmodel.F_CreateBy>0)
                    {
                        var user = new BLL.T_Sys_UserAccount().GetModel(rmodel.F_CreateBy.Value);
                        if (user !=null )
                        {
                            if (user .F_RoleId ==2  )
                            {
                                var dapt = new BLL.T_Sys_Department().GetModel(user.F_DeptId );
                                if (dapt != null)
                                {
                                    logModel.F_KeyWords = dapt.F_DeptName;
                                    logModel.F_Expand1 = dapt.F_DeptId.ToString();
                                }
                            }
                        }
                    }
                }
                catch
                {

                }
               
               
            }
            else
            {
                logModel.F_Title = rmodel.F_Title;
                logModel.F_Content = rmodel.F_Content;
                logModel.F_KeyWords = rmodel.F_KeyWords;
            }
            logModel.F_IntExpand2 = rmodel.F_Key;
            logModel.F_RepositoryId = rmodel.F_RepositoryId;
            logModel.F_Url = rmodel.F_Url;
            logModel.F_CreateBy = User.F_UserId;
            logModel.F_CreateOn = DateTime.Now;
          
            logid = new BLL.T_RepositoryLog().Add(logModel);
            return logid;
        }

    }
}