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

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

        /// <summary>
        /// 获取全部巡檢表單
        /// </summary>
        /// <returns></returns>
        // GET: api/InspectionForms
        [HttpGet]
        public async Task<ActionResult<IEnumerable<InspectionForm>>> GetInspectionForms()
        {
            IQueryable<InspectionForm> q = _context.InspectionForms;
            q = q.OrderBy(p => p.InspectionFormID);
            var InspectionForms = await q.ToListAsync();

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

            return InspectionForms;
        }

        /// <summary>
        /// 用ID获取该巡檢表單
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET: api/InspectionForms/5
        [HttpGet("{id}")]
        public async Task<ActionResult<IEnumerable<InspectionForm>>> GetInspectionForms(int id)
        {
           
            IQueryable<InspectionForm> q = _context.InspectionForms;
            q = q.Where(p => p.InspectionFormID.Equals(id));
            var InspectionForm = await q.ToListAsync();

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

            return InspectionForm;
        }

        /// <summary>
        /// 获取该巡檢表單By Query
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        // GET: api/InspectionForms/Query/5
        [HttpGet("Query/{id}/{status}")]
        public async Task<ActionResult<IEnumerable<InspectionForm>>> GetInspectionFormsByQuery(int id,string status)
        {

            IQueryable<InspectionForm> q = _context.InspectionForms;
            q = q.Where(p => p.InspectionTypeID.Equals(id));
            q = q.Where(p => p.StatusNo.Equals(status));
            var InspectionForm = await q.ToListAsync();

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

            return InspectionForm;
        }

        /// <summary>
        /// 更新巡檢表單资料
        /// </summary>
        /// <param name="id"></param>
        /// <param name="InspectionForm"></param>
        /// <returns></returns>
        // PUT: api/InspectionForms/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<InspectionForm>> PutInspectionForms(int id, [FromBody] InspectionForm InspectionForm)
        {
            ResultModel<InspectionForm> result = new ResultModel<InspectionForm>();
            if (id != InspectionForm.InspectionFormID)
            {
                result.Success = false;
                result.Msg = "序號錯誤";
                return result;
            } 

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

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                result.Success = false;
                result.Msg = e.Message;
                return result;
            }

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

        /// <summary>
        /// 新增巡檢表單资料
        /// </summary>
        /// <param name="InspectionForm"></param>
        /// <returns></returns>
        // POST: api/InspectionForms
        // 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<InspectionForm>> PostInspectionForms(InspectionForm InspectionForm)
        {
            ResultModel<InspectionForm> result = new ResultModel<InspectionForm>();
            Helper helper = new Helper(_context);
            var InspectionFormID = helper.GetIDKey("InspectionFormID").Result;

            InspectionForm.InspectionFormID = InspectionFormID;
            _context.InspectionForms.Add(InspectionForm);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                result.Success = false;
                result.Msg = e.Message;
                return result;
            }

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

        }

        /// <summary>
        /// 刪除巡檢表單资料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // DELETE: api/InspectionForms/5
        [HttpDelete("{id}")]
        public async Task<ResultModel<InspectionForm>> DeleteInspectionForms(int id)
        {
            ResultModel<InspectionForm> result = new ResultModel<InspectionForm>();
            var InspectionForm = await _context.InspectionForms.Where(m => m.InspectionFormID == id).FirstOrDefaultAsync();
            if (InspectionForm == null)
            {
                result.Success = false;
                result.Msg = "序號不存在";
                return result;
            }

            //_context.InspectionForms.Remove(InspectionForm);

            InspectionForm newInspectionForm = new InspectionForm();
            newInspectionForm = InspectionForm;

            if (InspectionForm.StatusNo == "Y") //yiru modify 2022-09-30
            {
                newInspectionForm.StatusNo = "N";
            }
            else
            {
                newInspectionForm.StatusNo = "Y";
            }
            _context.Entry(newInspectionForm).State = EntityState.Modified;
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (Exception e)
            {
                result.Success = false;
                result.Msg = e.Message;
                return result;
            }

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

        private bool InspectionFormsExists(int id)
        {
            return _context.InspectionForms.Any(e => e.InspectionFormID == id);
        }

    }
}