using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using AMESCoreStudio.WebApi.Models.AMES;
using AMESCoreStudio.CommonTools.Result;
using AMESCoreStudio.WebApi.DTO.AMES;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace AMESCoreStudio.WebApi.Controllers.AMES
{
    [Route("api/[controller]")]
    [ApiController]
    public class WipRuleController : ControllerBase
    {
        private readonly AMESContext _context;

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

        /// <summary>
        /// 工單投產纪錄資料文件
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<IEnumerable<WipRule>>> GetWipRule()
        {
            IQueryable<WipRule> q = _context.WipRules;
            q = q.OrderBy(p => p.WipNO);
            var WipRule = await q.ToListAsync();
            return WipRule;
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<WipRule>> GetWipRule(string id)
        {
            IQueryable<WipRule> q = _context.WipRules;

            var WipRule = await q.Where(p => p.WipNO == id).FirstOrDefaultAsync();

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

            return WipRule;
        }

        ///// <summary>
        ///// SOP文件查詢
        ///// </summary>
        ///// <param name="itemNo">料號</param>
        ///// <param name="unitNo">生產單位</param>
        ///// <param name="fileName">檔案名稱</param>
        ///// <param name="state">狀態</param>
        ///// <param name="date_str">建立日期起</param>
        ///// <param name="date_end">建立日期迄</param>
        ///// <returns></returns>
        //[Route("[action]")]
        //[HttpGet]
        //public async Task<ResultModel<WipRuleDto>> GetWipRuleQuery(string itemNo = null, string unitNo = null
        //    , string fileName = null, string state = null, string date_str = null, string date_end = null)
        //{
        //    IQueryable<WipRule> q = _context.WipRules;

        //    if (!string.IsNullOrWhiteSpace(itemNo))
        //        q = q.Where(w => w.ItemNo == itemNo);

        //    if (!string.IsNullOrWhiteSpace(unitNo))
        //        q = q.Where(w => w.UnitNo == unitNo);

        //    if (!string.IsNullOrWhiteSpace(fileName))
        //        q = q.Where(w => w.FileName.Contains(fileName));

        //    if (!string.IsNullOrWhiteSpace(state))
        //        q = q.Where(w => w.State == state);


        //    DateTime dateValue;
        //    if (DateTime.TryParse(date_str, out dateValue))
        //    {
        //        q = q.Where(w => w.CreateDate >= DateTime.Parse(date_str));
        //    }

        //    if (DateTime.TryParse(date_end, out dateValue))
        //    {
        //        q = q.Where(w => w.CreateDate <= DateTime.Parse(date_end));
        //    }

        //    ResultModel<WipRuleDto> result = new ResultModel<WipRuleDto>();
        //    result.Data = await q.Select(s => new WipRuleDto
        //    {
        //        WipRuleID = s.WipRuleID,
        //        ItemNo = s.ItemNo,
        //        UnitName = s.FactoryUnit.UnitName,
        //        FileName = s.FileName,
        //        FilePath = s.FilePath,
        //        State = s.State == "Y" ? "使用中" : "停用",
        //        NewName = s.NewName,
        //        CreateDate = s.CreateDate,
        //        CreateUserID = s.CreateUserID,
        //        UpdateDate = s.UpdateDate,
        //        UpdateUserID = s.UpdateUserID
        //    }).ToListAsync();

        //    return result;
        //}

        [HttpPost]
        public async Task<ResultModel<WipRule>> PostWipRule([FromBody] WipRule WipRule)
        {
            ResultModel<WipRule> result = new ResultModel<WipRule>();
            _context.WipRules.Add(WipRule);
            try
            {
                await _context.SaveChangesAsync();
                result.Success = true;
                result.Msg = "OK";
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Msg = ex.InnerException.Message;
            }
            return result;
        }

        // PUT api/<WipRuleController>/5
        [HttpPut("{id}")]
        public async Task<ResultModel<WipRule>> PutWipRule(string id)
        {
            ResultModel<WipRule> result = new ResultModel<WipRule>();
            var WipRule = new WipRule {
                WipNO = id
           
            };
            _context.Attach(WipRule);

            // 指定更新某個欄位

            //_context.Entry(WipRule).Property(p => p.UpdateDate).IsModified = true;

            try
            {
                await _context.SaveChangesAsync();
                result.Success = true;
                result.Msg = "OK";
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Msg = ex.InnerException.Message;
            }
            return result;
        }

        // DELETE api/<WipRuleController>/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}