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

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

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        // GET: api/UserInfoes
        [HttpGet]
        public async Task<ResultModel<UserInfo>> GetUserInfo(int page = 0, int limit = 10)
        {
            ResultModel<UserInfo> result = new ResultModel<UserInfo>();

            IQueryable<UserInfo> q = _context.UserInfoes;
            q = q.Where(p => p.UserID > 0);

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

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

            var userInfo = await q.ToListAsync();

            result.Data = userInfo;

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

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

        /// <summary>
        /// 查詢用戶數據
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("[action]")]
        [HttpGet]
        public async Task<ResultModel<dynamic>> GetUserData(int id)
        {
            ResultModel<dynamic> result = new ResultModel<dynamic>();
            var q = from q1 in _context.UserInfoes
                    join q2 in _context.FactoryInfos on q1.FactoryID equals q2.FactoryID
                    select new
                    {
                        q1.UserID,
                        q1.UserName,
                        q2.FactoryID,
                        q2.FactoryNo
                    };
            q = q.Where(p => p.UserID == id);

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

            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="id"></param>
            /// <returns></returns>
            // GET: api/UserInfoes/5
            [HttpGet("{id}")]
        public async Task<ActionResult<IEnumerable<UserInfo>>> GetUserInfo(int id)
        {
            IQueryable<UserInfo> q = _context.UserInfoes;
            q = q.Where(p => p.UserID.Equals(id));
            var userInfo = await q.ToListAsync();

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

            return userInfo;
        }

        /// <summary>
        /// UserInfo By UserNo
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET: api/UserInfoes/5
        [HttpGet("ByUserNo/{id}")]
        public async Task<ActionResult<UserInfo>> GetUserInfoByUserNo(string id)
        {
            IQueryable<UserInfo> q = _context.UserInfoes.Where(w => w.UserNo.ToUpper() == id.ToUpper());
            var userInfo = await q.FirstOrDefaultAsync();
            return userInfo;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        // PUT: api/UserInfoes/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<UserInfo>> PutUserInfo(int id, [FromBody] UserInfo userInfo)
        {
            ResultModel<UserInfo> result = new ResultModel<UserInfo>();

            if (id != userInfo.UserID)
            {
                result.Msg = "用戶編號錯誤";
                result.Success = false;
                return result;
            }

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

            userInfo.UpdateUserId = 0;
            userInfo.UpdateDateTime = DateTime.Now;

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

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

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        // POST: api/UserInfoes
        // 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<UserInfo>> PostUserInfo([FromBody] UserInfo userInfo)
        {
            ResultModel<UserInfo> result = new ResultModel<UserInfo>();

            Helper helper = new Helper(_context);
            userInfo.UserID = helper.GetIDKey("USER_ID").Result;
            userInfo.CreateUserId = 0;
            userInfo.CreateDateTime = DateTime.Now;

            _context.UserInfoes.Add(userInfo);
            await _context.SaveChangesAsync();

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

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

            var userInfo = await _context.UserInfoes.Where(m => m.UserID == id).FirstOrDefaultAsync();

            if (userInfo == null)
            {
                result.Msg = "用戶編號不存在";
                result.Success = false;
                return result;
            }

            _context.UserInfoes.Remove(userInfo);
            await _context.SaveChangesAsync();

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

        private bool UserInfoExists(int id)
        {
            return _context.UserInfoes.Any(e => e.UserID == id);
        }
    }
}