using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using AMESCoreStudio.CommonTools.Result;
using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json.Linq;
using AMESCoreStudio.Web.Models;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;
using AMESCoreStudio.Web.ViewModels.QRS;

namespace AMESCoreStudio.Web.Controllers
{
    public class QRSController : Controller
    {
        private readonly ILogger<QRSController> _logger;
        public readonly IREP _repApi;
        public readonly IPPS _ppsApi;
        public readonly IBAS _basApi;
        public readonly IPCS _pcsApi;
        private readonly IWebHostEnvironment _env;

        public QRSController(ILogger<QRSController> logger, IREP repApi, IPPS ppsApi, IBAS basApi, IPCS pcsApi, IWebHostEnvironment env)
        {
            _logger = logger;
            _repApi = repApi;
            _ppsApi = ppsApi;
            _basApi = basApi;
            _pcsApi = pcsApi;
            _env = env;
        }

        public async Task<IActionResult> QRS009()
        {
            IResultModel<dynamic> result = await _pcsApi.GetWipInfo4QRS009();
            
            string wipDataList = "<font size='3'>";
            if (result.DataTotal > 0)
            {
                foreach (var item in result.Data)
                {
                    JObject jo = JObject.Parse(item.ToString());
                    int wip_id = int.Parse(jo["wipID"].ToString());
                    int flow_rule_id = int.Parse(jo["flowRuleID"].ToString());
                    int line_id = int.Parse(jo["lineID"].ToString());
                    string item_no = jo["itemNO"].ToString();
                    string unit_name = jo["unitName"].ToString();
                    string line_desc = jo["lineDesc"].ToString();
                    string wip_no = jo["wipNO"].ToString();
                    int plan_qty = int.Parse(jo["planQTY"].ToString());
                    int input_qty = int.Parse(jo["completeQTY"].ToString());
                    int output_qty = 0;

                    var cycle_time = await _ppsApi.GetCycleTime(item_no + "," + line_id);

                    string ct1 = "";
                    if (cycle_time.Count > 0)
                    {
                        ct1 = cycle_time[0].CT1.ToString()+"s";
                    }

                    wipDataList = wipDataList + "<font color='#FF80FF'>" + unit_name + " - " + line_desc + "</font>" + " - " + "<font color='#0080FF'>" + wip_no + "</font>" + "<font color='#FFC90E'>" + "(" + item_no + ")" + "</font>" + " - " + "<font color='#0080FF'>" + plan_qty + " / " + input_qty + " / " + output_qty + "</font>" +" | "+ "<font color='#0080FF'>" + "標準工時: " + "</font>" + ct1 + "<br/>";

                    var rule_sation = await _basApi.GetRuleStationsByFlow(flow_rule_id);
                    wipDataList = wipDataList + "<table><tr><td width='120'></td>";
                    
                    string stationQty = "<table><tr><td width='120'>過站數量</td>";
                    string stationRate = "<table><tr><td width='120'>良率</td>";
                    string stationWip = "<table><tr><td width='120'>WIP</td>";

                    string stationList = "";
                    for (int j = 0; j < rule_sation.Count; j++)
                    {
                        if (rule_sation[j].StationID != 1000 && rule_sation[j].StationType == "M")
                        {
                            stationList = stationList + rule_sation[j].RuleStationID + ",";

                            wipDataList = wipDataList + "<td width='150' style='text-align:left'>" + rule_sation[j].StationDesc + "</td>";

                            var wip_station = await _pcsApi.GetWipStation4QRS009(wip_id, rule_sation[j].RuleStationID);

                            int okQty = 0, ngQty = 0;
                            if (wip_station.Count > 0)
                            {
                                for (int k = 0; k < wip_station.Count; k++)
                                {
                                    if (wip_station[k].RuleStatus == "P")
                                    {
                                        okQty = wip_station[k].FirstCnt;
                                    }
                                    else
                                    {
                                        ngQty = wip_station[k].FirstCnt;
                                    }
                                }
                            }

                            //stationQty = stationQty + "<td width='150' style='text-align:left'><a href=\"javascript:hg.open('過站PASS條碼資料','/QRS/QRS009P/" + wip_id + "_" + rule_sation[j].RuleStationID + "','','',true);\">" + okQty + "</a>/<a href=\"javascript:hg.open('過站FAIL條碼資料','/QRS/QRS009F','','',true);\">" + ngQty + "</a></td>";
                            stationQty = stationQty + "<td width='150' style='text-align:left'><a href=\"javascript:hg.open('過站PASS條碼資料','/QRS/QRS009P/" + wip_id + "_" + rule_sation[j].RuleStationID + "',800,600);\">" + okQty + "</a>/<a href=\"javascript:hg.open('過站FAIL條碼資料','/QRS/QRS009F/" + wip_id + "_" + rule_sation[j].RuleStationID + "',800,600);\">" + ngQty + "</a></td>";

                            double rate = ((okQty * 1.0) / (okQty + ngQty)) * 100;

                            if (j == rule_sation.Count - 2)
                            {
                                if (rate <= 90)
                                {
                                    stationRate = stationRate + "<td width='150' style='text-align:left;color:red'>" + rate.ToString("0.00") + "%" + "</td>";
                                }
                                else if (rate >= 95 && rate <= 97)
                                {
                                    stationRate = stationRate + "<td width='150' style='text-align:left;color:yellow'>" + rate.ToString("0.00") + "%" + "</td>";
                                }
                                else if (rate >= 98)
                                {
                                    stationRate = stationRate + "<td width='150' style='text-align:left;color:green'>" + rate.ToString("0.00") + "%" + "</td>";
                                }
                                else
                                {
                                    stationRate = stationRate + "<td width='150' style='text-align:left'>" + rate.ToString("0.00") + "%" + "</td>";
                                }
                                //stationRate = stationRate + "<td width='150' style='text-align:left'>" + rate.ToString("0.00") + "%" + "</td>";
                            }
                            else
                            {
                                //stationRate = stationRate + "<td width='90' style='text-align:left'>" + rate.ToString("0.00") + "%" + "</td>";
                                if (rate <= 90)
                                {
                                    stationRate = stationRate + "<td width='90' style='text-align:left;color:red'>" + rate.ToString("0.00") + "%" + "</td>";
                                }
                                else if (rate >= 95 && rate <= 97)
                                {
                                    stationRate = stationRate + "<td width='90' style='text-align:left;color:yellow'>" + rate.ToString("0.00") + "%" + "</td>";
                                }
                                else if (rate >= 98)
                                {
                                    stationRate = stationRate + "<td width='90' style='text-align:left;color:green'>" + rate.ToString("0.00") + "%" + "</td>";
                                }
                                else
                                {
                                    stationRate = stationRate + "<td width='90' style='text-align:left'>" + rate.ToString("0.00") + "%" + "</td>";
                                }
                                stationRate = stationRate + "<td width='60' style='text-align:left'>" + "<font color='#FF80FF'>" + " >> " + "</font>" + "</td>";
                            }
                        }
                    }
                    stationQty = stationQty + "</tr></table>";

                    stationRate = stationRate + "</tr></table>";

                    string[] station_list = stationList.Split(",");

                    for (int j = 0; j < station_list.Length - 1; j++)
                    {
                        var wip_station1 = await _pcsApi.GetWipStation4QRS009(wip_id, int.Parse(station_list[j]));

                        int okQty1 = 0, ngQty1 = 0;

                        if (wip_station1.Count > 0)
                        {
                            for (int k = 0; k < wip_station1.Count; k++)
                            {
                                if (wip_station1[k].RuleStatus == "P")
                                {
                                    okQty1 = wip_station1[k].FirstCnt;
                                }
                                else
                                {
                                    ngQty1 = wip_station1[k].FirstCnt;
                                }
                            }
                        }

                        int okQty2 = 0, ngQty2 = 0;
                        //计算WIP
                        if (j < station_list.Length - 2)
                        {
                            var wip_station2 = await _pcsApi.GetWipStation4QRS009(wip_id, int.Parse(station_list[j+1]));

                            if (wip_station2.Count > 0)
                            {
                                for (int k = 0; k < wip_station2.Count; k++)
                                {
                                    if (wip_station2[k].RuleStatus == "P")
                                    {
                                        okQty2 = wip_station2[k].FirstCnt;
                                    }
                                    else
                                    {
                                        ngQty2 = wip_station2[k].FirstCnt;
                                    }
                                }
                            }
                        }
                        stationWip = stationWip + "<td width='150' style='text-align:left'><a href=\"javascript:hg.open('在製條碼資料','/QRS/QRS009W/" + wip_id + "_" + station_list[j] + "',800,600);\">" + (okQty1 + ngQty1 - okQty2 - ngQty2) + "</a></td>";
                    }

                    stationWip = stationWip + "</tr></table><br/>";

                    wipDataList = wipDataList + "</tr></table>";

                    wipDataList = wipDataList + stationQty;
                    wipDataList = wipDataList + stationRate;
                    wipDataList = wipDataList + stationWip;

                    /*
                    wipDataList = wipDataList + "<table><tr><td width='120'>過站數量</td>";
                    for (int j = 0; j < rule_sation.Count; j++)
                    {
                        if (rule_sation[j].StationID != 1000 && rule_sation[j].StationType == "M")
                        {
                            wipDataList = wipDataList + "<td width='150' style='text-align:left'>" + "0/0" + "</td>";
                        }
                    }
                    wipDataList = wipDataList + "</tr></table>";
                    */

                    /*
                    wipDataList = wipDataList + "<table><tr><td width='120'>良率</td>";
                    for (int j = 0; j < rule_sation.Count; j++)
                    {
                        if (rule_sation[j].StationID != 1000 && rule_sation[j].StationType == "M")
                        {
                            if (j == rule_sation.Count - 2)
                            {
                                wipDataList = wipDataList + "<td width='150' style='text-align:left'>" + "100%" + "</td>";
                            }
                            else
                            { 
                                wipDataList = wipDataList + "<td width='90' style='text-align:left'>" + "100%" + "</td>";
                                wipDataList = wipDataList + "<td width='60' style='text-align:left'>" + "<font color='#FF80FF'>" + " >> " + "</font>" + "</td>";
                            }
                        }
                    }
                    wipDataList = wipDataList + "</tr></table>";
                    */

                    /*
                    wipDataList = wipDataList + "<table><tr><td width='120'>WIP</td>";
                    for (int j = 0; j < rule_sation.Count; j++)
                    {
                        if (rule_sation[j].StationID != 1000 && rule_sation[j].StationType == "M")
                        {
                            wipDataList = wipDataList + "<td width='150' style='text-align:left'>" + "0" + "</td>";
                        }
                    }
                    wipDataList = wipDataList + "</tr></table><br/>";
                    */
                }
            }
            else
            {
                wipDataList = wipDataList + "查无资料";
            }
            wipDataList = wipDataList + "</font>";
            ViewData["WipDataList"] = wipDataList;
            return View();
        }

        public IActionResult QRS009P(string id)
        {
            string[] param = id.Split("_");
            ViewBag.WIP_ID = param[0];
            ViewBag.RULE_STATION_ID = param[1];

            return View();
        }

        public IActionResult QRS009F(string id)
        {
            string[] param = id.Split("_");
            ViewBag.WIP_ID = param[0];
            ViewBag.RULE_STATION_ID = param[1];

            return View();
        }

        public IActionResult QRS009W(string id)
        {
            string[] param = id.Split("_");
            ViewBag.WIP_ID = param[0];
            ViewBag.RULE_STATION_ID = param[1];

            return View();
        }

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> GetWipStationPassBarcode(string id, int page = 0, int limit = 10)
        {
            string[] param = id.Split("_");
            int wip_id = int.Parse(param[0]);
            int rule_station_id = int.Parse(param[1]);

            var result = await _pcsApi.GetWipStationBarcode4QRS009(wip_id, rule_station_id, "P", page, limit);

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

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

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> GetWipStationFailBarcode(string id, int page = 0, int limit = 10)
        {
            string[] param = id.Split("_");
            int wip_id = int.Parse(param[0]);
            int rule_station_id = int.Parse(param[1]);

            var result = await _pcsApi.GetWipStationBarcode4QRS009(wip_id, rule_station_id, "F", page, limit);

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

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

        [ResponseCache(Duration = 0)]
        [HttpGet]
        public async Task<IActionResult> GetWipStationBarcode(string id, int page = 0, int limit = 10)
        {
            string[] param = id.Split("_");
            int wip_id = int.Parse(param[0]);
            int rule_station_id = int.Parse(param[1]);

            var result = await _pcsApi.GetWipBarcode4QRS009(wip_id, rule_station_id, page, limit);

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

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

        private async Task GetProductTypeList()
        {
            var result = await _pcsApi.GetProductTypes();

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

            ViewBag.ProductTypeList = ProductTypes;
        }

        private async Task GetMFGTypeList()
        {
            var result = await _pcsApi.GetMFGTypes();

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

            ViewBag.MFGTypeList = MFGTypes;
        }

        private async Task GetTestTypeList()
        {
            var result = await _basApi.GetTestTypes();

            var TestTypeItems = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                TestTypeItems.Add(new SelectListItem(result[i].TypeName, result[i].TypeNo.ToString()));
            }
            ViewBag.TestTypeList = TestTypeItems;
        }


        private async Task GetUnitList()
        {
            var result = await _basApi.GetFactoryUnits();

            var UnitItems = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                UnitItems.Add(new SelectListItem(result[i].UnitName, result[i].UnitNo.ToString()));
            }
            ViewBag.UnitList = UnitItems;
        }

        private async Task GetLineInfoList()
        {
            var result = await _basApi.GetLineInfoes();

            var LineItems = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                LineItems.Add(new SelectListItem(result[i].LineDesc, result[i].LineID.ToString()));
            }
            ViewBag.LineList = LineItems;
        }

        [HttpPost]
        public async Task<JsonResult> GetUnitLineJson(string unit_no)
        {
            var result = await _basApi.GetLineInfoByUnit(unit_no);

            var item = new List<SelectListItem>();

            for (int i = 0; i < result.Count; i++)
            {
                item.Add(new SelectListItem(result[i].LineDesc, result[i].LineID.ToString()));
            }

            if (item.Count == 0)
            {
                item.Add(new SelectListItem("全部", "*"));
            }

            //将数据Json化并传到前台视图
            return Json(new { data = item });
        }

        private async Task GetStationList()
        {
            var result = await _basApi.GetStationses();

            var StationItems = new List<SelectListItem>();
            for (int i = 0; i < result.Count; i++)
            {
                StationItems.Add(new SelectListItem(result[i].StationName, result[i].StationID.ToString()));
            }
            ViewBag.StationList = StationItems;
        }

        [HttpPost]
        public async Task<JsonResult> GetUnitStationJson(string unit_no)
        {
            var result = await _basApi.GetStationsByUnit(unit_no);

            var item = new List<SelectListItem>();

            for (int i = 0; i < result.Count; i++)
            {
                item.Add(new SelectListItem(result[i].StationName, result[i].StationID.ToString()));
            }

            if (item.Count == 0)
            {
                item.Add(new SelectListItem("全部", "*"));
            }

            //将数据Json化并传到前台视图
            return Json(new { data = item });
        }

        public async Task<IActionResult> QRS010()
        {
            await GetProductTypeList();
            await GetTestTypeList();
            await GetUnitList();
            await GetLineInfoList();
            await GetStationList();
            await GetMFGTypeList();

            return View();
        }

        public async Task<IActionResult> QRS010QueryAsync(string unitNo, string lineID, string stationID, string mfgTypeNo, string wipNO, string itemNO,  string dateStart, string dateEnd, int page = 0, int limit = 10)
        {
            var result = await _pcsApi.GetYieldData4QRS010(unitNo, lineID, stationID, mfgTypeNo, wipNO, itemNO, dateStart, dateEnd, page, limit);

            var query = new QRS010ViewModel();

            foreach (var data in result.Data)
            {
                JObject jo = JObject.Parse(data.ToString());

                var passData = await _pcsApi.GetPassData4QRS010(jo["lineDesc"].ToString(), jo["stationID"].ToString(),jo["wipNO"].ToString());

                foreach (var pass in passData.Data)
                {
                    JObject joPass = JObject.Parse(pass.ToString());

                    query.YieldDatas.Add(new YieldData
                    {
                        WipID = int.Parse(jo["wipID"].ToString()),
                        WipNO = jo["wipNO"].ToString(),
                        PlanQTY = int.Parse(jo["planQTY"].ToString()),
                        RuleStationID = int.Parse(jo["ruleStationID"].ToString()),
                        StationID = int.Parse(jo["stationID"].ToString()),
                        StationDesc = jo["stationDesc"].ToString(),
                        ItemNO = jo["itemNO"].ToString(),
                        LineDesc = jo["lineDesc"].ToString(),
                        ModelNO = jo["modelNO"].ToString(),
                        FirstCnt = int.Parse(joPass["firstCnt"].ToString()),
                        PassCnt = int.Parse(jo["passCnt"].ToString()),
                        Yield = int.Parse(joPass["firstCnt"].ToString()) * 1.0 / int.Parse(jo["passCnt"].ToString()) * 100.0
                    });
                }
            }

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

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

        public IActionResult QRS010A(string id)
        {
            ViewData["ParamList"] = id;
            return View();
        }

        [HttpPost]
        public async Task<JsonResult> GetYieldData4QRS010Async(string id)
        {
            string[] param = id.Split('_');

            var result = await _pcsApi.GetYieldData4QRS010(param[0], param[1], param[2], param[3], param[4], param[5], param[6], param[7], 0, 10);

            var query = new QRS010ViewModel();

            foreach (var data in result.Data)
            {
                JObject jo = JObject.Parse(data.ToString());

                var passData = await _pcsApi.GetPassData4QRS010(jo["lineDesc"].ToString(), jo["stationID"].ToString(), jo["wipNO"].ToString());

                foreach (var pass in passData.Data)
                {
                    JObject joPass = JObject.Parse(pass.ToString());

                    query.YieldDatas.Add(new YieldData
                    {
                        WipID = int.Parse(jo["wipID"].ToString()),
                        WipNO = jo["wipNO"].ToString(),
                        PlanQTY = int.Parse(jo["planQTY"].ToString()),
                        RuleStationID = int.Parse(jo["ruleStationID"].ToString()),
                        StationID = int.Parse(jo["stationID"].ToString()),
                        StationDesc = jo["stationDesc"].ToString(),
                        ItemNO = jo["itemNO"].ToString(),
                        LineDesc = jo["lineDesc"].ToString(),
                        ModelNO = jo["modelNO"].ToString(),
                        FirstCnt = int.Parse(joPass["firstCnt"].ToString()),
                        PassCnt = int.Parse(jo["passCnt"].ToString()),
                        Yield = int.Parse(joPass["firstCnt"].ToString()) * 1.0 / int.Parse(jo["passCnt"].ToString()) * 100.0
                    });
                }
            }

            return Json(query.YieldDatas);
        }

        public async Task<IActionResult> GetYieldData4QRS010ListAsync(string id)
        {

            string[] param = id.Split('_');

            var result = await _pcsApi.GetYieldData4QRS010(param[0], param[1], param[2], param[3], param[4], param[5], param[6], param[7], 0, 10);

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