using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
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 RepositoryController : BaseController
    {
        // 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 = new BLL.T_Sys_UserAccount().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"));
            string strusercode = HttpUtility.UrlDecode(RequestString.GetQueryString("usercode"));
            int deptid = RequestString.GetInt("deptid", 0);

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

            #region sql 语句相关处理

            if (strkey.Trim() != "" && strkey != "undefined")
            {
                sql += " and (F_Key like '%" + strkey + "%' or F_Title like '%" + strkey + "%') ";
            }
            if (strusercode.Trim() != "" && strusercode != "undefined")
            {
                sql += " and F_CreateUser = '" + strusercode + "' ";
            }

            if (deptid != 0)
            {
                sql += " and F_DeptId ='" + 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);

            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 id = RequestString.GetInt("id", 0);
            Model.T_Repository_List dModel = new BLL.T_Repository_List().GetModel(id);

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

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

                foreach (DataRow dr in dt.Rows)
                {
                    dr["F_FileUrl"] = configfj.F_ParamValue + dr["F_FileUrl"].ToString();
                }

                var obj = new
                {
                    data = dModel,
                    file = dt
                };
                return Success("获取信息成功", obj);
            }
            else
            {
                var obj = new
                {
                    data = dModel,
                    file = new DataTable()
                };
                return Success("获取信息成功", obj);
            }
        }

        /// <summary>
        /// 添加知识库
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AddRepository()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);

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

            Model.T_Repository_List dModel = new Model.T_Repository_List();
            if (id == 0)
            {
                dModel.F_DeptId = deptid;
                dModel.F_Key = key;
                dModel.F_Title = title;
                dModel.F_MainDept = maindept;
                dModel.F_PublicPhone1 = publicphone1;
                dModel.F_PublicPhone2 = publicphone2;
                dModel.F_PrivatePhone1 = privatephone1;
                dModel.F_PrivatePhone2 = privatephone2;
                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_IsDelete = 0;
                dModel.F_CreateUser = userModel.F_UserCode;
                dModel.F_CreateTime = DateTime.Now;
                int n = new BLL.T_Repository_List().Add(dModel);
                if (n > 0)
                    return Success("添加成功", n);
                else
                    return Error("添加失败");
            }
            else
            {
                dModel = new BLL.T_Repository_List().GetModel(id);
                if (dModel != null)
                {
                    dModel.F_DeptId = deptid;
                    dModel.F_Key = key;
                    dModel.F_Title = title;
                    dModel.F_MainDept = maindept;
                    dModel.F_PublicPhone1 = publicphone1;
                    dModel.F_PublicPhone2 = publicphone2;
                    dModel.F_PrivatePhone1 = privatephone1;
                    dModel.F_PrivatePhone2 = privatephone2;
                    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;

                    if (new BLL.T_Repository_List().Update(dModel))
                        return Success("修改成功");
                    else
                        return Error("修改失败");
                }
                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);
            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);

            if (ids == null || ids.Length <= 0)
                return Error("请选择要删除的部门");

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

            //if (new BLL.T_Repository_List().DeleteList(idStr))
            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)
            {
                return Success("删除成功");
            }
            return Error("删除失败");
        }

    }
}