using ExternalDataSync;
using ExternalDataSync.ESB_daq;
using ExternalDataSync.MOM;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Security.Policy;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI.WebControls;

namespace SlMesDbIterface
{
    public class UpLoadMessage
    {
        enum InterFaceType
        {
            passStation = 1,
            deviceAlarm = 2
        };

        /// <summary>
        /// UUID生成
        /// </summary>
        /// <returns></returns>
        public static string UuidUtil()
        {
            string result = Guid.NewGuid().ToString();

            return result;
        }

        public void GetUpLoadMessageButton(string productName)
        {
            try
            {
                // 第一个存储过程 查询一个总成号的所有过点信息 第一个表
                DataLinkMesWork.SQLCommon.ExecuteStoredProcedure(productName + "_查询", Program.ConnectionString, out DataTable dt, out string errorMessage);
                //InterFaceType interFaceTypeEnum = (InterFaceType)interFaceType;
                if (dt.Rows.Count > 0)
                {
                    switch (productName)
                    {
                       
                        case "接口_上传_质量数据":
                            ReportUploadData(dt,productName);
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception err)
            {
            }
        }
        public void GetUpLoadMessage(string productName, int interFaceType)
        {
            new Thread(new ThreadStart(delegate ()
            {
                while (true)
                {
                    try
                    {
                        DataLinkMesWork.SQLCommon.ExecuteStoredProcedure(productName + "_查询", Program.ConnectionString, out DataTable dt, out string errorMessage);
                        InterFaceType interFaceTypeEnum = (InterFaceType)interFaceType;
                        if (dt.Rows.Count > 0)
                        {
                            switch (interFaceTypeEnum)
                            {
                                case InterFaceType.passStation:
                                    //UpLoadPassStation(dt, productName);
                                    break;
                                case InterFaceType.deviceAlarm:
                                    //UpLoadDeviceAlarmn(dt);
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    catch (Exception err)
                    {
                    }
                    Thread.Sleep(Form_MoveSqlTable.upload_Interval);
                }
            }))
            { IsBackground = true }.Start();
        }

        /// <summary>
        /// 接口_上传_生产报工
        /// </summary>
        /// <param name="dt" >变更执行结果上传 父表数据集 只有一条未上传的父表数据</param>
        public void ReportUploadData(DataTable dt, string productName)
        {
            string ParentId = dt.Rows[0]["ID"].ToString();

            try
            {
                // 创建父集合
                ReportUploadData BaseData = new ReportUploadData();
                // 填充基本数据
                BaseData.orderNumber = dt.Rows[0]["订单号"].ToString();
                BaseData.snCode = dt.Rows[0]["SN号"].ToString();
                BaseData.productModel = dt.Rows[0]["产品型号"].ToString();
                BaseData.recipeNumber = dt.Rows[0]["配方号"].ToString();
                BaseData.qualityResult = dt.Rows[0]["合格标志"].ToString();
                BaseData.stationCode = dt.Rows[0]["工位号"].ToString();
                BaseData.productionDate = dt.Rows[0]["生产日期"].ToString();

                // 通过ParentId 去查找子表数据 获取结果集
                var ChildrenParam1 = new SqlParameter[] {
                    new SqlParameter("@parentId",ParentId)
                };

                string ChildrenTableName1 = "接口_上传_质量数据_质量";
                DataLinkMesWork.SQLCommon.ExecuteStoredProcedure(ChildrenTableName1 + "_查询", Program.ConnectionString, ref ChildrenParam1, out DataTable ChildrenDt1, out string errormessage1);
               
                // 创建子对象列表
                List<ReportUploadQualityData> reportUploadQualityDataList = new List<ReportUploadQualityData>();

                // 遍历子表结果集
                // 工单
                for (int i = 0; i < ChildrenDt1.Rows.Count; i++)
                {
                    // 子对象
                    ReportUploadQualityData reportUploadQualityData = new ReportUploadQualityData();
                    DataRow item = ChildrenDt1.Rows[i];

                    // 填充数据
                    reportUploadQualityData.screwPositionNumber = item["螺钉孔号"].ToString();
                    reportUploadQualityData.torque = item["扭矩"].ToString();
                    reportUploadQualityData.dowelHeightValue = item["螺桩高度测量值"].ToString();
                    reportUploadQualityData.qualityResult = item["合格标志"].ToString();

                    // 添加到集合列表中
                    reportUploadQualityDataList.Add(reportUploadQualityData);
                }

                // 将子表结果List加入到父对象中
                BaseData.qualityList = reportUploadQualityDataList;

                //准备上传的数据 反序列化
                string bodydata = JsonConvert.SerializeObject(BaseData);

                string urlstr = Program.reportUploadUrl;
                string retString;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlstr);
                request.Method = "post";
                byte[] bytes = Encoding.UTF8.GetBytes(bodydata);
                request.Accept = "*/*";
                request.ContentType = "application/json;charset=utf-8";


                // 反序列化后先把JSON做接口记录
                //存储日志
                int AID = -1;
                var CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                //Event_MOM_Log_Insert,@创建时间,@内容
                var reqParam = new SqlParameter[] {
                new SqlParameter("@接口地址",urlstr),
                new SqlParameter("@接口类型",1), // 1. 主动调用接口  2. 被调用接口 
                new SqlParameter("@请求内容",bodydata),
                new SqlParameter("@请求时间",CreateTime)
                };
                DataLinkMesWork.SQLCommon.ExecuteStoredProcedure("接口_IOT接口交互日志_请求记录", Program.ConnectionString, ref reqParam, out DataTable reqDt, out string errorMessage);
                if (reqDt.Rows.Count > 0)
                {
                    AID = Convert.ToInt32(reqDt.Rows[0]["AID"]);
                }

                // 根据接口需要 准备Header
                msgHeader mHeader = new msgHeader();
                mHeader.version = 1;            //协议版本,默认1.0
                mHeader.taskId = UuidUtil();    //消息ID
                mHeader.taskType = "";          //接口类型 固定为接口目录编号，""

                // 根据接口需要 添加Header
                request.Headers.Add("version", mHeader.version.ToString());
                request.Headers.Add("taskId", mHeader.taskId);
                request.Headers.Add("taskType", mHeader.taskType);

                request.ContentLength = bytes.Length;

                // 准备请求体
                Stream myResponseStream = request.GetRequestStream();
                myResponseStream.Write(bytes, 0, bytes.Length);
                //发送webapi请求 等待相应
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                retString = myStreamReader.ReadToEnd();

                //响应结果
                CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                var resParam = new SqlParameter[] {
                new SqlParameter("@AID",AID),
                new SqlParameter("@响应时间",CreateTime),
                new SqlParameter("@响应内容",retString)
                };
                DataLinkMesWork.SQLCommon.ExecuteStoredProcedure("接口_IOT接口交互日志_响应记录", Program.ConnectionString, ref resParam, out errorMessage);

                // 序列化响应内容 
                msgResHeader mrh = JsonConvert.DeserializeObject<msgResHeader>(retString);
                int statusCode = (int)response.StatusCode;
                // 对响应内容进行处理 更新数据库标志 
                if (statusCode == 200)
                {
                    myStreamReader.Close();
                    myResponseStream.Close();
                    // 这里的接口不返回任何数据，200 直接成功！
                    updateUpLoadMessage(productName, ParentId, mrh.msg, 1);
                    //if (response != null)
                    //{
                    //    // 成功
                    //    if (mrh.code == "0")
                    //    {
                    //        updateUpLoadMessage(productName, ParentId, mrh.msg, 1);
                    //    }
                    //    // 失败
                    //    else
                    //    {
                    //        updateUpLoadMessage(productName, ParentId, mrh.msg, 2);
                    //    }
                    //    response.Close();
                    //}
                    if (request != null)
                    {
                        request.Abort();
                    }
                    MyLog4Net.MyLogHelper.Info("res:", retString);
                    // 
                }
                else
                {
                    updateUpLoadMessage(productName, ParentId, "请求失败，请求结果码" + statusCode, 2);
                    MyLog4Net.MyLogHelper.Error(productName + "接口" + ParentId + "上传失败", "请求失败，请求结果码" + statusCode);
                }
            }
            catch (Exception err)
            {
                updateUpLoadMessage(productName, ParentId, err.Message, 2);
                MyLog4Net.MyLogHelper.Error(productName + "接口" + ParentId + "上传失败", err.Message);
            }
            Thread.Sleep(100);
        }

        /// <summary>
        /// 上传成功更新数据库
        /// </summary>
        /// <param name="productName"></param>
        /// <param name="parentId"></param>
        /// <param name="resMsg"></param>
        /// <param name="isOk"> 1成功 2 不成功</param>
        public void updateUpLoadMessage(string productName, string parentId,string resMsg,int isOk)
        {
            try
            {
                var param = new SqlParameter[] {
                new SqlParameter("@主键值", parentId),
                new SqlParameter("@文本", resMsg),
                new SqlParameter("@是否成功", isOk),  //1成功 2 不成功
                new SqlParameter("@接口表", productName)  //1成功 2 不成功
                };
                DataLinkMesWork.SQLCommon.ExecuteStoredProcedure(productName + "_更新", Program.ConnectionString, ref param, out string errorMessage);
            }
            catch (Exception err)
            {
            }
        }
        /// <summary>
        /// 上传失败更新数据库
        /// </summary>
        /// <param name="productName"></param>
        /// <param name="ID"></param>
        /// <param name="err_msg"></param>
        public void updateUpLoadMessage_error(string productName, string ParentId, string err_msg)
        {
            try
            {
                var param = new SqlParameter[] {
                new SqlParameter("@主键值", ParentId),
                new SqlParameter("@接口表", productName),
                new SqlParameter("@文本", err_msg),
                };
                DataLinkMesWork.SQLCommon.ExecuteStoredProcedure("接口_上传_失败日志_增加", Program.ConnectionString, ref param, out string errorMessage);
            }
            catch (Exception err)
            {
            }
        }

    }
}
