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

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

        /// <summary>
        /// 獲取全部清線資料
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        // GET: api/WipClears
        [HttpGet]
        public async Task<ResultModel<dynamic>> GetWipClear(int page = 0, int limit = 10)
        {
            ResultModel<dynamic> result = new ResultModel<dynamic>();

            var q = from a in _context.WipClears
                    join b in _context.WipInfos on a.WipID equals b.WipID
                    join c in _context.WipAtts on b.WipNO equals c.WipNO
                    select new 
                    {
                        a.ClearID,
                        a.ClearNo,
                        a.WipID,
                        b.WipNO,
                        b.WerksNO,
                        b.PlanQTY,
                        c.ModelNO,
                        a.DetailQty,
                        a.HeadmanCheckFlag,
                        a.DirectorCheckFlag,
                        a.DirectorCheckDate,
                        a.ClearDesc
                    };

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

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

            var wipClear = await q.ToListAsync();

            result.Data = wipClear;

            if (wipClear == 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/WipClears/5
        [HttpGet("{id}")]
        public async Task<ActionResult<IEnumerable<WipClear>>> GetWipClear(int id)
        {
            IQueryable<WipClear> q = _context.WipClears;
            q = q.Where(p => p.ClearID.Equals(id));

            var wipClear = await q.ToListAsync();

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

            return wipClear;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="wipClear"></param>
        /// <returns></returns>
        // PUT: api/WipClears/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<WipClear>> PutWipClear(int id, WipClear wipClear)
        {
            ResultModel<WipClear> result = new ResultModel<WipClear>();

            if (id != wipClear.ClearID)
            {
                result.Success = false;
                result.Msg = "清線編號錯誤";
                return result;
            }

            _context.Entry(wipClear).State = EntityState.Modified;
            if (wipClear.HeadmanCheckFlag != null && wipClear.HeadmanCheckFlag == "Y")
            {
                if (wipClear.HeadmanCheckDate.ToString("yyyyMMdd") == "00010101")
                {
                    wipClear.HeadmanCheckDate = DateTime.Now;
                    _context.Entry(wipClear).Property(p => p.HeadmanCheckDate).IsModified = true;
                }
                else
                {
                    _context.Entry(wipClear).Property(p => p.HeadmanCheckDate).IsModified = false;
                }
            }
            if (wipClear.DirectorCheckFlag != null && wipClear.DirectorCheckFlag == "Y")
            {
                if (wipClear.DirectorCheckDate.ToString("yyyyMMdd") == "00010101")
                {
                    wipClear.DirectorCheckDate = DateTime.Now;
                    _context.Entry(wipClear).Property(p => p.DirectorCheckDate).IsModified = true;
                }
                else
                {
                    _context.Entry(wipClear).Property(p => p.DirectorCheckDate).IsModified = false;
                }
            }


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

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

        /// <summary>
        /// 
        /// </summary>
        /// <param name="wipClear"></param>
        /// <returns></returns>
        // POST: api/WipClears
        // 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<WipClear>> PostWipClear(WipClear wipClear)
        {
            ResultModel<WipClear> result = new ResultModel<WipClear>();

            Helper helper = new Helper(_context);
            int clearID = helper.GetIDKey("CLEAR_ID").Result;
            wipClear.ClearID = clearID;
            wipClear.ClearNo = DateTime.Now.ToString("yyMM") + clearID.ToString().PadLeft(8, '0');

            _context.WipClears.Add(wipClear);
            await _context.SaveChangesAsync();

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

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

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

            _context.WipClears.Remove(wipClear);
            await _context.SaveChangesAsync();

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

        private bool WipClearExists(int id)
        {
            return _context.WipClears.Any(e => e.ClearID == id);
        }
    }
}