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.BAS;
using AMESCoreStudio.CommonTools.Result;

namespace AMESCoreStudio.WebApi.Controllers.BAS
{
    /// <summary>
    /// 工廠资料维护
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class StationsesController : ControllerBase
    {
        private readonly AMESContext _context;

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

        /// <summary>
        /// 获取全部站別资料
        /// </summary>
        /// <returns></returns>
        // GET: api/Stationses
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Stations>>> GetStations()
        {
            IQueryable<Stations> q = _context.Stationses;
            q = q.Where(p => p.UnitNo != "0");
            q = q.OrderBy(p => p.StationID);

            var Stations = await q.ToListAsync();

            foreach (var data in Stations)
            {
                //data.Dept = _context.DeptInfoes.Find(data.DeptID);
                if (data.UnitNo != "0")
                    data.Unit = _context.FactoryUnits.Find(data.UnitNo);
                else
                    data.Unit.UnitName = "N/A";

            }


            return Stations;
        }

        /// <summary>
        /// 用ID获取该站別资料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET: api/Stationses/5
        [HttpGet("{id}")]
        public async Task<ActionResult<IEnumerable<Stations>>> GetStations(int id)
        {

            IQueryable<Stations> q = _context.Stationses;
            q = q.Where(p => p.StationID.Equals(id));
            var stations = await q.ToListAsync();

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

            return stations;
        }

        /// <summary>
        /// 获取全部F/T站別资料
        /// </summary>
        /// <returns></returns>
        // GET: api/Stationses
        [HttpGet("FT/{id}")]
        public async Task<ActionResult<IEnumerable<Stations>>> GetStations4FT(string id)
        {
            IQueryable<Stations> q = _context.Stationses;
            /*
            if (id != "0")
            {
                q = q.Where(p => p.UnitNo.Equals(id));
            }
            */
            q = q.Where(p => p.TestType == "F/T" && p.TypeNo == "T" && p.StatusNo == "A");
            q = q.OrderBy(p => p.StationName);

            var Stations = await q.ToListAsync();

            foreach (var data in Stations)
            {
                if (data.UnitNo != "0")
                    data.Unit = _context.FactoryUnits.Find(data.UnitNo);
                else
                    data.Unit.UnitName = "N/A";
            }


            return Stations;
        }

        /// <summary>
        /// 根据單位ID获取该站別资料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET: api/MailGroupDetails/Unit/5
        [HttpGet("Unit/{id}")]
        public async Task<ActionResult<IEnumerable<Stations>>> GetClassInfoByUnit(String id)
        {
            IQueryable<Stations> q = _context.Stationses;

            if (id != "0")
            {
                q = q.Where(p => p.UnitNo.Equals(id));
            }
            q.OrderBy(p => p.UnitNo);

            var stations = await q.ToListAsync();

            if (stations is null)
            {
                return NotFound();
            }

            return stations;
        }


        /// <summary>
        /// 更新站別资料
        /// </summary>
        /// <param name="id"></param>
        /// <param name="stations"></param>
        /// <returns></returns>
        // PUT: api/Stationses/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<Stations>> PutStations(int id, [FromBody] Stations Stations)
        {
            ResultModel<Stations> result = new ResultModel<Stations>();
            if (id != Stations.StationID)
            {
                result.Success = false;
                result.Msg = "序號錯誤";
                return result;
            }

            _context.Entry(Stations).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="stations"></param>
        /// <returns></returns>
        // POST: api/Stationses
        // 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<Stations>> PostStations(Stations Stations)
        {
            ResultModel<Stations> result = new ResultModel<Stations>();

            Helper helper = new Helper(_context);
            Stations.StationID = helper.GetIDKey("STATION_ID").Result;
            Stations.SectionNo = "A";

            _context.Stationses.Add(Stations);
            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="id"></param>
        /// <returns></returns>
        // DELETE: api/Stationses/5
        [HttpDelete("{id}")]
        public async Task<ResultModel<Stations>> DeleteStations(int id)
        {
            //var stations = await _context.Stations.FindAsync(id);
            ResultModel<Stations> result = new ResultModel<Stations>();
            var stations = await _context.Stationses.Where(m => m.StationID == id).FirstOrDefaultAsync();
            if (stations == null)
            {
                result.Success = false;
                result.Msg = "序號錯誤";
                return result;
            }

            //////
            var stationsNew = new Stations();
            stationsNew = stations;

            _context.Entry(stationsNew).State = EntityState.Modified;
            if(stations.StatusNo == "A")
                stationsNew.StatusNo = "S";
            else
                stationsNew.StatusNo = "A";
            try
            {
                await _context.SaveChangesAsync();
                result.Success = true;
                result.Msg = "OK";
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Msg = ex.InnerException.Message;
            }

            return result;



            /////

            //_context.Stationses.Remove(stations);
            //await _context.SaveChangesAsync();

            //return stations;
        }

        private bool StationsExists(int id)
        {
            return _context.Stationses.Any(e => e.StationID == id);
        }
    }
}