using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using AMESCoreStudio.WebApi;
using AMESCoreStudio.WebApi.Models.SYS;

namespace AMESCoreStudio.WebApi.Controllers.SYS
{
    /// <summary>
    /// 角色功能资料维护
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class RoleProgramsController : ControllerBase
    {
        private readonly AMESContext _context;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public RoleProgramsController(AMESContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 获取全部角色功能资料
        /// </summary>
        /// <returns></returns>
        // GET: api/RolePrograms
        [HttpGet]
        public async Task<ActionResult<IEnumerable<RoleProgram>>> GetRoleProgram()
        {
            IQueryable<RoleProgram> q = _context.RolePrograms;

            q.OrderBy(p => p.ProgramID);

            var roleProgram = await q.ToListAsync();

            foreach (var data in roleProgram)
            {
                data.Program = _context.ProgramInfoes.Find(data.ProgramID);
            }

            if (roleProgram == null)
            {
                return NotFound();
            }

            return roleProgram;
        }

        /// <summary>
        /// 根据角色ID获取该角色功能资料
        /// </summary>
        /// <param name="id"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        // GET: api/RolePrograms/Role/5
        [HttpGet("Role/{id}")]
        public async Task<ActionResult<IEnumerable<RoleProgram>>> GetRoleProgramByRole(int id, int page = 1, int limit = 10)
        {
            IQueryable<RoleProgram> q = _context.RolePrograms;

            if (id > 0)
            {
                q = q.Where(p => p.RoleID.Equals(id));
            }
            if (page > 0)
            {
                q = q.OrderBy(p => p.ProgramID).Skip((page - 1) * limit).Take(limit);
            }
            else
            {
                q = q.OrderBy(p => p.ProgramID);
            }

            var roleProgram = await q.ToListAsync();

            foreach (var data in roleProgram)
            {
                data.Program = _context.ProgramInfoes.Where(p1 => p1.ProgramID.Equals(data.ProgramID)).FirstOrDefault();
            }

            if (roleProgram == null)
            {
                return NotFound();
            }

            return roleProgram;
        }

        /// <summary>
        /// 根据角色功能ID获取指定单一资料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET: api/RolePrograms/5
        [HttpGet("{id}")]
        public async Task<ActionResult<IEnumerable<RoleProgram>>> GetRoleProgram(int id)
        {
            IQueryable<RoleProgram> q = _context.RolePrograms;

            q = q.Where(p => p.RoleProgramID.Equals(id));

            var roleProgram = await q.ToListAsync();

            if (roleProgram == null)
            {
                return NotFound();
            }

            return roleProgram;
        }

        /// <summary>
        /// 更新角色功能资料
        /// </summary>
        /// <param name="id"></param>
        /// <param name="roleProgram"></param>
        /// <returns></returns>
        // PUT: api/RolePrograms/5
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
        [HttpPut("{id}")]
        public async Task<ActionResult<RoleProgram>> PutRoleProgram(int id,[FromBody] RoleProgram roleProgram)
        {
            if (id != roleProgram.RoleProgramID)
            {
                return BadRequest();
            }

            _context.Entry(roleProgram).State = EntityState.Modified;

            if (roleProgram.EnableFlag == "N")
            {
                roleProgram.DisableUserId = 0;
                roleProgram.DisableDateTime = DateTime.Now;
            }
            if (roleProgram.EnableFlag == "Y")
            {
                roleProgram.EnableUserId = 0;
                roleProgram.EnableDateTime = DateTime.Now;
                roleProgram.DisableUserId = -1;
                roleProgram.DisableDateTime = DateTime.MinValue;
            }

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RoleProgramExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return roleProgram;
        }

        /// <summary>
        /// 新增角色功能资料
        /// </summary>
        /// <param name="roleProgram"></param>
        /// <returns></returns>
        // POST: api/RolePrograms
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
        [HttpPost]
        public async Task<ActionResult<RoleProgram>> PostRoleProgram([FromBody] RoleProgram roleProgram)
        {
            Helper helper = new Helper(_context);
            roleProgram.RoleProgramID = helper.GetIDKey("ROLE_PROGRAMID").Result;

            _context.RolePrograms.Add(roleProgram);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetRoleProgram", new { id = roleProgram.RoleProgramID }, roleProgram);
        }

        /// <summary>
        /// 删除角色功能资料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // DELETE: api/RolePrograms/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<RoleProgram>> DeleteRoleProgram(int id)
        {
            var roleProgram = await _context.RolePrograms.FindAsync(id);
            if (roleProgram == null)
            {
                return NotFound();
            }

            _context.RolePrograms.Remove(roleProgram);
            await _context.SaveChangesAsync();

            return roleProgram;
        }

        private bool RoleProgramExists(int id)
        {
            return _context.RolePrograms.Any(e => e.RoleProgramID == id);
        }
    }
}