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

namespace ConfigurationApi.Controllers
{
    /// <summary>
    /// 岗位
    /// </summary>
    [Authorize]
    [ApiVersion("6.0")]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class PostController : BaseController
    {
        private readonly ILogger<PostController> _logger;
        private readonly ISys_Post_InfoRepository _sys_post_inforepository;
        public PostController(ILogger<PostController> logger, ISys_Post_InfoRepository sys_post_inforepository)
        {
            _logger = logger;
            _sys_post_inforepository = sys_post_inforepository;
        }

        /// <summary>
        /// 获取字典下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlistdrop")]
        public async Task<IActionResult> GetListDropAsync()
        {
            var list = await _sys_post_inforepository.Get(x => x.isdelete == 0);
            return Success("获取全部数据成功", list);
        }

        /// <summary>
        /// 获取岗位分页
        /// </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 async Task<IActionResult> GetListsByPageAsync(string keyword, int pageindex = 1, int pagesize = 10)
        {
            #region 条件信息
            ////排序字段
            var sort = Builders<Sys_Post_Info>.Sort.Ascending("sort");

            //根据条件查询集合
            var listApp = new List<FilterDefinition<Sys_Post_Info>>();
            listApp.Add(Builders<Sys_Post_Info>.Filter.Eq("isdelete", 0));

            //模糊查询
            if (!string.IsNullOrEmpty(keyword))
                listApp.Add(Builders<Sys_Post_Info>.Filter.Where(s => s.postcode.Contains(keyword) || s.postname.Contains(keyword)));
            #endregion
            int recordCount = 0;

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

            recordCount = int.Parse(redCount.ToString());

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

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

        /// <summary>
        /// 添加岗位
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(PostInfoInput input)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(input.postname))
                return Error("请输入岗位名称");
            if (string.IsNullOrEmpty(input.postcode))
                return Error("请输岗位入代码");
            var modelold = await _sys_post_inforepository.GetSingle(p => p.postname == input.postname && p.isdelete==0);
            if (modelold != null)
            {
                return Error("名称已经存在");
            }
            #endregion

            var model = new Sys_Post_Info();
            model.parentid = input.parentid;
            model.postname = input.postname;
            model.postcode = input.postcode;
            model.remark = input.remark;
            model.sort = input.sort;
            model.createby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            if (await _sys_post_inforepository.Add(model))
            {
                return Success("添加成功");
            }
            else
            {
                return Error("添加失败");
            }
        }

        /// <summary>
        /// 修改岗位信息
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(PostInfoInput input)
        {
            #region 验证判断
            if (string.IsNullOrEmpty(input.postname))
                return Error("请输入岗位名称");
            if (string.IsNullOrEmpty(input.postcode))
                return Error("请输岗位入代码");
            var modelold = await _sys_post_inforepository.GetSingle(p => p.postname == input.postname && p.isdelete == 0 && p.id != input.id);
            if (modelold != null)
            {
                return Error("名称已经存在");
            }
            #endregion

            var model = await _sys_post_inforepository.GetSingle(input.id);
            if (model == null)
                return Error("操作失败");
            model.parentid = input.parentid;
            model.postname = input.postname;
            model.postcode = input.postcode;
            model.remark = input.remark;
            model.sort = input.sort;
            bool b = await _sys_post_inforepository.Update(model);
            if (b)
                return Success("修改成功");
            return Error("修改失败");
        }

        /// <summary>
        /// 删除岗位信息 by ids
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> DeleteAsync(string[] ids)
        {
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var ml = await _sys_post_inforepository.GetSingle(item);
                    ml.isdelete = 1;
                    ml.deletetime = DateTime.Now.ToLocalTime();
                    ml.deleteby = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                    if (_sys_post_inforepository.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("请选择要删除的记录");
        }

    }
}