using System;
using System.Collections.Generic;
using System.IRepositories;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System.Model;
using TVShoppingCallCenter_ZLJ.Models.Inputs;
using Microsoft.Extensions.Configuration;

namespace TVShoppingCallCenter_ZLJ.Controllers
{
    [Authorize]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class UserAccountController : BaseController
    {
        private readonly ISys_UserAccountRepository _sys_useraccountRepository;
        private readonly ISys_RoleInfoRepository _sys_role_infoRepository;
        private readonly IConfiguration _configuration;
        private readonly ISys_DepartmentRepository _sys_departmentRepository;
        public UserAccountController(IConfiguration configuration, ISys_UserAccountRepository sys_useraccountRepository, ISys_RoleInfoRepository sys_role_infoRepository,
            ISys_DepartmentRepository sys_departmentRepository )
        {
            _configuration = configuration;
            _sys_useraccountRepository = sys_useraccountRepository;
            _sys_role_infoRepository = sys_role_infoRepository;
            _sys_departmentRepository = sys_departmentRepository;
        }

        /// <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, int pageindex = 1, int pagesize = 20)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 筛选
            conModels.Add(new ConditionalModel() { FieldName = "F_DeleteFlag", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumUserCountState.Enabled).ToString() });
            if (!string.IsNullOrEmpty(deptid))
                conModels.Add(new ConditionalModel() { FieldName = "F_DeptId", ConditionalType = ConditionalType.Equal, FieldValue = deptid });
            if (!string.IsNullOrEmpty(roleid))
                conModels.Add(new ConditionalModel() { FieldName = "F_RoleId", ConditionalType = ConditionalType.Equal, FieldValue = roleid });
            if (!string.IsNullOrEmpty(keyword))
                conModels.Add(new ConditionalCollections()
                {
                    ConditionalList = new List<KeyValuePair<WhereType, ConditionalModel>>()
                    {
                        new  KeyValuePair<WhereType, ConditionalModel>(WhereType.And, new ConditionalModel() { FieldName = "F_UserCode", ConditionalType = ConditionalType.Like, FieldValue = keyword }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or , new ConditionalModel() { FieldName = "F_UserName", ConditionalType = ConditionalType.Like, FieldValue = keyword }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or, new ConditionalModel() { FieldName = "F_Mobile", ConditionalType = ConditionalType.Like, FieldValue = keyword }),
                        new  KeyValuePair<WhereType, ConditionalModel>( WhereType.Or, new ConditionalModel() { FieldName = "F_Telephone", ConditionalType = ConditionalType.Like, FieldValue = keyword })
                    }
                });
            #endregion
            int recordCount = 0;
            var list = await _sys_useraccountRepository.GetListViewByPage(conModels, new MyPageModel() { PageIndex = pageindex, PageSize = pagesize, PageCount = recordCount }, "F_CreateOn desc");
            return Success("获取成功", list);
        }

        [HttpGet("getlistdrop")]
        public async Task<IActionResult> GetListDropAsync(string deptid, string roleid, string rolecode)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 筛选
            conModels.Add(new ConditionalModel() { FieldName = "F_DeleteFlag", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumUserCountState.Enabled).ToString() });
            if (!string.IsNullOrEmpty(deptid))
                conModels.Add(new ConditionalModel() { FieldName = "F_DeptId", ConditionalType = ConditionalType.Equal, FieldValue = deptid });
            if (!string.IsNullOrEmpty(roleid))
                conModels.Add(new ConditionalModel() { FieldName = "F_RoleId", ConditionalType = ConditionalType.Equal, FieldValue = roleid });
            if (!string.IsNullOrEmpty(rolecode))
            {
                var rolemodel = await _sys_role_infoRepository.GetSingle(x => x.F_RoleCode == rolecode && x.F_State == (int)EnumDelState.Enabled);
                if (rolemodel != null)
                    conModels.Add(new ConditionalModel() { FieldName = "F_RoleId", ConditionalType = ConditionalType.Equal, FieldValue = rolemodel.F_RoleId.ToString() });
                else
                    conModels.Add(new ConditionalModel() { FieldName = "F_RoleId", ConditionalType = ConditionalType.Equal, FieldValue = "-1" });
            }
            #endregion
            var list = await _sys_useraccountRepository.GetListALL(conModels, "F_CreateOn desc");
            var result = list.Select(x => new
            {
                x.F_UserCode,
                x.F_UserName,
                x.F_DeptId,
                x.F_RoleId,
                x.F_UserId
            });

            return Success("获取成功", result);
        }

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

            var model = await _sys_useraccountRepository.GetSingle(x => x.F_UserId == id && x.F_DeleteFlag == (int)EnumUserCountState.Enabled);
            if (model != null)
            {
                return Success("获取成功！", GetDeptName(model));
            }
            return Error("获取失败");
        }
        private T_Sys_UserAccount GetDeptName(T_Sys_UserAccount model)
        {
            if (model.F_DeptId>0)
            {
                var dept = _sys_departmentRepository.GetSingle(x => x.F_DeptId == model.F_DeptId ).Result;
                if (model != null)
                    model.F_Dept  = dept.F_DeptName;
            }
            return model;
        }
        /// <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("手机号码不能为空");

            if (await _sys_useraccountRepository.GetCount(p => p.F_UserCode == input.usercode && p.F_DeleteFlag == (int)EnumUserCountState.Enabled) > 0)
            {
                return Error("账号已经存在");
            }
            if (await _sys_useraccountRepository.GetCount(p =>( p.F_Mobile == input.mobile||p.F_Telephone== input.mobile) && p.F_DeleteFlag == (int)EnumUserCountState.Enabled) > 0)
            {
                return Error("手机号已经存在");
            }
            #endregion
            var model = new T_Sys_UserAccount();
            model.F_UserCode = input.usercode;
            model.F_UserName = input.username;
            model.F_Password = input.password;
            model.F_SexFlag = input.sexflag;
            model.F_DeptId = input.deptid;
            model.F_ExtensionNumber = input.extensionnumber;
            model.F_RoleId = input.roleid;
            model.F_SeartGroupID = input.seartgroupiD;
            model.F_SeatFlag = input.seatflag;
            model.F_SeatLevel = input.seatlevel;
            model.F_SeatRight = input.seatright;
            model.F_RemindFlag = input.remindflag;
            model.F_Remark = input.remark;
            model.F_HeadImg = input.headimg;
            model.F_WXNo = input.wxno;
            model.F_Telephone = input.telephone;
            model.F_Mobile = input.mobile;
            model.F_HomePhone = input.remark;
            model.F_WxOpenId = "";

            model.F_DutyId = input.dutyid;
            model.F_DeptTeamId = input.deptteamid;
            model.F_EntryDate = input.entrydate;
            model.F_FullDate = input.fulldate;
            model.F_TermDate = input.termdate;

            model.F_DeleteFlag = (int)EnumUserCountState.Enabled;
            model.F_CreateBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            model.F_CreateOn = DateTime.Now;

            var b = await _sys_useraccountRepository.Add(model);
            if (b > 0)
                return Success("添加成功");
            else
                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 (await _sys_useraccountRepository.GetCount(p => p.F_UserCode == input.usercode && p.F_UserId != input.userid && p.F_DeleteFlag == (int)EnumUserCountState.Enabled) > 0)
            {
                return Error("账号已经存在");
            }
            #endregion

            if (await _sys_useraccountRepository.GetCount(p =>p.F_UserId!= input.userid && (p.F_Mobile == input.mobile || p.F_Telephone == input.mobile) && p.F_DeleteFlag == (int)EnumUserCountState.Enabled) > 0)
            {
                return Error("手机号已经存在");
            }

            var model = new T_Sys_UserAccount();
            model = await _sys_useraccountRepository.GetSingle(p => p.F_UserId == input.userid && p.F_DeleteFlag == (int)EnumUserCountState.Enabled);
            if (model == null)
                return Error("获取信息失败");
            model.F_UserCode = input.usercode;
            model.F_UserName = input.username;
            model.F_SexFlag = input.sexflag;
            model.F_DeptId = input.deptid;
            model.F_ExtensionNumber = input.extensionnumber;
            model.F_RoleId = input.roleid;
            model.F_SeartGroupID = input.seartgroupiD;
            model.F_SeatFlag = input.seatflag;
            model.F_SeatLevel = input.seatlevel;
            model.F_SeatRight = input.seatright;
            model.F_RemindFlag = input.remindflag;
            model.F_Remark = input.remark;
            model.F_HeadImg = input.headimg;
            model.F_WXNo = input.wxno;
            model.F_Telephone = input.telephone;
            model.F_Mobile = input.mobile;
            model.F_HomePhone = input.homephone;

            model.F_DutyId = input.dutyid;
            model.F_DeptTeamId = input.deptteamid;
            model.F_EntryDate = input.entrydate;
            model.F_FullDate = input.fulldate;
            model.F_TermDate = input.termdate;

            model.F_LastModifyBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            model.F_LastModifyOn = DateTime.Now;

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

        /// <summary>
        /// 逻辑删除用户
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> Delete(int[] 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_useraccountRepository.GetSingle(p => p.F_UserId == item);
                    if (eq != null)
                    {
                        eq.F_DeleteFlag = (int)EnumUserCountState.Delete;
                        eq.F_DeleteBy = usercode;
                        eq.F_DeleteOn = DateTime.Now.ToLocalTime();
                        bool bl = await _sys_useraccountRepository.Update(eq);
                    }

                }

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

        /// <summary>
        /// 获取当前用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet("getnowuser")]
        public async Task<IActionResult> GetNowUser()
        {
            string nowusercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var userModel = await _sys_useraccountRepository.GetSingle(u => u.F_UserCode == nowusercode && u.F_DeleteFlag == (int)EnumUserCountState.Enabled);
            if (userModel == null)
                return Error("获取失败");
            userModel.F_HeadImg = _configuration["appSettings:ApiHost"].ToString() + userModel.F_HeadImg;
            return Success("获取成功", userModel);
        }

        /// <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_useraccountRepository.GetSingle(p => p.F_UserCode == usercode && p.F_DeleteFlag == (int)EnumUserCountState.Enabled);
            if (model == null)
                return Error("操作失败");
            model.F_Password = password;

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

        /// <summary>
        /// 更新头像
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("updateavatar")]
        public async Task<IActionResult> UpdateAvatar(string usercode, string headimg)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(usercode))
                return Error("请选择账号");
            if (string.IsNullOrEmpty(headimg))
                return Error("头像不能为空");


            #endregion
            T_Sys_UserAccount model = await _sys_useraccountRepository.GetSingle(p => p.F_UserCode == usercode && p.F_DeleteFlag == (int)EnumUserCountState.Enabled);
            if (model == null)
                return Error("操作失败");
            model.F_HeadImg = headimg;
            List<T_Sys_UserAccount> list = new List<T_Sys_UserAccount>();
            list.Add(model);
            bool b = await _sys_useraccountRepository.UpdateListToColumns(list, s => new { s.F_HeadImg });
            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_useraccountRepository.GetSingle(p => p.F_UserCode == usercode && p.F_Password == oldpassword && p.F_DeleteFlag == (int)EnumUserCountState.Enabled);
            if (model == null)
                return Error("原密码输入错误");
            model.F_Password = password;

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


        [HttpGet("getseatlist")]
        public async Task<IActionResult> GetSeatList(string usercode, string rolecode, string deptid = "")
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();

            if (!string.IsNullOrEmpty(rolecode))
            {
                T_Sys_RoleInfo rolemodelList = await _sys_role_infoRepository.GetFirst(x => x.F_RoleCode == rolecode && x.F_State == (int)EnumDelState.Enabled);
                conModels.Add(new ConditionalModel() { FieldName = "F_SeatFlag", ConditionalType = ConditionalType.Equal, FieldValue = "1" });
            }

           
            #region 筛选
            conModels.Add(new ConditionalModel() { FieldName = "F_DeleteFlag", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumUserCountState.Enabled).ToString() });
            conModels.Add(new ConditionalModel() { FieldName = "F_SeatFlag", ConditionalType = ConditionalType.Equal, FieldValue = "1" });
            if (!string.IsNullOrEmpty(deptid))
                conModels.Add(new ConditionalModel() { FieldName = "F_DeptId", ConditionalType = ConditionalType.Equal, FieldValue = deptid });
            if (!string.IsNullOrEmpty(usercode))
                conModels.Add(new ConditionalModel() { FieldName = "F_UserCode", ConditionalType = ConditionalType.Equal, FieldValue = usercode });
            #endregion


            var list = await _sys_useraccountRepository.GetListALL(conModels, "F_CreateOn desc");
            var result = list.Select(x => new
            {
                x.F_UserCode,
                x.F_UserName,
                x.F_DeptId,
                x.F_RoleId,
                x.F_UserId,
                x.F_SeatRight,
                x.F_SeartGroupID,
                x.F_ExtensionNumber
            });

            return Success("获取成功", result);
        }
    }
}