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 WipClearDetailsController : ControllerBase
    {
        private readonly AMESContext _context;

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

        /// <summary>
        /// 根據清線ID查詢全部明細資料
        /// </summary>
        /// <param name="id"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        // GET: api/WipClearDetails/Clear/1
        [HttpGet("Clear/{id}")]
        public async Task<ResultModel<dynamic>> GetWipClearDetailByClear(int id, int page = 0, int limit = 10)
        {
            ResultModel<dynamic> result = new ResultModel<dynamic>();

            var q = from a in _context.WipClearDetails
                    join b in _context.Stationses on a.StationID equals b.StationID
                    select new
                    {
                        a.ClearID,
                        a.ClearDetailID,
                        a.StationID,
                        b.StationName,
                        a.SurplusFlag,
                        a.PartNo,
                        a.Qty,
                        a.ReasonDesc,
                        a.CheckUser
                    };

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

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

            if (page > 0)
            {
                q = q.OrderBy(p => p.ClearDetailID).Skip((page - 1) * limit).Take(limit);
            }
            else
            {
                q = q.OrderBy(p => p.ClearDetailID);
            }

            var wipClearDetail = await q.ToListAsync();

            result.Data = wipClearDetail;

            if (wipClearDetail == null)
            {
                result.Success = false;
                result.Msg = "查无资料";
                return result;
            }

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

        /// <summary>
        /// 根據清線明細ID查詢指定資料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET: api/WipClearDetails/5
        [HttpGet("{id}")]
        public async Task<ActionResult<IEnumerable<WipClearDetail>>> GetWipClearDetail(int id)
        {
            IQueryable<WipClearDetail> q = _context.WipClearDetails;
            q = q.Where(p => p.ClearDetailID.Equals(id));

            var wipClearDetail = await q.ToListAsync();

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

            return wipClearDetail;
        }

        /// <summary>
        /// 根據清線明細ID修改指定資料
        /// </summary>
        /// <param name="id"></param>
        /// <param name="wipClearDetail"></param>
        /// <returns></returns>
        // PUT: api/WipClearDetails/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<WipClearDetail>> PutWipClearDetail(int id, WipClearDetail wipClearDetail)
        {
            ResultModel<WipClearDetail> result = new ResultModel<WipClearDetail>();

            if (id != wipClearDetail.ClearDetailID)
            {
                result.Success = false;
                result.Msg = "清線明細編號錯誤";
                return result;
            }

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

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!WipClearDetailExists(id))
                {
                    result.Success = false;
                    result.Msg = "清線明細編號不存在";
                    return result;
                }
                else
                {
                    throw;
                }
            }

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

        /// <summary>
        /// 
        /// </summary>
        /// <param name="wipClearDetail"></param>
        /// <returns></returns>
        // POST: api/WipClearDetails
        // 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<WipClearDetail>> PostWipClearDetail(WipClearDetail wipClearDetail)
        {
            ResultModel<WipClearDetail> result = new ResultModel<WipClearDetail>();

            Helper helper = new Helper(_context);
            int detailID = helper.GetIDKey("CLEAR_DETAILID").Result;
            wipClearDetail.ClearDetailID = detailID;

            _context.WipClearDetails.Add(wipClearDetail);

            //更新wip_clear
            var wipClear = await _context.WipClears.FindAsync(wipClearDetail.ClearID);
            if(wipClear!=null)
            {
                wipClear.DetailQty = wipClear.DetailQty + 1;
                _context.WipClears.Attach(wipClear);

                _context.Entry(wipClear).Property(p => p.DetailQty).IsModified = true;
            }

            await _context.SaveChangesAsync();

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

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // DELETE: api/WipClearDetails/5
        [HttpDelete("{id}")]
        public async Task<ResultModel<WipClearDetail>> DeleteWipClearDetail(int id)
        {
            ResultModel<WipClearDetail> result = new ResultModel<WipClearDetail>();

            var wipClearDetail = await _context.WipClearDetails.FindAsync(id);
            if (wipClearDetail == null)
            {
                result.Success = false;
                result.Msg = "清線明細編號不存在";
                return result;
            }

            _context.WipClearDetails.Remove(wipClearDetail);

            //更新wip_clear
            var wipClear = await _context.WipClears.FindAsync(wipClearDetail.ClearID);
            if (wipClear != null)
            {
                wipClear.DetailQty = wipClear.DetailQty - 1;
                _context.WipClears.Attach(wipClear);

                _context.Entry(wipClear).Property(p => p.DetailQty).IsModified = true;
            }

            await _context.SaveChangesAsync();

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

        private bool WipClearDetailExists(int id)
        {
            return _context.WipClearDetails.Any(e => e.ClearDetailID == id);
        }
    }
}