using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Interface.Models.Input;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers
{

    public class UserAccountController : BaseController
    {
        private BLL.T_Sys_UserAccount sysUserAccountBll = new BLL.T_Sys_UserAccount();
        private BLL.T_Sys_Department departmentBLL = new BLL.T_Sys_Department();
        private BLL.T_Sys_DictionaryValue dicValueBLL = new BLL.T_Sys_DictionaryValue();

        //用户列表
        [Authority]
        public ActionResult GetList()
        {
            DataTable dt = new DataTable();
            string sql = " ";
            try
            {
                string Key = RequestString.GetQueryString("Key");
                int Id = RequestString.GetInt("Id", 0);
                string strpageindex = RequestString.GetQueryString("page");
                int pageindex = 1;
                string strpagesize = RequestString.GetQueryString("pagesize");
                int pagesize = 10;

                if (Id > 0)
                {
                    sql += " and F_DeptId=" + Id;
                }
                if (!string.IsNullOrWhiteSpace(Key))
                {
                    sql = "";
                    string str = string.Format(" and (F_UserCode like '%{0}%' or F_UserName like '%{1}%')", Key, Key);
                    sql += str;
                }
                if (strpageindex.Trim() != "")
                {
                    pageindex = Convert.ToInt32(strpageindex);
                }

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

                int recordCount = 0;
                dt = BLL.PagerBLL.GetListPager(
                                        "T_Sys_UserAccount",
                                        "F_UserId",
                                        "*",
                                        sql,
                                        "ORDER BY F_UserId desc",
                                        pagesize,
                                        pageindex,
                                        true,
                                        out recordCount);

                List<Model.UserAccount> modelList = new BLL.UserAccount().DataTableToList(dt);
                var obj = new
                {
                    rows = modelList.Select(x => new
                    {
                        F_UserId = x.F_UserId,
                        F_UserCode = x.F_UserCode,
                        F_ExtensionNumber = x.F_ExtensionNumber,
                        F_UserName = x.F_UserName,
                        F_GroupName = x.F_GroupName,
                        F_DeptId = x.F_DeptId,
                        F_RoleId = x.F_RoleId,
                        F_GroupId = x.F_GroupId,
                        F_SeatFlag = x.F_SeatFlag,
                        F_SeatRight = x.F_SeatRight,
                        F_SeatLevel = x.F_SeatLevel,
                        F_SexFlag = x.F_SexFlag,
                        F_RemindFlag = x.F_RemindFlag,
                        F_Remark = x.F_Remark,
                        F_Telephone = x.F_Telephone,
                        F_Mobile = x.F_Mobile,
                        F_HomePhone = x.F_HomePhone,
                        F_Birthday = x.F_Birthday,
                        F_CreateOn = x.F_CreateOn,
                        F_CancelOn = x.F_CancelOn,
                        F_DeleteFlag = x.F_DeleteFlag,
                        F_APPOnFlag = x.F_APPOnFlag,
                        F_LastActiveTime = x.F_LastActiveTime,
                        F_See = x.F_See,
                        F_HJType = x.F_HJType,
                        F_PId = x.F_PId,
                        F_TmId = x.F_TmId,
                        F_RoleName = x.F_RoleName,
                        F_DeptName = x.F_DeptName,
                        F_WorkNumber = x.F_WorkNumber
                    }),
                    total = recordCount
                };

                return Content(obj.ToJson());
            }
            catch (Exception err)
            {
                return Error("错误：" + err.ToString());
            }
            finally
            {
                dt.Clear();
                dt.Dispose();
            }
        }


        //获取用户信息
        [Authority]
        public ActionResult GetUser(int userId = 0, string userCode = "")
        {
            string sql = "";
            if (userId > 0)
            {
                sql += " and F_UserId=" + userId;
            }
            if (!string.IsNullOrWhiteSpace(userCode))
            {
                sql += " and F_UserCode='" + userCode+"'";
            }
            if (string.IsNullOrWhiteSpace(sql))
                return Error("获取失败");

            Model.T_Sys_UserAccount userModel = sysUserAccountBll.GetModelList(" 1=1 " + sql).FirstOrDefault();
            if (userModel == null) return Error("获取失败");
            var depModel = departmentBLL.GetModel(userModel.F_DeptId);
            var zxzModel = dicValueBLL.GetModel(userModel.F_GroupId ?? 0);
            return Success("获取成功", new
            {
                F_UserId = userModel.F_UserId,
                F_UserCode = userModel.F_UserCode,
                F_ExtensionNumber = userModel.F_ExtensionNumber,
                F_UserName = userModel.F_UserName,
                F_DeptId = userModel.F_DeptId,
                F_RoleId = userModel.F_RoleId,
                F_GroupId = userModel.F_GroupId,
                F_SeatFlag = userModel.F_SeatFlag,
                F_SeatRight = userModel.F_SeatRight,
                F_SeatLevel = userModel.F_SeatLevel,
                F_SexFlag = userModel.F_SexFlag,
                F_RemindFlag = userModel.F_RemindFlag,
                F_Remark = userModel.F_Remark,
                F_Telephone = userModel.F_Telephone,
                F_Mobile = userModel.F_Mobile,
                F_HomePhone = userModel.F_HomePhone,
                F_Birthday = (userModel.F_Birthday ?? DateTime.MinValue).ToString("yyyy-MM-dd"),
                F_CreateOn = userModel.F_CreateOn,
                F_CancelOn = userModel.F_CancelOn,
                F_DeleteFlag = userModel.F_DeleteFlag,
                F_APPOnFlag = userModel.F_APPOnFlag,
                F_LastActiveTime = userModel.F_LastActiveTime,
                F_See = userModel.F_See,
                F_HJType = userModel.F_HJType ?? 0,
                F_PId = userModel.F_PId,
                F_TmId = userModel.F_TmId,
                F_WorkNumber = userModel.F_WorkNumber,
                F_Responsibility = userModel.F_Responsibility,
                F_Post = userModel.F_Post,
                F_ContactPhone = userModel.F_ContactPhone,
                //zxzname = zxzModel?.F_Name ?? "",
                depname = depModel?.F_DeptName ?? ""
            });

        }
        [Authority]
        //添加用户信息
        public ActionResult AddUsers(UserAccountInput input)
        {
            Regex reg = new Regex(@"^[1-9]\d*$");
            //if (!reg.IsMatch(input.Usercode.Trim()))
            //{
            //    return Error("工号必须为正整数");
            //}
            //try
            //{
            //    int usercode = int.Parse(input.Usercode.Trim());
            //}
            //catch
            //{
            //    return Error("工号必须为数字");
            //}

            Model.T_Sys_UserAccount userAccountModel = new Model.T_Sys_UserAccount();
            userAccountModel.F_UserCode = input.Usercode.Trim();
            userAccountModel.F_UserName = input.Username.Trim();
            userAccountModel.F_Password = input.Password.Trim();
            //userAccountModel.F_ExtensionNumber = input.Extno.Trim();
            //userAccountModel.F_WorkNumber = input.Usercode;
            userAccountModel.F_DeptId = input.DeptId;
            userAccountModel.F_RoleId = input.RoleId;
            //userAccountModel.F_GroupId = input.GroupId;
            userAccountModel.F_SeatFlag = input.IsSeat;
            userAccountModel.F_SeatRight = input.SearRight;
            userAccountModel.F_SexFlag = input.Sex;
            userAccountModel.F_Remark = input.Remark;
            userAccountModel.F_Mobile = input.Mobile;
            userAccountModel.F_Telephone = input.Telphone;
            userAccountModel.F_Birthday = input.Birth;
            userAccountModel.F_CreateOn = DateTime.Now;
            userAccountModel.F_DeleteFlag = 0;
            //userAccountModel.F_HJType = input.HjType;

            var model = sysUserAccountBll.GetModel(input.Usercode);
            if (model != null)
                return Error("当前员工工号存在，请更换！");

            if (input.IsSeat)
            {
                userAccountModel.F_WorkNumber = input.Usercode.Trim();
                if (input.ClassId.Value > 0)
                {
                    var cls = new BLL.T_Sys_Class().GetModel(input.ClassId.Value);
                    userAccountModel.F_ClassCode = (cls != null ? cls.F_Code : "");
                }

                SysConfigController sys = new SysConfigController();
                //话务人员限制权限判断
                if (sys.IsValidSeatPermission())
                {
                    if (sysUserAccountBll.Add(userAccountModel) > 0)
                        return Success("新增成功！");
                    else
                        return Error("新增失败！");
                }
                else
                {
                    return Error("话务人员数量已超！");
                }
            }
            if (sysUserAccountBll.Add(userAccountModel) > 0)
                return Success("新增成功！");
            else
                return Error("新增失败！");
        }
        [Authority]
        //修改用户信息
        public ActionResult EditUsers(UserAccountInput input)
        {
            //Regex reg = new Regex(@"^[1-9]\d*$");
            //if (!reg.IsMatch(input.Usercode.Trim()))
            //{
            //    return Error("工号必须为正整数");
            //}

            BLL.T_Sys_UserAccount sysUserAccountBll = new BLL.T_Sys_UserAccount();
            Model.T_Sys_UserAccount userAccountModel = sysUserAccountBll.GetModelList("  F_UserId = " + input.UserId).FirstOrDefault();
            if (userAccountModel == null)
                return Error("获取用户失败");
            userAccountModel.F_UserCode = input.Usercode.Trim();
            userAccountModel.F_UserName = input.Username.Trim();
            //userAccountModel.F_Password = input.Password.Trim();
            //userAccountModel.F_ExtensionNumber = input.Extno.Trim();
            //userAccountModel.F_WorkNumber = input.Usercode;
            userAccountModel.F_DeptId = input.DeptId;
            userAccountModel.F_RoleId = input.RoleId;
            //userAccountModel.F_GroupId = input.GroupId;
            userAccountModel.F_SeatFlag = input.IsSeat;
            userAccountModel.F_SeatRight = input.SearRight;
            userAccountModel.F_SexFlag = input.Sex;
            userAccountModel.F_Remark = input.Remark;
            userAccountModel.F_Mobile = input.Mobile;
            userAccountModel.F_Telephone = input.Telphone;
            userAccountModel.F_Birthday = input.Birth;
            userAccountModel.F_CreateOn = DateTime.Now;
            //userAccountModel.F_DeleteFlag = 0;
            //userAccountModel.F_HJType = input.HjType;
            if (input.IsSeat)
            {
                userAccountModel.F_WorkNumber = input.Usercode.Trim();
                if (input.ClassId.Value > 0)
                {
                    var cls = new BLL.T_Sys_Class().GetModel(input.ClassId.Value);
                    userAccountModel.F_ClassCode = (cls != null ? cls.F_Code : "");
                }

                SysConfigController sys = new SysConfigController();
                //话务人员限制权限判断
                if (sys.IsValidSeatPermission())
                {
                    if (sysUserAccountBll.Update(userAccountModel))
                        return Success("编辑成功！");
                    else
                        return Error("编辑失败！");
                }
                else
                {
                    return Error("话务人员数量已超！");
                }
            }
            if (sysUserAccountBll.Update(userAccountModel))
                return Success("编辑成功！");
            else
                return Error("编辑失败！");
        }
        [Authority]
        //删除/禁用/启用 用户
        public ActionResult DelUsers(string[] ids, int state = 0)
        {
            if (ids == null || ids.Length <= 0)
                return Error("请选择用户");
            var idStr = string.Join(",", ids);
            if (string.IsNullOrEmpty(idStr))
                return Error("请选择用户");

            SysConfigController sys = new SysConfigController();
            //话务人员限制权限判断
            if (state == 0) {
                if (sys.IsValidSeatPermission())
                {
                    if (sysUserAccountBll.DeleteList(idStr, state))
                        return Success("设置成功");
                    else
                        return Error("设置失败");
                }
                else
                {
                    return Error("话务人员数量已超！");
                }
            }
            if (sysUserAccountBll.DeleteList(idStr, state))
                return Success("设置成功");
            else
                return Error("设置失败");
        }

        [Authority]
        //删除用户
        public ActionResult WLDelUsers(string[] ids)
        {
            if (ids == null || ids.Length <= 0)
                return Error("请选择用户");
            var idStr = string.Join(",", ids);
            if (string.IsNullOrEmpty(idStr))
                return Error("请选择用户");

            if (sysUserAccountBll.DeleteList(idStr))
                return Success("删除成功");
            else
                return Error("删除失败");
        }

        //获取坐席列表
        public ActionResult GetSeatList()
        {
            List<Model.T_Sys_UserAccount> userSeartList = sysUserAccountBll.GetModelList(" f_seatflag=1 order by f_userid desc ");
            if (userSeartList.Count > 0)
                return Success("列表加载成功", userSeartList);
            else
                return Error("列表加载失败");
        }
        //根据角色获取用户
        public ActionResult GetUsersList(string rolecode)
        {
            var sql = " 1=1 ";
            if (!string.IsNullOrWhiteSpace(rolecode.Trim()))
                sql += " and F_RoleId in (select F_RoleId from T_Sys_RoleInfo where F_RoleCode='" + rolecode.Trim() + "')";
            List<Model.T_Sys_UserAccount> userList = sysUserAccountBll.GetModelList(sql + " order by f_userid desc ");
            if (userList.Count > 0)
                return Success("列表加载成功", userList);
            else
                return Error("列表加载失败");
        }

        //根据部门获取用户
        public ActionResult GetDeptUserList(int deptid = 0)
        {
            List<Model.T_Sys_UserAccount> DeptUserList = sysUserAccountBll.GetModelList("F_DeptId='" + deptid + "' order by f_userid desc ");
            return Success("列表加载成功", DeptUserList);

        }

        [Authority]
        //获取当前用户信息
        public ActionResult GetNowUser()
        {
            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(User.UserData["F_UserCode"]);
            if (userModel == null)
                return Error("获取失败");
            Model.T_Sys_RoleInfo roleModel = new BLL.T_Sys_RoleInfo().GetModel(userModel.F_RoleId);
            var obj = new
            {
                user = userModel,
                role = roleModel
            };
            return Success("获取成功", obj);

        }
        [Authority]
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="usercode"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public ActionResult ResetPwd(string usercode = "", string pwd = "")
        {
            if (string.IsNullOrWhiteSpace(pwd))
                return Error("请输入密码");
            var model = sysUserAccountBll.GetModel(usercode);
            if (model == null) return Error("此用户不存在");
            model.F_Password = pwd;
            if (sysUserAccountBll.Update(model))
                return Success("重置密码成功");
            else
                return Error("重置密码失败");

        }
        public ActionResult UpdatePwd( string post,string responsibility,string contactPhone,
       string usercode = "", string pwd = "", string oldPwd = ""
          )
        {
            if (string.IsNullOrEmpty(usercode))
                return Error("用户不能为空");
           // if (string.IsNullOrWhiteSpace(pwd))
             //   return Error("请输入密码");
            var model = sysUserAccountBll.GetModel(usercode);
            if (model == null) return Error("此用户不存在");
            if (!string .IsNullOrEmpty (pwd))
            {
                if (pwd.Equals(oldPwd))
                    return Error("新密码不能和原密码相同");
                if (!model.F_Password.Equals(oldPwd)) return Error("原密码不正确");
                model.F_Password = pwd;
            }
            if (!string.IsNullOrEmpty(responsibility))
                model.F_Responsibility  = responsibility;
            if (!string.IsNullOrEmpty(contactPhone))
                model.F_ContactPhone = contactPhone;
            if (!string.IsNullOrEmpty(post))
                model.F_Post = post;
            if (sysUserAccountBll.Update(model))
                return Success("修改成功");
            else
                return Error("修改失败");

        }
   
        #region App手机端 用户列表
        /// <summary>
        /// App手机端 用户列表
        /// </summary>
        /// <returns></returns>
        [Authority]
        public ActionResult GetAppUserList()
        {
            DataTable dt = new DataTable();
            string sql = " 1=1 and F_RoleId=2 ";
            try
            {
                string Key = RequestString.GetQueryString("Key");
                if (!string.IsNullOrWhiteSpace(Key))
                {
                    string str = string.Format(" and (F_DeptId IN (SELECT F_DeptId FROM dbo.T_Sys_Department WHERE F_DeptName like '%{0}%') or F_UserName like '%{1}%' or F_Mobile like '%{2}%' or F_Telephone like '%{3}%' or F_HomePhone like '%{3}%')", Key, Key, Key, Key, Key);
                    sql += str;
                }
                dt = sysUserAccountBll.GetList(sql).Tables[0];

                List<Model.UserAccount> modelList = new BLL.UserAccount().DataTableToList(dt);
                return Success("获取成功",
                    modelList.Select(x => new
                    {
                        F_UserId = x.F_UserId,
                        F_UserCode = x.F_UserCode,
                        F_UserName = x.F_UserName,
                        F_DeptId = x.F_DeptId,
                        F_SexFlag = x.F_SexFlag,
                        F_Remark = x.F_Remark,
                        F_Telephone = x.F_Telephone,
                        F_Mobile = x.F_Mobile,
                        F_HomePhone = x.F_HomePhone,
                        F_Birthday = x.F_Birthday,
                        F_CreateOn = x.F_CreateOn,
                        F_APPOnFlag = x.F_APPOnFlag,
                        F_LastActiveTime = x.F_LastActiveTime,
                        F_RoleName = x.F_RoleName,
                        F_DeptName = x.F_DeptName
                    })
                    );

            }
            catch (Exception err)
            {
                return Error("错误：" + err.ToString());
            }
            finally
            {
                dt.Clear();
                dt.Dispose();
            }
        }
        #endregion
    }
}