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;


namespace AMESCoreStudio.WebApi.Controllers.AMES
{
    /// <summary>
    /// 工單製程對應SOP資料檔
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class WipSopController : ControllerBase
    {
        private readonly AMESContext _context;

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

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

        [HttpGet("{id}")]
        public async Task<ActionResult<WipSop>> GetWipSop(int id)
        {
            IQueryable<WipSop> q = _context.WipSops;

            var WipSop = await q.Where(p => p.WipSOPID == id).FirstOrDefaultAsync();

            //if (WipSopLog == null)
            //{
            //    return NotFound();
            //}

            return WipSop;
        }


        /// <summary>
        /// ByWipNo 
        /// </summary>
        /// <param name="id">工單號碼</param>
        /// <returns></returns>
        [HttpGet("ByWipNo/{id}")]
        public async Task<ActionResult<IEnumerable<WipSopDto>>> GetWipSopByWipNo(string id)
        {
            var q = from q1 in _context.WipSops.Where(w => w.WipNo == id)
                    join q2 in _context.FactoryUnits on q1.UnitNo equals q2.UnitNo
                    select new WipSopDto
                    {
                        WipSOPID = q1.WipSOPID,
                        WipNo = q1.WipNo,
                        ItemNo = q1.ItemNo,
                        SOPName = q1.SOPName,
                        SOPPath = q1.SOPPath,
                        SOPType = q1.SOPType,
                        UnitNo = q1.UnitNo,
                        SOPVer = q1.SOPVer,
                        UnitNoName = q2.UnitName,
                        UpdateTime = q1.UpdateDate
                    };

            var result = await q.ToListAsync();
            result.Select(s => s.SOPTypeName
           = Enum.EnumPCS.GetDisplayName((Enum.EnumPCS.EnumWipSopType)System.Enum.Parse(typeof(Enum.EnumPCS.EnumWipSopType), s.SOPType))).ToList();

            return result;
        }

        /// <summary>
        /// 查詢是否有紀錄SOP版本
        /// </summary>
        /// <param name="wipNo">工單號碼</param>
        /// <param name="itemNo">料號</param>
        /// <param name="sopName">SOP文號</param>
        /// <returns></returns>
        [HttpGet("SelectSopVer")]
        public async Task<ResultModel<WipSop>> GetWipSopForSopVer(string wipNo = "", string itemNo = "", string sopName = "")
        {
            ResultModel<WipSop> result = new ResultModel<WipSop>();
            IQueryable<WipSop> q = _context.WipSops.Where(w => w.WipNo.Trim().ToUpper() == wipNo.Trim().ToUpper() &&
                                                               w.ItemNo.Trim().ToUpper() == itemNo.Trim().ToUpper() &&
                                                               w.SOPName.Trim().ToUpper() == sopName.Trim().ToUpper() &&
                                                               w.SOPType == "A" && !string.IsNullOrWhiteSpace(w.SOPVer));
            var query = await q.ToListAsync();
            try
            {
                if (query.Count() == 0)
                {
                    result.Msg = "N";
                }
                else
                {
                    result.Msg = "Y";
                }

                result.Success = true;
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Msg = ex.InnerException.Message;
            }
            return result;
        }

        /// <summary>
        /// 新增工單製程對應SOP資料檔
        /// </summary>
        /// <param name="wipSop"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultModel<WipSop>> PostWipSop([FromBody] WipSop wipSop)
        {
            ResultModel<WipSop> result = new ResultModel<WipSop>();
            Helper helper = new Helper(_context);
            wipSop.WipSOPID = helper.GetIDKey("WIP_SOP_ID").Result;
            _context.WipSops.Add(wipSop);
            try
            {
                await _context.SaveChangesAsync();
                result.Success = true;
                result.Msg = "OK";
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Msg = ex.InnerException.Message;
            }
            return result;
        }

        /// <summary>
        /// 更新工單製程對應SOP資料檔
        /// </summary>
        /// <param name="wipSop"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ResultModel<WipSop>> PutWipSop(WipSop wipSop)
        {
            ResultModel<WipSop> result = new ResultModel<WipSop>();
            _context.Entry(wipSop).State = EntityState.Modified;
            //設置容器空間某一個模型的某一個欄位 不提交到資料庫
            //DbContent.Entry是要更新到資料庫的整個對象
            _context.Entry<WipSop>(wipSop).Property("CreateDate").IsModified = false;
            _context.Entry<WipSop>(wipSop).Property("CreateUserID").IsModified = false;
            wipSop.UpdateDate = DateTime.Now;
            try
            {
                await _context.SaveChangesAsync();
                result.Success = true;
                result.Msg = "OK";
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Msg = ex.InnerException.Message;

            }
            return result;
        }

        /// <summary>
        /// 刪除工單製程對應SOP資料檔
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ResultModel<WipSop>> DeleteWipSop(int id)
        {
            ResultModel<WipSop> result = new ResultModel<WipSop>();
            var wipSop = await _context.WipSops.FindAsync(id);

            try
            {
                if (wipSop != null)
                {
                    _context.WipSops.Remove(wipSop);
                    await _context.SaveChangesAsync();
                    result.Success = true;
                    result.Msg = "OK";
                }
                else
                {
                    result.Success = true;
                    result.Msg = "找不到資料刪除";
                }
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Msg = ex.InnerException.Message;
            }
            return result;
        }
    }
}