
using CentralControl;
using DataLinkMesWork;
using Newtonsoft.Json;
using SlMesDbIterface;
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading;

/// <summary>
/// 
/// </summary>
namespace MesWork
{
    /// <summary>
    /// 质量数据的拆解和存储
    /// </summary>
    public class MesWork_QC_upload
    {

        /// <summary>
        /// 同步执行任务
        /// </summary>
        public static void SyncTask_UploadMeasureData(string id_tagCF)
        {
            new Thread(new ThreadStart(delegate ()
            {
                string msg = "";
                try
                {
                    // 查询质量数据
                    bool isUploadOk = false;
                    var sql_AMS_Plan = $"SELECT * FROM 质量数据上传_视图" +
                    $" where [接口输出] != 1 and id_tagCF = {id_tagCF} order by [工位号],[TagID] ";
                    bool isOk = SqlOperation.ExecuteSql(sql_AMS_Plan, out DataTable dt_MeasureData, out string err1);
                    if (isOk)
                    { 
                        if(dt_MeasureData.Rows.Count > 0)
                        {
                            isUploadOk = upLoadData(dt_MeasureData, out msg);
                        }
                    }
                    if(isUploadOk)
                    {
                        upLoadUpdate(id_tagCF, 1, msg);
                    } 
                    else
                    {
                        upLoadUpdate(id_tagCF, 2, msg);
                    }
                }
                catch (Exception err)
                {
                    msg = err.Message;
                    upLoadUpdate(id_tagCF, 2, msg);
                }
            }))
            { IsBackground = true }.Start();
        }

        public static bool upLoadData(DataTable dt, out string msg)
        {
            try
            {
                List<SapMeasureData> SapMeasureDataList = new List<SapMeasureData>();
                string dateShort = new DateTime().ToString("yyyyMMdd");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    SapMeasureData sapMeasureData = new SapMeasureData();
                    sapMeasureData.ID = dt.Rows[i]["Id"].ToString();
                    sapMeasureData.operationCode = dt.Rows[i]["工位代码"].ToString();
                    sapMeasureData.itemCode = dt.Rows[i]["订货号"].ToString();
                    sapMeasureData.productCode = dt.Rows[i]["EngineID"].ToString();
                    sapMeasureData.characterName = dt.Rows[i]["测量位置"].ToString() + dt.Rows[i]["测量项目"].ToString();
                    sapMeasureData.content = "";
                    sapMeasureData.cNumber = "";
                    sapMeasureData.positionNumber = dt.Rows[i]["列位置"].ToString();
                    sapMeasureData.specialCategory = "";
                    sapMeasureData.cImportance = "";
                    sapMeasureData.unit = dt.Rows[i]["测量单位"].ToString();
                    sapMeasureData.normalMin = Convert.ToInt32(dt.Rows[i]["下限值"]);
                    sapMeasureData.normalMax = Convert.ToInt32(dt.Rows[i]["上限值"]);
                    sapMeasureData.checkInput = dt.Rows[i]["TagValue"].ToString();
                    sapMeasureData.isNormal = Convert.ToInt32(dt.Rows[i]["IsGoodBad"]);
                    sapMeasureData.checkToolNumber = "";
                    sapMeasureData.checkToolName = "";
                    sapMeasureData.machineNumber = "";
                    sapMeasureData.machineSpindleNumber = "";
                    sapMeasureData.machineClampingNumber = "";
                    sapMeasureData.inputDate = dt.Rows[i]["操作时间"].ToString();
                    sapMeasureData.reMarks = "";
                    SapMeasureDataList.Add(sapMeasureData);
                }
                ResponseBody_WebAPI_Boms res = CALL_Interfalce_WebAPI.RequestPost_UploadMeasureData_To_SAP(JsonConvert.SerializeObject(SapMeasureDataList));

                if (res.code == "200")
                {
                    msg = res.message;
                    return true;
                }
                else
                {
                    msg = res.message;
                    return false;
                }
            }
            catch (Exception err)
            {
                msg = err.Message;
                return false;
            }
        }

        public static void upLoadUpdate(string id_tagCF, int isOk, string msg)
        {
            try
            {
                var sql_AMS_Plan = $"UPDATE [dbo].[测量数据合格] SET [接口输出] = {isOk},数据说明 = '{msg}'" +
                    $" where [id_tagCF] = '{id_tagCF}'";
                DataAccess.ExecuteDataTable(sql_AMS_Plan, out DataTable dt_MeasureData);
            }
            catch (Exception err)
            {

            }
        }











    }
    class SapMeasureData
    {
        /*
id	number(12)			id
line_id	varchar2(10)	y		生产线id
operation_code	varchar2(10)	y		工位编码
item_code	varchar2(255)	y		物料编码
product_code	varchar2(16)	y		序列号
character_name	varchar2(255)	y		特性名称
content	varchar2(255)	y		特性内容（产品/过程规格/公差）φ是大写
c_number	varchar2(40)	y		特性编号
position_number	varchar2(40)	y		位置编号
special_category	varchar2(10)	y		特殊特性分类
c_importance	varchar2(10)	y		特性重要度
unit	varchar2(10)	y		单位
normal_min	number	y		合格下限
normal_max	number	y		合格上限
check_input	varchar2(255)	y		质检结果
isnormal	number(1)	y		是否合格(0：否；1：是；)
check_tool_number	varchar2(30)	y		测量设备编号
check_tool_name	varchar2(80)	y		测量设备名称  
machine_number	varchar2(40)	y	null	加工设备编号 
machine_spindle_number	varchar2(40)	y	null	加工设备主轴编号
machine_clamping_number	varchar2(40)	y		加工设备工装编号 
input_date	date	y		录入时间
remarks	varchar2(255)	y		备注

         
         
         */

        public string ID;
        public string lineId = MesWorkForm.LineID_Product;
        public string operationCode;
        public string itemCode;
        public string productCode;
        public string characterName;
        public string content;
        public string cNumber;
        public string positionNumber;
        public string specialCategory;
        public string cImportance;
        public string unit;
        public int normalMin;
        public int normalMax;
        public string checkInput;
        public int isNormal;
        public string checkToolNumber;
        public string checkToolName;
        public string machineNumber;
        public string machineSpindleNumber;
        public string machineClampingNumber;
        public string inputDate;
        public string reMarks;


    }
    class SapMeasureDataResult
    {
        public List<SapMeasureData> SapMeasureDataList;
    }
}

