using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using AMESCoreStudio.Web.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using AMESCoreStudio.WebApi;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;
using AMESCoreStudio.WebApi.Models.AMES;
using AMESCoreStudio.WebApi.Models.BAS;
using AMESCoreStudio.Web.ViewModels;
using AMESCoreStudio.Web.ViewModels.PCS;
using AMESCoreStudio.WebApi.DTO.AMES;
using System.Linq;
using AMESCoreStudio.CommonTools.Result;
using System;
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using System.ComponentModel.DataAnnotations;

namespace AMESCoreStudio.Web.Controllers
{
    /// <summary>
    /// FQC管理模組
    /// </summary>
    public class FQCController : Controller
    {
        private readonly ILogger<PCSController> _logger;
        public readonly IFQC _fqcApi;

        public FQCController(ILogger<PCSController> logger, IFQC fqcApi)
        {
            _logger = logger;
            _fqcApi = fqcApi;
        }

        #region 下拉選單
        /// <summary>
        /// 檢驗類別 Select
        /// </summary>
        /// <returns></returns>
        private async Task GetQCGroupSelect()
        {

            var result = await _fqcApi.GetQcGroup();

            var QCGroupList = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                QCGroupList.Add(new SelectListItem(result[i].GroupNameCN + "【" + result[i].GroupNameEN + "】", result[i].GroupID.ToString()));
            }

            if (QCGroupList.Count == 0)
            {
                QCGroupList.Add(new SelectListItem("N/A", null));
            }

            ViewBag.QCGroupSelect = QCGroupList;
        }

        /// <summary>
        /// 抽驗係數 Select
        /// </summary>
        /// <returns></returns>
        private async Task GetQcQuotSelect()
        {
            var result = await _fqcApi.GetQcQuot();

            var QcQuotList = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                QcQuotList.Add(new SelectListItem(result[i].QuotName, result[i].QuotID.ToString()));
            }

            if (QcQuotList.Count == 0)
            {
                QcQuotList.Add(new SelectListItem("N/A", null));
            }

            ViewBag.QcQuotSelect = QcQuotList;
        }

        /// <summary>
        /// FQC狀態維護 Select
        /// </summary>
        /// <returns></returns>
        private async Task GetStatusTypeSelect()
        {
            var result = await _fqcApi.GetStatusType();

            var StatusTypetList = new List<SelectListItem>();
            result = result.OrderByDescending(o => o.StatusNo).ToList();
            for (int i = 0; i < result.Count; i++)
            {
                StatusTypetList.Add(new SelectListItem(result[i].StatusName, result[i].StatusNo.ToString()));
            }

            if (StatusTypetList.Count == 0)
            {
                StatusTypetList.Add(new SelectListItem("N/A", null));
            }

            ViewBag.StatusTypeSelect = StatusTypetList;
        }

        /// <summary>
        /// 不良群組
        /// </summary>
        /// <returns></returns>
        private async Task GetNGGroupSelect()
        {
            var result = await _fqcApi.GetNGGroups(0);

            var NGGroupList = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                NGGroupList.Add(new SelectListItem(result[i].NGGroupName, result[i].NGGroupNo.ToString()));
            }
            ViewBag.NGGroupSelect = NGGroupList;
        }

        /// <summary>
        /// 不良類別 By NGGroup
        /// </summary>
        /// <param name="group_no">NGGroupNo</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> GetNGClassByGroupAsync(string group_no)
        {
            var result = await _fqcApi.GetNGClassesByGroup(group_no);

            var item = new List<SelectListItem>();

            for (int i = 0; i < result.Count; i++)
            {
                item.Add(new SelectListItem(result[i].NGClassName, result[i].NGClassNo.ToString()));
            }
            //将数据Json化并传到前台视图
            return Json(new { data = item });
        }

        /// <summary>
        /// 不良原因 By NGClass
        /// </summary>
        /// <param name="ngClassNo"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> GetNGReasonsByClassAsync(string ngClassNo)
        {
            var result = await _fqcApi.GetNGReasonsByClass(ngClassNo);

            var item = new List<SelectListItem>();

            for (int i = 0; i < result.Count; i++)
            {
                item.Add(new SelectListItem(result[i].NGReasonDesc, result[i].NGReasonNo.ToString()));
            }
            //将数据Json化并传到前台视图
            return Json(new { data = item });
        }
        #endregion

        #region FQC001 檢驗類別維護
        public IActionResult FQC001()
        {
            return View();
        }

        //新增頁面
        public IActionResult FQC001C()
        {
            return View();
        }

        //修改页面
        [HttpGet]
        public async Task<IActionResult> FQC001UAsync(int id)
        {
            var result = await _fqcApi.GetQcGroup(id);
            return View(result);
        }

        public async Task<IActionResult> FQC001DAsync(int id)
        {
            var result = await _fqcApi.DeleteQcGroup(id);
            return Json(new Result() { success = result.Success, msg = result.Msg });
        }

        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> FQC001Async(QcGroup model)
        {
            if (ModelState.IsValid)
            {
                IResultModel result;
                if (model.GroupID == 0)
                {
                    result = await _fqcApi.PostQcGroup(JsonConvert.SerializeObject(model));
                }
                else
                {
                    result = await _fqcApi.PutQcGroup(JsonConvert.SerializeObject(model));
                }

                if (result.Success)
                {
                    var _msg = model.GroupID == 0 ? "新增成功!" : "修改成功!";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }
                else
                {

                    ModelState.AddModelError("error", result.Msg);
                }
            }
            if (model.GroupID == 0)
            {
                return View("FQC001C", model);
            }
            return View("FQC001U", model);
        }

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> FQC001QueryAsync(int page = 0, int limit = 10)
        {
            var result = await _fqcApi.GetQcGroupQuery(page, limit);

            if (result.Data.Count() != 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.DataTotal });
            }

            return Json(new Table() { count = 0, data = null });
        }
        #endregion

        #region FQC002 檢驗項目維護
        public async Task<IActionResult> FQC002()
        {
            await GetQCGroupSelect();
            return View();
        }

        //新增頁面
        public async Task<IActionResult> FQC002C()
        {
            await GetQCGroupSelect();
            return View();
        }

        //修改页面
        [HttpGet]
        public async Task<IActionResult> FQC002UAsync(int id)
        {
            await GetQCGroupSelect();
            var result = await _fqcApi.GetQcItem(id);
            return View(result);
        }

        public async Task<IActionResult> FQC002DAsync(int id)
        {
            var result = await _fqcApi.DeleteQcItem(id);
            return Json(new Result() { success = result.Success, msg = result.Msg });
        }

        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> FQC002Async(QcItem model)
        {
            if (ModelState.IsValid)
            {
                IResultModel result;
                if (model.ItemID == 0)
                {
                    result = await _fqcApi.PostQcItem(JsonConvert.SerializeObject(model));
                }
                else
                {
                    result = await _fqcApi.PutQcItem(JsonConvert.SerializeObject(model));
                }

                if (result.Success)
                {
                    var _msg = model.ItemID == 0 ? "新增成功!" : "修改成功!";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }
                else
                {

                    ModelState.AddModelError("error", result.Msg);
                }
            }
            if (model.ItemID == 0)
            {
                return View("FQC002C", model);
            }
            return View("FQC002U", model);
        }

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> FQC002QueryAsync(int groupID = 0, int page = 0, int limit = 10)
        {
            var result = await _fqcApi.GetQcItemQuery(groupID, page, limit);

            if (result.Data.Count() != 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.DataTotal });
            }

            return Json(new Table() { count = 0, data = null });
        }
        #endregion

        #region FQC003 檢驗結果維護
        public IActionResult FQC003()
        {
            return View();
        }

        //新增頁面
        public IActionResult FQC003C()
        {
            return View();
        }

        //修改页面
        [HttpGet]
        public async Task<IActionResult> FQC003UAsync(string id)
        {
            var result = await _fqcApi.GetFqcResult(id);
            return View(result);
        }

        public async Task<IActionResult> FQC003DAsync(string id)
        {
            var result = await _fqcApi.DeleteFqcResult(id);
            return Json(new Result() { success = result.Success, msg = result.Msg });
        }

        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> FQC003Async(FqcResult model)
        {
            if (ModelState.IsValid)
            {
                IResultModel result;
                if (string.IsNullOrWhiteSpace(model.FqcNo))
                {
                    result = await _fqcApi.PostFqcResult(JsonConvert.SerializeObject(model));
                }
                else
                {
                    result = await _fqcApi.PutFqcResult(JsonConvert.SerializeObject(model));
                }

                if (result.Success)
                {
                    var _msg = string.IsNullOrWhiteSpace(model.FqcNo) ? "新增成功!" : "修改成功!";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }
                else
                {

                    ModelState.AddModelError("error", result.Msg);
                }
            }
            if (string.IsNullOrWhiteSpace(model.FqcNo))
            {
                return View("FQC003C", model);
            }
            return View("FQC003U", model);
        }

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> FQC003QueryAsync(int page = 0, int limit = 10)
        {
            var result = await _fqcApi.GetFqcResultQuery(page, limit);

            if (result.Data.Count() != 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.DataTotal });
            }

            return Json(new Table() { count = 0, data = null });
        }
        #endregion

        #region FQC004 抽驗係數維護
        public IActionResult FQC004()
        {
            return View();
        }

        //新增頁面
        public IActionResult FQC004C()
        {
            return View();
        }

        //修改页面
        [HttpGet]
        public async Task<IActionResult> FQC004UAsync(int id)
        {
            var result = await _fqcApi.GetQcQuot(id);
            return View(result);
        }

        public async Task<IActionResult> FQC004DAsync(int id)
        {
            var result = await _fqcApi.DeleteQcQuot(id);
            return Json(new Result() { success = result.Success, msg = result.Msg });
        }

        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> FQC004Async(QcQuot model)
        {
            if (ModelState.IsValid)
            {
                IResultModel result;
                if (model.QuotID == 0)
                {
                    result = await _fqcApi.PostQcQuot(JsonConvert.SerializeObject(model));
                }
                else
                {
                    result = await _fqcApi.PutQcQuot(JsonConvert.SerializeObject(model));
                }

                if (result.Success)
                {
                    var _msg = model.QuotID == 0 ? "新增成功!" : "修改成功!";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }
                else
                {

                    ModelState.AddModelError("error", result.Msg);
                }
            }
            if (model.QuotID == 0)
            {
                return View("FQC004C", model);
            }
            return View("FQC004U", model);
        }

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> FQC004QueryAsync(int page = 0, int limit = 10)
        {
            var result = await _fqcApi.GetQcQuotQuery(page, limit);

            if (result.Data.Count() != 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.DataTotal });
            }

            return Json(new Table() { count = 0, data = null });
        }
        #endregion

        #region FQC005 抽驗係數維護
        public async Task<IActionResult> FQC005()
        {
            await GetQcQuotSelect();
            return View();
        }

        //新增頁面
        public async Task<IActionResult> FQC005C()
        {
            await GetQcQuotSelect();
            return View();
        }

        //修改页面
        [HttpGet]
        public async Task<IActionResult> FQC005UAsync(int id)
        {
            await GetQcQuotSelect();
            var result = await _fqcApi.GetQcCriterion(id);
            return View(result);
        }

        public async Task<IActionResult> FQC005DAsync(int id)
        {
            var result = await _fqcApi.DeleteQcCriterion(id);
            return Json(new Result() { success = result.Success, msg = result.Msg });
        }

        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> FQC005Async(QcCriterion model)
        {
            await GetQcQuotSelect();
            if (ModelState.IsValid)
            {
                #region 判斷設定起訖數量區間是否有重疊
                var query = await _fqcApi.GetQcCriterionByQuotID(model.QuotID);
                // 排除自己
                query = query.Where(w => w.CritID != model.CritID).ToList();

                if (query.Where(w => w.QcStart <= model.QcStart && model.QcStart <= w.QcEnd).Any() ||
                    query.Where(w => w.QcStart <= model.QcEnd && model.QcEnd <= w.QcEnd).Any())
                {
                    ModelState.AddModelError("error", "設定起訖數量區間有重疊,請確認");
                    if (model.CritID == 0)
                    {
                        return View("FQC005C", model);
                    }
                    return View("FQC005U", model);
                }
                #endregion

                IResultModel result;
                if (model.CritID == 0)
                {
                    result = await _fqcApi.PostQcCriterion(JsonConvert.SerializeObject(model));
                }
                else
                {
                    result = await _fqcApi.PutQcCriterion(JsonConvert.SerializeObject(model));
                }

                if (result.Success)
                {
                    var _msg = model.CritID == 0 ? "新增成功!" : "修改成功!";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }
                else
                {
                    ModelState.AddModelError("error", result.Msg);
                }
            }
            if (model.CritID == 0)
            {
                return View("FQC005C", model);
            }
            return View("FQC005U", model);
        }

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> FQC005QueryAsync(int quotID = 0, int page = 0, int limit = 10)
        {
            var result = await _fqcApi.GetQcCriterionQuery(quotID, page, limit);

            if (result.Data.Count() != 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.DataTotal });
            }

            return Json(new Table() { count = 0, data = null });
        }
        #endregion

        #region FQC006 FQC狀態維護
        public IActionResult FQC006()
        {
            return View();
        }

        //新增頁面
        public IActionResult FQC006C()
        {
            return View();
        }

        //修改页面
        [HttpGet]
        public async Task<IActionResult> FQC006UAsync(string id)
        {
            var result = await _fqcApi.GetStatusType(id);
            return View(result);
        }

        public async Task<IActionResult> FQC006DAsync(string id)
        {
            var result = await _fqcApi.DeleteStatusType(id);
            return Json(new Result() { success = result.Success, msg = result.Msg });
        }

        // 添加
        [HttpPost]
        public async Task<IActionResult> FQC006CAsync(StatusType model)
        {
            if (ModelState.IsValid)
            {
                IResultModel result;

                result = await _fqcApi.PostStatusType(JsonConvert.SerializeObject(model));

                if (result.Success)
                {
                    var _msg = "新增成功!";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }
                else
                {
                    ModelState.AddModelError("error", result.Msg);
                }
            }

            return View("FQC006C", model);
        }

        // 修改
        [HttpPost]
        public async Task<IActionResult> FQC006UAsync(StatusType model)
        {
            if (ModelState.IsValid)
            {
                IResultModel result;

                result = await _fqcApi.PutStatusType(JsonConvert.SerializeObject(model));

                if (result.Success)
                {
                    var _msg = "修改成功!";
                    return RedirectToAction("Refresh", "Home", new { msg = _msg });
                }
                else
                {
                    ModelState.AddModelError("error", result.Msg);
                }
            }

            return View("FQC006U", model);
        }

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> FQC006QueryAsync(int page = 0, int limit = 10)
        {
            var result = await _fqcApi.GetStatusTypeQuery(page, limit);

            if (result.Data.Count() != 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.DataTotal });
            }

            return Json(new Table() { count = 0, data = null });
        }
        #endregion

        #region FQC007 FQC抽驗作業
        public IActionResult FQC007()
        {
            var model = new FqcDto();
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> FQC007Async(FqcDto model)
        {
            if (string.IsNullOrWhiteSpace(model.InhouseNo))
            {
                ModelState.AddModelError("error", "請輸入入庫單號");
                return View("FQC007", model);
            }

            IResultModel<FqcDto> result;

            result = await _fqcApi.GetFqcQuery(model.InhouseNo, model.SeqID);

            if (result.Data.Count() != 0)
            {
                model = result.Data.FirstOrDefault();
                model.h_InhouseNo = model.InhouseNo;
                model.h_SeqID = model.SeqID.ToString();
            }
            else
            {
                ModelState.AddModelError("error", "找不到入庫單號【" + model.InhouseNo + "】的資料");
                model.h_InhouseNo = "";
                model.h_SeqID = "";
            }

            return View("FQC007", model);
        }

        #region 抽驗
        [HttpGet]
        public async Task<IActionResult> FQC007C(string inhouseNo, string seq)
        {
            await GetStatusTypeSelect();
            await GetNGGroupSelect();
            var model = new FqcResultDto();
            model.InhouseNo = inhouseNo;
            model.SeqID = int.Parse(seq);
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> FQC007CAsync(FqcResultDto model)
        {
            await GetStatusTypeSelect();
            await GetNGGroupSelect();
            if (string.IsNullOrWhiteSpace(model.BarcodeNo) &&
                string.IsNullOrWhiteSpace(model.BoxNo) &&
                string.IsNullOrWhiteSpace(model.ExtraBarcodeNo))
            {
                ModelState.AddModelError("error", "請輸入要抽驗的相關序號");
                return View("FQC007C", model);
            }

            #region 相關查詢序號找出包裝箱號
            var result_BarCodeInfo = new List<BarcodeInfo>();
            if (!string.IsNullOrWhiteSpace(model.BarcodeNo))
            {
                result_BarCodeInfo = await _fqcApi.GetBarcodeInfoesByNo(model.BarcodeNo);
            }
            else if (!string.IsNullOrWhiteSpace(model.ExtraBarcodeNo))
            {
                result_BarCodeInfo = await _fqcApi.GetBarcodeInfoesByExtraNo(model.ExtraBarcodeNo);
            }
            else if (!string.IsNullOrWhiteSpace(model.BoxNo))
            {
                result_BarCodeInfo = await _fqcApi.GetBarcodeInfoesByBoxNo(model.BoxNo);
            }

            if (result_BarCodeInfo.Count == 0)
            {
                ModelState.AddModelError("error", "找不到相關資料");
                return View("FQC007C", model);
            }
            else
                model.BoxNo = result_BarCodeInfo.FirstOrDefault().BoxNo;
            #endregion

            #region 判斷是否包裝外箱是否跟入庫單號綁一起
            var result_FqcInhouseDetail = await _fqcApi.GetFqcInhouseDetail(model.InhouseNo, model.SeqID);
            if (!result_FqcInhouseDetail.Where(w => w.SerialNo == model.BoxNo).Any())
            {
                ModelState.AddModelError("error", "入庫單號【" + model.InhouseNo + "】找不到包裝箱號【" + model.BoxNo + "】");
                return View("FQC007C", model);
            }
            #endregion

            #region Set_FqcResultDetail
            if (model.StatusNo == "F" && model.NgReasonNo == "0")
            {
                ModelState.AddModelError("error", "請選擇不良代碼");
                return View("FQC007C", model);
            };

            var FqcResultDetail = new FqcResultDetail
            {
                BarcodeNo = result_BarCodeInfo.FirstOrDefault().BarcodeNo,
                ExtraBarcodeNo = result_BarCodeInfo.FirstOrDefault().ExtraBarcodeNo,
                BoxNo = result_BarCodeInfo.FirstOrDefault().BoxNo,
                StatusNo = model.StatusNo,
                NgMemo = model.NgMemo,
                NgReasonNo = model.NgReasonNo
            };

            if (string.IsNullOrWhiteSpace(FqcResultDetail.ExtraBarcodeNo))
            {
                ModelState.AddModelError("error", "找不到該筆資料的客戶序號");
                return View("FQC007C", model);
            }
            #endregion

            #region 判斷已有抽驗過
            var result_FqcResultMaster = await _fqcApi.GetFqcResultMasterByInhouseNo(model.InhouseNo, model.SeqID);
            if (result_FqcResultMaster.Count() != 0)
            {
                var result_ResultDetail = await _fqcApi.GetFqcResultDetail(result_FqcResultMaster.FirstOrDefault().FqcID);
                if (result_ResultDetail.Where(w => w.BarcodeNo == FqcResultDetail.BarcodeNo).Any())
                {
                    ModelState.AddModelError("error", "內部序號【" + FqcResultDetail.BarcodeNo + "】已抽驗過");
                    return View("FQC007C", model);
                }
            }
            #endregion

            #region Set_FqcResultMaster
            var FqcResultMaster = new FqcResultMaster();
            if (result_FqcResultMaster.Count != 0)
            {
                FqcResultMaster = result_FqcResultMaster.FirstOrDefault();
                FqcResultMaster.QaQty += 1;
                FqcResultMaster.UpdateDate = DateTime.Now;
            }
            else
            {
                IResultModel<FqcDto> FqcDto;
                FqcDto = await _fqcApi.GetFqcQuery(model.InhouseNo, model.SeqID);
                var FirstFqc = FqcDto.Data.FirstOrDefault();
                FqcResultMaster.InhouseNo = model.InhouseNo;
                FqcResultMaster.SeqID = model.SeqID;
                FqcResultMaster.LotQty = FirstFqc.InhouseQty;
                FqcResultMaster.WipNo = FirstFqc.WipNo;
                FqcResultMaster.QaQty = 1;
                FqcResultMaster.ItemNo = FirstFqc.ItemNo;
                FqcResultMaster.ModelNo = FirstFqc.ModelNo;
                FqcResultMaster.StartTime = DateTime.Now;
                FqcResultMaster.EndTime = DateTime.Now;
            }

            // 判斷是PASS || FAIL
            if (model.StatusNo == "F")
                FqcResultMaster.FailQty += 1;
            else
                FqcResultMaster.PassQty += 1;
            #endregion

            IResultModel<FqcResultMaster> result;
            if (result_FqcResultMaster.Count == 0)
            {
                result = await _fqcApi.PostFqcResultMaster(JsonConvert.SerializeObject(FqcResultMaster));
                FqcResultDetail.FqcID = result.Data.FirstOrDefault().FqcID;
            }
            else
            {
                result = await _fqcApi.PutFqcResultMaster(JsonConvert.SerializeObject(FqcResultMaster));
                FqcResultDetail.FqcID = result_FqcResultMaster.FirstOrDefault().FqcID;
            }
            IResultModel result_detail;
            result_detail = await _fqcApi.PostFqcResultDetail(JsonConvert.SerializeObject(FqcResultDetail));

            if (result_detail.Success)
            {
                var _msg = "新增成功!";
                return RedirectToAction("WindowReload", "Home", new { msg = _msg });
            }
            else
            {
                ModelState.AddModelError("error", result_detail.Msg);
            }


            return View("FQC007C", model);
        }
        #endregion

        #region 檢驗結果
        [HttpGet]
        public async Task<IActionResult> FQC007B(string inhouseNo, string seq, int fqc)
        {
            var model = new FqcResultMaster();
            model.InhouseNo = inhouseNo;
            model.SeqID = int.Parse(seq);
            model.FqcID = fqc;
            var result = await _fqcApi.GetFqcQuery(model.InhouseNo, model.SeqID);
            var fqcItem = result.Data.FirstOrDefault();

            //當抽驗數量 小於 抽樣數量就離開
            if (fqcItem.QcQty > fqcItem.PassQty + fqcItem.FailQty)
            {
                var _msg = "抽樣數量不足,無法判定";
                return RedirectToAction("Refresh", "Home", new { msg = _msg });
            }

            // 判斷狀態選擇
            if (fqcItem.FailQty >= fqcItem.ReQty)
                model.QaResult = "R";
            else
                model.QaResult = "P";

            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> FQC007BAsync(FqcResultMaster model, string Result)
        {
            var FqcQuery = await _fqcApi.GetFqcQuery(model.InhouseNo, model.SeqID);
            var fqcItem = FqcQuery.Data.FirstOrDefault();
            // 判斷狀態選擇
            if (fqcItem.FailQty >= fqcItem.ReQty)
            {
                if (model.QaResult == "P" && string.IsNullOrWhiteSpace(model.SpecialPo))
                {
                    ModelState.AddModelError("error", "請輸入特採單號");
                    return View("FQC007B", model);
                }
            }

            var fqcResultMaster = await _fqcApi.GetFqcResultMaster(model.FqcID);
            var fqcInhouseMaster = await _fqcApi.GetFqcInhouseMaster(model.InhouseNo, model.SeqID);

            fqcResultMaster.QaResult = model.QaResult;
            fqcResultMaster.QaMeno = model.QaMeno;
            fqcResultMaster.EndTime = DateTime.Now;
            fqcResultMaster.UpdateDate = DateTime.Now;
            fqcResultMaster.SpecialPo = model.SpecialPo;

            fqcInhouseMaster.Status = model.QaResult;
            fqcInhouseMaster.UpdateDate = DateTime.Now;

            IResultModel result;
            result = await _fqcApi.PutFqcInhouseMaster(JsonConvert.SerializeObject(fqcInhouseMaster));
            result = await _fqcApi.PutFqcResultMaster(JsonConvert.SerializeObject(fqcResultMaster));
            if (result.Success)
            {
                var _msg = "新增成功!";
                return RedirectToAction("WindowReload", "Home", new { msg = _msg });
            }
            else
            {
                ModelState.AddModelError("error", result.Msg);
            }

            return View("FQC007B", model);
        }
        #endregion

        #region 文件
        [HttpGet]
        public async Task<IActionResult> FQC007D(int fqc)
        {
            FqcDto fqcDto = new FqcDto();
            var model = await _fqcApi.GetFqcResultMasterBlobByFqcID(fqc);
            fqcDto.fqcResultMasterBlobs = model;
            fqcDto.FqcID = fqc;
            return View(fqcDto);
        }

        [HttpPost]
        public async Task<IActionResult> FQC007DAsync(FqcResultMaster model, string Result)
        {
            var FqcQuery = await _fqcApi.GetFqcQuery(model.InhouseNo, model.SeqID);
            var fqcItem = FqcQuery.Data.FirstOrDefault();
            // 判斷狀態選擇
            if (fqcItem.FailQty >= fqcItem.ReQty)
            {
                if (model.QaResult == "P" && string.IsNullOrWhiteSpace(model.SpecialPo))
                {
                    ModelState.AddModelError("error", "請輸入特採單號");
                    return View("FQC007B", model);
                }
            }

            var fqcResultMaster = await _fqcApi.GetFqcResultMaster(model.FqcID);
            var fqcInhouseMaster = await _fqcApi.GetFqcInhouseMaster(model.InhouseNo, model.SeqID);

            fqcResultMaster.QaResult = model.QaResult;
            fqcResultMaster.QaMeno = model.QaMeno;
            fqcResultMaster.EndTime = DateTime.Now;
            fqcResultMaster.UpdateDate = DateTime.Now;
            fqcResultMaster.SpecialPo = model.SpecialPo;

            fqcInhouseMaster.Status = model.QaResult;
            fqcInhouseMaster.UpdateDate = DateTime.Now;

            IResultModel result;
            result = await _fqcApi.PutFqcInhouseMaster(JsonConvert.SerializeObject(fqcInhouseMaster));
            result = await _fqcApi.PutFqcResultMaster(JsonConvert.SerializeObject(fqcResultMaster));
            if (result.Success)
            {
                var _msg = "新增成功!";
                return RedirectToAction("WindowReload", "Home", new { msg = _msg });
            }
            else
            {
                ModelState.AddModelError("error", result.Msg);
            }

            return View("FQC007B", model);
        }
        #endregion

        #endregion

        #region FQC008 FQC查詢
        public IActionResult FQC008()
        {
            return View();
        }

        public async Task<IActionResult> FQC008QueryAsync(string barcodeNo, string wipNo
          , string boxNo, string inhouseNo, string date_str, string date_end
          , string status, int page = 0, int limit = 10)
        {
            IResultModel<FqcInhouseMasterDto> result = await _fqcApi.GetFqcInhouseMasterQuery(barcodeNo: barcodeNo, wipNo: wipNo
            , boxNo: boxNo, inhouseNo: inhouseNo, date_str: date_str, date_end: date_end
            , status: status, page: page, limit: limit);

            if (result.Data.Count() != 0)
            {
                return Json(new Table() { code = 0, msg = "", data = result.Data, count = result.DataTotal });
            }
            return Json(new Table() { count = 0, data = null });
        }
        #endregion

        #region FQC009 料號對應檢驗工項

        public ActionResult FQC009()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> FQC009Async(string itemID, string groupID, string itemNo)
        {
            var result = await _fqcApi.GetMaterialItemByItemNO(itemNo);
            if (result == null)
            {
                var Msg = "在料號主檔找不到該筆料號【" + itemNo + "】";
                return Json(new { code = 0, msg = Msg, success = false });
            }

            // 取料號綁定檢驗工項
            var result_MasterFQC = await _fqcApi.GetMaterialFqcItemsByitemNo(itemNo);
            // 有勾選的ItemID
            var checkItemID = itemID.Split(',').ToList();
            // 有勾選的GroupID
            var checkGroupID = groupID.Split(',').ToList();

            // 取勾選有的 = 新增
            var insertItemID = checkItemID.Except(result_MasterFQC.Select(s => s.QcItemID.ToString()));
            for (int i = 0; i < checkItemID.Count; i++)
            {
                if (insertItemID.Where(w => w == checkItemID[i]).Any())
                {
                    MaterialFqcItem materialFqcItem = new MaterialFqcItem
                    {
                        ItemID = result.ItemID,
                        QcItemID = Int32.Parse(checkItemID[i]),
                        QcGroupID = Int32.Parse(checkGroupID[i]),
                        CreateUserID = GetLogInUserID(),
                        CreateDate = DateTime.Now,
                        UpdateUserID = GetLogInUserID(),
                        UpdateDate = DateTime.Now
                    };
                    await _fqcApi.PostMaterialFqcItem(JsonConvert.SerializeObject(materialFqcItem));
                }
            }

            // 取有料號綁定 = 需要刪除
            var deteleItemID = result_MasterFQC.Select(s => s.QcItemID.ToString()).Except(checkItemID);
            foreach (var item in deteleItemID)
            {
                var masterFQCID = result_MasterFQC.Where(w => w.QcItemID == Int32.Parse(item)).FirstOrDefault().MaterialFqcitemID;
                await _fqcApi.DeleteMaterialFqcItem(masterFQCID);
            }

            return Json(new { code = 0, msg = "", success = true });
        }

        [HttpGet]
        public async Task<IActionResult> FQC009ItemQueryAsync(int groupID = 0, int page = 0, int limit = 1, string itemNo = null)
        {
            var msg = "";
            var result = await _fqcApi.GetQcItemQuery(groupID, 0, limit, itemNo);
            if (result.Data.Count() != 0)
            {
                if (!string.IsNullOrWhiteSpace(itemNo))
                {
                    var masterlItem = await _fqcApi.GetMaterialItemByItemNO(itemNo);
                    if (masterlItem == null)
                    {
                        msg = "在料號主檔找不到該筆料號【" + itemNo + "】";
                    }
                }
                return Json(new Table() { code = 0, msg = msg, data = result.Data, count = result.DataTotal });
            }

            return Json(new Table() { count = 0, data = null });
        }
        #endregion

        /// <summary>
        /// 登入UserID
        /// </summary>
        /// <returns></returns>
        public int GetLogInUserID()
        {
            int user_id = -1;
            HttpContext.Request.Cookies.TryGetValue("UserID", out string userID);

            if (userID != null)
            {
                if (int.Parse(userID.ToString()) >= 0)
                {
                    user_id = int.Parse(userID.ToString());
                }
            }
            return user_id;
        }
    }
}