using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using MadRunFabric.Common;
using MadRunFabric.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using SignTokenApi.IRepositories;
using SignTokenApi.Model.Input;

namespace SignTokenApi.Areas.Hy_User
{
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class HyUserAccountController : BaseController
    {
        private readonly IConfiguration _configuration;
        private readonly ILogger<HyUserAccountController> _logger;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        public HyUserAccountController(IConfiguration configuration, ILogger<HyUserAccountController> logger, ISys_User_AccountRepository sys_user_accountRepository)
        {
            _configuration = configuration;
            _logger = logger;
            _sys_user_accountRepository = sys_user_accountRepository;
        }

        /// <summary>
        /// 用户信息列表 by page
        /// </summary>
        /// <param name="pageindex">当前页</param>
        /// <param name="pagesize">每页条数</param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListByPageAsync(string keyword, string deptid, string roleid, string projectid, int type = -1, int pageindex = 1, int pagesize = 10)
        {
            #region 条件信息
            ////排序字段
            var sort = Builders<Sys_User_Account>.Sort.Descending("create_time");

            //根据条件查询集合
            var listFilter = new List<FilterDefinition<Sys_User_Account>>();
            listFilter.Add(Builders<Sys_User_Account>.Filter.Eq("delete_flag", false));
            listFilter.Add(Builders<Sys_User_Account>.Filter.Where(s => s.type != 2));

            //查询
            if (type != -1)
                listFilter.Add(Builders<Sys_User_Account>.Filter.Where(s => s.type.Equals(type)));
            if (!string.IsNullOrEmpty(deptid))
                listFilter.Add(Builders<Sys_User_Account>.Filter.Where(s => s.dept_id.Equals(deptid)));
            if (!string.IsNullOrEmpty(roleid))
                listFilter.Add(Builders<Sys_User_Account>.Filter.Where(s => s.role_id.Equals(roleid)));
            if (!string.IsNullOrEmpty(projectid))
                listFilter.Add(Builders<Sys_User_Account>.Filter.Where(s => s.projectlist.Contains(projectid)));
            if (!string.IsNullOrEmpty(keyword))
                listFilter.Add(Builders<Sys_User_Account>.Filter.Where(s => s.usercode.Contains(keyword) || s.username.Contains(keyword) || s.mobile.Contains(keyword) || s.telephone.Contains(keyword)));
            #endregion

            var filter = Builders<Sys_User_Account>.Filter.And(listFilter);
            var list = await _sys_user_accountRepository.GetByPage(filter, pageindex, pagesize, sort);
            var redCount = await _sys_user_accountRepository.CountAsync(filter);   //获取总数


            var obj = new
            {
                rows = list,
                total = redCount,
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 设备用户列表 by page - 关联查询
        /// </summary>
        /// <param name="pageindex">当前页</param>
        /// <param name="pagesize">每页条数</param>
        /// <returns></returns>
        [HttpGet("getlistsbypage")]
        public IActionResult GetListsByPage(string keyword, string deptid, string roleid, string projectid, int type = -1, int pageindex = 1, int pagesize = 10)
        {
            
            int recordCount = 0;
            var result = _sys_user_accountRepository.HyGetListsByPage(keyword, deptid, roleid, projectid, type, pageindex, pagesize, out recordCount);
            var obj = new
            {
                rows = result,
                total = recordCount,
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取用户列表 - 关联查询
        /// </summary>
        /// <returns></returns>
        [HttpGet("getapplists")]
        public IActionResult GetAppLists(string keyword, string deptid, string roleid, string projectid, int type = -1)
        {
            
            var result = _sys_user_accountRepository.HyGetAppLists(keyword, deptid, roleid, projectid, type);
            return Success("获取成功", result);
        }

        /// <summary>
        /// 获取用户详情 by id
        /// </summary>
        /// <param name="id">设备id</param>
        /// <returns></returns>
        [HttpGet("getdetailes")]
        public async Task<IActionResult> GetDetailsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");

            var model = await _sys_user_accountRepository.GetSingle(id);
            if (model != null)
            {
                return Success("获取成功！", model);
            }
            return Error("获取失败");
        }

        /// <summary>
        /// 获取用户详情 by id - 关联查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("getdetails")]
        public IActionResult GetDetails(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            var model = _sys_user_accountRepository.HyGetDetails(id);
            if (model != null)
            {
                return Success("获取成功！", model);
            }
            return Error("获取失败");
        }

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <param name="input">用户信息参数</param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> Add(UserAccountInput input)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(input.usercode))
                return Error("账号不能为空");
            if (string.IsNullOrEmpty(input.password))
                return Error("密码不能为空");
            if (string.IsNullOrEmpty(input.mobile))
                return Error("手机号码不能为空");
            var modelold = new Sys_User_Account();
            modelold = await _sys_user_accountRepository.GetSingle(p => p.usercode == input.usercode && p.delete_flag == false);
            if (modelold != null)
            {
                return Error("账号已经存在");
            }
            #endregion
            var model = new Sys_User_Account();
            model.usercode = input.usercode;
            model.username = input.username;
            model.type = input.type;
            model.password = input.password;
            model.sex = input.sex;
            model.birthday = input.birthday;
            model.call_type = input.call_type;
            model.delete_flag = false;
            model.dept_id = input.dept_id;
            model.extensionnumber = input.extensionnumber;
            model.group = input.group;
            model.groupid = input.groupid;
            model.head_img = input.head_img;
            model.head_small_img = input.head_small_img;
            model.homephone = input.homephone;
            model.lock_flag = false;
            model.mail = input.mail;
            model.mobile = input.mobile;
            model.qq = input.qq;
            model.remark = input.remark;
            model.role_id = input.role_id;
            model.seat_flag = input.seat_flag;
            model.seat_level = input.seat_level;
            model.seat_right = input.seat_right;
            model.see_flag = input.see_flag;
            model.sina = input.sina;
            model.team_id = input.team_id;
            model.telephone = input.telephone;
            model.idcardno = input.idcardno;
            model.entrytime = input.entrytime;
            model.transfertime = input.transfertime;
            model.quittime = input.quittime;

            if (input.idcard != null)
            {
                model.idcard = input.idcard;
            }
            else
            {
                model.idcard = new List<FileBaseModel>();
            }
            if (input.certificate != null)
            {
                model.certificate = input.certificate;
            }
            else
            {
                model.certificate = new List<FileBaseModel>();
            }
            if (input.postlist != null)
            {
                model.postlist = input.postlist;
            }
            else
            {
                model.postlist = new List<string>();
            }
            if (input.projectlist != null)
            {
                model.projectlist = input.projectlist;
            }
            else
            {
                model.projectlist = new List<string>();
            }

            model.create_user = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            bool b = await _sys_user_accountRepository.Add(model);
            if (b)
                return Success("添加成功");
            //日志
            _logger.LogError($"账号：{input.usercode}添加失败");
            return Error("添加失败");
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task<IActionResult> Update(UserAccountInput input)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(input.usercode))
                return Error("账号不能为空");
            //if (string.IsNullOrEmpty(input.password))
            //    return Error("密码不能为空");
            var modelold = new Sys_User_Account();
            modelold = await _sys_user_accountRepository.GetSingle(p => p.usercode == input.usercode && p.id != input.id && p.delete_flag == false);
            if (modelold != null)
            {
                return Error("账号已经存在");
            }
            #endregion
            var model = new Sys_User_Account();
            model = await _sys_user_accountRepository.GetSingle(input.id);
            if (model == null)
                return Error("操作失败");
            model.usercode = input.usercode;
            model.username = input.username;
            model.type = input.type;
            //model.password = input.password;
            model.sex = input.sex;
            model.birthday = input.birthday;
            model.call_type = input.call_type;
            model.dept_id = input.dept_id;
            model.extensionnumber = input.extensionnumber;
            model.group = input.group;
            model.groupid = input.groupid;
            model.head_img = input.head_img;
            model.head_small_img = input.head_small_img;
            model.homephone = input.homephone;
            model.mail = input.mail;
            model.mobile = input.mobile;
            model.qq = input.qq;
            model.remark = input.remark;
            model.role_id = input.role_id;
            model.seat_flag = input.seat_flag;
            model.seat_level = input.seat_level;
            model.seat_right = input.seat_right;
            model.see_flag = input.see_flag;
            model.sina = input.sina;
            model.team_id = input.team_id;
            model.telephone = input.telephone;
            model.idcardno = input.idcardno;
            model.entrytime = input.entrytime;
            model.transfertime = input.transfertime;
            model.quittime = input.quittime;

            if (input.idcard != null)
            {
                model.idcard = input.idcard;
            }
            else
            {
                model.idcard = new List<FileBaseModel>();
            }
            if (input.certificate != null)
            {
                model.certificate = input.certificate;
            }
            else
            {
                model.certificate = new List<FileBaseModel>();
            }
            if (input.postlist != null)
            {
                model.postlist = input.postlist;
            }
            else
            {
                model.postlist = new List<string>();
            }
            if (input.projectlist != null)
            {
                model.projectlist = input.projectlist;
            }
            else
            {
                model.projectlist = new List<string>();
            }

            bool b = await _sys_user_accountRepository.UpdateOne(model);
            if (b)
                return Success("保存成功");
            //日志
            _logger.LogError($"账号：{input.usercode}修改失败");
            return Error("保存失败");
        }

        /// <summary>
        /// 逻辑删除用户
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> Delete(string[] ids)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            //使用逻辑删除
            //物理删除的数据无法恢复

            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var eq = await _sys_user_accountRepository.GetSingle(item);
                    if (eq != null)
                    {
                        eq.delete_flag = true;
                        eq.delete_user = usercode;
                        eq.delete_time = DateTime.Now.ToLocalTime();
                        bool bl = await _sys_user_accountRepository.UpdateOne(eq);
                        //if (bl)
                        //{
                        //    var data = await _sys_user_dataRepository.GetSingle(p => p.usercode == eq.usercode);
                        //    if (data != null)
                        //    {
                        //        await _sys_user_dataRepository.UpdateUserPost(data.usercode, "", usercode);
                        //        await _sys_user_dataRepository.UpdateUserProject(data.usercode, "", usercode);

                        //        data.isdelete = 1;
                        //        data.deleteby = usercode;
                        //        data.deletetime = DateTime.Now.ToLocalTime();
                        //        await _sys_user_dataRepository.Update(data);
                        //    }
                        //}
                    }

                }

                return Success("删除成功");
            }
            else
                return Error("请选择要删除的记录");
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("updatepassword")]
        public async Task<IActionResult> UpdatePassword(string usercode, string password, string surepassword)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(usercode))
                return Error("请选择账号");
            if (string.IsNullOrEmpty(password))
                return Error("密码不能为空");
            if (string.IsNullOrEmpty(surepassword))
                return Error("确认密码不能为空");
            if (password != surepassword)
                return Error("两次输入的密码不一致");

            #endregion
            var model = await _sys_user_accountRepository.GetSingle(p => p.usercode == usercode);
            if (model == null)
                return Error("操作失败");
            model.password = password;

            bool b = await _sys_user_accountRepository.UpdateOne(model);
            if (b)
                return Success("保存成功");
            return Error("保存失败");
        }

        /// <summary>
        /// 修改我的密码
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("updatemypassword")]
        public async Task<IActionResult> UpdateMyPassword(string oldpassword, string password, string surepassword)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(oldpassword))
                return Error("原始密码不能为空");
            if (string.IsNullOrEmpty(surepassword))
                return Error("确认密码不能为空");
            if (password != surepassword)
                return Error("两次输入的密码不一致");

            #endregion
            var usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var model = await _sys_user_accountRepository.GetSingle(p => p.usercode == usercode && p.password == oldpassword);
            if (model == null)
                return Error("原始密码输入错误");
            model.password = password;

            bool b = await _sys_user_accountRepository.UpdateOne(model);
            if (b)
                return Success("更新成功");
            return Error("更新失败");
        }

        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("getnowuser")]
        public IActionResult GetUserInfo()
        {
            
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var model = _sys_user_accountRepository.HyGetUserInfo(nowusercode);
            if (model != null)
            {
                return Success("获取成功！", model);
            }
            return NoToken("获取失败");
        }

        /// <summary>
        /// 获取用户详情 by id - 关联查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet("getuserinfo")]
        public IActionResult GetUserInfo(string usercode)
        {
            
            var model = _sys_user_accountRepository.HyGetUserInfo(usercode);
            if (model != null)
            {
                return Success("获取成功！", model);
            }
            return Error("获取失败");
        }

        //2018-7-21获取坐席实时状态使用
        [HttpGet("getlist")]
        public async Task<IActionResult> GetListsAsync(string groupid, string agentid)
        {
            //根据条件查询集合
            var list = new List<FilterDefinition<Sys_User_Account>>();
            list.Add(Builders<Sys_User_Account>.Filter.Eq("seat_flag", true));
            list.Add(Builders<Sys_User_Account>.Filter.Eq("delete_flag", false));
            if (groupid != null)
                list.Add(Builders<Sys_User_Account>.Filter.Where(s => s.group.Contains(groupid)));
            if (agentid != null)
                list.Add(Builders<Sys_User_Account>.Filter.Where(s => s.usercode.Contains(agentid)));


            var filter = Builders<Sys_User_Account>.Filter.And(list);
            var agentlist = await _sys_user_accountRepository.Get(filter, null, null);

            #region 
            System.Data.DataTable dt = new System.Data.DataTable();

            dt.Columns.Add("groupid");
            dt.Columns.Add("agentid");
            //dt.Columns.Add("group");
            foreach (Object obj in agentlist)
            {
                if (obj is Sys_User_Account)//这个是类型的判断，类或结构
                {
                    Sys_User_Account s = (Sys_User_Account)obj;
                    System.Data.DataRow dr = dt.NewRow();
                    dr["groupid"] = s.groupid;
                    dr["agentid"] = s.usercode;
                    //dr["group"] = s.group;
                    dt.Rows.Add(dr);

                }
            }
            //var dtlist = new
            //{
            //    rows=dt
            //};
            #endregion

            return Success("根据条件获取坐席id数据成功", dt);
        }

        /// <summary>
        /// 获取某项目某角色人员
        /// </summary>
        /// <returns></returns>
        [HttpGet("getprojectuser")]
        public IActionResult GetProjectUser(string projectid, string rolecode = "YWYG")
        {
            var result = _sys_user_accountRepository.HyGetProjectUser(projectid, rolecode);
            return Success("获取成功", result);
        }

        /// <summary>
        /// 获取坐席列表
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        [HttpGet("getseatlist")]
        public async Task<IActionResult> GetSeatListsAsync(string key)
        {
            //根据条件查询集合
            var list = new List<FilterDefinition<Sys_User_Account>>();
            list.Add(Builders<Sys_User_Account>.Filter.Eq("seat_flag", true));
            list.Add(Builders<Sys_User_Account>.Filter.Eq("delete_flag", false));
            if (!string.IsNullOrEmpty(key))
                list.Add(Builders<Sys_User_Account>.Filter.Where(s => s.usercode.Contains(key) || s.username.Contains(key)));


            var filter = Builders<Sys_User_Account>.Filter.And(list);
            var agentlist = await _sys_user_accountRepository.Get(filter, null, null);

            return Success("根据条件获取坐席数据成功", agentlist);
        }
    }
}