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

namespace AMESCoreStudio.WebApi.Controllers.SYS
{
    /// <summary>
    /// 部門資料維護
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class DeptInfoesController : ControllerBase
    {
        private readonly AMESContext _context;

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

        /// <summary>
        /// 获取部门资料
        /// </summary>
        /// <returns></returns>
        // GET: api/DeptInfoes
        [HttpGet]
        public async Task<ActionResult<IEnumerable<DeptInfo>>> GetDeptInfo()
        {
            IQueryable<DeptInfo> q = _context.DeptInfoes;
            q = q.Where(p => p.DeptID > 0);
            q = q.OrderBy(p => p.DeptNo);

            var deptInfo = await q.ToListAsync();
            return deptInfo;

            //return await _context.DeptInfoes.ToListAsync();
        }

        /// <summary>
        /// 根据ID查询部门资料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET: api/DeptInfoes/5
        [HttpGet("{id}")]
        public async Task<ActionResult<IEnumerable<DeptInfo>>> GetDeptInfo(int id)
        {
            //var deptInfo = await _context.DeptInfoes.FindAsync(id);

            IQueryable<DeptInfo> q = _context.DeptInfoes;
            q = q.Where(p => p.DeptID.Equals(id));

            var deptInfo = await q.ToListAsync();

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

            return deptInfo;
        }

        /// <summary>
        /// 修改部门资料
        /// </summary>
        /// <param name="id"></param>
        /// <param name="deptInfo"></param>
        /// <returns></returns>
        // PUT: api/DeptInfoes/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<ResultModel<DeptInfo>> PutDeptInfo(int id, [FromBody] DeptInfo deptInfo)
        {
            ResultModel<DeptInfo> result = new ResultModel<DeptInfo>();

            if (id != deptInfo.DeptID)
            {
                result.Msg = "部門編號錯誤";
                result.Success = false;
                return result;
            }

            _context.Entry(deptInfo).State = EntityState.Modified;
            deptInfo.UpdateUserId = 0;
            deptInfo.UpdateDateTime = DateTime.Now;
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!DeptInfoExists(id))
                {
                    result.Msg = "部門編號不存在";
                    result.Success = false;
                    return result;
                }
                else
                {
                    throw;
                }
            }

            result.Msg = "OK";
            result.Success = true;
            return result;
        }

        /// <summary>
        /// 新增部门资料
        /// </summary>
        /// <param name="deptInfo"></param>
        /// <returns></returns>
        // POST: api/DeptInfoes
        // 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<ResultModel<DeptInfo>> PostDeptInfo([FromBody] DeptInfo deptInfo)
        {
            ResultModel<DeptInfo> result = new ResultModel<DeptInfo>();

            Helper helper = new Helper(_context);
            deptInfo.DeptID = helper.GetIDKey("DEPT_ID").Result;

            deptInfo.CreateUserId = 0;
            deptInfo.CreateDateTime = DateTime.Now;

            _context.DeptInfoes.Add(deptInfo);
            await _context.SaveChangesAsync();

            result.Msg = "OK";
            result.Success = true;
            return result;
        }

        /// <summary>
        /// 刪除部門資料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // DELETE: api/DeptInfoes/5
        [HttpDelete("{id}")]
        public async Task<ResultModel<DeptInfo>> DeleteDeptInfo(int id)
        {
            ResultModel<DeptInfo> result = new ResultModel<DeptInfo>();

            var deptInfo = await _context.DeptInfoes.Where(m => m.DeptID == id).FirstOrDefaultAsync();

            if (deptInfo == null)
            {
                result.Msg = "部門編號不存在";
                result.Success = false;
                return result;
            }

            _context.DeptInfoes.Remove(deptInfo);
            await _context.SaveChangesAsync();

            result.Msg = "OK";
            result.Success = true;
            return result;
        }

        private bool DeptInfoExists(int id)
        {
            return _context.DeptInfoes.Any(e => e.DeptID == id);
        }
    }
}