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

namespace CallCenterApi.Interface.Controllers
{
    public class ChatController : BaseController
    {
        // GET: Chat

        /// <summary>
        /// 获取微信openid
        /// </summary>
        /// <param name="login"></param>
        /// <returns></returns>
        public ActionResult GetOpenId(WxLoginDto wld)
        {
            wld.RedirectUrl = RequestString.GetUrlReferrer();

            if (string.IsNullOrEmpty(wld.OpenId))
            {
                var temp = WxHelper.GetUserInfo(wld);
                if (string.IsNullOrWhiteSpace(temp.OpenId))
                {
                    return Redirect("请求", temp.RedirectUrl);
                }
                wld.OpenId = temp.OpenId;
                wld.UserInfo = temp.UserInfo;
            }
            var model = new BLL.T_Chat_User().GetModelList(" F_OpenId='" + wld.OpenId + "'").FirstOrDefault();
            if (model == null)
            {
                model = new Model.T_Chat_User();
                model.F_OpenId = wld.OpenId;
                model.F_Account = wld.OpenId;
                model.F_Name = wld.UserInfo.nickname;
                model.F_HeadImgUrl = wld.UserInfo.headimgurl;
                model.F_Type = 2;
                model.F_State = 0;
                model.F_IsDelete = 0;
                model.F_CreateTime = DateTime.Now;
                new BLL.T_Chat_User().Add(model);
            }

            return Success("成功", wld.OpenId);
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetUserList(int isdc = 0)
        {
            DataTable dt = new DataTable();
            string sql = " and F_IsDelete=0 ";
            string strcode = HttpUtility.UrlDecode(RequestString.GetQueryString("code"));
            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));

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


            if (strcode.Trim() != "" && strcode != "undefined")
            {
                sql += " and F_MainUserCode = '" + strcode.Trim() + "' ";
            }
            if (strname.Trim() != "" && strname != "undefined")
            {
                sql += " and F_Name like '%" + strname + "%' ";
            }


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

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

            string cols = "*,dbo.GetUserName(F_MainUserCode) as UserName";

            if (isdc > 0)
            {
                var dtdc = DbHelperSQL.Query(" select " + cols + " from T_Chat_User 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_Chat_User",
                "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>
        /// <returns></returns>
        [Authority]
        public ActionResult GetMessageList(int isdc = 0)
        {
            DataTable dt = new DataTable();
            string sql = " and F_IsDelete=0 ";
            string strcususer = HttpUtility.UrlDecode(RequestString.GetQueryString("cususer"));
            string strseruser = HttpUtility.UrlDecode(RequestString.GetQueryString("seruser"));

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


            if (strcususer.Trim() != "" && strcususer != "undefined")
            {
                sql += " and (F_FromUser = '" + strcususer.Trim() + "' or F_ToUser = '" + strcususer.Trim() + "' )";
            }
            if (strseruser.Trim() != "" && strseruser != "undefined")
            {
                sql += " and (F_FromUser = '" + strseruser.Trim() + "' or F_ToUser = '" + strseruser.Trim() + "' )";
            }


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

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

            string cols = "*";

            if (isdc > 0)
            {
                var dtdc = DbHelperSQL.Query(" select " + cols + " from T_Chat_Message 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_Chat_Message",
                "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>
        /// 获取IP列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetIPList(int isdc = 0)
        {
            DataTable dt = new DataTable();
            string sql = " and F_IsDelete=0 ";
            string strcode = HttpUtility.UrlDecode(RequestString.GetQueryString("code"));
            string strip = HttpUtility.UrlDecode(RequestString.GetQueryString("ip"));
            int type = RequestString.GetInt("type",0);

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

            if (strcode.Trim() != "" && strcode != "undefined")
            {
                sql += " and F_OpenId like '%" + strcode.Trim() + "%' ";
            }
            if (strip.Trim() != "" && strip != "undefined")
            {
                sql += " and F_IP like '%" + strip.Trim() + "%' ";
            }
            if (type != 0)
            {
                sql += " and F_Type = '" + type + "' ";
            }


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

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

            string cols = "*";

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

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Chat_IPList",
                "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>
        /// <returns></returns>
        [Authority]
        public ActionResult GetInOutList(int isdc = 0)
        {
            DataTable dt = new DataTable();
            string sql = " and F_IsDelete=0 ";
            string strcode = HttpUtility.UrlDecode(RequestString.GetQueryString("code"));
            string strip = HttpUtility.UrlDecode(RequestString.GetQueryString("ip"));
            int type = RequestString.GetInt("type", 0);

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


            if (strcode.Trim() != "" && strcode != "undefined")
            {
                sql += " and F_OpenId like '%" + strcode.Trim() + "%' ";
            }
            if (strip.Trim() != "" && strip != "undefined")
            {
                sql += " and F_IP like '%" + strip.Trim() + "%' ";
            }
            if (type != 0)
            {
                sql += " and F_Type = '" + type + "' ";
            }


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

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

            string cols = "*";

            if (isdc > 0)
            {
                var dtdc = DbHelperSQL.Query(" select " + cols + " from T_Chat_InOut 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_Chat_InOut",
                "F_Id",
                cols,
                sql,
                "ORDER BY F_InTime DESC",
                pagesize,
                pageindex,
                true,
                out recordCount);

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

        }

        /// <summary>
        /// 获取黑名单IP列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetBlackIPList(int isdc = 0)
        {
            DataTable dt = new DataTable();
            string sql = " and F_IsDelete=0 ";
            string strip = HttpUtility.UrlDecode(RequestString.GetQueryString("ip"));

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

            if (strip.Trim() != "" && strip != "undefined")
            {
                sql += " and F_IP like '%" + strip + "%' ";
            }


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

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

            string cols = "*,dbo.GetUserName(F_CreateUser) as UserName";

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

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Chat_IPBlackList",
                "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>
        /// 获取黑名单IP
        /// </summary>
        /// <param name="areaId"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult GetBlackIP()
        {
            int id = RequestString.GetInt("id", 0);
            Model.T_Chat_IPBlackList dModel = new BLL.T_Chat_IPBlackList().GetModel(id);
            return Success("成功", dModel);
        }

        /// <summary>
        /// 添加/编辑黑名单IP
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        [Authority]
        public ActionResult AddBlackIP()
        {
            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);
            string ip = RequestString.GetFormString("ip");
            string remark = RequestString.GetFormString("remark");
            string starttime = RequestString.GetFormString("starttime");
            string endtime = RequestString.GetFormString("endtime");

            Model.T_Chat_IPBlackList dModel = new Model.T_Chat_IPBlackList();
            if (id == 0)
            {
                var list = new BLL.T_Chat_IPBlackList().GetModelList(" F_IP='" + ip + "' and  F_IsDelete=0 ");
                if (list.Count > 0)
                {
                    return Error("已经存在此IP");
                }
                else
                {
                    dModel.F_IP = ip;
                    dModel.F_Remark = remark;
                    
                    if (!string.IsNullOrEmpty(starttime))
                    {
                        dModel.F_StartTime =  DateTime.Parse(starttime);
                    }
                    if (!string.IsNullOrEmpty(endtime))
                    {
                        dModel.F_EndTime = DateTime.Parse(endtime);
                    }
                    dModel.F_State = 1;
                    dModel.F_IsDelete = 0;
                    dModel.F_CreateUser = userModel.F_UserCode;
                    dModel.F_CreateTime = DateTime.Now;
                    int n = new BLL.T_Chat_IPBlackList().Add(dModel);
                    if (n > 0)
                        return Success("添加成功", n);
                    else
                        return Error("添加失败");
                }
            }
            else
            {
                dModel = new BLL.T_Chat_IPBlackList().GetModel(id);
                if (dModel != null)
                {
                    var list = new BLL.T_Chat_IPBlackList().GetModelList(" F_IP='" + ip + "' and  F_IsDelete=0 and F_Id!='" + id + "' ");
                    if (list.Count > 0)
                    {
                        return Error("已经存在此IP");
                    }
                    else
                    {
                        dModel.F_IP = ip;
                        dModel.F_Remark = remark;

                        if (!string.IsNullOrEmpty(starttime))
                        {
                            dModel.F_StartTime = DateTime.Parse(starttime);
                        }
                        if (!string.IsNullOrEmpty(endtime))
                        {
                            dModel.F_EndTime = DateTime.Parse(endtime);
                        }

                        if (new BLL.T_Chat_IPBlackList().Update(dModel))
                            return Success("修改成功");
                        else
                            return Error("修改失败");
                    }
                }
                else
                {
                    return Error("修改失败");
                }
            }
        }

        /// <summary>
        /// 删除黑名单IP
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [Authority]
        public ActionResult DelBlackIP(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("请选择要删除的黑名单IP");
            }

            var idStr = string.Join(",", ids);
            if (string.IsNullOrEmpty(idStr.Trim()))
            {
                return Error("请选择要删除的黑名单IP");
            }
            int n = DbHelperSQL.ExecuteSql(" update T_Chat_IPBlackList set F_IsDelete=1,F_DeleteUser='" + userModel.F_UserCode + "',F_DeleteTime=getdate() where F_Id in (" + idStr + ")");
            if (n > 0)
            {
                return Success("删除成功");
            }
            return Error("删除失败");
        }
    }
}