using MisDataSaveDate;
using MisDataSaveDate.MOM;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using DataLinkMesWork2;
using static MisDataSaveDate.Helper.ApiLogHelper;
using MisDataFunDll;

namespace ExternalDataSync.MOM
{
    public class Other
    {
        public static string OnlineCheckData(string url, [FromBody] JObject jobj)
        {
            var result = new OnlineCheckDataResponse();
            result.Code = "200";
            result.Message = "";
            result.MsgId = "";
            result.Data = "";

            string errorMessage = string.Empty;

            if (jobj == null)
            {
                result.Code = "500";
                result.Message = "参数格式不正确！";
                string retString1 = JsonConvert.SerializeObject(result);
                MyLog4Net.MyLogHelper.Info("接收检测数据_res", retString1);
                return retString1;
            }

            string str = jobj.ToString();
            // 存储接口请求日志
            SaveLog_Interface_Request(url, 2, str, out int AID);

            try
            {
                OnlineCheckData onlineCheckData = JsonConvert.DeserializeObject<OnlineCheckData>(str);
                if (onlineCheckData == null)
                {
                    throw new Exception("请求体反序列化失败！");
                }
                if (string.IsNullOrWhiteSpace(onlineCheckData.MsgId))
                {
                    throw new Exception("参数MsgId为空！");
                }
                // 设置响应的MsgId（带回请求编号）
                result.MsgId = onlineCheckData.MsgId;

                if (string.IsNullOrWhiteSpace(onlineCheckData.OpCode))
                {
                    throw new Exception("参数OpCode为空！");
                }
                if (string.IsNullOrWhiteSpace(onlineCheckData.ProductionCode))
                {
                    throw new Exception("参数ProductionCode为空！");
                }
                if (string.IsNullOrWhiteSpace(onlineCheckData.ScanTime))
                {
                    throw new Exception("参数ScanTime为空！");
                }
                if (string.IsNullOrWhiteSpace(onlineCheckData.CheckPerson))
                {
                    throw new Exception("参数CheckPerson为空！");
                }

                string opName = onlineCheckData.OpCode;
                int idTagCf = 0;

                SqlParameter[] paramIndex = new SqlParameter[8];
                paramIndex[0] = new SqlParameter("@EngineID", onlineCheckData.ProductionCode);
                paramIndex[1] = new SqlParameter("@工位号", opName);
                paramIndex[2] = new SqlParameter("@操作者工号", onlineCheckData.CheckPerson);
                paramIndex[3] = new SqlParameter("@扫码时间", onlineCheckData.ScanTime);
                paramIndex[4] = new SqlParameter("@合格标志", onlineCheckData.QualityMark);
                paramIndex[5] = new SqlParameter("@完成时间", onlineCheckData.EndTime);
                paramIndex[6] = new SqlParameter("@能耗", onlineCheckData.Powerused);
                paramIndex[7] = new SqlParameter("@Id_tagCF", SqlDbType.Int)
                {
                    Direction = ParameterDirection.Output
                };

                DataAccess2.ExecuteStoredProcedure("测量数据合格索引_增加_测试设备", ref paramIndex, out errorMessage);
                if (!string.IsNullOrEmpty(errorMessage))
                {
                    throw new Exception(errorMessage);
                }

                if (paramIndex[7].Value == null || paramIndex[7].Value == DBNull.Value)
                {
                    throw new Exception("测量数据合格索引_增加_测试设备 未返回Id_tagCF！");
                }

                idTagCf = Convert.ToInt32(paramIndex[7].Value);

                List<OnlineCheckData_CheckData> detailList = onlineCheckData.CheckData ?? new List<OnlineCheckData_CheckData>();

                foreach (var item in detailList)
                {
                    var paramDetail = new SqlParameter[]
                    {
                        new SqlParameter("@Id_tagCF", idTagCf),
                        new SqlParameter("@EngineID", onlineCheckData.ProductionCode),
                        new SqlParameter("@TagID", item.CheckCode ?? string.Empty),
                        new SqlParameter("@TagValue", item.CheckValue ?? string.Empty),
                        new SqlParameter("@IsGoodBad", item.QualityMark),
                        new SqlParameter("@工位号", opName),
                        new SqlParameter("@理论值", item.StandardValue ?? string.Empty),
                        new SqlParameter("@上限值", item.MaxValue ?? string.Empty),
                        new SqlParameter("@下限值", item.MinValue ?? string.Empty),
                        new SqlParameter("@测量项目", item.CheckName ?? string.Empty),
                        new SqlParameter("@测量单位", item.Unit ?? string.Empty)
                    };

                    DataAccess2.ExecuteStoredProcedure("测量数据合格_增加_测试设备", ref paramDetail, out errorMessage);
                    if (!string.IsNullOrEmpty(errorMessage))
                    {
                        throw new Exception(errorMessage);
                    }
                }
                // 存储到接口表里
                MisDataFun.SaveQualityInterfaceData(opName, onlineCheckData.ProductionCode);
            }
            catch (Exception err)
            {
                result.Code = "500";
                result.Message = err.Message;
            }

            string retString = JsonConvert.SerializeObject(result);
            SaveLog_Interface_Response(retString, AID);
            MyLog4Net.MyLogHelper.Info("接收检测数据_res", retString);
            return retString;
        }

        public static string OnlineStatusData(string url, [FromBody] JObject jobj)
        {
            var result = new MsgResHeader<string>();
            result.code = 200;
            result.message = "";
            result.Data = "";

            string errorMessage = string.Empty;

            if (jobj == null)
            {
                result.code = 500;
                result.message = "参数格式不正确！";
                string retString1 = JsonConvert.SerializeObject(result);
                MyLog4Net.MyLogHelper.Info("接收设备状态数据_res", retString1);
                return retString1;
            }

            string str = jobj.ToString();
            SaveLog_Interface_Request(url, 2, str, out int AID);

            try
            {
                var statusData = JsonConvert.DeserializeObject<OnlineStatusData>(str);
                if (statusData == null)
                {
                    throw new Exception("请求体反序列化失败！");
                }
                if (string.IsNullOrWhiteSpace(statusData.MsgId))
                {
                    throw new Exception("参数MsgId为空！");
                }
                if (string.IsNullOrWhiteSpace(statusData.DeviceCode))
                {
                    throw new Exception("参数DeviceCode为空！");
                }
                if (string.IsNullOrWhiteSpace(statusData.DataType))
                {
                    throw new Exception("参数DataType为空！");
                }
                if (statusData.CheckData == null || statusData.CheckData.Count == 0)
                {
                    throw new Exception("参数CheckData为空！");
                }

                string dataType = statusData.DataType.ToUpper();

                if (dataType == "STATUS")
                {
                    // 设备运行状态监测 - 必填字段校验
                    string deviceStatus = GetCheckDataValue(statusData.CheckData, "DeviceStatus");
                    string statusTime = GetCheckDataValue(statusData.CheckData, "StatusTime");
                    string statusCode = GetCheckDataValue(statusData.CheckData, "StatusCode");

                    if (string.IsNullOrWhiteSpace(deviceStatus))
                    {
                        throw new Exception("设备状态(DeviceStatus)为必填项！");
                    }
                    if (string.IsNullOrWhiteSpace(statusTime))
                    {
                        throw new Exception("状态时间(StatusTime)为必填项！");
                    }
                    if (string.IsNullOrWhiteSpace(statusCode))
                    {
                        throw new Exception("状态代码(StatusCode)为必填项！");
                    }

                    // 非必填字段
                    string malfunctionCode = GetCheckDataValue(statusData.CheckData, "MalfunctionCode");
                    string malfunctionName = GetCheckDataValue(statusData.CheckData, "MalfunctionName");
                    string malfunctionExplain = GetCheckDataValue(statusData.CheckData, "Malfunctionexplain");
                    string flag = GetCheckDataValue(statusData.CheckData, "Flag");
                    string remark = GetCheckDataValue(statusData.CheckData, "Remark");
                    string alarmRemove = GetCheckDataValue(statusData.CheckData, "alarmRemove");

                    var param = new SqlParameter[]
                    {
                        new SqlParameter("@DeviceCode", statusData.DeviceCode),
                        new SqlParameter("@DeviceStatus", deviceStatus),
                        new SqlParameter("@StatusTime", DateTime.Parse(statusTime)),
                        new SqlParameter("@StatusCode", statusCode),
                        new SqlParameter("@MalfunctionCode", string.IsNullOrWhiteSpace(malfunctionCode) ? (object)DBNull.Value : malfunctionCode),
                        new SqlParameter("@MalfunctionName", string.IsNullOrWhiteSpace(malfunctionName) ? (object)DBNull.Value : malfunctionName),
                        new SqlParameter("@Malfunctionexplain", string.IsNullOrWhiteSpace(malfunctionExplain) ? (object)DBNull.Value : malfunctionExplain),
                        new SqlParameter("@Flag", string.IsNullOrWhiteSpace(flag) ? (object)DBNull.Value : flag),
                        new SqlParameter("@Remark", string.IsNullOrWhiteSpace(remark) ? (object)DBNull.Value : remark),
                        new SqlParameter("@alarmRemove", string.IsNullOrWhiteSpace(alarmRemove) ? (object)DBNull.Value : alarmRemove)
                    };

                    DataAccess2.ExecuteStoredProcedure("EquipmentStatus_Backup_TestDeviceAdd", ref param, out errorMessage);
                    if (!string.IsNullOrEmpty(errorMessage))
                    {
                        throw new Exception(errorMessage);
                    }
                }
                else if (dataType == "USE")
                {
                    // 设备使用情况记录 - 必填字段校验
                    string workDate = GetCheckDataValue(statusData.CheckData, "WorkDate");

                    if (string.IsNullOrWhiteSpace(workDate))
                    {
                        throw new Exception("工作日期(WorkDate)为必填项！");
                    }

                    // 非必填字段
                    string onhours = GetCheckDataValue(statusData.CheckData, "Onhours");
                    string workhours = GetCheckDataValue(statusData.CheckData, "Workhours");
                    string powerused = GetCheckDataValue(statusData.CheckData, "Powerused");
                    string flag = GetCheckDataValue(statusData.CheckData, "Flag");

                    var param = new SqlParameter[]
                    {
                        new SqlParameter("@Device", statusData.DeviceCode),
                        new SqlParameter("@WorkDate", DateTime.Parse(workDate)),
                        new SqlParameter("@Onhours", string.IsNullOrWhiteSpace(onhours) ? (object)DBNull.Value : double.Parse(onhours)),
                        new SqlParameter("@Workhours", string.IsNullOrWhiteSpace(workhours) ? (object)DBNull.Value : double.Parse(workhours)),
                        new SqlParameter("@Powerused", string.IsNullOrWhiteSpace(powerused) ? (object)DBNull.Value : double.Parse(powerused)),
                        new SqlParameter("@Flag", string.IsNullOrWhiteSpace(flag) ? (object)DBNull.Value : flag)
                    };

                    DataAccess2.ExecuteStoredProcedure("EquipmentUse_Backup_TestDeviceAdd", ref param, out errorMessage);
                    if (!string.IsNullOrEmpty(errorMessage))
                    {
                        throw new Exception(errorMessage);
                    }
                }
                else
                {
                    throw new Exception($"DataType值不正确，只支持Status或Use，当前值：{statusData.DataType}");
                }
            }
            catch (Exception err)
            {
                result.code = 500;
                result.message = err.Message;
            }

            string retString = JsonConvert.SerializeObject(result);
            SaveLog_Interface_Response(retString, AID);
            MyLog4Net.MyLogHelper.Info("接收设备状态数据_res", retString);
            return retString;
        }

        /// <summary>
        /// 从CheckData列表中获取指定StatuCode的StatuValue
        /// </summary>
        private static string GetCheckDataValue(List<OnlineStatusData_CheckData> checkDataList, string statuCode)
        {
            var item = checkDataList.FirstOrDefault(x => x.StatuCode?.Trim().Equals(statuCode, StringComparison.OrdinalIgnoreCase) == true);
            return item?.StatuValue ?? string.Empty;
        }

        /// <summary>
        /// 获取位置待测试产品信息
        /// </summary>
        public static string GetWaitCheckProductData(string url, [FromBody] JObject jobj)
        {
            var result = new GetWaitCheckProductDataResponse();
            result.Code = "200";
            result.Message = "";
            result.MsgId = "";
            result.Data = new GetWaitCheckProductDataResult();

            if (jobj == null)
            {
                result.Code = "500";
                result.Message = "参数格式不正确！";
                string retString1 = JsonConvert.SerializeObject(result);
                MyLog4Net.MyLogHelper.Info("获取待测产品信息_res", retString1);
                return retString1;
            }

            string str = jobj.ToString();
            // 存储接口请求日志
            SaveLog_Interface_Request(url, 2, str, out int AID);

            try
            {
                var requestData = JsonConvert.DeserializeObject<GetWaitCheckProductDataRequest>(str);
                if (requestData == null)
                {
                    throw new Exception("请求体反序列化失败！");
                }
                if (string.IsNullOrWhiteSpace(requestData.MsgId))
                {
                    throw new Exception("参数MsgId为空！");
                }
                // 设置响应的MsgId（带回请求编号）
                result.MsgId = requestData.MsgId;

                if (string.IsNullOrWhiteSpace(requestData.OpCode))
                {
                    throw new Exception("参数OpCode为空！");
                }

                // TODO: 后续实现查询待测产品逻辑
                // 目前固定返回无待测产品
                result.Data = new GetWaitCheckProductDataResult
                {
                    ProductionCode = "",
                    ProductModel = "",
                    ProductModelCode = 0
                };
            }
            catch (Exception err)
            {
                result.Code = "500";
                result.Message = err.Message;
            }

            string retString = JsonConvert.SerializeObject(result);
            SaveLog_Interface_Response(retString, AID);
            MyLog4Net.MyLogHelper.Info("获取待测产品信息_res", retString);
            return retString;
        }
    }
}
