using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using MadRunFabric.Common;
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")]
    [Route("api/[controller]")]
    [Produces("application/json")]
    public class WorkClassController : BaseController
    {
        private readonly ILogger<WorkClassController> _logger;
        private readonly IConfiguration _configuration;
        private readonly ISys_Work_ClassGroupRepository _sys_work_classgrouprepository;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;
        public WorkClassController(
            ILogger<WorkClassController> logger,
            IConfiguration configuration,
            ISys_Work_ClassGroupRepository sys_work_classgrouprepository,
            ISys_User_AccountRepository sys_user_accountRepository
            )
        {
            _logger = logger;
            _configuration = configuration;
            _sys_work_classgrouprepository = sys_work_classgrouprepository;
            _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_classgrouprepository.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 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_classgrouprepository.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);

            //排班排序
            DateTime dtNow = DateTime.Now;
            string dayNow = dtNow.ToString("yyyy-MM-dd");
            var lists = list;
            var result = lists.Select(p => new
            {
                id = p.id,
                projectid = p.projectid,
                usertype = p.usertype,
                code = p.code,
                name = p.name,
                starttime = p.starttime,
                endtime = p.endtime,
                orderbytime = DateTime.Parse(dayNow + " " + p.starttime),
                remark = p.remark,
                createby = p.createby,
                createtime = p.createtime,
                isdelete = p.isdelete
            }).ToList().OrderBy(x => x.orderbytime);

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

        /// <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_classgrouprepository.GetSingle(id);
            if (model != null)
            {
                return Success("获取成功！", model);
            }
            return Error("获取失败");
        }

        /// <summary>
        /// 添加班别
        /// </summary>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(WorkClassInput 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.name))
                return Error("名称不能为空");
            var model = new Sys_Work_ClassGroup();
            //model.id = input.id;
            model.projectid = input.projectid;
            model.usertype = input.usertype;
            model.name = input.name;
            model.code = input.code;
            model.starttime = input.starttime;
            model.endtime = input.endtime;
            model.remark = input.remark;
            model.createby = usercode;
            model.createname = username;
            model.createtime = DateTime.Now.ToLocalTime();
            bool b = await _sys_work_classgrouprepository.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(WorkClassInput 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.name))
                return Error("名称不能为空");
            var model = await _sys_work_classgrouprepository.GetSingle(input.id);
            if (model == null)
                return Error("参数错误");

            model.id = input.id;
            model.projectid = input.projectid;
            model.usertype = input.usertype;
            model.name = input.name;
            model.code = input.code;
            model.starttime = input.starttime;
            model.endtime = input.endtime;
            model.remark = input.remark;
            model.createby = usercode;
            model.createname = username;
            model.createtime = DateTime.Now.ToLocalTime();
            bool b = await _sys_work_classgrouprepository.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_classgrouprepository.GetSingle(item);
                    ml.isdelete = 1;
                    ml.deleteby = usercode;
                    ml.deletetime = DateTime.Now.ToLocalTime();
                    if (_sys_work_classgrouprepository.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("请选择要删除的记录");
        }
    }
}