using AMESCoreStudio.CommonTools.Result;
using AMESCoreStudio.WebApi.Models.BAS;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks;
using System;
using System.Net.Mail;
using Microsoft.Extensions.Configuration;
using System.Net;
using System.Linq;
using System.Text.RegularExpressions;
using System.IO;
using AMESCoreStudio.WebApi.Controllers.AMES;
using AMESCoreStudio.WebApi.DTO.AMES;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using AMESCoreStudio.WebApi.Controllers.SYS;

namespace AMESCoreStudio.WebApi.Controllers.BLL
{
    /// <summary>
    /// 報表資料
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class RPTController : Controller
    {
        private readonly AMESContext _context;
        private readonly IConfiguration _config;

        /// <summary>
        /// 建構式
        /// </summary>
        /// <param name="context"></param>
        public RPTController(AMESContext context, IConfiguration config)
        {
            _config = config;
            _context = context;
        }

        /// <summary>
        /// 生產即時效率 
        /// </summary>
        /// <param name="sDate">開始日期</param>
        /// <param name="eDate">結束日期</param>
        /// <returns></returns>
        [HttpGet("GetRPT001View")]
        public async Task<RPT001ViewDto> GetRPT001View(string sDate, string eDate)
        {
            if (string.IsNullOrWhiteSpace(sDate) || string.IsNullOrWhiteSpace(eDate))
            {
                sDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("yyyy/MM/dd");
                eDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)).ToString("yyyy/MM/dd");
            }

            var result = new RPT001ViewDto();
            // 未結工單數
            var a = await new WipInfosController(_context).GetWipInfoPCS008(new DTO.AMES.WipInfoDto
            {
                date_str = sDate,
                date_end = eDate
            });
            result.openOrderWipQty = a.DataTotal;

            // 完工入庫數:GetFqcInhouseMasterMultiQuery
            var b = await new FqcInhouseMasterController(_context).GetFqcInhouseMasteMultiQuery("", "", "", "", date_str: sDate, date_end: eDate, "");
            result.finishedProducts = b.DataTotal;

            //異常工時:GetExceptionWorktime4RPT001
            var c = await new ExceptionWorktimesController(_context).GetExceptionWorktime4RPT001(sDate, eDate);
            decimal errorTime = 0;
            double errTime = 0.00;
            if (c.DataTotal > 0)
            {
                foreach (var item in c.Data)
                {
                    string str = item.ToString();
                    string[] str2 = str.Replace("{", "").Replace("}", "").Split(',');
                    string str3 = "";
                    for (int i = 0; i < str2.Length; i++)
                    {
                        string[] str21 = str2[i].Split("=");
                        str3 = str3 + str21[0].Trim() + ":" + "'" + str21[1].Trim() + "',";
                    }
                    JObject j1 = JObject.Parse("{" + str3.Substring(0, str3.Length - 1) + "}");
                    decimal time = decimal.Parse(j1["Time"].ToString());
                    errorTime = errorTime + time;
                }
                errTime = double.Parse(errorTime.ToString()) / 60.0;
            }
            result.abnormalTime = double.Parse(errTime.ToString("0.00"));

            //直通率:GetWipStation4QRS014GroupALL
            var d = await new WipStationController(_context).GetWipStation4QRS014GroupALL(null, sDate, eDate, null, null, null);
            if (d.DataTotal > 0)
            {
                double sum_rate = 100.0;
                int sum_idx = 1;

                DataTable dtRate = new DataTable();
                dtRate.Columns.Add("STATION_ID");
                dtRate.Columns.Add("OK_QTY");
                dtRate.Columns.Add("NG_QTY");
                dtRate.PrimaryKey = new DataColumn[] { dtRate.Columns[0] };
                dtRate.AcceptChanges();

                foreach (var data in d.Data)
                {
                    string str = data.ToString();
                    string[] str2 = str.Replace("{", "").Replace("}", "").Split(',');
                    string str3 = "";
                    for (int i = 0; i < str2.Length; i++)
                    {
                        string[] str21 = str2[i].Split("=");
                        str3 = str3 + str21[0].Trim() + ":" + "'" + str21[1].Trim() + "',";
                    }
                    JObject j0 = JObject.Parse("{" + str3.Substring(0, str3.Length - 1) + "}");
                    int stationID = int.Parse(j0["StationID"].ToString());

                    bool existFlag = false;
                    int idx = 0;

                    for (int i = 0; i < dtRate.Rows.Count; i++)
                    {
                        if (dtRate.Rows[i]["STATION_ID"].ToString() == stationID.ToString())
                        {
                            idx = i;
                            existFlag = true;
                            break;
                        }
                    }

                    int okQty = 0, ngQty = 0;

                    if (j0["RuleStatus"].ToString() == "P")
                    {
                        okQty = int.Parse(j0["FirstCnt"].ToString());
                    }
                    else
                    {
                        ngQty = int.Parse(j0["FirstCnt"].ToString());
                    }

                    if (existFlag)
                    {
                        if (okQty > 0)
                        {
                            dtRate.Rows[idx][1] = okQty;
                        }
                        if (ngQty > 0)
                        {
                            dtRate.Rows[idx][2] = ngQty;
                        }

                        dtRate.AcceptChanges();
                    }
                    else
                    {
                        DataRow dr = dtRate.NewRow();
                        dr[0] = stationID;
                        dr[1] = okQty;
                        dr[2] = ngQty;

                        dtRate.Rows.Add(dr);
                        dtRate.AcceptChanges();
                    }
                }

                if (dtRate.Rows.Count > 0)
                {
                    for (int j = 0; j < dtRate.Rows.Count; j++)
                    {
                        int okQty = int.Parse(dtRate.Rows[j][1].ToString());
                        int ngQty = int.Parse(dtRate.Rows[j][2].ToString());

                        int inputQty = okQty + ngQty;

                        double rate = 0;
                        if (okQty > 0)
                        {
                            rate = (okQty * 1.0 / inputQty) * 100;
                        }

                        if (rate > 0)
                        {
                            //sum_rate = sum_rate * (rate / 100.0);
                            sum_idx = sum_idx + 1;
                            sum_rate = sum_rate + rate;
                        }
                    }
                }
                result.test = double.Parse((sum_rate / sum_idx).ToString("0.00"));
            }
            else
            {
                result.test = 0.00;
            }

            //IPQC
            var e = await new InspectionResultMastersController(_context).GetIPQCHeaderData4QRS015(null, null, null, sDate, eDate);

            int sumIpqcCnt = 0, sumPassCnt = 0, sumFailCnt = 0;
            foreach (var item in e.Data)
            {
                string str = item.ToString();
                JObject jo = JObject.Parse(str.Replace("=", ":"));

                string ipqc_week = jo["IPQCWeek"].ToString();
                int ipqc_cnt = int.Parse(jo["IPQCCnt"].ToString());
                int pass_cnt = int.Parse(jo["PassCnt"].ToString());
                int fail_cnt = int.Parse(jo["FailCnt"].ToString());
                double ipqc_rate = pass_cnt * 100.0 / ipqc_cnt;
                sumIpqcCnt = sumIpqcCnt + ipqc_cnt;
                sumPassCnt = sumPassCnt + pass_cnt;
                sumFailCnt = sumFailCnt + fail_cnt;
            }
            double sum_ipqc_rate = 0.00;
            if (sumIpqcCnt > 0)
            {
                sum_ipqc_rate = sumPassCnt * 100.0 / sumIpqcCnt;
            }

            result.ipqc = double.Parse(sum_ipqc_rate.ToString("0.00"));


            //FQC
            var f = await new FqcResultMasterController(_context).GetFQCHeaderData4QRS016(null, null, null, sDate, eDate, null);
            if (f.DataTotal > 0)
            {
                int sumFqcCnt = 0, sumFqcPassCnt = 0, sumFqcFailCnt = 0;
                foreach (var item in f.Data)
                {
                    string str = item.ToString();
                    JObject jo = JObject.Parse(str.Replace("=", ":"));

                    string fqc_week = jo["FQCWeek"].ToString();
                    int fqc_cnt = int.Parse(jo["FQCCnt"].ToString());
                    int pass_cnt = int.Parse(jo["PassCnt"].ToString());
                    int fail_cnt = int.Parse(jo["FailCnt"].ToString());
                    double fqc_rate = pass_cnt * 100.0 / fqc_cnt;

                    sumFqcCnt = sumFqcCnt + fqc_cnt;
                    sumFqcPassCnt = sumFqcPassCnt + pass_cnt;
                }
                double sum_fqc_rate = 0.00;
                if (sumFqcCnt > 0)
                {
                    sum_fqc_rate = sumFqcPassCnt * 100.0 / sumFqcCnt;
                }
                result.fqc = double.Parse(sum_fqc_rate.ToString("0.00"));
            }

            /*
            //应出勤人数
            var ea = await new UserInfoesController(_context).GetUserData4EA();
            int eaTime = ea.DataTotal * 8;

            var g = await new WorkManPowersController(_context).GetWorkManPower4RPT001(sDate, eDate);
            double sumAATime = 0.00, sumOverTime = 0.00;
            double aaRate = 0.00;

            if (g.DataTotal > 0)
            {
                foreach (var item in g.Data)
                {
                    //string str = item.ToString();
                    //JObject jo = JObject.Parse(str.Replace("=", ":"));

                    string str = item.ToString();
                    string[] str2 = str.Replace("{", "").Replace("}", "").Split(',');
                    string str3 = "";
                    for (int i = 0; i < str2.Length; i++)
                    {
                        string[] str21 = str2[i].Split("=");
                        str3 = str3 + str21[0].Trim() + ":" + "'" + str21[1].Trim() + "',";
                    }
                    JObject jo = JObject.Parse("{" + str3.Substring(0, str3.Length - 1) + "}");

                    double aa_time = double.Parse(jo["FactWorkH"].ToString());
                    double over_time = double.Parse(jo["OvarH"].ToString());

                    sumAATime = sumAATime + aa_time;
                    sumOverTime = sumOverTime + over_time;

                }

                if (eaTime > 0)
                {
                    aaRate = sumAATime * 100.0 / (eaTime * g.DataTotal);
                }
            }

            //出勤率
            result.attendance = double.Parse(aaRate.ToString("0.00"));
            //加班工时
            result.overtime = double.Parse(sumOverTime.ToString("0.00"));

            //异常工时
            var h = await new ExceptionWorktimesController(_context).GetExceptionWorktime4RPT001(sDate, eDate);
            double sumExceptionTime = 0.00;
            if (h.DataTotal > 0)
            {
                foreach (var item in h.Data)
                {
                    string str = item.ToString();
                    string[] str2 = str.Replace("{", "").Replace("}", "").Split(',');
                    string str3 = "";
                    for (int i = 0; i < str2.Length; i++)
                    {
                        string[] str21 = str2[i].Split("=");
                        str3 = str3 + str21[0].Trim() + ":" + "'" + str21[1].Trim() + "',";
                    }
                    JObject jo = JObject.Parse("{" + str3.Substring(0, str3.Length - 1) + "}");

                    double exception_time = double.Parse(jo["Time"].ToString());

                    sumExceptionTime = sumExceptionTime + exception_time;
                }
            }

            result.abnormalTime = double.Parse((sumExceptionTime / 60.0).ToString("0.00"));
            */

            var pi = await new ProductionIndexesController(_context).GetProductionIndex4RPT001(sDate, eDate);

            int sumPI_EA = 0;
            double sumPI_EATime = 0.00, sumPI_AATime = 0.00, sumPI_InvalidTIme = 0.00, sumPI_OverTime = 0.00, sumPI_ActualTime = 0.00;
            double PI_Attendance = 0.00, PI_Efficiency = 0.00, PI_Productivity = 0.00;
            double attendance = 0.00, efficiency = 0.00, productivity = 0.00;

            if (pi.DataTotal > 0)
            {
                foreach (var item in pi.Data)
                {
                    string str = item.ToString();
                    string[] str2 = str.Replace("{", "").Replace("}", "").Split(',');
                    string str3 = "";
                    for (int i = 0; i < str2.Length; i++)
                    {
                        string[] str21 = str2[i].Split("=");
                        str3 = str3 + str21[0].Trim() + ":" + "'" + str21[1].Trim() + "',";
                    }
                    JObject jo = JObject.Parse("{" + str3.Substring(0, str3.Length - 1) + "}");

                    int pi_ea = int.Parse(jo["EA"].ToString());
                    double pi_eatime = double.Parse(jo["EATime"].ToString());
                    double pi_aatime = double.Parse(jo["AATime"].ToString());
                    double pi_overtime = double.Parse(jo["OverTime"].ToString());
                    double pi_invalidtime = double.Parse(jo["InvalidTime"].ToString());
                    double pi_actualtime = double.Parse(jo["ActualTime"].ToString());
                    double pi_efficiency = double.Parse(jo["Efficiency"].ToString());
                    double pi_productivity = double.Parse(jo["Productivity"].ToString());
                    double pi_attendance = double.Parse(jo["Attendance"].ToString());

                    sumPI_EA = sumPI_EA + pi_ea;
                    sumPI_EATime = sumPI_EATime + pi_eatime;
                    sumPI_AATime = sumPI_AATime + pi_aatime;
                    sumPI_InvalidTIme = sumPI_InvalidTIme + pi_invalidtime;
                    sumPI_OverTime = sumPI_OverTime + pi_overtime;
                    sumPI_ActualTime = sumPI_ActualTime + pi_actualtime;

                    PI_Attendance = PI_Attendance + pi_attendance;
                    PI_Efficiency = PI_Efficiency + pi_efficiency;
                    PI_Productivity = PI_Productivity + pi_productivity;
                }

                if (PI_Attendance > 0)
                {
                    attendance = PI_Attendance / (pi.DataTotal * 1.0);
                }
                if (PI_Efficiency > 0)
                {
                    efficiency = PI_Efficiency / (pi.DataTotal * 1.0);
                }
                if (PI_Productivity > 0)
                {
                    productivity = PI_Productivity / (pi.DataTotal * 1.0);
                }
            }

            result.productivity = double.Parse(efficiency.ToString("0.00"));
            result.attendance = double.Parse(attendance.ToString("0.00"));
            result.productiveForces = double.Parse(productivity.ToString("0.00"));

            result.overtime = sumPI_OverTime;
            result.invalidHours = sumPI_InvalidTIme;

            return result;
        }

        /// <summary>
        /// 品質看板
        /// </summary>
        /// <param name="sDate">開始日期</param>
        /// <param name="eDate">結束日期</param>
        /// <returns></returns>
        [HttpGet("GetRPT002View")]
        public async Task<RPT002ViewDto> GetRPT002View(string sDate, string eDate)
        {
            if (string.IsNullOrWhiteSpace(sDate) || string.IsNullOrWhiteSpace(eDate))
            {
                sDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).ToString("yyyy/MM/dd");
                eDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month)).ToString("yyyy/MM/dd");
            }

            var result = new RPT002ViewDto();
            // 進料批退率 電子
            result.IQLRR_EE = 0.0;

            // 進料批退率 機構
            result.IQLRR_ME = 0.0;

            // 線上材料品質
            result.LQC = 0.0;

            // QRC件數 新增筆數
            result.QRCNew = 0;

            // QRC件數 結案筆數
            result.QRCClose = 0;

            // QRC件數 總筆數
            result.QRCTotal = 0;

            //IPQC異常件數 新增筆數
            result.IPQCNew = 0;

            // IPQC異常件數 結案筆數
            result.IPQCClose = 0;

            // IPQC異常件數 總筆數
            result.IPQCTotal = 0;

            // FQC批退率 Board
            result.FQCRRBoard = 0.0;

            // FQC批退率 System
            result.FQCRRSystem = 0.0;

            // FQC批退率 Medical
            result.FQCRRMedical = 0.0;

            // DOA Board
            result.DOABoard = 0.0;

            // DOA System
            result.DOASystem = 0.0;

            // DOA Medical
            result.DOAMedical = 0.0;

            // FPY 立德 Board
            result.FPYBoard_LEI = 0.0;

            // FPY 立德 System
            result.FPYSystem_LEI = 0.0;

            // FPY 立德 Medical
            result.FPYMedical_LEI = 0.0;

            // FPY Board
            result.FPYBoard = 0.0;

            // FPY System
            result.FPYSystem = 0.0;

            // FPY Medical
            result.FPYMedical = 0.0;

            // RMA Board
            result.RMABoard = 0.0;

            // RMA System
            result.RMASystem = 0.0;

            // RMA Medical
            result.RMAMedical = 0.0;

            // CFQR件數 新增筆數
            result.CFQRNew = 0;

            // CFQR件數 結案筆數
            result.CFQRClose = 0;

            // CFQR件數 總筆數
            result.CFQRTotal = 0;

            return result;
        }
    }
}