using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Common;
using CallCenterApi.Model;
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 RepositoryController : BaseController
    {
        private information.InternalMessagesController msg = new information.InternalMessagesController();
        BLL.T_Repository_List_log repLogBLL = new BLL.T_Repository_List_log();
        BLL.T_Repository_List_Audit repAudBLL = new BLL.T_Repository_List_Audit();
        BLL.T_Repository_List repBLL = new BLL.T_Repository_List();
        BLL.T_Repository_List_Demands demandsBLL = new BLL.T_Repository_List_Demands();
        BLL.T_Repository_Operation oprBLL = new BLL.T_Repository_Operation();
        BLL.T_Sys_UserAccount userBLL = new BLL.T_Sys_UserAccount();
        BLL.T_Sys_Department deptBLL = new BLL.T_Sys_Department();
        // GET: Repository
        /// <summary>
        /// 获取知识库列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList(int isdc = 0)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);

            DataTable dt = new DataTable();
            string sql = " and F_IsDelete=0 ";
            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
         

            int deptid = RequestString.GetInt("deptid", 0);
          
           
            int type = RequestString.GetInt("type", 0);
            int state = RequestString.GetInt("state", 0);

            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            #region sql 语句相关处理
                if (type == 1)
                {//查看通过审核和紧急事项
                    sql += " and F_State in (" + (int)Model.EnumRepositoryState.AuditPass + "," + (int)Model.EnumRepositoryState.Urgent + ")";
                }
                else if(type==2)
                {//待审核列表
                    sql += " and F_State in (" + (int)Model.EnumRepositoryState.Audit + ")";
                }
                else
                {//个人草稿箱
                    sql += " and F_State in (" + (int)Model.EnumRepositoryState.Draft + "," + (int)Model.EnumRepositoryState.AuditFailed + "," + (int)Model.EnumRepositoryState.Invalid + ") and F_CreateUser = '" + userModel.F_UserCode + "'";
                }

            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_Key like '%" + strkey + "%' or F_Title like '%" + strkey + "%') ";
            }
            if (state != 0)
            {
                sql += " and F_State =" + state + " ";
            }
            if (deptid != 0)
            {
                sql += " and F_DeptId ='" + deptid + "'";
            }
            else
            {
                if (userModel.F_RoleCode == "GLY" || userModel.F_RoleCode == "ZXLD" || userModel.F_RoleCode == "ZXHWY")
                {
                }
                else
                {
                    sql += " and F_DeptId  in  (select  F_DeptId from  T_Sys_Department" +
                         " where F_State=0 and  (F_DeptId='" + userModel.F_DeptId + "'or   F_PartentId='" + userModel.F_DeptId + "'))";
                }
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,F_CreateTime,'" + strendtime + "')>=0   ";
            }
            #endregion

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

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            string cols = "*,dbo.GetUserName(F_CreateUser) as UserName,dbo.GetDeptName(F_DeptId) as DeptName";

            if (isdc > 0)
            {
                var dtdc = DbHelperSQL.Query(" select " + cols + " from T_Repository_List where 1=1 " + sql).Tables[0];
                var msg = new NPOIHelper().ExportToExcel("知识库列表", dtdc);
                if (msg == "")
                {
                    return Success("导出成功");
                }
                else
                {
                    return Error("导出失败");
                }
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Repository_List",
                "F_Id",
                cols,
                sql,
                "ORDER BY F_CreateTime DESC",
                pagesize,
                pageindex,
                true,
                out recordCount);
            dt.Columns.Add("Buttons", typeof(object));//操作按钮
            foreach (DataRow dr in dt.Rows)
            {
                var buttons = ButtonGroup.GetZSKButtons(dr["F_State"].ToString(), userModel.F_RoleCode.ToUpper(), dr["F_CreateUser"].ToString(), userModel.F_UserCode);
                dr["Buttons"] = buttons;
            }

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());

        }

        /// <summary>
        /// 获取知识库
        /// </summary>
        /// <param name="areaId"></param>
        /// <returns></returns>
        public ActionResult GetRepository()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            if (userId == 0)
                return Error("人员信息失效");
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            if (userModel == null)
                return Error("人员信息失效!");
            int id = RequestString.GetInt("id", 0);
            Model.T_Repository_List dModel = new BLL.T_Repository_List().GetModel(id);

            if (dModel != null)
            {
                DataTable dtfile = new DataTable();
                if (!string.IsNullOrEmpty(dModel.F_File))
                {
                    var configfj = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();

                    dtfile = DbHelperSQL.Query("select * from T_Sys_Accessories where F_FileId in (" + dModel.F_File + ")").Tables[0];

                    foreach (DataRow dr in dtfile.Rows)
                    {
                        dr["F_FileUrl"] = configfj.F_ParamValue + dr["F_FileUrl"].ToString();
                    }
                }
                //详情页可处理操作
                var buttons = ButtonGroup.GetZSKButtons(dModel.F_State.ToString(), userModel.F_RoleCode.ToUpper(), dModel.F_CreateUser, userModel.F_UserCode);

                var audlist = repAudBLL.GetModelList(" F_RepositoryId=" + dModel.F_Id);

                var wjjlist = oprBLL.GetModelList(" F_OptType="+ (int)Model.EnumRepositoryOptType.unsolved + " and F_RepositoryId=" + dModel.F_Id+ " order by F_OptOn desc");
                var newwjjlist = wjjlist.Select(x => new {
                    x.F_OptOn,
                    x.F_Reason
                });

                var obj = new
                {
                    data = dModel,
                    shData = audlist,
                    file = dtfile,
                    button= buttons,
                    wjjlist= newwjjlist
                };
                return Success("获取信息成功", obj);
            }
            return Error("获取信息失败");
        }

        /// <summary>
        /// 保存知识库
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveRepository()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            if (userId == 0)
                return Error("人员信息失效");
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            if (userModel == null)
                return Error("人员信息失效!");
            #region 获取参数
            int id = RequestString.GetInt("id", 0);
            int deptid = RequestString.GetInt("deptid", 0);
            string key = RequestString.GetFormString("key");
            string title = RequestString.GetFormString("title");
            string maindept = RequestString.GetFormString("maindept");
            string publicphone1 = RequestString.GetFormString("publicphone1");
            string publicphone2 = RequestString.GetFormString("publicphone2");
            string privatephone1 = RequestString.GetFormString("privatephone1");
            string privatephone2 = RequestString.GetFormString("privatephone2");
            string points = RequestString.GetFormString("points");
            string baseanswer = RequestString.GetFormString("baseanswer");
            string endanswer = RequestString.GetFormString("endanswer");
            string dealtype = RequestString.GetFormString("dealtype");
            string legallimittime = RequestString.GetFormString("legallimittime");
            string promiselimittime = RequestString.GetFormString("promiselimittime");
            int ispay = RequestString.GetInt("ispay", 0);
            float paymoney = RequestString.GetFloat("paymoney", 0);
            string officeaddress = RequestString.GetFormString("officeaddress");
            string serobject = RequestString.GetFormString("serobject");
            string busline = RequestString.GetFormString("busline");
            string officetime = RequestString.GetFormString("officetime");
            string otherdept = RequestString.GetFormString("otherdept");
            string otherpublicphone = RequestString.GetFormString("otherpublicphone");
            string otherprivatephone = RequestString.GetFormString("otherprivatephone");
            string remark = RequestString.GetFormString("remark");
            string baseon = WebHelper.UrlDecode(RequestString.GetFormString("baseon"));
            string process = WebHelper.UrlDecode(RequestString.GetFormString("process"));
            string material = WebHelper.UrlDecode(RequestString.GetFormString("material"));
            string template = WebHelper.UrlDecode(RequestString.GetFormString("template"));
            string payinfo = WebHelper.UrlDecode(RequestString.GetFormString("payinfo"));
            string files = RequestString.GetFormString("files");
            int issubmit = RequestString.GetInt("issubmit", 0);
            int isurgent = RequestString.GetInt("isurgent", 0);
            int demandsid = RequestString.GetInt("demandsid", 0);
            #endregion
            Model.T_Repository_List dModel = null;
            Model.T_Repository_Operation optModel = new Model.T_Repository_Operation();
            if (id > 0)
            {
                dModel = new BLL.T_Repository_List().GetModel(id);
            }
            if (dModel == null)
            {
                dModel = new Model.T_Repository_List();
                dModel.F_IsDelete = 0;
                dModel.F_CreateUser = userModel.F_UserCode;
                dModel.F_CreateTime = DateTime.Now;
            }
            #region 信息获取
            dModel.F_DeptId = deptid;
            dModel.F_Key = key;//关键字
            dModel.F_Title = title; //标题
            dModel.F_MainDept = maindept;//主办单位
            dModel.F_PublicPhone1 = publicphone1;//公开电话1
            dModel.F_PublicPhone2 = publicphone2;//公开电话2
            dModel.F_PrivatePhone1 = privatephone1;//内部电话1
            dModel.F_PrivatePhone2 = privatephone2;//内部电话2
            dModel.F_Points = points;//询问要点
            dModel.F_BaseAnswer = baseanswer;//标准话术
            dModel.F_EndAnswer = endanswer;//参考答案
            dModel.F_DealType = dealtype;//办理方式
            dModel.F_LegalLimitTime = legallimittime;//法定办结时限
            dModel.F_PromiseLimitTime = promiselimittime;//承诺办结时限
            dModel.F_IsPay = ispay;//是否收费
            dModel.F_PayMoney = Decimal.Parse(paymoney.ToString());//收费标准
            dModel.F_OfficeAddress = officeaddress;//办公地点
            dModel.F_Object = serobject;//办理对象
            dModel.F_BusLine = busline;//乘车路线
            dModel.F_OfficeTime = officetime;//办公时间
            dModel.F_OtherDept = otherdept;//协办单位
            dModel.F_OtherPublicPhone = otherpublicphone;//协办单位公开电话
            dModel.F_OtherPrivatePhone = otherprivatephone;//协办单位内部电话
            dModel.F_Remark = remark;//备注
            dModel.F_BaseOn = baseon;//设定依据
            dModel.F_Process = process;//办理流程
            dModel.F_Material = material;//办理材料
            dModel.F_Template = template;//办理结果样本
            dModel.F_PayInfo = payinfo;//收费标准及依据
            dModel.F_File = files;
            dModel.F_IsUrgent = isurgent;
            #endregion
            dModel.F_State = (int)Model.EnumRepositoryState.Draft;
            if (issubmit == 1)
                dModel.F_State = (int)Model.EnumRepositoryState.AuditPass;
            #region 
            //20191224 zhengbingbing 取消审核 提交后默认审核通过
            //dModel.F_State = (int)Model.EnumRepositoryState.Audit;
            #endregion
            if (isurgent == 1)
                dModel.F_State = (int)Model.EnumRepositoryState.Urgent;
            bool res = false;
            var optid = 0; int type = 0; var cont = "";
            int audid = 0; string typename = ""; int logid = 0;
            if (id > 0)
            {
                res = new BLL.T_Repository_List().Update(dModel);
                optid = dModel.F_Id;
                type = (int)Model.EnumRepositoryOptType.update; typename = "修改";
            }
            else
            {
                int n = new BLL.T_Repository_List().Add(dModel);
                res = n > 0;
                optid = dModel.F_Id = n;
                type = (int)Model.EnumRepositoryOptType.add; typename = "添加";
                #region 保存索要记录信息
                if (demandsid > 0)
                {
                    Model.T_Repository_List_Demands demandsModel = demandsBLL.GetModel(demandsid);
                    if(demandsModel!=null)
                    {
                        demandsModel.F_RepositoryId = n;
                        demandsModel.F_SubmitTime = DateTime.Now;
                        demandsModel.F_SubmitUser = userModel.F_UserCode;
                        demandsBLL.Update(demandsModel);
                    }
                }
                #endregion
            }
            if (res)
            {
                #region 日志
                if (issubmit == 1)
                {
                    type = (int)Model.EnumRepositoryOptType.submit;
                    typename += "并提交";
                }
                if (isurgent == 1)
                    typename += "紧急事项";
                logid = addlog(dModel, type, userModel.F_UserCode);//添加知识库日志
                //if (issubmit == 1)
                //{
                //    var beflist = repLogBLL.GetModelList(" F_RepositoryId=" + dModel.F_Id + " order by F_CreateOn desc ");
                //    int befid = beflist.Count > 0 ? beflist.FirstOrDefault().F_LogId : 0;
                //    typename += "并提交";
                //    audid = addaud(optid, befid, logid, type, userModel.F_UserCode);//添加审核
                //    dModel.F_AuditID = audid;
                //    repBLL.Update(dModel);
                //}
                cont = userModel.F_UserName + "(" + userModel.F_UserCode + ")" + typename + "信息";
                //添加操作日志
                addoptlog(optid, type, null, audid, dModel.F_State, cont, userModel.F_UserCode, "");
                #endregion
                return Success("保存成功");
            }
            else
                return Error("保存失败");
        }

        /// <summary>
        /// 删除知识库
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelRepository(string[] ids)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            if(userId==0)
                return Error("人员信息失效");
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            if(userModel==null)
                return Error("人员信息失效!");
            if (ids == null || ids.Length <= 0)
                return Error("请选择要删除的条目");

            var idStr = string.Join(",", ids);
            if (string.IsNullOrEmpty(idStr.Trim()))
                return Error("请选择要删除的条目");
            //int n = DbHelperSQL.ExecuteSql(" update T_Repository_List set F_IsDelete=1,F_DeleteUser='" + userModel.F_UserCode + "',F_DeleteTime=getdate() where F_Id in (" + idStr + ")");
            //if (n > 0)
            if (repBLL.DeleteList(idStr, userModel.F_UserCode))
            {
                foreach (var item in ids)
                {
                    var model = repBLL.GetModel(int.Parse(item));
                    if(model!=null)
                    {
                        var logid=addlog(model, (int)Model.EnumRepositoryOptType.delete, userModel.F_UserCode);
                        string cont = userModel.F_UserName + "(" + userModel.F_UserCode + ")删除了信息";
                        addoptlog(model.F_Id, (int)Model.EnumRepositoryOptType.delete, logid, null, model.F_State, cont, userModel.F_UserCode, "");
                    }
                }
                return Success("删除成功");
            }
            return Error("删除失败");
        }

        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="repid"></param>
        /// <param name="remark"></param>
        /// <param name="ispass"></param>
        /// <returns></returns>
        public ActionResult Audit(int repid,string remark,int ispass=0)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            if (userId == 0)
                return Error("人员信息失效");
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            if (userModel == null)
                return Error("人员信息失效!");
            if (repid <= 0)
                return Error("参数传输错误!");
            var repModel = repBLL.GetModel(repid);
            if (repModel == null)
                return Error("获取参数信息失败");
            if(repModel.F_AuditID==null)
                return Error("无审核信息");
            var audModel = repAudBLL.GetModel(repModel.F_AuditID.Value);
            if (audModel == null)
                return Error("无审核信息!");
            audModel.F_AuditBy = userModel.F_UserCode;
            audModel.F_AuditOn = DateTime.Now;
            audModel.F_AuditRemark = remark;
            audModel.F_ISPass = ispass;
            var res=repAudBLL.Update(audModel);
            if (res)
            {
                string cont = userModel.F_UserName + "(" + userModel.F_UserCode + ")审核了信息";
                #region 设置审核状态
                if (ispass ==1)
                {
                    repModel.F_State = (int)Model.EnumRepositoryState.AuditPass;
                    cont += ",审核通过";
                }
                else if (ispass == 2)
                {
                    repModel.F_State = (int)Model.EnumRepositoryState.AuditFailed;
                    cont += ",审核不通过，原因：" + remark;
                }
                repBLL.Update(repModel);
                #endregion
                addoptlog(repid, (int)Model.EnumRepositoryOptType.audit, null, audModel.F_AuditId, repModel.F_State, cont, userModel.F_UserCode, remark);
                return Success("操作成功");
            }
            else
                return Error("操作失败");
        }
        /// <summary>
        /// 操作知识库
        /// </summary>
        /// <param name="repid"></param>
        /// <param name="type">0查看，1解决，2未解决，3提交审核</param>
        /// <returns></returns>
        public ActionResult OptRep(int repid,string reason, int type=0)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            if (userId == 0)
                return Error("人员信息失效");
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            if (userModel == null)
                return Error("人员信息失效!");
            if (repid <= 0)
                return Error("参数传输错误!");
            var repModel = repBLL.GetModel(repid);
            if (repModel == null)
                return Error("获取参数信息失败");
            int opttype = (int)Model.EnumRepositoryOptType.look; string typename = "查看";
            switch (type)
            {
                case 1:
                    opttype = (int)Model.EnumRepositoryOptType.solved;
                    typename = "解决";
                    repModel.F_ValidCount += 1;
                    break;
                case 2:
                    opttype = (int)Model.EnumRepositoryOptType.unsolved;
                    typename = "未解决";
                    repModel.F_InValidCount += 1;
                    repModel.F_State = (int)Model.EnumRepositoryState.Invalid;//调整为1次未解决需要重新编辑
                    break;
                case 3:
                    opttype = (int)Model.EnumRepositoryOptType.submit;
                    typename = "提交";
                    repModel.F_InValidCount = 0;
                    repModel.F_State = (int)Model.EnumRepositoryState.AuditPass;
                    break;
                default:
                    break;
            }
            string cont = userModel.F_UserName + "(" + userModel.F_UserCode + ")对信息操作" + typename;
            int? logid = 0; var audid = 0;
            if (type>0)
            {
                //var configfj = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='InValidCount' ").FirstOrDefault();
                //var invalcount = configfj!=null && configfj.F_ParamValue != "" ? int.Parse(configfj.F_ParamValue) : 3;
                //if (repModel.F_InValidCount >= invalcount)//操作未解决超过几次后设置知识库无效
                //    repModel.F_State = (int)Model.EnumRepositoryState.Invalid;
                //if (opttype == (int)Model.EnumRepositoryOptType.submit)
                //    repModel.F_State = (int)Model.EnumRepositoryState.AuditPass;//.Audit; 提交默认审核通过
                var res=repBLL.Update(repModel);
                if (res)
                {
                    logid = addlog(repModel, opttype, userModel.F_UserCode);
                    //if (opttype == (int)Model.EnumRepositoryOptType.submit)
                    //{//提交审核需添加审核信息
                    //    var beflist = repLogBLL.GetModelList(" F_RepositoryId=" + repModel.F_Id + " order by F_CreateOn desc ");
                    //    int befid = beflist.Count > 0 ? beflist.FirstOrDefault().F_LogId : 0;
                    //    audid = addaud(repModel.F_Id, befid, logid, type, userModel.F_UserCode);//添加审核
                    //    repModel.F_AuditID = audid;
                    //    repBLL.Update(repModel);
                    //}
                }
            }
            addoptlog(repid, opttype, logid, audid, repModel.F_State, cont, userModel.F_UserCode,reason);
            return Success(typename + "操作成功");
        }

        #region 20191218 zhengbingbing 增加索要流程 只允许话务主管索要
        //获取知识库索要记录列表
        public ActionResult GetListDemands(string key, int? level, string stime, string etime, int deptid = 0)
        {
            string sql = " and F_IsDelete=0 ";
            DataTable dt = new DataTable();
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            if (userId == 0)
                return Error("人员信息失效");
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            if (userModel == null)
                return Error("人员信息失效!");
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            if (userModel.F_RoleCode == "ZXBZ")
                sql += " and F_CreateUser='" + userModel.F_UserCode + "'";
            if (userModel.F_RoleCode != "GLY" && userModel.F_RoleCode != "ZXBZ")
            {
                sql += " and F_Deptid='" + userModel.F_DeptId + "'";
            }
            else
            {
                if (deptid > 0)
                    sql += " and F_Deptid='" + deptid + "'";
            }
            if (key != null && key.Trim() != "")
                sql += " and F_Descript like '%" + key.Trim() + "%' ";
            if (stime != null && stime.Trim() != "")
                sql += " and F_CreateTime > '" + Convert.ToDateTime(stime.Trim()) + "' ";
            if (etime != null && etime.Trim() != "")
                sql += " and F_CreateTime < '" + Convert.ToDateTime(etime.Trim()) + "' ";
            if (level != null)
                sql += " and F_Level=" + level;

            if (strpageindex.Trim() != "")
                pageindex = Convert.ToInt32(strpageindex);
            if (strpagesize.Trim() != "")
                pagesize = Convert.ToInt32(strpagesize);

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Repository_List_Demands",
                "F_DemandsId",
                "*,dbo.GetDeptName(F_Deptid) F_DeptName,dbo.GetUserName(F_CreateUser) as F_CreateUserName,dbo.GetUserName(F_SubmitUser) as F_SubmitUserName",
                sql,
                "ORDER BY F_CreateTime desc",
                pagesize,
                pageindex,
                true,
                out recordCount);
            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }

        //获取知识库索要记录
        public ActionResult GetModel_Demands(string demandsid)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            if (userModel == null)
                return Error("人员信息失效!");
            if (demandsid == null || demandsid.Trim() == "")
                return Error("参数错误");
            Model.T_Repository_List_Demands dModel = demandsBLL.GetModel(int.Parse(demandsid.Trim()));
            if (dModel != null)
            {
                var createusername = "";
                var createmodel = userBLL.GetModel(dModel.F_CreateUser);
                createusername = createmodel != null ? createmodel.F_UserName : "";
                var submitusername = "";
                if(dModel.F_SubmitUser!=null && dModel.F_SubmitUser!="")
                {
                    var submodel = userBLL.GetModel(dModel.F_SubmitUser);
                    submitusername = submodel != null ? submodel.F_UserName : "";
                }
                var deptname = "";
                if (dModel.F_Deptid != null)
                {
                    var deptmodel = deptBLL.GetModel(dModel.F_Deptid.Value);
                    deptname = deptmodel != null ? deptmodel.F_DeptName : "";
                }

                DataTable dtfile = new DataTable();
                if (!string.IsNullOrEmpty(dModel.F_File))
                {
                    var configfj = new BLL.T_Sys_SystemConfig().GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();

                    dtfile = DbHelperSQL.Query("select * from T_Sys_Accessories where F_FileId in (" + dModel.F_File + ")").Tables[0];

                    foreach (DataRow dr in dtfile.Rows)
                    {
                        dr["F_FileUrl"] = configfj.F_ParamValue + dr["F_FileUrl"].ToString();
                    }
                }
                var obj = new
                {
                    model = dModel,
                    deptname,
                    createusername,
                    submitusername,
                    file = dtfile
                };

                return Success("获取记录成功", obj);
            }
            else
                return Error("获取记录失败");
        }

        //添加知识库索要记录
        public ActionResult AddDemands(int deptid,string des,DateTime limittime,string file,int demandsid=0, int level=0)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            if (userModel == null)
                return Error("人员信息失效!");
            if (deptid <= 0)
                return Error("请选择部门");
            Model.T_Repository_List_Demands dModel = null;
            if (demandsid > 0)
                dModel = demandsBLL.GetModel(demandsid);
            if(dModel==null)
            {
                dModel = new Model.T_Repository_List_Demands();
                dModel.F_IsDelete = 0;
                dModel.F_CreateUser = userModel.F_UserCode;
                dModel.F_CreateTime = DateTime.Now;
            }
            dModel.F_Deptid = deptid;
            dModel.F_Descript = des;
            dModel.F_File = file;
            dModel.F_LimitTime = limittime;
            dModel.F_Level = level;

            bool res = false;
            var optid = 0; int type = 0;
            string typename = ""; var cont = "";
            if (demandsid > 0)
            {
                res=demandsBLL.Update(dModel);
                optid = dModel.F_DemandsId;
                type = (int)Model.EnumRepositoryOptType.updatedemands; typename = "修改索要";
            }
            else
            {
                int n = demandsBLL.Add(dModel);
                res = n > 0;
                optid = dModel.F_DemandsId = n;
                type = (int)Model.EnumRepositoryOptType.adddemands; typename = "添加索要";
                if (res)
                {
                    //var msgss = "有坐席向您索要关于“"+ des+"”的内容，截止至"+ limittime.ToString("yyyy-MM-dd HH:mm:ss")+"，请尽快处理";
                    var msgss = des + "|" + limittime.ToString("yyyy-MM-dd HH:mm:ss");
                    var users = userBLL.GetModelList(" F_DeptId='" + deptid + "' ");

                    foreach (var u in users)
                    {
                        msg.AddInternalMessagesInfo("知识库消息", msgss, u.F_UserCode, userModel.F_UserCode,(int)EnumSmsType.knowledge, level);
                    }
                }
            }
            if (res)
            {
                #region 日志
                cont = userModel.F_UserName + "(" + userModel.F_UserCode + ")" + typename + "信息";
                //添加操作日志
                addoptlog(optid, type, null, null, null, cont, userModel.F_UserCode, "");
                #endregion
                return Success("保存成功");
            }
            else
                return Error("保存失败");
        }

        //删除知识库索要记录记录
        public ActionResult DelDemands(string[] ids)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            if (userId == 0)
                return Error("人员信息失效");
            Model.T_Sys_UserAccount userModel = userBLL.GetModel(userId);
            if (userModel == null)
                return Error("人员信息失效!");
            if (ids == null || ids.Length <= 0)
                return Error("请选择要删除的记录");

            var idStr = string.Join(",", ids);
            if (string.IsNullOrEmpty(idStr.Trim()))
                return Error("请选择要删除的记录");

            if (demandsBLL.DeleteList(idStr, userModel.F_UserCode))
            {
                foreach (var item in ids)
                {
                    var model = demandsBLL.GetModel(int.Parse(item));
                    if (model != null)
                    {
                        string cont = userModel.F_UserName + "(" + userModel.F_UserCode + ")删除了索要信息";
                        addoptlog(model.F_DemandsId, (int)Model.EnumRepositoryOptType.deletedemands, null, null, null, cont, userModel.F_UserCode,"");
                    }
                }
                return Success("删除成功");
            }
            return Error("删除失败");

        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 添加审核
        /// </summary>
        /// <param name="repid"></param>
        /// <param name="preid"></param>
        /// <param name="afterid"></param>
        /// <param name="action"></param>
        /// <param name="usercode"></param>
        /// <returns></returns>
        private int addaud(int repid, int? preid, int? afterid, int action, string usercode)
        {
            Model.T_Repository_List_Audit audModel = new Model.T_Repository_List_Audit();
            audModel.F_RepositoryId = repid;
            audModel.F_PreLogID = preid;
            audModel.F_AfterLogID = afterid;
            audModel.F_Action = action;
            audModel.F_CreateBy = usercode;
            audModel.F_CreateOn = DateTime.Now;
            audModel.F_ISPass = 0;
            return repAudBLL.Add(audModel);
        }
        /// <summary>
        /// 记录详情
        /// </summary>
        /// <param name="dModel"></param>
        /// <param name="action"></param>
        /// <param name="usercode"></param>
        /// <returns></returns>
        private int addlog(Model.T_Repository_List dModel, int action, string usercode)
        {
            if (dModel != null)
            {
                Model.T_Repository_List_log logmodel = new Model.T_Repository_List_log();
                #region 保存信息
                logmodel.F_RepositoryId = dModel.F_Id;
                logmodel.F_DeptId = dModel.F_DeptId;
                logmodel.F_Key = dModel.F_Key;
                logmodel.F_Title = dModel.F_Title;
                logmodel.F_MainDept = dModel.F_MainDept;
                logmodel.F_PublicPhone1 = dModel.F_PublicPhone1;
                logmodel.F_PublicPhone2 = dModel.F_PublicPhone2;
                logmodel.F_PrivatePhone1 = dModel.F_PrivatePhone1;
                logmodel.F_PrivatePhone2 = dModel.F_PrivatePhone2;
                logmodel.F_Points = dModel.F_Points;
                logmodel.F_BaseAnswer = dModel.F_BaseAnswer;
                logmodel.F_EndAnswer = dModel.F_EndAnswer;
                logmodel.F_DealType = dModel.F_DealType;
                logmodel.F_LegalLimitTime = dModel.F_LegalLimitTime;
                logmodel.F_PromiseLimitTime = dModel.F_PromiseLimitTime;
                logmodel.F_IsPay = dModel.F_IsPay;
                logmodel.F_PayMoney = dModel.F_PayMoney;
                logmodel.F_OfficeAddress = dModel.F_OfficeAddress;
                logmodel.F_Object = dModel.F_Object;
                logmodel.F_BusLine = dModel.F_BusLine;
                logmodel.F_OfficeTime = dModel.F_OfficeTime;
                logmodel.F_OtherDept = dModel.F_OtherDept;
                logmodel.F_OtherPublicPhone = dModel.F_OtherPublicPhone;
                logmodel.F_OtherPrivatePhone = dModel.F_OtherPrivatePhone;
                logmodel.F_Remark = dModel.F_Remark;
                logmodel.F_BaseOn = dModel.F_BaseOn;
                logmodel.F_Process = dModel.F_Process;
                logmodel.F_Material = dModel.F_Material;
                logmodel.F_Template = dModel.F_Template;
                logmodel.F_PayInfo = dModel.F_PayInfo;
                logmodel.F_File = dModel.F_File;
                logmodel.F_State = dModel.F_State;
                logmodel.F_IsUrgent = dModel.F_IsUrgent;

                logmodel.F_Action = action;
                logmodel.F_CreateBy = usercode;
                logmodel.F_CreateOn = DateTime.Now;
                #endregion
                var id = new BLL.T_Repository_List_log().Add(logmodel);
                return id;
            }
            else
                return 0;
        }
        /// <summary>
        /// 操作日志
        /// </summary>
        /// <param name="repid"></param>
        /// <param name="opttype"></param>
        /// <param name="logid"></param>
        /// <param name="audid"></param>
        /// <param name="state"></param>
        /// <param name="cont"></param>
        /// <param name="optby"></param>
        private void addoptlog(int repid, int opttype, int? logid, int? audid, int? state, string cont, string optby,string reason)
        {
            Model.T_Repository_Operation optModel = new Model.T_Repository_Operation();
            optModel.F_RepositoryId = repid;
            optModel.F_OptType = opttype;
            optModel.F_State = state;
            optModel.F_LogId = logid;
            optModel.F_AuditId = audid;
            optModel.F_OptContent = cont;
            optModel.F_OptBy = optby;
            optModel.F_OptOn = DateTime.Now;
            optModel.F_Reason = reason;
            new BLL.T_Repository_Operation().Add(optModel);
        }
        #endregion
    }
}