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

        /// <summary>
        /// 異常工時查資料
        /// </summary>
        /// <param name="context"></param>
        public ExceptionWorktimesController(AMESContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 取得異常工時
        /// </summary>
        /// <returns></returns>
        // GET: api/ExceptionWorktimes
        [HttpGet]
        public async Task<ActionResult<IEnumerable<ExceptionWorktime>>> GetExceptionWorktime()
        {
            IQueryable<ExceptionWorktime> q = _context.ExceptionWorktimes;

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

            var exceptionWorktime = await q.ToListAsync();

            return exceptionWorktime;
        }

        /// <summary>
        /// 取得異常工時BY ID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET: api/ExceptionWorktimes/5
        [HttpGet("{id}")]
        public async Task<ActionResult<IEnumerable<ExceptionWorktime>>> GetExceptionWorktime(string id)
        {
            IQueryable<ExceptionWorktime> q = _context.ExceptionWorktimes;
            q = q.Where(p => p.ExceptionID == int.Parse(id));

            var exceptionWorktime = await q.ToListAsync();

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

            return exceptionWorktime;
        }

        /// <summary>
        /// 異常工時查詢Query
        /// </summary>
        /// <param name="factoryid"></param>
        /// <param name="unitid"></param>
        /// <param name="lineid"></param>
        /// <param name="deptid"></param>
        /// <param name="sdate"></param>
        /// <param name="edate"></param>
        /// <returns></returns>
        // GET: api/ExceptionWorktimeOnlines/5
        [HttpGet("Query/{factoryid}/{unitid}/{lineid}/{deptid}/{sdate}/{edate}")]
        public async Task<ActionResult<IEnumerable<ExceptionWorktime>>> GetExceptionWorktimeByQuery(string factoryid, string unitid, string lineid, string deptid, string sdate, string edate)
        {
            IQueryable<ExceptionWorktime> q = _context.ExceptionWorktimes;
            if (factoryid != "*")
                q = q.Where(p => p.FactoryNo.Equals(factoryid));
            if (unitid != "*")
                q = q.Where(p => p.UnitNo.Equals(unitid));
            if (deptid != "*")
                q = q.Where(p => p.DecidDeptID ==int.Parse(deptid));
            if (lineid != "*")
                q = q.Where(p => p.LineID == int.Parse(lineid));

            DateTime dateValue;
            if (sdate != "*")
            {

                if (DateTime.TryParse(sdate, out dateValue))
                {
                    q = q.Where(p => p.ExceptionDate >= DateTime.Parse(sdate));
                }
            }
            if (edate != "*")
            {
                if (DateTime.TryParse(edate, out dateValue))
                {
                    q = q.Where(p => p.ExceptionDate <= DateTime.Parse(edate));
                }

            }


            var exceptionWorktime = await q.ToListAsync();

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

            return exceptionWorktime;
        }


        /// <summary>
        /// 修改異常工時資料
        /// </summary>
        /// <param name="id"></param>
        /// <param name="exceptionWorktime"></param>
        /// <returns></returns>
        // PUT: api/ExceptionWorktimes/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<ExceptionWorktime>> PutExceptionWorktime(int id, [FromBody] ExceptionWorktime exceptionWorktime)
        {
            ResultModel<ExceptionWorktime> result = new ResultModel<ExceptionWorktime>();

            if (id != exceptionWorktime.ExceptionID)
            {
                result.Success = false;
                result.Msg = "序號錯誤";
                return result;
            }

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

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

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

        }


        /// <summary>
        /// 新增異常工時资料
        /// </summary>
        /// <param name="exceptionWorktime"></param>
        /// <returns></returns>
        // POST: api/ExceptionWorktimes
        // 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<ExceptionWorktime>> PostExceptionWorktime(ExceptionWorktime exceptionWorktime)
        {
            ResultModel<ExceptionWorktime> result = new ResultModel<ExceptionWorktime>();
            Helper helper = new Helper(_context);
            exceptionWorktime.ExceptionID = helper.GetIDKey("EXCEPTION_WORKTIMEID").Result;

            _context.ExceptionWorktimes.Add(exceptionWorktime);

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                throw;
            }



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

        }

        /// <summary>
        /// 刪除異常工時資料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // DELETE: api/ExceptionWorktimes/5
        [HttpDelete("{id}")]
        public async Task<ResultModel<ExceptionWorktime>> DeleteExceptionWorktime(int id)
        {
            ResultModel<ExceptionWorktime> result = new ResultModel<ExceptionWorktime>();
            var exceptionWorktime = await _context.ExceptionWorktimes.Where(p => p.ExceptionID == id).FirstOrDefaultAsync();
            if (exceptionWorktime == null)
            {
                result.Success = false;
                result.Msg = "序號不存在";
                return result;
            }

            _context.ExceptionWorktimes.Remove(exceptionWorktime);
            await _context.SaveChangesAsync();

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


        private bool ExceptionWorktimeExists(int id)
        {
            return _context.ExceptionWorktimes.Any(e => e.ExceptionID == id);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sdate"></param>
        /// <param name="edate"></param>
        /// <returns></returns>
        [Route("[action]")]
        [HttpGet]
        public async Task<ResultModel<dynamic>> GetExceptionWorktime4RPT001(string sdate, string edate)
        {
            ResultModel<dynamic> result = new ResultModel<dynamic>();
            var q = from q1 in _context.ExceptionWorktimes
                    select new
                    {
                        q1.ExceptionID,
                        q1.ExceptionDate,
                        q1.Time

                    };

            DateTime dateValue;
            if (sdate != "*")
            {

                if (DateTime.TryParse(sdate, out dateValue))
                {
                    q = q.Where(p => p.ExceptionDate >= DateTime.Parse(sdate));
                }
            }
            if (edate != "*")
            {
                if (DateTime.TryParse(edate, out dateValue))
                {
                    q = q.Where(p => p.ExceptionDate <= DateTime.Parse(edate));
                }

            }

            //紀錄筆數
            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="sdate"></param>
        /// <param name="edate"></param>
        /// <returns></returns>
        [Route("[action]")]
        [HttpGet]
        public async Task<ResultModel<dynamic>> GetExceptionWorktime4RPT001D(string sdate, string edate)
        {
            ResultModel<dynamic> result = new ResultModel<dynamic>();
            var q = from q1 in _context.ExceptionWorktimes
                    join q2 in _context.ExceptionCodes on q1.ExceptionNo equals q2.ExceptionNo
                    select new
                    {
                        q1.ExceptionID,
                        q1.ExceptionDate,
                        q1.ExceptionNo,
                        q2.ExceptionDescCH,
                        q1.Time

                    };

            DateTime dateValue;
            if (sdate != "*")
            {

                if (DateTime.TryParse(sdate, out dateValue))
                {
                    q = q.Where(p => p.ExceptionDate >= DateTime.Parse(sdate));
                }
            }
            if (edate != "*")
            {
                if (DateTime.TryParse(edate, out dateValue))
                {
                    q = q.Where(p => p.ExceptionDate <= DateTime.Parse(edate));
                }

            }

            var g = q.GroupBy(x => new { x.ExceptionNo, x.ExceptionDescCH }).Select(x => new
            {
                ExceptionNo = x.Key.ExceptionNo,
                ExceptionDesc = x.Key.ExceptionDescCH,
                ExceptionTime = x.Sum(h => h.Time)
            });

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

            result.Data = await g.ToListAsync();

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

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


        //YIRU ADD  ------------------------------------------------------------------------------------------

        /// <summary>
        /// 異常工時查詢QuerybyWHS009
        /// </summary>
        /// <param name="factoryid"></param>
        /// <param name="unitid"></param>
        /// <param name="lineid"></param>
        /// <param name="deptid"></param>
        /// <param name="sdate"></param>
        /// <param name="edate"></param>
        /// <returns></returns>
        [HttpGet("ByQueryWHS009/{factoryid}/{unitid}/{lineid}/{deptid}/{sdate}/{edate}")]
        public async Task<ActionResult<IEnumerable<ExceptionWorktimeDto>>> GetExceptionWorktimeByQueryWHS009(string factoryid, string unitid, string lineid, string deptid, string sdate, string edate)
        {

            IQueryable<ExceptionWorktimeDto> q = from q1 in _context.ExceptionWorktimes
                                                 join q2 in _context.UserInfoes on q1.DecidUserID equals q2.UserID
                                                 join q3 in _context.DeptInfoes on q1.DutyDeptID equals q3.DeptID
                                                 join q4 in _context.LineInfoes on q1.LineID equals q4.LineID
                                                 select new ExceptionWorktimeDto
                                                 {
                                                     ExceptionID = q1.ExceptionID,
                                                     FactoryNo = q1.FactoryNo,
                                                     UnitNo = q1.UnitNo,
                                                     LineID = q1.LineID,
                                                     LineDesc = q4.LineDesc,
                                                     ExceptionDate = q1.ExceptionDate,
                                                     ClassNo = q1.ClassNo,
                                                     ExceptionNo = q1.ExceptionNo,
                                                     WipNo = q1.WipNo,
                                                     ModelNo = q1.ModelNo,
                                                     Time = q1.Time,
                                                     DeptID = q1.DeptID,
                                                     Memo = q1.Memo,
                                                     StationID = q1.StationID,
                                                     T2UserName = q1.T2UserName,
                                                     StartTime = q1.StartTime,
                                                     EndTime = q1.EndTime,
                                                     DecideDept = q1.DecideDept,
                                                     DecideUser = q1.DecideUser,
                                                     DutyDept = q1.DutyDept,
                                                     Measure = q1.Measure,
                                                     PersonNum = q1.PersonNum,
                                                     ReasonNameCh = q1.ReasonNameCh,
                                                     PersonNo = q1.PersonNo,
                                                     MeasureDate = q1.MeasureDate,
                                                     MeasureMemo = q1.MeasureMemo,
                                                     DecidDeptID = q1.DecidDeptID,
                                                     DecidUserID = q1.DecidUserID,
                                                     DecideUserName = q2.UserName,
                                                     DutyDeptID = q1.DutyDeptID,
                                                     DutyDeptName = q3.DeptName,
                                                     DutyUserID = q1.DutyUserID,
                                                     DutyUser = q1.DutyUser,
                                                     CreateUserID = q1.CreateUserID,
                                                     CreateDate = q1.CreateDate,
                                                     UpdateUserID = q1.UpdateUserID,
                                                     UpdateDate = q1.UpdateDate,

                                                 };




            if (factoryid != "*")
                q = q.Where(p => p.FactoryNo.Equals(factoryid));
            if (unitid != "*")
                q = q.Where(p => p.UnitNo.Equals(unitid));
            if (deptid != "*")
                q = q.Where(p => p.DecidDeptID == int.Parse(deptid));
            if (lineid != "*")
                q = q.Where(p => p.LineID == int.Parse(lineid));

            DateTime dateValue;
            if (sdate != "*")
            {

                if (DateTime.TryParse(sdate, out dateValue))
                {
                    q = q.Where(p => p.ExceptionDate >= DateTime.Parse(sdate));
                }
            }
            if (edate != "*")
            {
                if (DateTime.TryParse(edate, out dateValue))
                {
                    q = q.Where(p => p.ExceptionDate <= DateTime.Parse(edate));
                }

            }


            var exceptionWorktime = await q.ToListAsync();

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


        }

        //YIRU End  ------------------------------------------------------------------------------------------

    }
}