using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using AMESCoreStudio.Web.Models;
using Newtonsoft.Json;
using AMESCoreStudio.WebApi.Models.AMES;
using AMESCoreStudio.CommonTools.Result;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;
using AMESCoreStudio.Web.ViewModels;
using System.ComponentModel.DataAnnotations;

namespace AMESCoreStudio.Web.Controllers
{
    public class REPController : Controller
    {
        private readonly ILogger<REPController> _logger;
        public readonly IREP _repApi;
        public readonly IPPS _ppsApi;
        public readonly IBAS _basApi;

        public REPController(ILogger<REPController> logger, IREP repApi, IPPS ppsApi,IBAS basApi)
        {
            _logger = logger;
            _repApi = repApi;
            _ppsApi = ppsApi;
            _basApi = basApi;
        }


        private async Task GetRMAReasonList()
        {
            var result = await _ppsApi.GetRMAReasons();

            var RMAReasonList = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                RMAReasonList.Add(new SelectListItem(result[i].RMAReasonDesc, result[i].RMAReasonNo.ToString()));
            }
            ViewBag.RMAReasonList = RMAReasonList;
        }


        private async Task GetRepairTypeList()
        {
            var result = await _ppsApi.GetRepairTypes();

            var RepairTypeList = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                RepairTypeList.Add(new SelectListItem(result[i].RepairTypeDesc, result[i].RepairTypeNo.ToString()));
            }
            ViewBag.RepairTypeList = RepairTypeList;
        }

        private async Task GetNGReasonList()
        {
            var result = await _ppsApi.GetNGReasons();

            var NGReasonList = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                NGReasonList.Add(new SelectListItem(result[i].NGReasonDesc, result[i].NGReasonNo.ToString()));
            }
            ViewBag.NGReasonList = NGReasonList;
        }

        private async Task GetRepairResponsibleUnitList()
        {
            var result = await _basApi.GetRepairResponsibleUnitses();

            var RepairResponsibleUnitList = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                RepairResponsibleUnitList.Add(new SelectListItem(result[i].RRDesc, result[i].RRID.ToString()));
            }
            ViewBag.RepairResponsibleUnitList = RepairResponsibleUnitList;
        }

        #region REP001 前判維修輸入

        public IActionResult REP001()
        {
            return View();
        }

        public async Task<IActionResult> REP001V(int id)
        {
            REP001ViewModel model = new REP001ViewModel();
            var result = await _repApi.GetNgInfo(id);
            if (result.Count != 0)
            {
                model.ngInfo = result[0];
            }
            return View(model);
        }

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> GetNgInfoByBarcode(string barcodeNo)
        {
            var result = await _repApi.GetNgInfoByBarcode(barcodeNo);

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

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

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> GetNgComponentByNGID(int id)
        {
            var result = await _repApi.GetNgComponentByNGID(id);

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

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

        public async Task<IActionResult> REP001R(int id)
        {
            await GetRMAReasonList();
            await GetRepairTypeList();
            await GetNGReasonList();
            await GetRepairResponsibleUnitList();

            REP001ViewModel model = new REP001ViewModel();
            var result1 = await _repApi.GetNgComponent(id);
            if (result1.Count != 0)
            {
                model.ngComponent = result1[0];

                var result2 = await _repApi.GetNgInfo((int)result1[0].NgID);
                if (result2.Count != 0)
                {
                    model.ngInfo = result2[0];
                }

                var result3 = await _repApi.GetRepairRecord((int)result1[0].ComponentID);
                if (result3.Count != 0)
                {
                    model.repairRecord = result3[0];
                }

                var result4 = await _repApi.GetNgRepairByComponent((int)result1[0].ComponentID);
                if (result4.Count != 0)
                {
                    model.ngRepair = result4[0];
                }
            }
            
            return View(model);
        }

        //頁面提交,id=0 添加,id>0 修改
        [HttpPost]
        public async Task<IActionResult> REP001RSaveAsync(REP001ViewModel model)
        {
            IResultModel result;
            var userID = "";
            HttpContext.Request.Cookies.TryGetValue("UserID", out userID);
            int user_id = 0;
            if (userID != null)
            {
                if (int.Parse(userID.ToString()) >= 0)
                {
                    user_id = int.Parse(userID.ToString());
                }
            }
            model.ngComponent.ReplyUserID = user_id;
            model.ngComponent.ReplyDate = System.DateTime.Now;
            model.ngComponent.Status = 1;

            result = await _repApi.PutNgComponent((int)model.ngComponent.ComponentID,JsonConvert.SerializeObject(model.ngComponent));

            if (model.repairRecord.ComponentID > 0)
            {
                result = await _repApi.PutRepairRecord((int)model.repairRecord.ComponentID, JsonConvert.SerializeObject(model.repairRecord));
            }
            else
            {
                model.repairRecord.NgID = model.ngComponent.NgID;
                model.repairRecord.ComponentID = model.ngComponent.ComponentID;
                result = await _repApi.PostRepairRecord(JsonConvert.SerializeObject(model.repairRecord));
            }

            if (model.ngRepair.RepairID > 0)
            {
                result = await _repApi.PutNgRepair((int)model.ngRepair.RepairID, JsonConvert.SerializeObject(model.ngRepair));
            }
            else
            {
                model.ngRepair.NgID = model.ngComponent.NgID;
                model.ngRepair.ComponentID = model.ngComponent.ComponentID;
                result = await _repApi.PostNgRepair(JsonConvert.SerializeObject(model.ngRepair));
            }

            if (result.Success)
            {
                var _msg = "保存成功!";
                //return RedirectToAction("REP001V", "REP", new { id = model.ngComponent.NgID, msg = _msg });
                return RedirectToAction("Refresh", "Home", new { id = model.ngComponent.NgID, msg = _msg });
            }
            else
            {
                if (result.Errors.Count > 0)
                {
                    ModelState.AddModelError(result.Errors[0].Id, result.Errors[0].Msg);
                }
                else
                {
                    ModelState.AddModelError("error", result.Msg);
                }
            }

            return View("REP001R", model);
            //return RedirectToAction("REP001V", "REP", new { id = model.ngComponent.NgID });
        }

        #endregion
    }
}