using MOKA_Factory_Tools.DAL;
using MOKA_Factory_Tools.Models;
using SXLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MOKA_Factory_Tools.BLL
{
    public partial class NTFBLL
    {
        /// <summary>
        /// ""=异常,OncePass，NTF，ReadFial
        /// </summary>
        public string ResultType = "";
        private string _strLastSN = "";
        protected readonly DAL_AMResult dalAMResult = new DAL_AMResult();
        protected readonly DAL_AMYields dalAMYields = new DAL_AMYields();
        protected readonly DAL_AMResult_TR dalAMResultTR = new DAL_AMResult_TR();
        protected readonly DAL_AMYields_TR dalAMYieldsTR = new DAL_AMYields_TR();
        /// <summary>
        /// 设置数据抄写结果;
        /// </summary>
        /// <param name="strLine">线体，UI输入</param>
        /// <param name="strStation">默认为:DataBurning</param>
        /// <param name="strSN"></param>
        /// <param name="bResult">抄写结果：成功或失败</param>
        /// <param name="strErrMsg">抄写失败时的描述</param>
        /// <returns></returns>
        public bool SetDataBuringResult(string strLine, string strStation, string strSN, string strDSN, bool bResult, string strLastSN, int nOrderType, string strErrMsg = "")
        {
            MaInfo maInfo;
            _strLastSN = strLastSN;
            DateTime dateNow = DateTime.Now;
            // 通过SN获取MES服务器中记录的ODF、Model、Dissemination信息;            
            if (GMethod.GetMaInfo(strSN, out maInfo, null))
            {
                // 1.通过SN查询出订单类型;
                if (nOrderType == 1)    // 量产;
                {
                    AMResult aMResult = new AMResult();
                    // 测试日期;
                    string strTestDate = dateNow.ToString("yyyy-MM-dd");
                    // 测试完成时间;
                    string strTestTime = dateNow.ToString("yyyy-MM-dd HH:mm:ss");

                    #region 赋值model
                    aMResult.TestDate = dateNow.Date;
                    aMResult.Line = strLine;
                    aMResult.Station = strStation;
                    aMResult.DSN = strDSN;
                    aMResult.ODF = maInfo.ODF;
                    aMResult.Model = maInfo.Model;
                    aMResult.Dimension = maInfo.SIZE;
                    aMResult.TestHour = dateNow.Hour;
                    aMResult.TestTime = strTestTime;
                    aMResult.SN = strSN;
                    #endregion

                    if (IsRecordExist(aMResult))
                    {
                        if (!UpdateAMResults(aMResult, bResult, strErrMsg))
                        {
                            // 更新失败;
                            return false;
                        }
                    }
                    else
                    {
                        if (!AddAMResult(aMResult, bResult, strErrMsg))
                        {
                            // 更新失败;
                            return false;
                        }
                    }

                    // 更新统计结果;
                    if (!UpdateAMYields(aMResult, bResult, strErrMsg))
                    {
                        return false;
                    }

                    return true;
                }
                else if (nOrderType == 0)   // 试产;
                {
                    AMResult_TR aMResult = new AMResult_TR();
                    // 测试日期;
                    string strTestDate = dateNow.ToString("yyyy-MM-dd");
                    // 测试完成时间;
                    string strTestTime = dateNow.ToString("yyyy-MM-dd HH:mm:ss");

                    #region 赋值model
                    aMResult.TestDate = dateNow.Date;
                    aMResult.Line = strLine;
                    aMResult.Station = strStation;
                    aMResult.DSN = strDSN;
                    aMResult.ODF = maInfo.ODF;
                    aMResult.Model = maInfo.Model;
                    aMResult.Dimension = maInfo.SIZE;
                    aMResult.TestHour = dateNow.Hour;
                    aMResult.TestTime = strTestTime;
                    aMResult.SN = strSN;
                    #endregion

                    if (IsRecordExist(aMResult))
                    {
                        if (!UpdateAMResults(aMResult, bResult, strErrMsg))
                        {
                            // 更新失败;
                            return false;
                        }
                    }
                    else
                    {
                        if (!AddAMResult(aMResult, bResult, strErrMsg))
                        {
                            // 更新失败;
                            return false;
                        }
                    }

                    // 更新统计结果;
                    if (!UpdateAMYields(aMResult, bResult, strErrMsg))
                    {
                        return false;
                    }

                    return true;
                }
            }

            return false;
        }

        #region ------量产NTF------;
        public bool IsRecordExist(AMResult model)
        {
            return dalAMResult.Exists(string.Format("Station='{0}' and SN='{1}'", model.Station, model.SN));
        }

        /// <summary>
        /// 新增记录;
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddAMResult(AMResult model, bool TestResult, string strErrMsg)
        {
            // 赋新值;
            model.Test01 = model.FinalTest = TestResult ? "PASS" : "FAIL";
            model.Test02 = "null";
            model.ReDo = "0";
            ResultType = model.ResultType = TestResult ? "OncePass" : "RealFail";
            if (!TestResult)
                model.ErrorMsg = strErrMsg;
            return dalAMResult.Add(model);
        }

        public bool UpdateAMResults(AMResult model, bool TestResult, string strErrMsg)
        {
            // 先获取ReDo="0"的记录;
            AMResult redo0Model = dalAMResult.GetModel(string.Format("Station='{0}' and SN='{1}' and ReDo='{2}'", model.Station, model.SN, "0"));
            if (_strLastSN == model.SN)
            {// 连续抄写数据,更新ReDo="0"的记录;
                Log.WriteInfoLog(string.Format("上一次SN={0} 与当前SN={1} 相同，只更新数据", _strLastSN, model.SN));
                if (!UpdateReDo0AMResult(redo0Model, TestResult, strErrMsg))
                {
                    // 更新失败;
                    Log.WriteInfoLog(string.Format("AMResult更新SN={0}，Station={1}，TestTime={2}，ReDo={3} 失败", redo0Model.SN, redo0Model.Station, redo0Model.TestTime, redo0Model.ReDo));
                    return false;
                }
            }
            else
            {// 将原ReDo="0"更新为ReDo=Max(ReDo)+1,并新增ReDo="0"的记录;
                int maxReDo = dalAMResult.GetMaxID("convert(int,ReDo)", string.Format("Station='{0}' and SN='{1}'", model.Station, model.SN));
                redo0Model.ReDo = maxReDo.ToString();
                if (!dalAMResult.Update(redo0Model, string.Format("Station='{0}' and SN='{1}' and ReDo='{2}'", redo0Model.Station, redo0Model.SN, "0")))
                {
                    // 更新失败;
                    Log.WriteInfoLog(string.Format("AMResult更新SN={0}，Station={1}，TestTime={2}，ReDo={3} 失败", redo0Model.SN, redo0Model.Station, redo0Model.TestTime, redo0Model.ReDo));
                    return false;
                }

                // 新增ReDo=0记录;
                if (!AddAMResult(model, TestResult, strErrMsg))
                {
                    // 添加失败;
                    Log.WriteInfoLog(string.Format("AMResult新增SN={0}，Station={1}，TestTime={2}，ReDo={3} 失败", model.SN, model.Station, model.TestTime, model.ReDo));
                    return false;
                }
            }

            return true;
        }

        public bool UpdateReDo0AMResult(AMResult redo0Model, bool TestResult, string strErrMsg)
        {
            #region 测试第2次;
            if (redo0Model.Test01.ToLower() == "pass" && redo0Model.Test02.ToLower() == "null" && redo0Model.FinalTest.ToLower() == "pass")
            {// 1.resulttype=oncepass;
                if (TestResult)
                {
                    redo0Model.Test02 = "PASS";
                    redo0Model.FinalTest = "PASS";
                    redo0Model.ResultType = "OncePass";
                }
                else
                {
                    redo0Model.Test02 = "FAIL";
                    redo0Model.FinalTest = "FAIL";
                    redo0Model.ResultType = "RealFail";
                }
            }
            else if (redo0Model.Test01.ToLower() == "fail" && redo0Model.Test02.ToLower() == "null" && redo0Model.FinalTest.ToLower() == "fail")
            {// 2.resulttype=realfail;
                if (TestResult)
                {
                    redo0Model.Test02 = "PASS";
                    redo0Model.FinalTest = "PASS";
                    redo0Model.ResultType = "NTF";
                }
                else
                {
                    // 连续2次Fail，锁定该SN不允许再测试.
                    redo0Model.Test02 = "FAIL";
                    redo0Model.FinalTest = "FAIL";
                    redo0Model.ResultType = "RealFail";
                }
            }
            #endregion

            #region 测试第3次.
            else if (redo0Model.Test01.ToLower() == "pass" && redo0Model.Test02.ToLower() == "fail" && redo0Model.FinalTest.ToLower() == "fail")
            {// 3.resulttype=realfail;
                if (TestResult)
                {
                    //redo0Model.Test02 = "FAIL";
                    redo0Model.FinalTest = "PASS";
                    redo0Model.ResultType = "NTF";
                }
                else
                {
                    // 连续2次Fail，锁定该SN不允许再测试.
                    //redo0Model.Test02 = "FAIL";
                    redo0Model.FinalTest = "FAIL";
                    redo0Model.ResultType = "RealFail";
                }
            }

            else if (redo0Model.Test01.ToLower() == "pass" && redo0Model.Test02.ToLower() == "pass" && redo0Model.FinalTest.ToLower() == "pass")
            {// 4.resulttype=oncepass;
                if (TestResult)
                {
                    //redo0Model.Test02 = "PASS";
                    redo0Model.FinalTest = "PASS";
                    redo0Model.ResultType = "OncePass";
                }
                else
                {
                    //redo0Model.Test02 = "PASS";
                    redo0Model.FinalTest = "FAIL";
                    redo0Model.ResultType = "RealFail";
                }
            }

            #region 已经累计出现2次fail了，不允许继续测试，也不允许修改记录;
            else if (redo0Model.Test01.ToLower() == "fail" && redo0Model.Test02.ToLower() == "fail" && redo0Model.FinalTest.ToLower() == "fail")
            {// 5.resulttype=realfail; 已经累计出现2次fail了，不允许继续测试，也不允许修改记录;
                Log.WriteInfoLog(string.Format("5.resulttype=realfail; Test01={0},Test02={1},已经累计出现2次fail了，不允许继续测试，也不允许修改记录", redo0Model.Test01, redo0Model.Test02));
            }
            #endregion

            else if (redo0Model.Test01.ToLower() == "fail" && redo0Model.Test02.ToLower() == "pass" && redo0Model.FinalTest.ToLower() == "pass")
            {// 4.resulttype=ntf;
                if (TestResult)
                {
                    //redo0Model.Test02 = "PASS";
                    redo0Model.FinalTest = "PASS";
                    redo0Model.ResultType = "NTF";
                }
                else
                {
                    //redo0Model.Test02 = "PASS";
                    redo0Model.FinalTest = "FAIL";
                    redo0Model.ResultType = "RealFail";
                }
            }
            #endregion
            if (!TestResult)
                redo0Model.ErrorMsg = strErrMsg;

            // 更新测试时间;
            DateTime dateNow = DateTime.Now;
            redo0Model.TestDate = dateNow.Date;
            redo0Model.TestTime = dateNow.ToString("yyyy-MM-dd HH:mm:ss");
            redo0Model.TestHour = dateNow.Hour;
            ResultType = redo0Model.ResultType;
            return dalAMResult.Update(redo0Model, string.Format("Station='{0}' and SN='{1}' and ReDo='{2}'", redo0Model.Station, redo0Model.SN, redo0Model.ReDo));
        }

        public bool UpdateAMYields(AMResult model, bool TestResult, string strErrMsg)
        {
            bool IsNewRecord = false;
            // 查询出统计的记录;
            AMYields yields = dalAMYields.GetModel(model.Line, model.Station, model.ODF, model.TestDate, model.TestHour);
            // 根据当前model所在的Line、Station、ODF、Model、TestDate、TestHour，统计该TestHour内的数据;
            List<AMResult> mResults = dalAMResult.GetModelList(model.Line, model.Station, model.ODF, model.TestDate, model.TestHour);
            // 查询每小时统计值;
            HourlyResultData hourlydata = dalAMResult.GetHourlyResultData(model.Line, model.Station, model.ODF, model.TestDate, model.TestHour);

            if (yields == null || yields.IsValueEmpty())
            {// 添加新记录;
                IsNewRecord = true;
                if (yields == null)
                    yields = new AMYields();

                yields.TestDate = model.TestDate;
                yields.TestHour = model.TestHour;
                yields.Line = model.Line;
                yields.Station = model.Station;
                yields.ODF = model.ODF;
                yields.Dimension = model.Dimension;
                yields.Model = model.Model;
            }

            yields.Total = hourlydata.TotalAllCount;
            yields.OncePass = hourlydata.OncePassAllCount;
            //yields.TwiceFail = hourlydata.TwiceFailCount;
            yields.NTF = hourlydata.NTFAllCount;
            yields.RealFail = hourlydata.RealFailCount;
            yields.NTF_SN = hourlydata.NTFSN;
            yields.FailDSN = hourlydata.FailDSN;
            // 计算百分比;
            try
            {
                int totalAll = int.Parse(hourlydata.TotalAllCount);
                int totalZero = int.Parse(hourlydata.TotalZeroCount);

                int oncepassAll = int.Parse(hourlydata.OncePassAllCount);
                int oncepassZero = int.Parse(hourlydata.OncePassZeroCount);

                int ntfAll = int.Parse(hourlydata.NTFAllCount);
                int ntfZero = int.Parse(hourlydata.NTFZeroCount);

                int realfailCount = int.Parse(hourlydata.RealFailCount);

                // 统计合格率;
                yields.FPY = (oncepassAll / (double)totalAll).ToString("P");
                yields.SPY = ((oncepassAll + ntfAll) / (double)totalAll).ToString("P");
                yields.RPY = ((oncepassAll + ntfAll) / (double)totalAll).ToString("P");
                yields.YieldRate = ((oncepassZero + ntfZero) / (double)totalZero).ToString("P");
            }
            catch
            {
                return false;
            }

            return IsNewRecord ? dalAMYields.Add(yields) : dalAMYields.Update(yields);
        }
        #endregion


        #region ------试产NTF------
        /// <summary>
        /// 记录是否存在;
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool IsRecordExist(AMResult_TR model)
        {
            // 如果存在重流的话，可能不会在原来的Line上，可以流到其他Line。
            // dalAMResult.Exists(string.Format("Station='{0}' and SN='{1}' and Line = '{2}'", model.Station, model.SN, model.Line));
            return dalAMResultTR.Exists(string.Format("Station='{0}' and SN='{1}'", model.Station, model.SN));
        }

        /// <summary>
        /// 新增记录;
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddAMResult(AMResult_TR model, bool TestResult, string strErrMsg)
        {
            // 赋新值;
            model.Test01 = model.FinalTest = TestResult ? "PASS" : "FAIL";
            model.Test02 = "null";
            model.Test03 = "null";
            model.ReDo = "0";
            ResultType = model.ResultType = TestResult ? "OncePass" : "RealFail";
            if (!TestResult)
                model.ErrorMsg = strErrMsg;
            return dalAMResultTR.Add(model);
        }

        public bool UpdateAMResults(AMResult_TR model, bool TestResult, string strErrMsg)
        {
            // 先获取ReDo="0"的记录;
            AMResult_TR redo0Model = dalAMResultTR.GetModel(string.Format("Station='{0}' and SN='{1}' and ReDo='{2}'", model.Station, model.SN, "0"));
            if (_strLastSN == model.SN)
            {// 连接抄写数据,更新ReDo="0"的记录;
                Log.WriteInfoLog(string.Format("上一次SN={0} 与当前SN={1} 相同，只更新数据", _strLastSN, model.SN));
                if (!UpdateReDo0AMResult(redo0Model, TestResult, strErrMsg))
                {
                    // 更新失败;
                    Log.WriteInfoLog(string.Format("AMResult更新SN={0}，Station={1}，TestTime={2}，ReDo={3} 失败", redo0Model.SN, redo0Model.Station, redo0Model.TestTime, redo0Model.ReDo));
                    return false;
                }
            }
            else
            {// 将原ReDo="0"更新为ReDo=Max(ReDo)+1,并新增ReDo="0"的记录;
                int maxReDo = dalAMResultTR.GetMaxID("convert(int,ReDo)", string.Format("Station='{0}' and SN='{1}'", model.Station, model.SN));
                redo0Model.ReDo = maxReDo.ToString();
                if (!dalAMResultTR.Update(redo0Model, string.Format("Station='{0}' and SN='{1}' and ReDo='{2}'", redo0Model.Station, redo0Model.SN, "0")))
                {
                    // 更新失败;
                    Log.WriteInfoLog(string.Format("AMResult更新SN={0}，Station={1}，TestTime={2}，ReDo={3} 失败", redo0Model.SN, redo0Model.Station, redo0Model.TestTime, redo0Model.ReDo));
                    return false;
                }

                // 新增ReDo=0记录;
                if (!AddAMResult(model, TestResult, strErrMsg))
                {
                    // 添加失败;
                    Log.WriteInfoLog(string.Format("AMResult新增SN={0}，Station={1}，TestTime={2}，ReDo={3} 失败", model.SN, model.Station, model.TestTime, model.ReDo));
                    return false;
                }
            }

            return true;
        }

        public bool UpdateReDo0AMResult(AMResult_TR redo0Model, bool TestResult, string strErrMsg)
        {
            #region 测试第2次
            if (redo0Model.Test02.ToLower() == "null" && redo0Model.Test03.ToLower() == "null")
            {
                if (redo0Model.Test01.ToLower() == "pass")
                {
                    if (TestResult)
                    {
                        redo0Model.Test02 = "PASS";
                        redo0Model.FinalTest = "PASS";
                        redo0Model.ResultType = "OncePass";
                    }
                    else
                    {
                        redo0Model.Test02 = "FAIL";
                        redo0Model.FinalTest = "FAIL";
                        redo0Model.ResultType = "RealFail";
                    }
                }
                else if (redo0Model.Test01.ToLower() == "fail")
                {
                    if (TestResult)
                    {
                        redo0Model.Test02 = "PASS";
                        redo0Model.FinalTest = "PASS";
                        redo0Model.ResultType = "RealFail";
                    }
                    else
                    {
                        redo0Model.Test02 = "FAIL";
                        redo0Model.FinalTest = "FAIL";
                        redo0Model.ResultType = "RealFail";
                    }
                }
            }
            #endregion
            #region 测试第3次
            else if (redo0Model.Test02.ToLower() != "null" && redo0Model.Test03.ToLower() == "null")
            {
                if (redo0Model.Test01.ToLower().Equals("pass") && redo0Model.Test02.ToLower().Equals("pass"))
                {
                    if (TestResult)
                    {
                        redo0Model.Test03 = "PASS";
                        redo0Model.FinalTest = "PASS";
                        redo0Model.ResultType = "OncePass";
                    }
                    else
                    {
                        redo0Model.Test03 = "FAIL";
                        redo0Model.FinalTest = "FAIL";
                        redo0Model.ResultType = "RealFail";
                    }
                }
                else if (redo0Model.Test01.ToLower().Equals("pass") && redo0Model.Test02.ToLower().Equals("fail"))
                {
                    if (TestResult)
                    {
                        redo0Model.Test03 = "PASS";
                        redo0Model.FinalTest = "PASS";
                        redo0Model.ResultType = "NTF";
                    }
                    else
                    {
                        redo0Model.Test03 = "FAIL";
                        redo0Model.FinalTest = "FAIL";
                        redo0Model.ResultType = "RealFail";
                    }
                }
                else if (redo0Model.Test01.ToLower().Equals("fail") && redo0Model.Test02.ToLower().Equals("pass"))
                {
                    if (TestResult)
                    {
                        redo0Model.Test03 = "PASS";
                        redo0Model.FinalTest = "PASS";
                        redo0Model.ResultType = "NTF";
                    }
                    else
                    {
                        redo0Model.Test03 = "FAIL";
                        redo0Model.FinalTest = "FAIL";
                        redo0Model.ResultType = "RealFail";
                    }
                }
                else if (redo0Model.Test01.ToLower().Equals("fail") && redo0Model.Test02.ToLower().Equals("fail"))
                {
                    Log.WriteInfoLog("连接2次Fail，测试锁定");
                }
            }
            #endregion
            #region 测试第4次;
            else if (redo0Model.Test03.ToLower() != "null")
            {
                if (redo0Model.FinalTest.ToLower() == "pass" && redo0Model.ResultType.ToLower() == "ntf")
                {
                    if (!TestResult)
                    {
                        redo0Model.FinalTest = "FAIL";
                        redo0Model.ResultType = "RealFail";
                    }
                }
                else if (redo0Model.FinalTest.ToLower() == "pass" && redo0Model.ResultType.ToLower() == "oncepass")
                {// 异常测试;
                    if (!TestResult)
                    {
                        redo0Model.FinalTest = "FAIL";
                        redo0Model.ResultType = "RealFail";
                    }
                }
                else
                {
                    Log.WriteErrorLog("异常测试，超过3次测试次数");
                }
            }
            #endregion
            if (!TestResult)
                redo0Model.ErrorMsg = strErrMsg;

            // 更新测试时间;
            DateTime dateNow = DateTime.Now;
            redo0Model.TestDate = dateNow.Date;
            redo0Model.TestTime = dateNow.ToString("yyyy-MM-dd HH:mm:ss");
            redo0Model.TestHour = dateNow.Hour;
            ResultType = redo0Model.ResultType;
            return dalAMResultTR.Update(redo0Model, string.Format("Station='{0}' and SN='{1}' and ReDo='{2}'", redo0Model.Station, redo0Model.SN, redo0Model.ReDo));
        }

        public bool UpdateAMYields(AMResult_TR model, bool TestResult, string strErrMsg)
        {
            bool IsNewRecord = false;
            // 查询出统计的记录;
            AMYields_TR yields = dalAMYieldsTR.GetModel(model.Line, model.Station, model.ODF, model.TestDate, model.TestHour);
            // 根据当前model所在的Line、Station、ODF、Model、TestDate、TestHour，统计该TestHour内的数据;
            List<AMResult_TR> mResults = dalAMResultTR.GetModelList(model.Line, model.Station, model.ODF, model.TestDate, model.TestHour);
            // 查询每小时统计值;
            HourlyResultTRData hourlydata = dalAMResultTR.GetHourlyResultData(model.Line, model.Station, model.ODF, model.TestDate, model.TestHour);

            if (yields == null || yields.IsValueEmpty())
            {// 添加新记录;
                IsNewRecord = true;
                if (yields == null)
                    yields = new AMYields_TR();

                yields.TestDate = model.TestDate;
                yields.TestHour = model.TestHour;
                yields.Line = model.Line;
                yields.Station = model.Station;
                yields.ODF = model.ODF;
                yields.Dimension = model.Dimension;
                yields.Model = model.Model;
            }

            yields.Total = hourlydata.TotalAllCount;
            yields.OncePass = hourlydata.OncePassAllCount;
            //yields.TwiceFail = hourlydata.TwiceFailCount;
            yields.NTF = hourlydata.NTFAllCount;
            yields.RealFail = hourlydata.RealFailCount;
            yields.NTF_SN = hourlydata.NTFSN;
            yields.FailDSN = hourlydata.FailDSN;
            // 计算百分比;
            try
            {
                int totalAll = int.Parse(hourlydata.TotalAllCount);
                int totalZero = int.Parse(hourlydata.TotalZeroCount);

                int oncepassAll = int.Parse(hourlydata.OncePassAllCount);
                int oncepassZero = int.Parse(hourlydata.OncePassZeroCount);

                int ntfAll = int.Parse(hourlydata.NTFAllCount);
                int ntfZero = int.Parse(hourlydata.NTFZeroCount);

                int realfailCount = int.Parse(hourlydata.RealFailCount);

                // 统计合格率;
                yields.FPY = (oncepassAll / (double)totalAll).ToString("P");
                yields.SPY = ((oncepassAll + ntfAll) / (double)totalAll).ToString("P");
                yields.RPY = ((oncepassAll + ntfAll) / (double)totalAll).ToString("P");
                yields.YieldRate = ((oncepassZero + ntfZero) / (double)totalZero).ToString("P");
            }
            catch
            {
                return false;
            }

            return IsNewRecord ? dalAMYieldsTR.Add(yields) : dalAMYieldsTR.Update(yields);
        }

        #endregion
    }
}
