using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
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 WipBarcodeOtherController : Controller
    {
        private readonly AMESContext _context;

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

        /// <summary>
        /// 獲取產品別資料
        /// </summary>
        /// <returns></returns>
        // GET: api/SystemInfoes
        [HttpGet]
        public async Task<ActionResult<IEnumerable<WipBarcodeOther>>> GetWipBarcodeOther()
        {
            IQueryable<WipBarcodeOther> q = _context.WipBarcodeOthers;

            q = q.OrderBy(p => p.OtherID);

            //q = q.OrderByDescending(p => p.SystemID);

            var wipBarcodeOther = await q.ToListAsync();

            //return await _context.SystemInfoes.ToListAsync();

            return wipBarcodeOther;
        }

        [HttpGet("WipNo/{id}")]
        public async Task<ActionResult<WipBarcodeOther>> GetWipBarcodeOtherByWipNo(string id)
        {
            IQueryable<WipBarcodeOther> q = _context.WipBarcodeOthers;

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

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

            return wipBarcodeOther;
        }

        /// <summary>
        /// 查詢客戶區間
        /// </summary>
        /// <param name="wipNO">工單號碼</param>
        /// <param name="No">序號</param>
        /// <returns></returns>
        [HttpGet("ByNo")]
        public async Task<ActionResult<IEnumerable<WipBarcodeOther>>> CheckWipBarcodeOtherByNo(string wipNO, string No)
        {
            var wipBarcodeOther = _context.WipBarcodeOthers
                .FromSqlInterpolated($" SELECT * FROM JHAMES.WIP_BARCODE_OTHER WHERE {No} BETWEEN START_NO AND END_NO AND length(START_NO) = length({No}) ")                 
                .AsNoTracking().ToList();

            wipBarcodeOther = wipBarcodeOther.Where(W => W.WipNO == wipNO).ToList();

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

            return wipBarcodeOther;
        }

        /// <summary>
        /// 確認是否有重複出貨序號區間
        /// </summary>
        /// <param name="startNo">起始出貨條碼/param>
        /// <param name="endNo">結束出貨條碼</param>
        /// <returns></returns>
        [HttpGet("CheckRepeat")]
        public ActionResult<IEnumerable<WipBarcodeOther>> CheckWipBarcodeOtherRepeat(string startNo, string endNo)
        {
            var wipBarcodeOther = _context.WipBarcodeOthers
                .FromSqlInterpolated($@" SELECT * FROM JHAMES.WIP_BARCODE_OTHER WHERE {startNo} BETWEEN START_NO AND END_NO
                                      OR {endNo} BETWEEN START_NO AND END_NO ").AsNoTracking().ToList();

            return wipBarcodeOther;
        }

        /// <summary>
        /// 新增工單出貨條碼區間設定檔
        /// </summary>
        /// <param name="wipBarcodeOther"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultModel<WipBarcodeOther>> PostWipBarcodeOther([FromBody] WipBarcodeOther wipBarcodeOther)
        {
            ResultModel<WipBarcodeOther> result = new ResultModel<WipBarcodeOther>();
            Helper helper = new Helper(_context);
            wipBarcodeOther.OtherID = helper.GetIDKey("OTHER_ID").Result;

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

        /// <summary>
        /// 更新工單出貨條碼區間設定檔
        /// </summary>
        /// <param name="wipBarcodeOther"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ResultModel<WipBarcodeOther>> PutWipBarcodeOther(WipBarcodeOther wipBarcodeOther)
        {
            ResultModel<WipBarcodeOther> result = new ResultModel<WipBarcodeOther>();
            var wipNo = wipBarcodeOther.WipNO;
            try
            {
                var result_old = _context.WipBarcodeOthers.Where(w => w.WipNO == wipNo).Select(s =>s.OtherID).ToList();
                if (result_old.Count != 0)
                {
                    _context.Entry(wipBarcodeOther).State = EntityState.Modified;
                    _context.Entry<WipBarcodeOther>(wipBarcodeOther).Property("CreateDate").IsModified = false;
                    _context.Entry<WipBarcodeOther>(wipBarcodeOther).Property("CreateUserID").IsModified = false;
                }
                else
                {
                    _context.WipBarcodeOthers.Add(wipBarcodeOther);
                }
                await _context.SaveChangesAsync();
                result.Success = true;
                result.Msg = "OK";
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Msg = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 刪除工單出貨條碼區間
        /// </summary>
        /// <param name="id">工單號碼</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ResultModel<WipBarcodeOther>> DeleteWipBarcodeOther(string id)
        {
            ResultModel<WipBarcodeOther> result = new ResultModel<WipBarcodeOther>();
            var wipBarcodeOther = await _context.WipBarcodeOthers.Where(w => w.WipNO.Trim().ToUpper() == id.ToUpper().Trim()).FirstOrDefaultAsync();
            try
            {
                if (wipBarcodeOther != null)
                {
                    _context.WipBarcodeOthers.Remove(wipBarcodeOther);
                    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;
        }
    }
}