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

namespace SignTokenApi.Controllers
{
    /// <summary>
    /// 用户管理 - 普通排班（保洁，保安） - 公示系统展示
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class WorkUserController : BaseController
    {
        private readonly ILogger<WorkUserController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ISys_Work_UserRepository _sys_work_userRepository;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        public WorkUserController(
            ILogger<WorkUserController> logger,
            IConfiguration configuration,
            ISys_Work_UserRepository sys_work_userRepository,
            ISys_User_AccountRepository sys_user_accountRepository
            )
        {
            _logger = logger;
            _configuration = configuration;
            _sys_work_userRepository = sys_work_userRepository;
            _sys_user_accountRepository = sys_user_accountRepository;
        }

        /// <summary>
        /// 获取用户列表 by page
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="stime"></param>
        /// <param name="etime"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public IActionResult GetListByPageAsync(string keyword, string projectid, int pageindex = 1, int pagesize = 10)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            
            var userinfo = _sys_user_accountRepository.GetUserInfo(usercode).ToJson().ToObject<UserInfoModel>();

            //获取数据
            int recordCount = 0;
            var result = _sys_work_userRepository.GetListsByPage(keyword, projectid, userinfo, pageindex, pagesize, out recordCount);
            var obj = new
            {
                rows = result.ToList(),
                total = recordCount
            };
            return Success("获取成功", obj);
        }

        /// <summary>
        /// 获取所有用户列表 - 下拉
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlistdrop")]
        public async Task<IActionResult> GetListdrop(string projectid, string usertype)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            
            var userinfo = _sys_user_accountRepository.GetUserInfo(usercode).ToJson().ToObject<UserInfoModel>();

            var list = await _sys_work_userRepository.Get(p => p.isdelete == 0);
            if (userinfo.isallproject == 0)
                list = list.Where(it => userinfo.projectlist.Contains(it.projectid));
            if (!string.IsNullOrEmpty(projectid))
                list = list.Where(it => it.projectid == projectid);
            if (!string.IsNullOrEmpty(usertype))
                list = list.Where(it => it.usertype == usertype);
            
            return Success("获取成功", list);
        }

        /// <summary>
        /// 获取用户详情 by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("getdetailes")]
        public async Task<IActionResult> GetDetailsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");
            var model = await _sys_work_userRepository.GetSingle(id);
            if (model != null)
            {
                return Success("获取成功！", model);
            }
            return Error("获取失败");
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(WorkUserInput input)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
            if (string.IsNullOrEmpty(input.username))
                return Error("名称不能为空");
            var model = new Sys_Work_User();
            model.projectid = input.projectid;
            model.usertype = input.usertype;
            model.username = input.username;
            model.sex = input.sex;
            model.mobile = input.mobile;
            model.remark = input.remark;
            model.createby = usercode;
            model.createname = username;
            model.createtime = DateTime.Now.ToLocalTime();
            bool b = await _sys_work_userRepository.Add(model);
            if (b)
                return Success("添加成功");
            return Error("添加失败");
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="id"></param>
        /// <param name="provincecode"></param>
        /// <param name="provincename"></param>
        /// <returns></returns>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(WorkUserInput input)
        {

            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            string username = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name).Value;
            if (string.IsNullOrEmpty(input.username))
                return Error("名称不能为空");
            var model = await _sys_work_userRepository.GetSingle(input.id);
            if (model == null)
                return Error("参数错误");

            model.id = input.id;
            model.projectid = input.projectid;
            model.usertype = input.usertype;
            model.username = input.username;
            model.sex = input.sex;
            model.mobile = input.mobile;
            model.remark = input.remark;
            model.createby = usercode;
            model.createname = username;
            model.createtime = DateTime.Now.ToLocalTime();
            bool b = await _sys_work_userRepository.Update(model);
            if (b)
                return Success("保存成功");
            return Error("保存失败");
        }

        /// <summary>
        /// 删除用户信息 by ids
        /// </summary>
        /// <param name="ids">string[] id</param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> DeleteAsync(string[] ids)
        {
            string usercode = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var ml = await _sys_work_userRepository.GetSingle(item);
                    ml.isdelete = 1;
                    ml.deleteby = usercode;
                    ml.deletetime = DateTime.Now.ToLocalTime();
                    if (_sys_work_userRepository.Update(ml).Result)
                        res += 1;
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
                return Error("请选择要删除的记录");
        }


    }
}