WFormSynchronizeData_SMR/EquipmentCollectionForm/EquipmentCollectionForm_KB.cs
@@ -25,546 +25,343 @@
            InitializeComponent();
        }
        private void EquipmentCollectionForm_Load(object sender, EventArgs e)
        private void btnWB_Click(object sender, EventArgs e)
        {
            this.txtBegin.ReadOnly = true;
            this.txtEnd.ReadOnly = true;
            this.txtLj.ReadOnly = true;
            this.btnSave.Enabled = false;
            this.txtHMaterNumber.ReadOnly = true;
            //this.btnRest.Enabled = false;
            //制单编码只读
            this.txtHMakerNumber.ReadOnly = true;
            //制单人提示
            this.txtHMaker.ForeColor = Color.LightGray;
            this.txtHMaker.Text = "请输入用户编码!";
            MessageBox.Show("数据读取中...", "操作提示");
        }
        //定时获取数据
        private async void timer_Tick(object sender, EventArgs e)
        {
            string Url = DBHelper.GetConfigKey(AppDomain.CurrentDomain.BaseDirectory + "Config/SQLAPI.config", "sUrl");
            string urls = Url + EquipmentType_KB.One;
            // 准备要发送的表单数据
            var formData = new FormUrlEncodedContent(new[]
            {
                    new KeyValuePair<string, string>("userName", "admin"),
                    new KeyValuePair<string, string>("password", "Youngsunabc123..")
                    // 添加更多键值对,根据您的需要
                });
            JsonResult_KB jsonResult = await getUrl(urls, formData);
            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:00");
            bindCbox();
            SaveInjectionMoldingMachine(jsonResult.data.token, Url, time);
        }
        private void btnBegin_Click(object sender, EventArgs e)
        //设备采集数据 保存
        public async void SaveInjectionMoldingMachine(string token, string Url, string time)
        {
            if (this.txtHBathNo.Text == "" || this.txtHBathNo.ReadOnly == false)
            //if (false)
            if (TimeDate == "")
            {
                MessageBox.Show("请输入批次号进行确认!");
                TimeDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); ;
            }
            //获取所有设备数据
            JsonEquipmentData_KB jsonResult = await FindDeviceList(Url, token);
            if (jsonResult.code != "0")
            {
                MessageBox.Show("设备列表报错:" + jsonResult.message);
            }
            else
            {
                this.txtBegin.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //this.txtBegin.Text = "2024-11-21 13:40:27";
                this.btnBegin.Enabled = false;
                if (cmbEquipFile.SelectedIndex == 1)
                string nos = "";
                //获取设备编码
                for (int i = 0; i < jsonResult.data.Count; i++)
                {
                    this.txtHBathNo.ReadOnly = true;
                    this.timer.Enabled = true;
                    nos += jsonResult.data[i].no + ",";
                }
            }
        }
                nos = nos.Substring(0, nos.Length - 1);
                //获取参数 获取每个设备对应的所有参数   20250723 凯贝没有工艺参数采集  20250814采集铆压机的工艺参数
                JsonEquipmentData_KB jsonEquipment = await FindAllDevicePropsDetailByTimeRange(Url, token, nos, TimeDate, time);
        private void btnEnd_Click(object sender, EventArgs e)
        {
            if (this.txtBegin.Text == "")
            {
                MessageBox.Show("请点击开始按钮进行开始确认!");
            }
            else
            {
                this.txtEnd.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                //this.txtEnd.Text = "2024-09-24 09:52:39";
                this.btnEnd.Enabled = false;
                //JsonEquipmentData_KB jsonEquipment= null;
                if (cmbEquipFile.SelectedIndex == 1)
                var JsonData_KB = "{\"data\":[";
                if (jsonEquipment == null)
                {
                    this.btnSave.Enabled = true;
                    CustomWriteLog("jsonEquipment对象为空", DateTime.Now.ToString("yyyy-MM-dd"));
                }
            }
        }
        private void btnLj_Click(object sender, EventArgs e)
        {
            if (this.txtEnd.Text == "")
            {
                MessageBox.Show("请点击结束按钮进行结束确认!");
            }
            else
            {
                //路径赋值给文本
                using (OpenFileDialog openFile = new OpenFileDialog())
                //20250723注释
                if (jsonEquipment.data == null)
                {
                    openFile.Multiselect = true; // 允许选择多个文件
                    DialogResult result = openFile.ShowDialog();
                    if (result == DialogResult.OK)
                    {
                        //保存按钮灰掉
                        this.btnSave.Enabled = true;
                        string selectedFolderPath = openFile.FileName;
                        this.txtLj.Text = selectedFolderPath;
                        objJsonResult = Xt_CSVReadText(openFile.FileNames, 1);
                        dt = objJsonResult.dataTable;
                        if (objJsonResult.code == "0")
                        {
                            MessageBox.Show(objJsonResult.Message);
                        }
                        else
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                ListData.Items.Add("底孔直径:" + dt.Rows[i]["BottomHoleDiameter"].ToString() +
                                    ",有无螺牙检测数据:" + dt.Rows[i]["TestingData"].ToString() +
                                    ",有无螺牙检测结果:" + dt.Rows[i]["DetectionResult"].ToString() +
                                ",时间:" + dt.Rows[i]["HDate"].ToString());
                            }
                        }
                    }
                }
            }
        }
        //读取CSV文件数据  根据文件路径找到对应文件 并获取对应的数据
        public json Xt_CSVReadText(string[] FilePath, int num)
        {
            try
            {
                DataTable dt = new DataTable(num.ToString());
                dt.Columns.Add("BottomHoleDiameter");
                dt.Columns.Add("TestingData");
                dt.Columns.Add("DetectionResult");
                dt.Columns.Add("HDate");
                DataTable dt2 = new DataTable();
                for (int u = 0; u < FilePath.Length; u++)
                {
                    using (StreamReader sr = new StreamReader(FilePath[u], Encoding.GetEncoding("gb2312")))
                    {
                        string[] headers = sr.ReadLine()?.Split(',');
                        if (headers != null && u == 0)
                        {
                            foreach (var header in headers)
                            {
                                dt2.Columns.Add(header.Trim());
                            }
                        }
                        string line;
                        while ((line = sr.ReadLine()) != null)
                        {
                            var values = line.Split(',');
                            DataRow row = dt2.NewRow();
                            for (int i = 0; i < values.Length; i++)
                            {
                                // 这里可能需要添加类型转换和错误处理
                                row[i] = values[i].Trim();
                            }
                            dt2.Rows.Add(row);
                        }
                    }
                }
                DateTime HBegin = DateTime.Parse(this.txtBegin.Text);
                DateTime HEnd = DateTime.Parse(this.txtEnd.Text);
                for (int i = 0; i < dt2.Rows.Count; i++)
                {
                    for (int j = 0; j < 2; j++)
                    {
                        DateTime Now = DateTime.Parse(dt2.Rows[i][dt2.Columns[6]].ToString() + " " + dt2.Rows[i][dt2.Columns[7]].ToString());
                        if (Now >= HBegin && Now <= HEnd)
                        {
                            DataRow dr = dt.NewRow();
                            dr["BottomHoleDiameter"] = dt2.Rows[i][dt2.Columns[j]].ToString();
                            dr["TestingData"] = dt2.Rows[i][dt2.Columns[j + 2]].ToString();
                            dr["DetectionResult"] = dt2.Rows[i][dt2.Columns[j + 4]].ToString();
                            dr["HDate"] = DateTime.Parse(dt2.Rows[i][dt2.Columns[6]].ToString() + " " + dt2.Rows[i][dt2.Columns[7]].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                            dt.Rows.Add(dr);
                        }
                    }
                }
                objJsonResult.code = "1";
                objJsonResult.count = 1;
                objJsonResult.Message = "";
                objJsonResult.dataTable = dt;
                return objJsonResult;
            }
            catch (Exception e)
            {
                objJsonResult.code = "0";
                objJsonResult.count = 0;
                objJsonResult.Message = e.Message;
                objJsonResult.dataTable = null;
                return objJsonResult;
            }
        }
        private void txtHBathNo_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (this.txtHMakerNumber.Text == "")
                {
                    MessageBox.Show("请输入制单人信息!");
                    CustomWriteLog("jsonEquipment.data属性为空", DateTime.Now.ToString("yyyy-MM-dd"));
                }
                else
                {
                    Get_DisplayBard();
                    CustomWriteLog("开始循环工艺参数总数为:'" + jsonEquipment.data.Count + "'", DateTime.Now.ToString("yyyy-MM-dd"));
                    //通过每个设备进行循环赋值
                    for (int i = 0; i < jsonEquipment.data.Count; i++)
                    {
                        //循环 螺母压装设备对应的所有工艺参数
                        for (int j = 0; j < jsonEquipment.data[i].props.Count; j++)
                        {
                            //循环 每个参数对应的所有数据
                            for (int k = 0; k < jsonEquipment.data[i].props[j].datas.Count; k++)
                            {
                                JsonData_KB += "{\"HDate\":\"" + jsonEquipment.data[i].props[j].datas[k].createTime + "\",\"HTechParamName\":\"" + jsonEquipment.data[i].props[j].propName + "\",\"HResult\":\"" + jsonEquipment.data[i].props[j].datas[k].value + "\",\"HCount\":1,\"HSourceCode\":\"" + jsonEquipment.data[i].deviceNo + "\"},";
                            }
                        }
                    }
                }
                //this.txtHBathNo.ReadOnly = true;
            }
        }
        //查询条码数据
        public void Get_DisplayBard()
        {
            string HBarCode = this.txtHBathNo.Text;
            DataSet ds = oCN.RunProcReturn("select HBatchNo,m.HNumber,a.HMaterID from Gy_BarCodeBill a left join Gy_Material m on a.HMaterID = m.HItemID where HBarCode='" + HBarCode + "'", "Gy_BarCodeBill");
            if (ds.Tables[0].Rows.Count == 0)
            {
                MessageBox.Show("条码查无数据!");
            }
            else
            {
                this.txtHBathNo.Text = ds.Tables[0].Rows[0]["HBatchNo"].ToString();
                this.txtHMaterNumber.Text = ds.Tables[0].Rows[0]["HNumber"].ToString();
                this.HMaterID.Text = ds.Tables[0].Rows[0]["HMaterID"].ToString();
            }
            this.txtHBathNo.ReadOnly = true;
        }
        private void btnRest_Click(object sender, EventArgs e)
        {
            this.txtHBathNo.Text = "";
            this.txtHMaterNumber.Text = "";
            this.HMaterID.Text = "0";
            this.txtHBathNo.ReadOnly = false;
            this.btnBegin.Enabled = true;
            this.txtBegin.Text = "";
            this.btnEnd.Enabled = true;
            this.txtEnd.Text = "";
            this.btnSave.Enabled = false;
            this.txtLj.Text = "";
            this.ListData.Items.Clear();
            this.timer.Enabled = false;
        }
        private async void btnSave_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("确认保存?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (dr == DialogResult.Yes)
            {
                string Url = DBHelper.GetConfigKey(AppDomain.CurrentDomain.BaseDirectory + "Config/SQLAPI.config", "sUrl");
                //通过接口 获取token
                JsonResult_KB jsonResult = await FindAccessToken(Url);
                string EquipFile = this.cmbEquipFile.Text;
                switch (EquipFile)
                {
                    case "螺母全检":
                        SaveFullInspectionOfNuts(jsonResult.data.token, Url);
                        break;
                    case "螺母压装":
                        SaveNutPressFit(jsonResult.data.token, Url, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        break;
                    case "注塑机":
                        SaveInjectionMoldingMachine(jsonResult.data.token, Url, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        break;
                //获取设备时间段产量    因为没有工艺参数采集 所以需要单独拉出来采集数量
                for (int i = 0; i < jsonResult.data.Count; i++)
                {
                    JsonEquipmentData_KB data = await FindProdByNosAndTime(Url, token, jsonResult.data[i].no, TimeDate, time);
                    for (int j = 0; j < data.data.Count; j++)
                    {
                        JsonData_KB += "{\"HDate\":\"" + time + "\",\"HTechParamName\":\"生产数量\",\"HResult\":\"OK\",\"HCount\":" + data.data[j].prod + ",\"HSourceCode\":\"" + jsonResult.data[i].no + "\"},";
                    }
                }
                this.btnSave.Enabled = false;
            }
        }
        //螺母全检保存
        public async void SaveFullInspectionOfNuts(string token, string url)
        {
            try
            {
                CustomWriteLog("02", DateTime.Now.ToString("yyyy-MM-dd"));
                //获取所有设备数据
                JsonEquipmentData_KB jsonResult = await FindDeviceList(url, token);
                if (jsonResult.code != "0")
                //获取设备运行状态
                var EquipmentStaus = await FindDeviceStatusByNos(Url, token, nos);
                if (EquipmentStaus == null)
                {
                    this.btnSave.Enabled = true;
                    MessageBox.Show("设备列表报错:" + jsonResult.message);
                    CustomWriteLog("EquipmentStaus对象为空", DateTime.Now.ToString("yyyy-MM-dd"));
                }
                if (EquipmentStaus.data == null)
                {
                    CustomWriteLog("EquipmentStaus.data属性为空", DateTime.Now.ToString("yyyy-MM-dd"));
                }
                else
                {
                    string nos = "";
                    //获取设备编码
                    for (int i = 0; i < jsonResult.data.Count; i++)
                    for (int i = 0; i < EquipmentStaus.data.Count; i++)
                    {
                        if (jsonResult.data[i].no == this.cmbEquipFile.SelectedValue.ToString())
                        //设备运行 开关停机时间
                        if (EquipmentStaus.data[i].no.Contains("KB01ZD") || EquipmentStaus.data[i].no.Contains("KBCY") || EquipmentStaus.data[i].no.Contains("KBMY"))
                        {
                            nos = jsonResult.data[i].no;
                            string HBegDate = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                            string HEndDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:00");
                            if (DateTime.Parse(HEndDate).AddMinutes(1).ToString("yyyy-MM-dd") != DateTime.Parse(HEndDate).ToString("yyyy-MM-dd"))
                            {
                                HEndDate = DateTime.Parse(HEndDate).AddMinutes(1).ToString("yyyy-MM-dd HH:mm:00");
                            }
                            JsonResult_KB HEqDate = await FindDeviceStatusTimeByNo(Url, token, EquipmentStaus.data[i].no, HBegDate, HEndDate);
                            // 记录开机时长
                            CustomWriteLog("设备开机时长: 开机时长" + ((float)(HEqDate.data.onlineTime / 60 / 60)).ToString("0.00") + "  " + EquipmentStaus.data[i].no + "",
                                            DateTime.Now.ToString("yyyy-MM-dd"));
                            // 记录关机时长
                            CustomWriteLog("设备关机时长: 关机时长" + ((float)(HEqDate.data.offlineTime / 60 / 60)).ToString("0.00") + "  " + EquipmentStaus.data[i].no + "",
                                            DateTime.Now.ToString("yyyy-MM-dd"));
                            // 记录停机时长
                            CustomWriteLog("设备停机时长: 停机时长" + ((float)(HEqDate.data.standbyTime / 60 / 60)).ToString("0.00") + "  " + EquipmentStaus.data[i].no + "",
                                            DateTime.Now.ToString("yyyy-MM-dd"));
                            // 记录运行时长
                            CustomWriteLog("设备运行时长: 运行时长" + ((float)(HEqDate.data.runTime / 60 / 60)).ToString("0.00") + "  " + EquipmentStaus.data[i].no + "",
                                            DateTime.Now.ToString("yyyy-MM-dd"));
                            JsonData_KB += "{\"HDate\":\"" + HEndDate + "\",\"HTechParamName\":\"开机时长\",\"HResult\":\"" + ((float)(HEqDate.data.onlineTime / 60 / 60)).ToString("0.00") + "\",\"HCount\":1,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            JsonData_KB += "{\"HDate\":\"" + HEndDate + "\",\"HTechParamName\":\"关机时长\",\"HResult\":\"" + ((float)(HEqDate.data.offlineTime / 60 / 60)).ToString("0.00") + "\",\"HCount\":1,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            JsonData_KB += "{\"HDate\":\"" + HEndDate + "\",\"HTechParamName\":\"停机时长\",\"HResult\":\"" + ((float)(HEqDate.data.standbyTime / 60 / 60)).ToString("0.00") + "\",\"HCount\":1,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            JsonData_KB += "{\"HDate\":\"" + HEndDate + "\",\"HTechParamName\":\"运行时长\",\"HResult\":\"" + ((float)(HEqDate.data.runTime / 60 / 60)).ToString("0.00") + "\",\"HCount\":1,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                        }
                    }
                    //开始时间
                    string HBegin = this.txtBegin.Text;
                    //结束时间
                    string HEnd = this.txtEnd.Text;
                    //获取不良数,合数数,可疑数 总数
                    jsonResult = await FindDevicePropCalc(url, token, nos, HBegin, HEnd);
                    if (jsonResult.code != "0")
                    {
                        this.btnSave.Enabled = true;
                        MessageBox.Show("数量获取报错:" + jsonResult.message);
                    }
                    else
                    {
                        double HInSpectQty = 0;//检验数量
                        double HRightQty = 0;//合格
                        double HUnRightQty = 0;//不合格
                        double HUnKnowQty = 0;//可疑
                        for (int i = 0; i < jsonResult.data.Count; i++)
                        string staus = "";
                        switch (EquipmentStaus.data[i].status)
                        {
                            if (jsonResult.data[i].propId == 173)
                            {
                                //HInSpectQty = jsonResult.data[i].sum;
                            }
                            else if (jsonResult.data[i].propId == 469)
                            {
                                HRightQty = jsonResult.data[i].sum;
                            }
                            else if (jsonResult.data[i].propId == 606)
                            {
                                HUnKnowQty = jsonResult.data[i].sum;
                            }
                            else if (jsonResult.data[i].propId == 470)
                            {
                                HUnRightQty = jsonResult.data[i].sum;
                            }
                        }
                        //通过双方讨论 最终采纳 检验数量=合格+不合格+可疑
                        HInSpectQty = HRightQty + HUnKnowQty + HUnRightQty;
                        string HNumber = "";
                        int HSourceID = 0;
                        string HSourceNumber = "";
                        switch (this.cmbEquipFile.Text)
                        {
                            case "螺母全检":
                                HNumber = "LMJC";
                                HSourceNumber = "1030";
                            //-1:未知,1:离线,2:待机,3:正常运行,4:告警
                            case "-1":
                                staus = "未知";
                                break;
                            case "螺母压装":
                                HNumber = "LMYZ";
                                HSourceNumber = "1029";
                            case "1":
                                staus = "离线";
                                break;
                            case "2":
                                staus = "待机";
                                break;
                            case "3":
                                staus = "正常运行";
                                break;
                            case "4":
                                staus = "告警";
                                break;
                        }
                        //查询生产资源
                        DataSet dsSouce = oCN.RunProcReturn("select * from Gy_Source with(nolock) where HNumber='" + HSourceNumber + "'", "Gy_Source");
                        if (dsSouce.Tables[0].Rows.Count == 0)
                        if (jsonEquipment == null || jsonEquipment.data == null)
                        {
                            this.btnSave.Enabled = true;
                            MessageBox.Show("生产资源查无数据!");
                            // 当 jsonEquipment 或 jsonEquipment.data 为 null 时,统一走这里
                            JsonData_KB += "{\"HDate\":\"" + time + "\",\"HTechParamName\":\"开关机状态\",\"HResult\":\"" + staus + "\",\"HCount\":0,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            CustomWriteLog("2.1", DateTime.Now.ToString("yyyy-MM-dd"));
                        }
                        else if (jsonEquipment.data.Count > 0)
                        {
                            JsonData_KB += "{\"HDate\":\"" + time + "\",\"HTechParamName\":\"开关机状态\",\"HResult\":\"" + staus + "\",\"HCount\":1,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            CustomWriteLog("2.2", DateTime.Now.ToString("yyyy-MM-dd"));
                        }
                        else
                        {
                            JsonData_KB += "{\"HDate\":\"" + time + "\",\"HTechParamName\":\"开关机状态\",\"HResult\":\"" + staus + "\",\"HCount\":0,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            CustomWriteLog("2.3", DateTime.Now.ToString("yyyy-MM-dd"));
                            HSourceID = int.Parse(dsSouce.Tables[0].Rows[0]["HItemID"].ToString());
                        }
                            //查询检验方案
                            DataSet dataSet = oCN.RunProcReturn(@"select a.HInterID HQCSchemeID,b.HQCCheckItemID, ch.HNumber HQCCheckItemNumber,m.HNumber,HUpLimit,HDownLimit,HTargetVal,a.HProcID,b.HInspectInstruMentID
,b.HAnalysisMethod
from  Gy_QCCheckProjectMain a with(nolock)
inner join Gy_QCCheckProjectSub b with(nolock) on a.HInterID=b.HInterID
left join Gy_Material m with(nolock) on a.HMaterID=m.HItemID
left join Gy_QCCheckItem ch with(nolock) on b.HQCCheckItemID=ch.HItemID
left join Gy_InspectInstruMent ment on b.HInspectInstruMentID=ment.HItemID
where m.HNumber='" + this.txtHMaterNumber.Text + "' and ment.HNumber='" + HNumber + "'", "Gy_QCCheckProjectMain");
                    }
                }
                            //保存数据
                            if (dataSet.Tables[0].Rows.Count > 0)
                            {
                                string sExeReturnInfo = "";
                                string BillType = "7519";
                                long HInterID = oCN.CreateBillID_Prod(BillType, ref sExeReturnInfo);
                                string HBillNo = oCN.CreateBillCode(BillType, ref sExeReturnInfo, true);
                                if (dataSet.Tables[0].Rows.Count <= dt.Columns.Count - 1)
                                {
                                    oCN.BeginTran();
                CustomWriteLog("03", DateTime.Now.ToString("yyyy-MM-dd"));
                                    string HProcID = dataSet.Tables[0].Rows[0]["HProcID"].ToString();
                                    string HMaterID = this.HMaterID.Text;
                                    string HQCSchemeID = dataSet.Tables[0].Rows[0]["HQCSchemeID"].ToString();
                                    string HBatchNo = this.txtHBathNo.Text;
                                    int HLastResults = 1;
                                    for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
                                    {
                                        int HLastResult = 1;
                                        string HAnalysisMethod = dataSet.Tables[0].Rows[i]["HAnalysisMethod"].ToString();
                                        decimal HUpLimit = 0;
                                        decimal HDownLimit = 0;
                //查询当前开工的设备 获取对应的物料信息
                DataSet datable = oCN.RunProcReturn(@"select m.HNumber,eq.HEquipFileNo from Sc_ICMOBillStatus_Tmp a
                                            inner join Gy_EquipFileBillMain eq on a.HSourceID = eq.HSourceID
                                            inner join Gy_Material m on a.HMaterID = m.HItemID
                                            where a.HICMOStatus = '1' ", "Sc_ICMOBillStatus_Tmp");
                                        //分析方法 为定量分析
                                        if (HAnalysisMethod == "2")
                                        {
                                            //获取上限
                                            HUpLimit = decimal.Parse(dataSet.Tables[0].Rows[i]["HTargetVal"].ToString()) + decimal.Parse(dataSet.Tables[0].Rows[i]["HUpLimit"].ToString());
                                            //获取下限
                                            HDownLimit = decimal.Parse(dataSet.Tables[0].Rows[i]["HTargetVal"].ToString()) + decimal.Parse(dataSet.Tables[0].Rows[i]["HDownLimit"].ToString());
                                        }
                if (datable.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < datable.Tables[0].Rows.Count; i++)
                    {
                        string HSourceCode = datable.Tables[0].Rows[i]["HEquipFileNo"].ToString();
                        string HNumber = datable.Tables[0].Rows[i]["HNumber"].ToString();
                        JsonData_KB += "{\"HDate\":\"" + DateTime.Now.ToString() + "\",\"HTechParamName\":\"物料代码\",\"HResult\":\"" + HNumber + "\",\"HCount\":1,\"HSourceCode\":\"" + HSourceCode + "\"},";
                    }
                }
                                        for (int j = 0; j < dt.Columns.Count - 1; j++)
                                        {
                CustomWriteLog("04", DateTime.Now.ToString("yyyy-MM-dd"));
                                            string HQCCheckItemName = "";
                                            switch (dt.Columns[j].ColumnName)
                                            {
                                                case "BottomHoleDiameter":
                                                    HQCCheckItemName = "DKZJ";
                                                    break;
                                                case "TestingData":
                                                    HQCCheckItemName = "LYJCSJ";
                                                    break;
                                                case "DetectionResult":
                                                    HQCCheckItemName = "LYJCJG";
                                                    break;
                                            }
                                            //SRM@101.2@VEN00005@CGDD000167@1.02.002.002@20231129@1000
                                            //判断检验项目的代码 跟列名是否一致
                                            if (dataSet.Tables[0].Rows[i]["HQCCheckItemNumber"].ToString().Contains(HQCCheckItemName))
                                            {
                                                for (int k = 0; k < dt.Rows.Count; k++)
                                                {
                                                    //只取时间范围内的数据
                                                    if (DateTime.Parse(dt.Rows[k]["HDate"].ToString()) >= DateTime.Parse(HBegin) && DateTime.Parse(dt.Rows[k]["HDate"].ToString()) <= DateTime.Parse(HEnd))
                                                    {
                                                        //获取检验值
                                                        decimal HInSpectValue = decimal.Parse(dt.Rows[k][dt.Columns[j].ColumnName].ToString());
                                                        //默认值结论为合格
                                                        int HInSpectResult = 1;
                                                        //定量分析 进行判断是否满足上下限
                                                        if (HAnalysisMethod == "2")
                                                        {
                                                            HInSpectResult = (HInSpectValue > HUpLimit || HDownLimit > HInSpectValue) ? 0 : 1;
                                                        }
                                                        else
                                                        {
                                                            HInSpectResult = int.Parse(HInSpectValue.ToString());
                                                        }
                JsonData_KB = JsonData_KB.Substring(0, JsonData_KB.Length - 1);
                JsonData_KB += "]}";
                                                        //如果当前结论为合格 并且历史结论也是合格 则继续保持合格
                                                        if (HInSpectResult == 1 && HLastResult != 0)
                                                        {
                                                            HLastResult = 1;
                                                        }
                                                        else
                                                        {
                                                            HLastResult = 0;
                                                        }
                CustomWriteLog("结束所有", DateTime.Now.ToString("yyyy-MM-dd"));
                                                        oCN.RunProc("Insert into QC_StockCheckBillSub_ValueGrid " +
                          " (HInterID,HEntryID,HSEQ" +
                          ",HInSpectResult,HInSpectValue,HInSpectValueB,HInSpectValueT)" +
                          "values(" + HInterID + "," + ((i + 1)) + "," + (k + 1) + "" +
                          "," + HInSpectResult + "," + dt.Rows[k][dt.Columns[j].ColumnName].ToString() + "," + dt.Rows[k][dt.Columns[j].ColumnName].ToString() + "," + dt.Rows[k][dt.Columns[j].ColumnName].ToString() + ") ");
                                                    }
                                                }
                                                break;
                                            }
                                        }
                //保存数据
                DataSave(JsonData_KB);
                if (TimeDate != "")
                {
                    TimeDate = time;
                }
            }
        }
                                        oCN.RunProc("Insert into QC_StockCheckBillSub " +
                        " (HInterID,HBillNo_bak,HEntryID,HCloseMan" +
                        ",HEntryCloseDate,HCloseType,HRemark,HSourceInterID" +
                        ",HSourceEntryID,HSourceBillNo,HSourceBillType,HRelationQty,HRelationMoney" +
                        ",HQCCheckItemID,HQCStd,HUnit,HQCNote,HResult" +
                        ",HMax,HMin,HAvg,HSampleSchemeID,HSampleQty,HSampleDamageQty,HAcceptQty" +
                        ",HRejectQty,HSampleUnRightQty,HStatus,HUnitID,HInspectVal,HTargetVal" +
                        ",HUpLimit,HDownLimit,HUpOffSet,HDownOffSet,HKeyInspect,HAnalysisMethod,HInspectInstruMentID,HInspectResult" +
                        ") values("
                        + HInterID + ",'" + HBillNo + "'," + (i + 1) + ",''" +
                        ",getdate(),0,'',0" +
                        ",0,'','',0,0" +
                        "," + dataSet.Tables[0].Rows[i]["HQCCheckItemID"].ToString() + ",'" + dataSet.Tables[0].Rows[i]["HTargetVal"].ToString() + "','','','" + HLastResult + "'" +
                        ",'" + dataSet.Tables[0].Rows[i]["HUpLimit"].ToString() + "','" + dataSet.Tables[0].Rows[i]["HDownLimit"].ToString() + "','',0,0,0,0" +
                        ",0,0,'',0,'','" + dataSet.Tables[0].Rows[i]["HTargetVal"].ToString() + "'" +
                        ",'" + dataSet.Tables[0].Rows[i]["HUpLimit"].ToString() + "','" + dataSet.Tables[0].Rows[i]["HDownLimit"].ToString() + "','','',0,'" + HAnalysisMethod + "'," + dataSet.Tables[0].Rows[i]["HInspectInstruMentID"].ToString() + ",'" + HLastResult + "'" +
                        ") ");
                                        //如果当前结论为合格 并且历史结论也是合格 则继续保持合格
                                        if (HLastResult == 1 && HLastResults != 0)
                                        {
                                            HLastResults = 1;
                                        }
                                        else
                                        {
                                            HLastResults = 0;
                                        }
                                    }
        //数据保存
        public void DataSave(string JsonData_KB)
        {
            JsonEquipmentData_KB data = JsonConvert.DeserializeObject<JsonEquipmentData_KB>(JsonData_KB);
                                    //主表
                                    oCN.RunProc("Insert Into QC_StockCheckBillMain " +
                                        "(HBillType,HBillSubType,HInterID,HBillNo,HBillStatus,HDate,HMaker,HMakeDate" +
                                        ",HYear,HPeriod,HRemark" +
                                        ",HSourceID,HICMOInterID,HICMOBillNo,HICMOQty,HProcExchInterID,HProcExchEntryID" +
                                        ",HProcExchBillNo,HProcExchQty,HMaterID,HFirstCheckEmp,HLastResult" +
                                        ",HMainSourceInterID,HMainSourceEntryID,HMainSourceBillNo,HMainSourceBillType,HICMOEntryID,HQCSchemeID,HShiftsID,HErrTreatment" +
                                        ",HProcID,HBatchNo,HInSpectQty ,HRightQty ,HUnRightQty ,HUnKnowQty " +
                                        ") " +
                                        " values('" + BillType + "','" + BillType + "'," + HInterID + ",'" + HBillNo + "',1,getdate(),'" + this.txtHMaker.Text + "',getdate()" +
                                        "," + DateTime.Now.Year + "," + DateTime.Now.Month + ",''" +
                                        "," + HSourceID + ",0,'',0,0,0" +
                                        ",'',0," + HMaterID + ",'" + this.labHMakerID.Text + "', " + HLastResults +
                                        ",0,0,'','',0," + HQCSchemeID + ",0,''" +
                                        "," + HProcID + ",'" + HBatchNo + "'," + HInSpectQty + "," + HRightQty + ", " + HUnRightQty + ", " + HUnKnowQty + ") ");
            for (int i = 0; i < data.data.Count; i++)
            {
                oCN.RunProc(@"insert into Sb_EquipMentCollectionTechParam_Temp(HDate,HSourceCode,HTechParamID,HTechParamName,HCount
                ,HCreateTime,HResult,HProcNumber,HFlag)
                values(getdate(),'" + data.data[i].HSourceCode + "',0,'" + data.data[i].HTechParamName + "'," + data.data[i].HCount
                + ",'" + data.data[i].HDate + "','" + data.data[i].HResult + "','" + data.data[i].HProcNumber + "',0)");
            }
        }
        //定时生成产量汇报单
        private async void Time_CLHB_Tick(object sender, EventArgs e)
        {
                                    oCN.Commit();
                                    MessageBox.Show("保存成功!");
                                    //this.btnRest.Enabled = true;
            string Url = DBHelper.GetConfigKey(AppDomain.CurrentDomain.BaseDirectory + "Config/SQLAPI.config", "sUrl");
            string urls = Url + EquipmentType_KB.One;
            //准备要发送的表单数据
            var formData = new FormUrlEncodedContent(new[]
           {
                     new KeyValuePair<string, string>("userName", "admin"),
                     new KeyValuePair<string, string>("password", "Youngsunabc123..")
                      //添加更多键值对,根据您的需要
               });
            JsonResult_KB jsonResult = await getUrl(urls, formData);
            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string token = jsonResult.data.token;
                                }
                                else
                                {
                                    this.btnSave.Enabled = true;
                                    MessageBox.Show("当前物料的检验方案与Excel的列不匹配!");
                                }
                            }
                            else
                            {
                                this.btnSave.Enabled = true;
                                MessageBox.Show("当前物料没有对应的检验方案!");
                            }
            //获取所有的设备数据
            JsonEquipmentData_KB jsonEquipment = await FindDeviceList(Url, token);
            if (jsonEquipment.code != "0")
            {
                MessageBox.Show("设备列表报错:" + jsonEquipment.message);
            }
            else
            {
                string nos = "";
                //获取去设备编码
                for (int i = 0; i < jsonEquipment.data.Count; i++)
                {
                    nos += "''" + jsonEquipment.data[i].no + "'',";
                }
                nos = nos.Substring(0, nos.Length - 1);
                CustomWriteLog("产量汇报单,设备编码:'" + nos + "'", DateTime.Now.ToString("yyyy-MM-dd"));
                //查询开工的设备信息 以及 查询当天设备对应的开工时间 和完工时间
                DataSet ds = oCN.RunProcReturn("exec h_p_Sc_TimeICMOReporList '" + nos + "'", "h_p_Sc_TimeICMOReporList");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    //根据当天只开工没有完工对应的产量数据 生成产量汇报单
                    DataTable dt = ds.Tables[0];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        nos = dt.Rows[i]["设备编码"].ToString();
                        string HICMInterID = dt.Rows[i]["HInterID"].ToString();
                        string HBegDate = DateTime.Parse(dt.Rows[i]["日期"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                        string HEndDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        jsonEquipment = await FindProdByNosAndTime(Url, token, nos, HBegDate, HEndDate);
                        if (decimal.Parse(jsonEquipment.data[0].prod) > 0)
                        {
                            //生成产量汇报单
                            oCN.RunProc("exec h_p_Sc_AddTimeICMORepor " + HICMInterID + "," + jsonEquipment.data[0].prod + ",'" + HEndDate + "'");
                            CustomWriteLog("生成产量汇报单1:'exec h_p_Sc_AddTimeICMORepor " + HICMInterID + "," + jsonEquipment.data[0].prod + ",'" + HEndDate + "''", DateTime.Now.ToString("yyyy-MM-dd"));
                        }
                    }
                }
                if (ds.Tables[1].Rows.Count > 0)
                {
                    //根据当天开工并且完工对应的产量数据 生成产量汇报单
                     DataTable dt = ds.Tables[1];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        nos = dt.Rows[i]["设备编码"].ToString();
                        string HICMInterID = dt.Rows[i]["HInterID"].ToString();
                        string HBegDate = DateTime.Parse(dt.Rows[i]["开始日期"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                        string HEndDate = DateTime.Parse(dt.Rows[i]["结束日期"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                        jsonEquipment = await FindProdByNosAndTime(Url, token, nos, HBegDate, HEndDate);
                        if (decimal.Parse(jsonEquipment.data[0].prod) > 0)
                        {
                            //生成产量汇报单
                            oCN.RunProc("exec h_p_Sc_AddTimeICMORepor " + HICMInterID + "," + jsonEquipment.data[0].prod + ",'" + HEndDate + "'");
                            CustomWriteLog("生成产量汇报单2:'exec h_p_Sc_AddTimeICMORepor " + HICMInterID + "," + jsonEquipment.data[0].prod + ",'" + HEndDate + "''", DateTime.Now.ToString("yyyy-MM-dd"));
                        }
                    }
                }
            }
            catch (Exception e)
        }
        private void EquipmentCollectionForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("确定要关闭吗?", "确认", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                this.btnSave.Enabled = true;
                MessageBox.Show("保存失败!" + e.Message);
                e.Cancel = true;
            }
        }
        #region  接口
        //获取登录的token
        public async Task<JsonResult_KB> getUrl(string url, FormUrlEncodedContent formData)
        {
            // 创建 HttpClient 实例
            using (var client = new HttpClient())
            {
@@ -589,12 +386,7 @@
            }
        }
        /// <summary>
        /// 获取设备列表
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        // 获取设备列表
        public async Task<JsonEquipmentData_KB> EquipmentList(string url, StringContent postData, string Type)
        {
@@ -746,7 +538,7 @@
            var postData = new StringContent(stringJson, System.Text.Encoding.UTF8, "application/json");
            string urls = url + EquipmentType_KB.Three;
            CustomWriteLog("设备运行状态:'" + urls + "' 参数值: '" + stringJson + "'", DateTime.Now.ToString("yyyy-MM-dd"));
            JsonEquipmentData_KB jsonResult = await EquipmentList(urls, postData, "POST");
            JsonEquipmentData_KB jsonResult = await EquipmentList(urls, postData, "POST");
            return jsonResult;
        }
@@ -772,7 +564,7 @@
            var postData = new StringContent(stringJson, System.Text.Encoding.UTF8, "application/json");
            string urls = url + EquipmentType_KB.Five;
            // 记录开机时长
            CustomWriteLog("设备运行时间接口:'"+ urls + "' 参数值: '" + stringJson + "'", DateTime.Now.ToString("yyyy-MM-dd"));
            CustomWriteLog("设备运行时间接口:'" + urls + "' 参数值: '" + stringJson + "'", DateTime.Now.ToString("yyyy-MM-dd"));
            JsonResult_KB jsonResult = await EquipResultList(urls, postData, "POST");
            return jsonResult;
        }
@@ -789,546 +581,7 @@
            JsonResult_KB jsonResult = await EquipResultList(urls, postData, "POST");
            return jsonResult;
        }
        //下拉框绑定数据
        private void bindCbox()
        {
            IList<Info_KB> infoList = new List<Info_KB>();
            Info_KB info1 = new Info_KB() { Id = "CMR-QC-SE-001", Name = "螺母全检" };
            Info_KB info2 = new Info_KB() { Id = "CMR-ZZ-SE-001", Name = "螺母压装" };
            Info_KB info3 = new Info_KB() { Id = "ZSJ07", Name = "注塑机#07" };
            //Info_KB info3 = new Info_KB() { Id = "3", Name = "王五" };
            infoList.Add(info1);
            infoList.Add(info2);
            infoList.Add(info3);
            cmbEquipFile.DataSource = infoList;
            cmbEquipFile.ValueMember = "Id";
            cmbEquipFile.DisplayMember = "Name";
            this.cmbEquipFile.SelectedIndex = 0;
            this.cmbEquipFile.DropDownStyle = ComboBoxStyle.DropDownList;
        }
        //选择下拉框值更改事件
        private void cmbEquipFile_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbEquipFile.SelectedIndex == 0)
            {
                this.btnLj.Enabled = true;
                this.timer.Enabled = false;
            }
            else
            {
                this.btnLj.Enabled = false;
                DialogResult dr = MessageBox.Show("是否确认开始采集?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                if (dr == DialogResult.Yes)
                {
                    this.txtHBathNo.ReadOnly = true;
                    this.txtBegin.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:00");
                    //this.txtBegin.Text = "2024-11-21 13:40:27";
                    this.btnBegin.Enabled = false;
                    this.timer.Enabled = true;
                    this.Time_CLHB.Enabled = true;
                }
            }
        }
        //定时获取数据
        private async void timer_Tick(object sender, EventArgs e)
        {
            //测试全检
            //this.timer.Enabled = false;
            string Url = DBHelper.GetConfigKey(AppDomain.CurrentDomain.BaseDirectory + "Config/SQLAPI.config", "sUrl");
            string urls = Url + EquipmentType_KB.One;
            // 准备要发送的表单数据
            var formData = new FormUrlEncodedContent(new[]
            {
                    new KeyValuePair<string, string>("userName", "admin"),
                    new KeyValuePair<string, string>("password", "Youngsunabc123..")
                    // 添加更多键值对,根据您的需要
                });
            JsonResult_KB jsonResult = await getUrl(urls, formData);
            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:00");
            if (cmbEquipFile.SelectedIndex == 1)
            {
                SaveNutPressFit(Url, jsonResult.data.token, time);
            }
            else if (cmbEquipFile.SelectedIndex == 2)
            {
                SaveInjectionMoldingMachine(jsonResult.data.token, Url, time);
            }
        }
        //螺母压装采集数据 保存
        public async void SaveNutPressFit(string Url, string token, string time)
        {
            if (TimeDate == "")
            {
                TimeDate = this.txtBegin.Text;
            }
            this.timer.Enabled = false;
            JsonEquipmentData_KB jsonResult = await FindDeviceList(Url, token);
            if (jsonResult.code != "0")
            {
                MessageBox.Show("设备列表报错:" + jsonResult.message);
            }
            else
            {
                string nos = "";
                //获取去设备编码
                for (int i = 0; i < jsonResult.data.Count; i++)
                {
                    if (jsonResult.data[i].no.Contains("CMR-ZZ-SE-001"))
                    {
                        nos += jsonResult.data[i].no + ",";
                    }
                }
                nos = nos.Substring(0, nos.Length - 1);
                //TimeDate = "2024-08-14 08:30:39";
                //time = "2024-08-14 15:05:39";
                JsonEquipmentData_KB jsonEquipment = await FindAllDevicePropsDetailByTimeRange(Url, token, nos, TimeDate, time);
                var JsonData_KB = "{\"data\":[";
                for (int i = 0; i < jsonEquipment.data[0].props.Count; i++)
                {
                    for (int j = 0; j < jsonEquipment.data[0].props[i].datas.Count; j++)
                    {
                        valueData_KB value = JsonConvert.DeserializeObject<valueData_KB>(jsonEquipment.data[0].props[i].datas[j].value);
                        if (value.type == "良品")
                        {
                            JsonData_KB += "{\"HDate\":\"" + jsonEquipment.data[0].props[i].datas[j].createTime + "\",\"HTechParamName\":\"螺母是否凸出\",\"HResult\":\"OK\",\"HCount\":1,\"HSourceCode\":\"" + nos + "\"},";
                        }
                        else
                        {
                            JsonData_KB += "{\"HDate\":\"" + jsonEquipment.data[0].props[i].datas[j].createTime + "\",\"HTechParamName\":\"螺母是否凸出\",\"HResult\":\"NG\",\"HCount\":1,\"HSourceCode\":\"" + nos + "\"},";
                        }
                        JsonData_KB += "{\"HDate\":\"" + jsonEquipment.data[0].props[i].datas[j].createTime + "\",\"HTechParamName\":\"生产周期\",\"HResult\":\"" + value.beat + "\",\"HCount\":1,\"HSourceCode\":\"" + nos + "\"},";
                    }
                }
                jsonEquipment = await FindDevicePropCalc(Url, token, nos, TimeDate, time);
                for (int i = 0; i < jsonEquipment.data.Count; i++)
                {
                    //合格数
                    if (jsonEquipment.data[i].propId == 469)
                    {
                        JsonData_KB += "{\"HDate\":\"" + time + "\",\"HTechParamName\":\"良品数\",\"HResult\":\"OK\",\"HCount\":" + jsonEquipment.data[i].sum + ",\"HSourceCode\":\"" + nos + "\"},";
                    }
                    //不良数
                    else if (jsonEquipment.data[i].propId == 470)
                    {
                        JsonData_KB += "{\"HDate\":\"" + time + "\",\"HTechParamName\":\"NG数量\",\"HResult\":\"NG\",\"HCount\":" + jsonEquipment.data[i].sum + ",\"HSourceCode\":\"" + nos + "\"},";
                    }
                }
                JsonData_KB = JsonData_KB.Substring(0, JsonData_KB.Length - 1);
                JsonData_KB += "]}";
                DataSave(JsonData_KB);
                if (TimeDate != "")
                {
                    TimeDate = time;
                }
            }
        }
        //注塑机采集数据 保存
        public async void SaveInjectionMoldingMachine(string token, string Url, string time)
        {
            ListData.Items.Clear();
            if (TimeDate == "")
            {
                TimeDate = this.txtBegin.Text;
            }
            //this.timer.Enabled = false;
            //TimeDate = "2025-02-10 13:10:50";
            //time = "2025-02-10 13:11:50";
            //获取所有设备数据
            JsonEquipmentData_KB jsonResult = await FindDeviceList(Url, token);
            if (jsonResult.code != "0")
            {
                MessageBox.Show("设备列表报错:" + jsonResult.message);
            }
            else
            {
                string nos = "";
                //获取设备编码
                for (int i = 0; i < jsonResult.data.Count; i++)
                {
                    nos += jsonResult.data[i].no + ",";
                    //if (jsonResult.data[i].no.Contains("JS_ZS"))
                    //{
                    //    nos += jsonResult.data[i].no + ",";
                    //}
                }
                nos = nos.Substring(0, nos.Length - 1);
                //获取参数 获取每个设备对应的所有参数   20250723 凯贝没有工艺参数采集
                //JsonEquipmentData_KB jsonEquipment = await FindAllDevicePropsDetailByTimeRange(Url, token, nos, TimeDate, time);
                JsonEquipmentData_KB jsonEquipment= null;
                var JsonData_KB = "{\"data\":[";
                if (jsonEquipment == null)
                {
                    CustomWriteLog("jsonEquipment对象为空", DateTime.Now.ToString("yyyy-MM-dd"));
                }
                //20250723注释
                //if (jsonEquipment.data == null)
                //{
                //    CustomWriteLog("jsonEquipment.data属性为空", DateTime.Now.ToString("yyyy-MM-dd"));
                //}
                else
                {
                    CustomWriteLog("开始循环工艺参数总数为:'" + jsonEquipment.data.Count + "'", DateTime.Now.ToString("yyyy-MM-dd"));
                    //通过每个设备进行循环赋值
                    for (int i = 0; i < jsonEquipment.data.Count; i++)
                    {
                        //循环 螺母压装设备对应的所有工艺参数
                        for (int j = 0; j < jsonEquipment.data[i].props.Count; j++)
                        {
                            //循环 每个参数对应的所有数据
                            for (int k = 0; k < jsonEquipment.data[i].props[j].datas.Count; k++)
                            {
                                JsonData_KB += "{\"HDate\":\"" + jsonEquipment.data[i].props[j].datas[k].createTime + "\",\"HTechParamName\":\"" + jsonEquipment.data[i].props[j].propName + "\",\"HResult\":\"" + jsonEquipment.data[i].props[j].datas[k].value + "\",\"HCount\":1,\"HSourceCode\":\"" + jsonEquipment.data[i].deviceNo + "\"},";
                                //CustomWriteLog("工艺参数具体值:{\"HDate\":\"" + jsonEquipment.data[i].props[j].datas[k].createTime + "\",\"HTechParamName\":\"" + jsonEquipment.data[i].props[j].propName + "\",\"HResult\":\"" + jsonEquipment.data[i].props[j].datas[k].value + "\",\"HCount\":1,\"HSourceCode\":\"" + jsonEquipment.data[i].deviceNo + "\"}", DateTime.Now.ToString("yyyy-MM-dd"));
                            }
                        }
                        //获取设备时间段产量
                        JsonEquipmentData_KB data = await FindProdByNosAndTime(Url, token, jsonEquipment.data[i].deviceNo, TimeDate, time);
                        for (int j = 0; j < data.data.Count; j++)
                        {
                            JsonData_KB += "{\"HDate\":\"" + time + "\",\"HTechParamName\":\"生产数量\",\"HResult\":\"OK\",\"HCount\":" + data.data[j].prod + ",\"HSourceCode\":\"" + jsonEquipment.data[i].deviceNo + "\"},";
                            //CustomWriteLog("{\"HDate\":\"" + time + "\",\"HTechParamName\":\"生产数量\",\"HResult\":\"OK\",\"HCount\":" + data.data[j].prod + ",\"HSourceCode\":\"" + jsonEquipment.data[i].deviceNo + "\"}", DateTime.Now.ToString("yyyy-MM-dd"));
                        }
                    }
                }
                //获取设备时间段产量    因为没有工艺参数采集 所以需要单独拉出来采集数量
                for (int i = 0; i < jsonResult.data.Count; i++)
                {
                    JsonEquipmentData_KB data = await FindProdByNosAndTime(Url, token, jsonResult.data[i].no, TimeDate, time);
                    for (int j = 0; j < data.data.Count; j++)
                    {
                        JsonData_KB += "{\"HDate\":\"" + time + "\",\"HTechParamName\":\"生产数量\",\"HResult\":\"OK\",\"HCount\":" + data.data[j].prod + ",\"HSourceCode\":\"" + jsonResult.data[i].no + "\"},";
                    }
                }
                CustomWriteLog("02", DateTime.Now.ToString("yyyy-MM-dd"));
                //获取设备运行状态
                var EquipmentStaus = await FindDeviceStatusByNos(Url, token, nos);
                if (EquipmentStaus == null)
                {
                    CustomWriteLog("EquipmentStaus对象为空", DateTime.Now.ToString("yyyy-MM-dd"));
                }
                if (EquipmentStaus.data == null)
                {
                    CustomWriteLog("EquipmentStaus.data属性为空", DateTime.Now.ToString("yyyy-MM-dd"));
                }
                else
                {
                    for (int i = 0; i < EquipmentStaus.data.Count; i++)
                    {
                        //卷绕  注塑  浸渍  组装  的设备运行 开关停机时间
                        if (EquipmentStaus.data[i].no.Contains("KB01ZD") || EquipmentStaus.data[i].no.Contains("KBCY"))
                        {
                            string HBegDate = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
                            string HEndDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:00");
                            if (DateTime.Parse(HEndDate).AddMinutes(1).ToString("yyyy-MM-dd") != DateTime.Parse(HEndDate).ToString("yyyy-MM-dd"))
                            {
                                HEndDate = DateTime.Parse(HEndDate).AddMinutes(1).ToString("yyyy-MM-dd HH:mm:00");
                            }
                            JsonResult_KB HEqDate = await FindDeviceStatusTimeByNo(Url, token, EquipmentStaus.data[i].no, HBegDate, HEndDate);
                            // 记录开机时长
                            CustomWriteLog("设备开机时长: 开机时长" + ((float)(HEqDate.data.onlineTime / 60 / 60)).ToString("0.00") + "  " + EquipmentStaus.data[i].no + "",
                                            DateTime.Now.ToString("yyyy-MM-dd"));
                            // 记录关机时长
                            CustomWriteLog("设备关机时长: 关机时长" + ((float)(HEqDate.data.offlineTime / 60 / 60)).ToString("0.00") + "  " + EquipmentStaus.data[i].no + "",
                                            DateTime.Now.ToString("yyyy-MM-dd"));
                            // 记录停机时长
                            CustomWriteLog("设备停机时长: 停机时长" + ((float)(HEqDate.data.standbyTime / 60 / 60)).ToString("0.00") + "  " + EquipmentStaus.data[i].no + "",
                                            DateTime.Now.ToString("yyyy-MM-dd"));
                            // 记录运行时长
                            CustomWriteLog("设备运行时长: 运行时长" + ((float)(HEqDate.data.runTime / 60 / 60)).ToString("0.00") + "  " + EquipmentStaus.data[i].no + "",
                                            DateTime.Now.ToString("yyyy-MM-dd"));
                            JsonData_KB += "{\"HDate\":\"" + HEndDate + "\",\"HTechParamName\":\"开机时长\",\"HResult\":\"" + ((float)(HEqDate.data.onlineTime / 60 / 60)).ToString("0.00") + "\",\"HCount\":1,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            JsonData_KB += "{\"HDate\":\"" + HEndDate + "\",\"HTechParamName\":\"关机时长\",\"HResult\":\"" + ((float)(HEqDate.data.offlineTime / 60 / 60)).ToString("0.00") + "\",\"HCount\":1,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            JsonData_KB += "{\"HDate\":\"" + HEndDate + "\",\"HTechParamName\":\"停机时长\",\"HResult\":\"" + ((float)(HEqDate.data.standbyTime / 60 / 60)).ToString("0.00") + "\",\"HCount\":1,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            JsonData_KB += "{\"HDate\":\"" + HEndDate + "\",\"HTechParamName\":\"运行时长\",\"HResult\":\"" + ((float)(HEqDate.data.runTime / 60 / 60)).ToString("0.00") + "\",\"HCount\":1,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                        }
                        string staus = "";
                        switch (EquipmentStaus.data[i].status)
                        {
                            //-1:未知,1:离线,2:待机,3:正常运行,4:告警
                            case "-1":
                                staus = "未知";
                                break;
                            case "1":
                                staus = "离线";
                                break;
                            case "2":
                                staus = "待机";
                                break;
                            case "3":
                                staus = "正常运行";
                                break;
                            case "4":
                                staus = "告警";
                                break;
                        }
                        if (jsonEquipment == null || jsonEquipment.data == null)
                        {
                            // 当 jsonEquipment 或 jsonEquipment.data 为 null 时,统一走这里
                            JsonData_KB += "{\"HDate\":\"" + time + "\",\"HTechParamName\":\"开关机状态\",\"HResult\":\"" + staus + "\",\"HCount\":0,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            CustomWriteLog("2.1", DateTime.Now.ToString("yyyy-MM-dd"));
                        }
                        else if (jsonEquipment.data.Count > 0)
                        {
                            JsonData_KB += "{\"HDate\":\"" + time + "\",\"HTechParamName\":\"开关机状态\",\"HResult\":\"" + staus + "\",\"HCount\":1,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            CustomWriteLog("2.2", DateTime.Now.ToString("yyyy-MM-dd"));
                        }
                        else
                        {
                            JsonData_KB += "{\"HDate\":\"" + time + "\",\"HTechParamName\":\"开关机状态\",\"HResult\":\"" + staus + "\",\"HCount\":0,\"HSourceCode\":\"" + EquipmentStaus.data[i].no + "\"},";
                            CustomWriteLog("2.3", DateTime.Now.ToString("yyyy-MM-dd"));
                        }
                    }
                }
                CustomWriteLog("03", DateTime.Now.ToString("yyyy-MM-dd"));
                //查询当前开工的设备 获取对应的物料信息
                DataSet datable = oCN.RunProcReturn(@"select m.HNumber,eq.HEquipFileNo from Sc_ICMOBillStatus_Tmp a
                                            inner join Gy_EquipFileBillMain eq on a.HSourceID = eq.HSourceID
                                            inner join Gy_Material m on a.HMaterID = m.HItemID
                                            where a.HICMOStatus = '1' ", "Sc_ICMOBillStatus_Tmp");
                if (datable.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < datable.Tables[0].Rows.Count; i++)
                    {
                        string HSourceCode = datable.Tables[0].Rows[i]["HEquipFileNo"].ToString();
                        string HNumber = datable.Tables[0].Rows[i]["HNumber"].ToString();
                        JsonData_KB += "{\"HDate\":\"" + DateTime.Now.ToString() + "\",\"HTechParamName\":\"物料代码\",\"HResult\":\"" + HNumber + "\",\"HCount\":1,\"HSourceCode\":\"" + HSourceCode + "\"},";
                    }
                }
                CustomWriteLog("04", DateTime.Now.ToString("yyyy-MM-dd"));
                JsonData_KB = JsonData_KB.Substring(0, JsonData_KB.Length - 1);
                JsonData_KB += "]}";
                CustomWriteLog("结束所有", DateTime.Now.ToString("yyyy-MM-dd"));
                //保存数据
                DataSave(JsonData_KB);
                if (TimeDate != "")
                {
                    TimeDate = time;
                }
            }
        }
        //数据保存
        public void DataSave(string JsonData_KB)
        {
            JsonEquipmentData_KB data = JsonConvert.DeserializeObject<JsonEquipmentData_KB>(JsonData_KB);
            for (int i = 0; i < data.data.Count; i++)
            {
                oCN.RunProc(@"insert into Sb_EquipMentCollectionTechParam_Temp(HDate,HSourceCode,HTechParamID,HTechParamName,HCount
                ,HCreateTime,HResult,HProcNumber,HFlag)
                values(getdate(),'" + data.data[i].HSourceCode + "',0,'" + data.data[i].HTechParamName + "'," + data.data[i].HCount
                + ",'" + data.data[i].HDate + "','" + data.data[i].HResult + "','" + data.data[i].HProcNumber + "',0)");
            }
            ListData.Items.Add($"时间: {DateTime.Now:yyyy-MM-dd HH:mm:ss},加载成功");
        }
        //定时生成产量汇报单
        private async void Time_CLHB_Tick(object sender, EventArgs e)
        {
            //this.Time_CLHB.Enabled = false;
            string Url = DBHelper.GetConfigKey(AppDomain.CurrentDomain.BaseDirectory + "Config/SQLAPI.config", "sUrl");
            string urls = Url + EquipmentType_KB.One;
            // 准备要发送的表单数据
            var formData = new FormUrlEncodedContent(new[]
            {
                    new KeyValuePair<string, string>("userName", "admin"),
                    new KeyValuePair<string, string>("password", "Youngsunabc123..")
                    // 添加更多键值对,根据您的需要
                });
            JsonResult_KB jsonResult = await getUrl(urls, formData);
            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string token = jsonResult.data.token;
            //获取所有的设备数据
            JsonEquipmentData_KB jsonEquipment = await FindDeviceList(Url, token);
            if (jsonEquipment.code != "0")
            {
                MessageBox.Show("设备列表报错:" + jsonEquipment.message);
            }
            else
            {
                string nos = "";
                //获取去设备编码
                for (int i = 0; i < jsonEquipment.data.Count; i++)
                {
                    nos += "''" + jsonEquipment.data[i].no + "'',";
                    //if (jsonEquipment.data[i].no.Contains("JS_ZS"))
                    //{
                    //    nos += "''" + jsonEquipment.data[i].no + "'',";
                    //}
                }
                nos = nos.Substring(0, nos.Length - 1);
                //this.Time_CLHB.Enabled = false;
                CustomWriteLog("产量汇报单,设备编码:'"+ nos + "'", DateTime.Now.ToString("yyyy-MM-dd"));
                //查询开工的设备信息 以及 查询当天设备对应的开工时间 和完工时间
                DataSet ds = oCN.RunProcReturn("exec h_p_Sc_TimeICMOReporList '" + nos + "'", "h_p_Sc_TimeICMOReporList");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    //根据当天只开工没有完工对应的产量数据 生成产量汇报单
                    DataTable dt = ds.Tables[0];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        nos = dt.Rows[i]["设备编码"].ToString();
                        string HICMInterID = dt.Rows[i]["HInterID"].ToString();
                        string HBegDate = DateTime.Parse(dt.Rows[i]["日期"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                        string HEndDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        jsonEquipment = await FindProdByNosAndTime(Url, token, nos, HBegDate, HEndDate);
                        if (decimal.Parse(jsonEquipment.data[0].prod) > 0)
                        {
                            //生成产量汇报单
                            oCN.RunProc("exec h_p_Sc_AddTimeICMORepor " + HICMInterID + "," + jsonEquipment.data[0].prod + ",'" + HEndDate + "'");
                            CustomWriteLog("生成产量汇报单1:'exec h_p_Sc_AddTimeICMORepor " + HICMInterID + "," + jsonEquipment.data[0].prod + ",'" + HEndDate + "''", DateTime.Now.ToString("yyyy-MM-dd"));
                        }
                    }
                }
                if (ds.Tables[1].Rows.Count > 0)
                {
                    //根据当天开工并且完工对应的产量数据 生成产量汇报单
                    DataTable dt = ds.Tables[1];
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        nos = dt.Rows[i]["设备编码"].ToString();
                        string HICMInterID = dt.Rows[i]["HInterID"].ToString();
                        string HBegDate = DateTime.Parse(dt.Rows[i]["开始日期"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                        string HEndDate = DateTime.Parse(dt.Rows[i]["结束日期"].ToString()).ToString("yyyy-MM-dd HH:mm:ss");
                        jsonEquipment = await FindProdByNosAndTime(Url, token, nos, HBegDate, HEndDate);
                        if (decimal.Parse(jsonEquipment.data[0].prod) > 0)
                        {
                            //生成产量汇报单
                            oCN.RunProc("exec h_p_Sc_AddTimeICMORepor " + HICMInterID + "," + jsonEquipment.data[0].prod + ",'" + HEndDate + "'");
                            CustomWriteLog("生成产量汇报单2:'exec h_p_Sc_AddTimeICMORepor " + HICMInterID + "," + jsonEquipment.data[0].prod + ",'" + HEndDate + "''", DateTime.Now.ToString("yyyy-MM-dd"));
                        }
                    }
                }
            }
        }
        private void EquipmentCollectionForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("确定要关闭吗?", "确认", MessageBoxButtons.YesNo) == DialogResult.No)
            {
                e.Cancel = true;
            }
        }
        private void txtHMaker_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtHMaker.Text))
            {
                this.txtHMaker.ForeColor = Color.LightGray;
                txtHMaker.Text = "请输入用户编码!";
            }
        }
        private void txtHMaker_Enter(object sender, EventArgs e)
        {
            if (txtHMaker.Text.Trim() == "请输入用户编码!")
            {
                txtHMaker.Text = "";
                this.txtHMaker.ForeColor = Color.Black;
            }
        }
        private void txtHMaker_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SelectHMaker(this.txtHMaker.Text);
            }
        }
        //查询职员信息
        public void SelectHMaker(string txtHMaker)
        {
            try
            {
                DataSet ds = oCN.RunProcReturn("select  HItemID,HName,HNumber from Gy_Employee where HNumber='" + txtHMaker + "' or HName ='" + txtHMaker + "'", "Gy_Employee");
                if (ds.Tables[0].Rows.Count > 0)
                {
                    string HName = ds.Tables[0].Rows[0]["HName"].ToString();
                    string HMakerID = ds.Tables[0].Rows[0]["HItemID"].ToString();
                    string HNumber = ds.Tables[0].Rows[0]["HNumber"].ToString();
                    this.txtHMaker.Text = HName;
                    this.txtHMakerNumber.Text = HNumber;
                    this.labHMakerID.Text = HMakerID;
                    this.txtHMaker.ReadOnly = true;
                }
                else
                {
                    MessageBox.Show(this, "编码:" + txtHMaker + ",查无数据,可能是输入编码有误!", "提示");
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(this, e.Message, "提示");
            }
        }
        private void EquipmentCollectionForm_Activated(object sender, EventArgs e)
        {
            //光标选中制单人
            this.txtHMaker.Focus();
        }
        #endregion
        private static readonly object lockObj = new object();
        //写日志