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.WebApi.DTO.AMES;
using AMESCoreStudio.CommonTools.Result;


namespace AMESCoreStudio.WebApi.Controllers.AMES
{
    /// <summary>
    /// 巡檢類別資料维护
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class InspectionResultDetailsController : ControllerBase
    {
        private readonly AMESContext _context;

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

        /// <summary>
        /// 获取全部巡檢類別資料
        /// </summary>
        /// <returns></returns>
        // GET: api/InspectionResultDetails
        [HttpGet]
        public async Task<ActionResult<IEnumerable<InspectionResultDetail>>> GetInspectionResultDetails()
        {
            IQueryable<InspectionResultDetail> q = _context.InspectionResultDetails;
            q = q.OrderBy(p => p.InspectionID);
            q = q.OrderBy(p => p.InspectionItemID);

            var InspectionResultDetails = await q.ToListAsync();

            return InspectionResultDetails;
        }

        /// <summary>
        /// 用ID获取该巡檢類別資料
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // GET: api/InspectionResultDetails/5
        [HttpGet("{id}")]
        public async Task<ActionResult<IEnumerable<InspectionResultDetail>>> GetInspectionResultDetails(int id)
        {
           
            IQueryable<InspectionResultDetail> q = _context.InspectionResultDetails;
            q = q.Where(p => p.InspectionID.Equals(id));
            q = q.OrderBy(p => p.InspectionItemID);
            var InspectionResultDetail = await q.ToListAsync();

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

            return InspectionResultDetail;
        }


        /// <summary>
        /// 巡檢資料
        /// </summary>
        /// <param name="id">InspectionID</param>
        /// <returns></returns>
        [HttpGet("Query/{id}")]
        //Task<ResultModel<InspectionResultDetailDto>>
        public async Task<ActionResult<IEnumerable<InspectionResultDetailDto>>>   GetInspectionResultDetailQuery(int id)
        {
            //yiru
            IQueryable<InspectionResultDetailDto> q = from q1 in _context.InspectionResultDetails
                       //join q2 in _context.InspectionItems on q1.InspectionItemID equals q2.InspectionItemID
                       join q3 in _context.UserInfoes on q1.CreateUserID equals q3.UserID
                               into subGrp3 from s3 in subGrp3.DefaultIfEmpty()
                       join q4 in _context.UserInfoes on q1.MissingUserID equals q4.UserID
                               into subGrp4 from s4 in subGrp4.DefaultIfEmpty()
                       join q5 in _context.LineInfoes on q1.LineID equals q5.LineID
                               into subGrp5 from s5 in subGrp5.DefaultIfEmpty()
                       join q6 in _context.Stationses on q1.RuleStationID equals q6.StationID
                               into subGrp6 from s6 in subGrp6.DefaultIfEmpty()
                       join q7 in _context.FactoryUnits on q1.MissingUnitNo equals q7.UnitNo
                               into subGrp7 from s7 in subGrp7.DefaultIfEmpty()
                        where q1.InspectionID == id
                     
                        //orderby q1.InspectionItemID descending
                        select new InspectionResultDetailDto
                        {
                            InspectionID = q1.InspectionID,
                            InspectionItemID = q1.InspectionItemID,
                            InspectionItemName = q1.InspectionItem.InspectionItemName,
                            Line = s5.LineDesc,
                            RuleStation = s6.StationName,
                            Location = q1.Location,
                            MissingUnitNo = s7.UnitName,
                            CreateUserID = s3.UserName,
                            MissingUserID = s4.UserName,
                            MissingRemark = q1.MissingRemark,
                            Result = q1.Result == "F" ? "FAIL" : q1.Result == "P" ? "PASS" : "N/A",
                            CreateDate = q1.CreateDate,
                            UpdateDate = q1.UpdateDate,
                            InspectionResult =q1.Result,
                            PeplyReason = q1.ReplyReason,
                            PeplyMethod = q1.ReplyMethod,



                        };
            var query = await q.ToListAsync();

            //ResultModel<InspectionResultDetailDto> result = new ResultModel<InspectionResultDetailDto>();
            //result.Data = query;

            return query;
        }

        /// <summary>
        /// 用ID获取该巡檢類別資料
        /// </summary>
        /// <param name="id"></param>
        /// <param name="Iid"></param>
        /// <returns></returns>
        // GET: api/InspectionResultDetails/5
        [HttpGet("Query/{id}/{Iid}")]
        public async Task<ActionResult<IEnumerable<InspectionResultDetail>>> GetInspectionResultDetailByQuery(int id,int Iid)
        {

            IQueryable<InspectionResultDetail> q = _context.InspectionResultDetails;
            q = q.Where(p => p.InspectionID.Equals(id));
            q = q.Where(p => p.InspectionItemID.Equals(Iid));
            var InspectionResultDetail = await q.ToListAsync();

            if (InspectionResultDetail == null)
            {
                return InspectionResultDetail;
            }

            return InspectionResultDetail;
        }


     

        /// <summary>
        /// 更新巡檢類別資料
        /// </summary>
        /// <param name="id"></param>
        /// <param name="InspectionResultDetail"></param>
        /// <returns></returns>
        // PUT: api/InspectionResultDetails/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<InspectionResultDetail>> PutInspectionResultDetail(int id, [FromBody] InspectionResultDetail InspectionResultDetail)
        {
            ResultModel<InspectionResultDetail> result = new ResultModel<InspectionResultDetail>();
            if (id != InspectionResultDetail.InspectionID)
            {
                result.Success = false;
                result.Msg = "序號錯誤";
                return result;
            } 

            _context.Entry(InspectionResultDetail).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="InspectionResultDetail"></param>
        /// <returns></returns>
        // POST: api/InspectionResultDetails
        // 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<InspectionResultDetail>> PostInspectionResultDetails(InspectionResultDetail InspectionResultDetail)
        {
            ResultModel<InspectionResultDetail> result = new ResultModel<InspectionResultDetail>();
            Helper helper = new Helper(_context);
            //var InspectionResultDetailID = helper.GetIDKey("IRDID").Result;
            //InspectionResultDetail.InspectionID = InspectionResultDetailID;
            _context.InspectionResultDetails.Add(InspectionResultDetail);
            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/InspectionResultDetails/5
        [HttpDelete("{id}")]
        public async Task<ResultModel<InspectionResultDetail>> DeleteInspectionResultDetails(int id)
        {
            ResultModel<InspectionResultDetail> result = new ResultModel<InspectionResultDetail>();
            var inspectionType = await _context.InspectionResultDetails.Where(m => m.InspectionID == id).FirstOrDefaultAsync();
            if (inspectionType == null)
            {
                result.Success = false;
                result.Msg = "序號不存在";
                return result;
            }

            _context.InspectionResultDetails.Remove(inspectionType);
            await _context.SaveChangesAsync();

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

        private bool InspectionResultDetailsExists(int id)
        {
            return _context.InspectionResultDetails.Any(e => e.InspectionID == id);
        }

    }
}