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

namespace AMESCoreStudio.WebApi.Controllers.SYS
{
    /// <summary>
    /// 
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class ProgramInfoesController : ControllerBase
    {
        private readonly AMESContext _context;

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

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        // GET: api/ProgramInfoes
        [HttpGet]
        public async Task<ActionResult<IEnumerable<ProgramInfo>>> GetProgramInfo()
        {
            IQueryable<ProgramInfo> q = _context.ProgramInfoes;

            q = q.OrderBy(p => p.ProgramNo);

            var programInfo = await q.ToListAsync();

            return programInfo;
            //return await _context.ProgramInfoes.ToListAsync();
        }

        /// <summary>
        /// 根據模組ID獲取該模組功能資料
        /// </summary>
        /// <param name="id"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        // GET: api/ProgramInfoes/Module/5
        [HttpGet("Module/{id}")]
        public async Task<ResultModel<ProgramInfo>> GetProgramInfoByModule(int id, int page = 0, int limit = 10)
        {
            ResultModel<ProgramInfo> result = new ResultModel<ProgramInfo>();

            IQueryable<ProgramInfo> q = _context.ProgramInfoes;

            if (id > 0)
            {
                q = q.Where(p => p.ModuleID.Equals(id));
            }

            result.DataTotal = q.ToList().Count;

            if (page > 0)
            {
                q = q.OrderBy(p => p.SortSeq).Skip((page - 1) * limit).Take(limit);
            }
            else
            {
                q = q.OrderBy(p => p.SortSeq);
            }

            try
            {
                var programInfo = await q.ToListAsync();

                result.Data = programInfo;

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

                result.Msg = "OK";
                result.Success = true;
                return result;
            }
            catch (Exception e1)
            {
                string msg = e1.Message;
            }

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


        }

        /// <summary>
        /// 根據系统ID&模組ID獲取該模組功能資料
        /// </summary>
        [Route("[action]")]
        [HttpGet]
        public async Task<ResultModel<dynamic>> GetProgramInfoesBySystemModule(int systemID,int moduleID, int page = 0, int limit = 10)
        {
            ResultModel<dynamic> result = new ResultModel<dynamic>();

            var q = from q1 in _context.ProgramInfoes
                    join q2 in _context.ModuleInfoes on q1.ModuleID equals q2.ModuleID
                    select new
                    {
                        q1.ProgramID,
                        q1.ProgramNo,
                        q1.ProgramName,
                        q1.ProgramDesc,
                        q1.ProgramPath,
                        q1.SortSeq,
                        q1.ModuleID,
                        q2.SystemID
                    };

            if (systemID > 0)
            {
                q = q.Where(p => p.SystemID.Equals(systemID));
            }

            if (moduleID > 0)
            {
                q = q.Where(p => p.ModuleID.Equals(moduleID));
            }

            result.DataTotal = q.ToList().Count;

            if (page > 0)
            {
                q = q.OrderBy(p => p.SortSeq).Skip((page - 1) * limit).Take(limit);
            }
            else
            {
                q = q.OrderBy(p => p.SortSeq);
            }

            try
            {
                var programInfo = await q.ToListAsync();

                result.Data = programInfo;

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

                result.Msg = "OK";
                result.Success = true;
                return result;
            }
            catch (Exception e1)
            {
                string msg = e1.Message;
            }

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


        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET: api/ProgramInfoes/5
        [HttpGet("{id}")]
        public async Task<ActionResult<IEnumerable<ProgramInfo>>> GetProgramInfo(int id)
        {
            //var programInfo = await _context.ProgramInfoes.FindAsync(id);

            IQueryable<ProgramInfo> q = _context.ProgramInfoes;

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

            var programInfo = await q.ToListAsync();

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

            return programInfo;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="programInfo"></param>
        /// <returns></returns>
        // PUT: api/ProgramInfoes/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<ProgramInfo>> PutProgramInfo(int id, [FromBody] ProgramInfo programInfo)
        {
            ResultModel<ProgramInfo> result = new ResultModel<ProgramInfo>();

            if (id != programInfo.ProgramID)
            {
                result.Msg = "程式編號錯誤";
                result.Success = false;
                return result;
            }

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

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProgramInfoExists(id))
                {
                    result.Msg = "程式編號不存在";
                    result.Success = false;
                    return result;
                }
                else
                {
                    throw;
                }
            }

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

        /// <summary>
        /// 
        /// </summary>
        /// <param name="programInfo"></param>
        /// <returns></returns>
        // POST: api/ProgramInfoes
        // 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<ProgramInfo>> PostProgramInfo([FromBody] ProgramInfo programInfo)
        {
            ResultModel<ProgramInfo> result = new ResultModel<ProgramInfo>();

            Helper helper = new Helper(_context);
            programInfo.ProgramID = helper.GetIDKey("PROGRAM_ID").Result;

            programInfo.CreateDateTime = DateTime.Now;
            programInfo.CreateUserId = 0;

            _context.ProgramInfoes.Add(programInfo);
            await _context.SaveChangesAsync();

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

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // DELETE: api/ProgramInfoes/5
        [HttpDelete("{id}")]
        public async Task<ResultModel<ProgramInfo>> DeleteProgramInfo(int id)
        {
            ResultModel<ProgramInfo> result = new ResultModel<ProgramInfo>();

            var programInfo = await _context.ProgramInfoes.Where(m => m.ProgramID == id).FirstOrDefaultAsync();

            if (programInfo == null)
            {
                result.Msg = "程式編號不存在";
                result.Success = false;
                return result;
            }

            _context.ProgramInfoes.Remove(programInfo);
            await _context.SaveChangesAsync();

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

        private bool ProgramInfoExists(int id)
        {
            return _context.ProgramInfoes.Any(e => e.ProgramID == id);
        }
    }
}