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.AMES;
using AMESCoreStudio.CommonTools.Result;

namespace AMESCoreStudio.WebApi.Controllers.AMES
{
    /// <summary>
    /// 不良現象原因代碼維護
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class NGReasonsController : ControllerBase
    {
        private readonly AMESContext _context;

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

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        // GET: api/NGReasons
        [HttpGet]
        public async Task<ActionResult<IEnumerable<NGReason>>> GetNGReason()
        {
            IQueryable<NGReason> q = _context.NGReasons;
            q = q.OrderBy(p => p.NGClassNo + p.NGReasonNo);

            var ngReason = await q.ToListAsync();

            return ngReason;
        }

        /// <summary>
        /// 根据不良現象類別代碼NO獲取該類別不良現象原因代碼資料
        /// </summary>
        /// <param name="no"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        // GET: api/NGReasons/Class/S
        [HttpGet("Class/{no}")]
        public async Task<ResultModel<NGReason>> GetNGReasonByClass(string no, int page = 0, int limit = 10)
        {
            ResultModel<NGReason> result = new ResultModel<NGReason>();

            IQueryable<NGReason> q = _context.NGReasons;

            if (no != null)
            {
                if (no != "*")
                {
                    q = q.Where(p => p.NGClassNo.Equals(no));
                }
            }

            result.DataTotal = q.ToList().Count;

            if (page > 0)
            {
                q = q.OrderBy(p => p.NGClassNo + p.NGReasonNo).Skip((page - 1) * limit).Take(limit);
            }
            else
            {
                q = q.OrderBy(p => p.NGClassNo + p.NGReasonNo);
            }
            
            var ngReason = await q.ToListAsync();

            result.Data = ngReason;

            if (ngReason.Count == 0)
            {
                result.Msg = "查無資料";
                result.Success = false;
                return result;
            }

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

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET: api/NGReasons/5
        [HttpGet("{id}")]
        public async Task<ActionResult<IEnumerable<NGReason>>> GetNGReason(string id)
        {
            IQueryable<NGReason> q = _context.NGReasons;
            q = q.Where(p => p.NGReasonNo.Equals(id));

            var ngReason = await q.ToListAsync();

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

            return ngReason;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="nGReason"></param>
        /// <returns></returns>
        // PUT: api/NGReasons/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<NGReason>> PutNGReason(string id, [FromBody] NGReason nGReason)
        {
            ResultModel<NGReason> result = new ResultModel<NGReason>();

            if (id != nGReason.NGReasonNo)
            {
                result.Success = false;
                result.Msg = "原因代碼錯誤";
                return result;
            }

            _context.NGReasons.Attach(nGReason);
            //_context.Entry(nGReason).State = EntityState.Modified;
            _context.Entry(nGReason).Property(p => p.NGReasonDesc).IsModified = true;
            _context.Entry(nGReason).Property(p => p.NGReasonDescEn).IsModified = true;
            _context.Entry(nGReason).Property(p => p.ResponseDept).IsModified = true;
            _context.Entry(nGReason).Property(p => p.Status).IsModified = true;
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!NGReasonExists(id))
                {
                    result.Success = false;
                    result.Msg = "原因代碼不存在";
                    return result;
                }
                else
                {
                    throw;
                }
            }

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

        /// <summary>
        /// 更新不良現象原因狀態
        /// </summary>
        /// <param name="id"></param>
        /// <param name="statusno"></param>
        /// <returns></returns>
        // PUT: api/RuleStations/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}/{statusno}")]
        public async Task<ResultModel<NGReason>> PutNGReasonStatus(string id, string statusno = null)
        {
            ResultModel<NGReason> result = new ResultModel<NGReason>();

            var ngReason = await _context.NGReasons.FindAsync(id);
            if (ngReason == null)
            {
                result.Success = false;
                result.Msg = "原因代碼不存在";
                return result;
            }

            ngReason.Status = statusno;

            _context.NGReasons.Attach(ngReason);

            // 指定更新某個欄位
            _context.Entry(ngReason).Property(p => p.Status).IsModified = true;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!NGReasonExists(id))
                {
                    result.Success = false;
                    result.Msg = "原因代碼不存在";
                    return result;
                }
                else
                {
                    throw;
                }
            }

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

        /// <summary>
        /// 
        /// </summary>
        /// <param name="nGReason"></param>
        /// <returns></returns>
        // POST: api/NGReasons
        // 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<NGReason>> PostNGReason([FromBody] NGReason nGReason)
        {
            ResultModel<NGReason> result = new ResultModel<NGReason>();

            _context.NGReasons.Add(nGReason);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (NGReasonExists(nGReason.NGReasonNo))
                {
                    result.Success = false;
                    result.Msg = "原因代碼重複";
                    return result;
                }
                else
                {
                    throw;
                }
            }

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

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // DELETE: api/NGReasons/5
        [HttpDelete("{id}")]
        public async Task<ResultModel<NGReason>> DeleteNGReason(string id)
        {
            ResultModel<NGReason> result = new ResultModel<NGReason>();

            var nGReason = await _context.NGReasons.FindAsync(id);
            if (nGReason == null)
            {
                result.Success = false;
                result.Msg = "原因代碼不存在";
                return result;
            }

            _context.NGReasons.Remove(nGReason);
            await _context.SaveChangesAsync();

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

        private bool NGReasonExists(string id)
        {
            return _context.NGReasons.Any(e => e.NGReasonNo == id);
        }
    }
}