using System.Collections.Generic;
using System.Linq;
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using AMESCoreStudio.WebApi.Models.AMES;
using AMESCoreStudio.CommonTools.Result;
using AMESCoreStudio.WebApi.DTO.AMES;

namespace AMESCoreStudio.WebApi.Controllers.AMES
{
    /// <summary>
    /// 條碼鎖定資料表
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class BarcodeLockController : ControllerBase
    {
        private readonly AMESContext _context;

        public BarcodeLockController(AMESContext context)
        {
            _context = context;
        }

        // GET: api/BarcodeLock
        [HttpGet]
        public async Task<ActionResult<IEnumerable<BarcodeLock>>> GetBarcodeLock()
        {
            return await _context.BarcodeLocks.ToListAsync();
        }

        // GET: api/BarcodeLock/5
        [HttpGet("{id}")]
        public async Task<ActionResult<BarcodeLock>> GetBarcodeLock(int id)
        {
            var barcodeLock = await _context.BarcodeLocks.FindAsync(id);

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

            return barcodeLock;
        }

        /// <summary>
        /// 條碼鎖定資料表 by BarCodeID
        /// </summary>
        /// <param name="id">BarCodeID</param>
        /// <returns></returns>
        // GET: api/BarcodeLock/5
        [HttpGet("BarCodeID/{id}")]
        public async Task<ActionResult<IEnumerable<BarcodeLock>>> GetBarcodeLockByBarCodeID(int id)
        {

            IQueryable<BarcodeLock> q = _context.BarcodeLocks;
            q = q.Where(p => p.BarcodeID.Equals(id));
            var barcodelock = await q.ToListAsync();

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

            return barcodelock;
        }

        /// <summary>
        /// 鎖定條碼資料查詢
        /// </summary>
        /// <param name="barCodeNo">內部條碼</param>
        /// <param name="wipNo">工單</param>
        /// <param name="lockStatus">條碼鎖定狀態</param>
        /// <param name="itemNo">料號</param>
        /// <param name="date_str">鎖定日期起</param>
        /// <param name="date_end">鎖定日期迄</param>
        /// <returns></returns>
        [HttpGet("GetBarcodeLockQuery")]
        public async Task<ResultModel<BarcodeLockDto>> GetBarcodeLockQuery(string barCodeNo, string wipNo, string lockStatus
            , string itemNo, string date_Str = null, string date_End = null, int page = 0, int limit = 10)
        {
            IQueryable<BarcodeLockDto> q = from s in _context.BarcodeLocks
                                           join q2 in _context.UserInfoes on s.LockUserID equals q2.UserID into cp2
                                           from q2 in cp2.DefaultIfEmpty()
                                           join q3 in _context.UserInfoes on s.UnLockUserID equals q3.UserID into cp3
                                           from q3 in cp3.DefaultIfEmpty()
                                           select new BarcodeLockDto
                                           {
                                               BarCodeLockID = s.BarcodeLockID,
                                               BarCodeNo = s.GetBarcodeInfo.BarcodeNo,
                                               WipNO = s.GetBarcodeInfo.GetWipInfo.WipNO,
                                               ItemNO = s.GetBarcodeInfo.GetWipInfo.GetWipAtt.ItemNO,
                                               LockDate = s.LockDate,
                                               UnLockDate = s.UnLockDate,
                                               LockUserID = s.LockUserID,
                                               LockUserName = q2.UserName,
                                               LockReason = s.LockReason,
                                               LockStatus = s.LockStatus == 0 ? "鎖定" : "解鎖",
                                               UnLockUserID = s.UnLockUserID,
                                               UnLockUserName = q3.UserName,
                                               UnLockReason = s.UnLockReason
                                           };


            if (!string.IsNullOrWhiteSpace(barCodeNo))
                q = q.Where(w => w.BarCodeNo == barCodeNo);

            if (!string.IsNullOrWhiteSpace(wipNo))
                q = q.Where(w => w.WipNO == wipNo);

            if (!string.IsNullOrWhiteSpace(lockStatus))
            {
                var LockStatusName = lockStatus == "0" ? "鎖定" : "解鎖";
                q = q.Where(w => w.LockStatus == LockStatusName);
            }
            if (!string.IsNullOrWhiteSpace(itemNo))
                q = q.Where(w => w.ItemNO == itemNo);

            if (DateTime.TryParse(date_Str, out _))
            {
                q = q.Where(w => w.LockDate >= DateTime.Parse(date_Str));
            }

            if (DateTime.TryParse(date_End, out _))
            {
                q = q.Where(w => w.LockDate <= DateTime.Parse(date_End));
            }

            ResultModel<BarcodeLockDto> result = new ResultModel<BarcodeLockDto>();

            // 紀錄筆數
            result.DataTotal = q.Count();

            // Table 頁數
            if (page > 0)
            {
                q = q.Skip((page - 1) * limit).Take(limit);
            }

            result.Data = await q.ToListAsync();
            return result;
        }


        [HttpPut]
        public async Task<ResultModel<BarcodeLock>> PutBarcodeLock(BarcodeLock barcodeLock)
        {

            ResultModel<BarcodeLock> result = new ResultModel<BarcodeLock>();
            _context.Entry(barcodeLock).State = EntityState.Modified;
            //設置容器空間某一個模型的某一個欄位 不提交到資料庫
            _context.Entry<BarcodeLock>(barcodeLock).Property("UnLockReason").IsModified = true;
            _context.Entry<BarcodeLock>(barcodeLock).Property("UnLockUserID").IsModified = true;
            _context.Entry<BarcodeLock>(barcodeLock).Property("UnLockDate").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;
        }


        [HttpPost]
        public async Task<ResultModel<BarcodeLock>> PostBarcodeLock(BarcodeLock barcodeLock)
        {
            ResultModel<BarcodeLock> result = new ResultModel<BarcodeLock>();
            Helper helper = new Helper(_context);
            barcodeLock.BarcodeLockID = helper.GetIDKey("BARCODE_LOCK_ID").Result;
            _context.BarcodeLocks.Add(barcodeLock);

            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/BarcodeLock/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<BarcodeLock>> DeleteBarcodeLock(decimal id)
        {
            var barcodeLock = await _context.BarcodeLocks.FindAsync(id);
            if (barcodeLock == null)
            {
                return NotFound();
            }

            _context.BarcodeLocks.Remove(barcodeLock);
            await _context.SaveChangesAsync();

            return barcodeLock;
        }

        private bool BarcodeLockExists(decimal id)
        {
            return _context.BarcodeLocks.Any(e => e.BarcodeLockID == id);
        }
    }
}