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.WebApi.DTO.AMES;
using AMESCoreStudio.CommonTools.Result;

namespace AMESCoreStudio.WebApi.Controllers.AMES
{
    /// <summary>
    /// 鋼板基本資料檔
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class SteelPlateInfoController : ControllerBase
    {
        private readonly AMESContext _context;

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

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

        // GET: api/SteelPlateInfo/5
        [HttpGet("{id}")]
        public async Task<ActionResult<SteelPlateInfo>> GetSteelPlateInfo(int id)
        {
            var steelPlateInfo = await _context.SteelPlateInfos.FindAsync(id);

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

            return steelPlateInfo;
        }

        /// <summary>
        /// By 鋼板編號 查詢
        /// </summary>
        /// <param name="id">鋼板編號</param>
        /// <returns></returns>
        [HttpGet("ByNo/{id}")]
        public async Task<ActionResult<IEnumerable<SteelPlateInfo>>> GetSteelPlateInfoByNo(string id)
        {

            var steelPlateInfos = await _context.SteelPlateInfos.Where(w => w.SteelPlateNo == id.ToUpper())
                                         .ToListAsync();

            return steelPlateInfos;
        }

        /// <summary>
        /// 鋼板資料查詢
        /// </summary>
        /// <param name="steelPlateNo">鋼板編號</param>
        /// <param name="pcbPartNo">PCB板號</param>
        /// <param name="side">正背面</param>
        /// <param name="status">狀態</param>
        /// <param name="page">頁數</param>
        /// <param name="limit">筆數</param>
        /// <returns></returns>
        [HttpGet("SteelPlateInfoQuery")]
        public async Task<ResultModel<SteelPlateInfoDto>> GetSteelPlateInfoQuery(string steelPlateNo, string pcbPartNo, string side
          , string status, int page = 0, int limit = 10)
        {
            var q = await _context.SteelPlateInfos.ToListAsync();

            if (!string.IsNullOrWhiteSpace(steelPlateNo))
            {
                q = q.Where(w => w.SteelPlateNo.Contains(steelPlateNo)).ToList();
            }

            if (!string.IsNullOrWhiteSpace(pcbPartNo))
            {
                q = q.Where(w => w.PcbPartNo.Contains(pcbPartNo)).ToList();
            }

            if (!string.IsNullOrWhiteSpace(side))
            {
                q = q.Where(w => w.Side.ToString() == side).ToList();
            }

            if (!string.IsNullOrWhiteSpace(status))
            {
                q = q.Where(w => w.Status == status).ToList();
                
            }
            ResultModel<SteelPlateInfoDto> result = new ResultModel<SteelPlateInfoDto>();

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

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

            result.Data = q.Select(s => new SteelPlateInfoDto
            {
                SteelPlateID = s.SteelPlateID,
                SteelPlateNo = s.SteelPlateNo,
                Specification = s.Specification,
                PcbPartNo = s.PcbPartNo,
                StandardTension1 = s.StandardTension1,
                StandardTension2 = s.StandardTension2,
                StandardTension3 = s.StandardTension3,
                StandardTension4 = s.StandardTension4,
                StandardTension5 = s.StandardTension5,
                Boards = s.Boards,
                SideName = s.Side == 11 ? "B/背面" : "A/正面",
                StatusName = s.Status == "0" ? "失效" : "有效",
                Remark = s.Remark
            }).ToList();
            return result;
        }

        /// <summary>
        /// 更新鋼板基本資料檔
        /// </summary>
        /// <param name="steelPlateInfo"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<ResultModel<SteelPlateInfo>> PutSteelPlateInfo(SteelPlateInfo steelPlateInfo)
        {
            ResultModel<SteelPlateInfo> result = new ResultModel<SteelPlateInfo>();
            _context.Entry(steelPlateInfo).State = EntityState.Modified;

            try
            {
                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="steelPlateInfo"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResultModel<SteelPlateInfo>> PostSteelPlateInfo(SteelPlateInfo steelPlateInfo)
        {
            ResultModel<SteelPlateInfo> result = new ResultModel<SteelPlateInfo>();
            Helper helper = new Helper(_context);
            steelPlateInfo.SteelPlateID = helper.GetIDKey("STEEL_PLATE_ID").Result;
            _context.SteelPlateInfos.Add(steelPlateInfo);
            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/SteelPlateInfo/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<SteelPlateInfo>> DeleteSteelPlateInfo(int id)
        {
            var steelPlateInfo = await _context.SteelPlateInfos.FindAsync(id);
            if (steelPlateInfo == null)
            {
                return NotFound();
            }

            _context.SteelPlateInfos.Remove(steelPlateInfo);
            await _context.SaveChangesAsync();

            return steelPlateInfo;
        }

        private bool SteelPlateInfoExists(int id)
        {
            return _context.SteelPlateInfos.Any(e => e.SteelPlateID == id);
        }
    }
}