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

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

        /// <summary>
        /// 獲取全部報廢轉出資料
        /// </summary>
        /// <returns></returns>
        // GET: api/BarcodeQngInfoes
        [HttpGet]
        public async Task<ActionResult<IEnumerable<BarcodeQngInfo>>> GetBarcodeQngInfo(int page = 0, int limit = 10)
        {
            IQueryable<BarcodeQngInfo> q = _context.BarcodeQngInfos;
            if (page > 0)
            {
                q = q.OrderBy(p => p.QngID).Skip((page - 1) * limit).Take(limit);
            }
            else
            {
                q = q.OrderBy(p => p.QngID);
            }
            var barcodeQngInfo = await q.ToListAsync();

            return barcodeQngInfo;
        }

        /// <summary>
        /// 根據ID獲取單一報廢轉出資料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET: api/BarcodeQngInfoes/5
        [HttpGet("{id}")]
        public async Task<ActionResult<IEnumerable<BarcodeQngInfo>>> GetBarcodeQngInfo(int id)
        {
            IQueryable<BarcodeQngInfo> q = _context.BarcodeQngInfos;

            q = q.Where(p => p.QngID.Equals(id));

            var barcodeQngInfo = await q.ToListAsync();

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

            return barcodeQngInfo;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="no"></param>
        /// <returns></returns>
        // GET: api/BarcodeQngInfoes/Barcode/S
        [HttpGet("Barcode/{no}")]
        public async Task<ActionResult<IEnumerable<BarcodeQngInfo>>> GetBarcodeQngInfoByBarcode(string no)
        {
            IQueryable<BarcodeInfo> q1 = _context.BarcodeInfoes;

            q1 = q1.Where(p1 => p1.BarcodeNo.Equals(no));

            var barcodeInfo = await q1.ToListAsync();

            int barcodeId = -1;
            if (barcodeInfo.Count > 0)
            {
                barcodeId = barcodeInfo[0].BarcodeID;
            }

            IQueryable<BarcodeQngInfo> q = _context.BarcodeQngInfos;

            q = q.Where(p => p.BarcodeID.Equals(barcodeId));

            var barcodeQngInfo = await q.ToListAsync();

            /*
            foreach (var data in barcodeQngInfo)
            {
                data.OpUser = _context.UserInfoes.Find(data.OperatorID);
                data.IPQAUser = _context.UserInfoes.Find(data.IPQAID);
                data.PEUser = _context.UserInfoes.Find(data.PEID);
                data.ManageUser = _context.UserInfoes.Find(data.ManagerID);
            }
            */

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

            return barcodeQngInfo;
        }

        /// <summary>
        /// ByBarCodeId 查詢 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("BarCodeId/{id}")]
        public async Task<ActionResult<IEnumerable<BarcodeQngInfo>>> GetBarcodeQngInfoByBarCodeId(int id)
        {
           
            IQueryable<BarcodeQngInfo> q = _context.BarcodeQngInfos;
            q = q.Where(p => p.BarcodeID == id);
            var barcodeQngInfo = await q.ToListAsync();
            if (barcodeQngInfo.Any())
            {
                Helper helper = new Helper(_context);
                barcodeQngInfo.ToList().ForEach(async s => s.OperatorName = await helper.GetUserName(s.OperatorID));
            }
            return barcodeQngInfo;
        }

        /// <summary>
        /// 報廢資料查詢
        /// </summary>
        /// <param name="unitNo"></param>
        /// <param name="wipNO"></param>
        /// <param name="itemNO"></param>
        /// <param name="dateStart"></param>
        /// <param name="dateEnd"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [Route("[action]")]
        [HttpGet]
        public async Task<ResultModel<dynamic>> GetQngInfoData4REP008(string unitNo, string wipNO, string itemNO, string dateStart, string dateEnd, int page = 0, int limit = 10)
        {
            Helper helper = new Helper(_context);

            ResultModel<dynamic> result = new ResultModel<dynamic>();
            var q = from a in _context.BarcodeQngInfos
                    join b in _context.BarcodeInfoes on a.BarcodeID equals b.BarcodeID
                    join c in _context.WipInfos on a.WipID equals c.WipID
                    join d in _context.WipAtts on c.WipNO equals d.WipNO
                    join e in _context.Stationses on a.StationID equals e.StationID
                    join f in _context.RepairResponsibleUnitses on a.DeptID equals f.RRID
                    select new
                    {
                        a.UnitNo,
                        b.BarcodeNo,
                        c.WipNO,
                        d.ModelNO,
                        d.ItemNO,
                        e.StationName,
                        ScrapDate = a.ScrapTime,
                        OpUserNo = helper.GetUserNo(a.OperatorID).Result,
                        IPQAUserNo = helper.GetUserNo(a.IPQAID).Result,
                        PEUserNo = helper.GetUserNo(a.PEID).Result,
                        ManagerUserNo = helper.GetUserNo(a.ManagerID).Result,
                        f.RRDesc,
                        a.NGReason,
                        a.NGReasonPrtreatment,
                        a.Precaution,
                        a.PreventiveTreatment,
                        a.RuleStatus
                    };


            if (dateStart != null && dateEnd != null)
            {
                if (dateStart != "" && dateEnd != "")
                {
                    q = q.Where(w => w.ScrapDate >= DateTime.Parse(dateStart) && w.ScrapDate <= DateTime.Parse(dateEnd).AddDays(1));
                }
            }
            if (unitNo != null)
            {
                if (unitNo != "*")
                {
                    q = q.Where(w => w.UnitNo == unitNo);
                }
            }
            if (wipNO != null)
            {
                if (wipNO != "")
                {
                    q = q.Where(w => w.WipNO == wipNO);
                }
            }

            if (itemNO != null)
            {
                if (itemNO != "")
                {
                    q = q.Where(w => w.ItemNO == itemNO);
                }
            }
            q = q.Where(w => w.RuleStatus.Equals("S"));

            q = q.OrderBy(w => w.ScrapDate);

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

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

            result.Data = await q.ToListAsync();

            if (result == null)
            {
                result.Msg = "查無資料";
                result.Success = false;
                return result;
            }

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

        /// <summary>
        /// 轉出資料查詢
        /// </summary>
        /// <param name="unitNo"></param>
        /// <param name="wipNO"></param>
        /// <param name="itemNO"></param>
        /// <param name="dateStart"></param>
        /// <param name="dateEnd"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [Route("[action]")]
        [HttpGet]
        public async Task<ResultModel<dynamic>> GetQngInfoData4REP009(string unitNo, string wipNO, string itemNO, string dateStart, string dateEnd, int page = 0, int limit = 10)
        {
            Helper helper = new Helper(_context);

            ResultModel<dynamic> result = new ResultModel<dynamic>();
            var q = from a in _context.BarcodeQngInfos
                    join b in _context.BarcodeInfoes on a.BarcodeID equals b.BarcodeID
                    join c in _context.WipInfos on a.WipID equals c.WipID
                    join d in _context.WipAtts on c.WipNO equals d.WipNO
                    join e in _context.Stationses on a.StationID equals e.StationID
                    join f in _context.RepairResponsibleUnitses on a.DeptID equals f.RRID
                    select new
                    {
                        a.UnitNo,
                        b.BarcodeNo,
                        c.WipNO,
                        d.ModelNO,
                        d.ItemNO,
                        e.StationName,
                        ScrapDate = a.ScrapTime,
                        OpUserNo = helper.GetUserNo(a.OperatorID).Result,
                        IPQAUserNo = helper.GetUserNo(a.IPQAID).Result,
                        PEUserNo = helper.GetUserNo(a.PEID).Result,
                        ManagerUserNo = helper.GetUserNo(a.ManagerID).Result,
                        f.RRDesc,
                        a.NGReason,
                        a.NGReasonPrtreatment,
                        a.Precaution,
                        a.PreventiveTreatment,
                        a.RuleStatus
                    };


            if (dateStart != null && dateEnd != null)
            {
                if (dateStart != "" && dateEnd != "")
                {
                    q = q.Where(w => w.ScrapDate >= DateTime.Parse(dateStart) && w.ScrapDate <= DateTime.Parse(dateEnd).AddDays(1));
                }
            }
            if (unitNo != null)
            {
                if (unitNo != "*")
                {
                    q = q.Where(w => w.UnitNo == unitNo);
                }
            }
            if (wipNO != null)
            {
                if (wipNO != "")
                {
                    q = q.Where(w => w.WipNO == wipNO);
                }
            }

            if (itemNO != null)
            {
                if (itemNO != "")
                {
                    q = q.Where(w => w.ItemNO == itemNO);
                }
            }
            q = q.Where(w => w.RuleStatus.Equals("C"));

            q = q.OrderBy(w => w.ScrapDate);

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

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

            result.Data = await q.ToListAsync();

            if (result == null)
            {
                result.Msg = "查無資料";
                result.Success = false;
                return result;
            }

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

        /// <summary>
        /// 根據ID修改單一筆報廢轉出資料
        /// </summary>
        /// <param name="id"></param>
        /// <param name="barcodeQngInfo"></param>
        /// <returns></returns>
        // PUT: api/BarcodeQngInfoes/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<BarcodeQngInfo>> PutBarcodeQngInfo(int id, BarcodeQngInfo barcodeQngInfo)
        {
            ResultModel<BarcodeQngInfo> result = new ResultModel<BarcodeQngInfo>();

            if (id != barcodeQngInfo.QngID)
            {
                result.Success = false;
                result.Msg = "報廢轉出ID錯誤";
                return result;
            }

            _context.Entry(barcodeQngInfo).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!BarcodeQngInfoExists(id))
                {
                    result.Success = false;
                    result.Msg = "報廢轉出ID不存在";
                    return result;
                }
                else
                {
                    throw;
                }
            }

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

        /// <summary>
        /// 新增報廢轉出資料
        /// </summary>
        /// <param name="barcodeQngInfo"></param>
        /// <returns></returns>
        // POST: api/BarcodeQngInfoes
        // 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<BarcodeQngInfo>> PostBarcodeQngInfo(BarcodeQngInfo barcodeQngInfo)
        {
            ResultModel<BarcodeQngInfo> result = new ResultModel<BarcodeQngInfo>();

            IQueryable<BarcodeQngInfo> q = _context.BarcodeQngInfos;

            q = q.Where(p => p.BarcodeID.Equals(barcodeQngInfo.BarcodeID) && p.RuleStatus.Equals(barcodeQngInfo.RuleStatus));

            var qng_info = await q.ToListAsync();
            if (qng_info.Count > 0)
            {
                result.Success = false;
                if (barcodeQngInfo.RuleStatus == "C")
                {
                    result.Msg = "重複轉出";
                }
                else
                {
                    result.Msg = "重複報廢";
                }

                return result;
            }

            Helper helper = new Helper(_context);
            barcodeQngInfo.QngID = helper.GetIDKey("QNG_ID").Result;

            _context.BarcodeQngInfos.Add(barcodeQngInfo);

            var barcodeInfo = await _context.BarcodeInfoes.FindAsync(barcodeQngInfo.BarcodeID);
            barcodeInfo.StatusID = -1;
            barcodeInfo.RuleStatus = barcodeQngInfo.RuleStatus;
            _context.Attach(barcodeInfo);

            _context.Entry(barcodeInfo).Property(p => p.RuleStatus).IsModified = true;
            _context.Entry(barcodeInfo).Property(p => p.StatusID).IsModified = true;

            await _context.SaveChangesAsync();

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

        /// <summary>
        /// 根據ID刪除單一筆報廢轉出資料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // DELETE: api/BarcodeQngInfoes/5
        [HttpDelete("{id}")]
        public async Task<ResultModel<BarcodeQngInfo>> DeleteBarcodeQngInfo(int id)
        {
            ResultModel<BarcodeQngInfo> result = new ResultModel<BarcodeQngInfo>();

            var barcodeQngInfo = await _context.BarcodeQngInfos.FindAsync(id);
            if (barcodeQngInfo == null)
            {
                result.Success = false;
                result.Msg = "報廢轉出ID不存在";
                return result;
            }

            _context.BarcodeQngInfos.Remove(barcodeQngInfo);
            await _context.SaveChangesAsync();

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

        private bool BarcodeQngInfoExists(int id)
        {
            return _context.BarcodeQngInfos.Any(e => e.QngID == id);
        }
    }
}