using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
using MisDataFunDll;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using Opc.Ua;
namespace MisDataSaveDate
{
    public class ND_Api
    {
        public static string LocalPath_Log = "D:\\MESlog";

        public static void miReleaseSfcWithActivity(string apiName, string opName, MiReleaseSfcWithActivityParams miReleaseSfcWithActivityParams, out string sfc, out string code, out string message) 
        {
            string apiNameCreateFile = "申请条码：miReleaseSfcWithActivity";
            string requestContent =$@"
                <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:mac=""http://machineintegration.ws.atlmes.com/"">
                   <soapenv:Header/>
                   <soapenv:Body>
                      <mac:miReleaseSfcWithActivity>
                         <!--Optional:-->
                         <ReleaseSfcWithActivityRequest>
                            <site>{miReleaseSfcWithActivityParams.site}</site>
                            <resource>{miReleaseSfcWithActivityParams.resource}</resource>
                            <operation>{miReleaseSfcWithActivityParams.operation}</operation>
                            <operationRevision>{miReleaseSfcWithActivityParams.operationRevision}</operationRevision>
                            <sfcQty>{miReleaseSfcWithActivityParams.sfcQty}</sfcQty>
                            <activity>{miReleaseSfcWithActivityParams.activity}</activity>
                            <user>{miReleaseSfcWithActivityParams.user}</user>
                            <modeProcessSFC>{miReleaseSfcWithActivityParams.modeProcessSFC}</modeProcessSFC>
                         </ReleaseSfcWithActivityRequest>
                      </mac:miReleaseSfcWithActivity>
                   </soapenv:Body>
                </soapenv:Envelope>
                "
            ;
            cmdApi(apiName, requestContent, opName, apiNameCreateFile, out code, out message, out sfc);
        }

        public static void miCheckInventoryAttributes(string apiName, string opName, MiCheckInventoryAttributes miCheckInventoryAttributes, out string code, out string message)
        {
            string apiNameCreateFile = "电芯校验：miCheckInventoryAttributes";

            string requiredQuantity = "";
            string inventoryArray = "";
            for (int i = 0; i < miCheckInventoryAttributes.inventoryArray.Count; i++)
            {
                inventoryArray += $@" <inventoryArray>{miCheckInventoryAttributes.inventoryArray[i]}</inventoryArray>";
            }

            string requestContent = $@"
               <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:mac=""http://machineintegration.ws.atlmes.com/"">
                   <soapenv:Header/>
                   <soapenv:Body>
                      <mac:miCheckInventoryAttributes>
                         <!--Optional:-->
                         <CheckInventoryAttributesRequest>
                            <site>{miCheckInventoryAttributes.site}</site>
                            <sfc>{miCheckInventoryAttributes.sfc}</sfc>
                            <operation>{miCheckInventoryAttributes.operation}</operation>
                            <operationRevision>{miCheckInventoryAttributes.operationRevision}</operationRevision>
                            <resource>{miCheckInventoryAttributes.resource}</resource>
                            <user>{miCheckInventoryAttributes.user}</user>
                            <activityId>{miCheckInventoryAttributes.activityId}</activityId>
                            <modeCheckInventory>{miCheckInventoryAttributes.modeCheckInventory}</modeCheckInventory>
                            <requiredQuantity>{requiredQuantity}</requiredQuantity>
                            {inventoryArray}
                         </CheckInventoryAttributesRequest>
                      </mac:miCheckInventoryAttributes>
                   </soapenv:Body>
                </soapenv:Envelope>
                "
            ;
            cmdApi(apiName, miCheckInventoryAttributes.sfc, requestContent, opName, apiNameCreateFile, out code, out message);
        }

        public static void cellCustomDCCheck(string apiName, string opName, CellCustomDCCheck cellCustomDCCheck, out string code, out string message)
        {
            string apiNameCreateFile = "电芯K值：cellCustomDCCheck";

            string inventoryListStr = "";
            for (int i = 0; i < cellCustomDCCheck.inventoryList.Count; i++)
            {
                List<InventoryData> inventoryDatalist = cellCustomDCCheck.inventoryList[i].inventoryDatalist;

                string inventoryDatalistStr = "";
                for (int j = 0; j < inventoryDatalist.Count; j++)
                {
                    inventoryDatalistStr += $@"
                        <inventoryDatalist>
                            <name>{inventoryDatalist[j].name}</name>
                            <value>{inventoryDatalist[j].value}</value>
                        </inventoryDatalist>
                    ";
                }
                inventoryListStr += $@" 
                    <inventoryList>
                        <inventoryId>{cellCustomDCCheck.inventoryList[i].inventoryId}</inventoryId>
                        <marking>{cellCustomDCCheck.inventoryList[i].marking}</marking>
                        {inventoryDatalistStr}
                    </inventoryList>
                ";
            }
            string requestContent = $@"
               <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:cus=""http://customcelldc.ws.atlmes.com/"">
                   <soapenv:Header/>
                   <soapenv:Body>
                      <cus:cellCustomDCCheck>
                         <Request>
                            <site>{cellCustomDCCheck.site}</site>
                            <dcSequence>{cellCustomDCCheck.dcSequence}</dcSequence>
                            <user>{cellCustomDCCheck.user}</user>
                            <Multispec>{cellCustomDCCheck.Multispec}</Multispec>
                            <operation>{cellCustomDCCheck.operation}</operation>
                            <resource>{cellCustomDCCheck.resource}</resource>
                            {inventoryListStr}
                         </Request>
                      </cus:cellCustomDCCheck>
                   </soapenv:Body>
                </soapenv:Envelope>";
            cmdApi(apiName, "", requestContent, opName, apiNameCreateFile, out code, out message);
        }

        public static void sfcStart(string apiName, string opName, SfcStart sfcStart, out string code, out string message)
        {
            string apiNameCreateFile = "产品进站：sfcStart";
            string requestContent = $@"
               <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:mac=""http://machine.ws.atlmes.com/"">
                   <soapenv:Header/>
                   <soapenv:Body>
                      <mac:sfcStart>
                         <StartSfcRequest>
                            <site>{sfcStart.site}</site>
                            <user>{sfcStart.user}</user>
                            <operation>{sfcStart.operation}</operation>
                            <operationRevision>{sfcStart.operationRevision}</operationRevision>
                            <resource>{sfcStart.resource}</resource>
                            <sfcArray>{sfcStart.sfcArray}</sfcArray>
                         </StartSfcRequest>
                      </mac:sfcStart>
                   </soapenv:Body>
                </soapenv:Envelope>
                ";
            cmdApi(apiName, sfcStart.sfcArray, requestContent, opName, apiNameCreateFile, out code, out message);
        }
        public static void miFindCustomAndSfcData(string apiName, string opName, MiFindCustomAndSfcData miFindCustomAndSfcData, out string code, out string message)
        {
            string apiNameCreateFile = "产品进站：miFindCustomAndSfcData";
            string requestContent = $@"
         <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:mac=""http://machineintegration.ws.atlmes.com/"">
           <soapenv:Header/>
           <soapenv:Body>
              <mac:miFindCustomAndSfcData>
                 <FindCustomAndSfcDataRequest>
                    <site>{miFindCustomAndSfcData.site}</site>
                    <operation>{miFindCustomAndSfcData.operation}</operation>
                    <operationRevision>{miFindCustomAndSfcData.operationRevision}</operationRevision>
                    <resource>{miFindCustomAndSfcData.resource}</resource>
                    <masterDataArray>{miFindCustomAndSfcData.masterDataArray}</masterDataArray>
                    <user>{miFindCustomAndSfcData.user}</user>
                    <activity>{miFindCustomAndSfcData.activity}</activity>
                    <sfc>{miFindCustomAndSfcData.sfc}</sfc>
                    <modeProcessSFC>{miFindCustomAndSfcData.modeProcessSfc}</modeProcessSFC>
                 </FindCustomAndSfcDataRequest>
              </mac:miFindCustomAndSfcData>
           </soapenv:Body>
        </soapenv:Envelope>

                ";
            cmdApi(apiName, miFindCustomAndSfcData.sfc, requestContent, opName, apiNameCreateFile, out code, out message);
        }
        public static void miCheckSFCStatusEx(string apiName, string opName, MiCheckSFCStatusEx miCheckSFCStatusEx, out string code, out string message)
        {
            string apiNameCreateFile = "产品进站：miCheckSFCStatusEx";
            string requestContent = $@"
         <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:mac=""http://machineintegration.ws.atlmes.com/"">
            <soapenv:Header/>
            <soapenv:Body>
                <mac:miCheckSFCStatusEx>
                    <ChangeSFCStatusExRequest>
                    <site>{miCheckSFCStatusEx.site}</site>
                    <operation>{miCheckSFCStatusEx.operation}</operation>
                    <operationRevision>{miCheckSFCStatusEx.operationRevision}</operationRevision>
                    <sfc>{miCheckSFCStatusEx.sfc}</sfc>
                    </ChangeSFCStatusExRequest>
                </mac:miCheckSFCStatusEx>
            </soapenv:Body>
        </soapenv:Envelope>


                ";
            cmdApi(apiName, miCheckSFCStatusEx.sfc, requestContent, opName, apiNameCreateFile, out code, out message);
        }
        public static void dataCollectForSfcEx(string apiName, string opName, DataCollectForSfcEx dataCollectForSfcEx, out string code, out string message)
        {
            string apiNameCreateFile = "产品出站：dataCollectForSfcEx";
            string parametricDataArrayStr = "";
            List<ParametricData> parametricDataArray = dataCollectForSfcEx.parametricDataArray;
            for (int i = 0; i < parametricDataArray.Count; i++)
            {
                parametricDataArrayStr += $@"
                    <parametricDataArray>
                        <name>{parametricDataArray[i].name}</name>
                        <value>{parametricDataArray[i].value}</value>
                        <dataType>{parametricDataArray[i].dataType.ToUpper()}</dataType>
                    </parametricDataArray>
                    ";
            }

            string requestContent = $@"
                <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:mac=""http://machine.ws.atlmes.com/"">
                   <soapenv:Header/>
                   <soapenv:Body>
                      <mac:dataCollectForSfcEx>
                         <!--Optional:-->
                         <SfcDcExRequest>
                            <site>{dataCollectForSfcEx.site}</site>
                            <sfc>{dataCollectForSfcEx.sfc}</sfc>
                            <dcGroup>{dataCollectForSfcEx.dcGroup}</dcGroup>
                            <dcGroupRevision>{dataCollectForSfcEx.dcGroupRevision}</dcGroupRevision>
                            <operation>{dataCollectForSfcEx.operation}</operation>
                            <operationRevision>{dataCollectForSfcEx.operationRevision}</operationRevision>
                            <resource>{dataCollectForSfcEx.resource}</resource>
                            <user>{dataCollectForSfcEx.user}</user>
                            <activityId>{dataCollectForSfcEx.activityId}</activityId>
                            <modeProcessSfc>{dataCollectForSfcEx.modeProcessSfc}</modeProcessSfc>
                            {parametricDataArrayStr}
                         </SfcDcExRequest>
                      </mac:dataCollectForSfcEx>
                   </soapenv:Body>
                </soapenv:Envelope>
                ";
            cmdApi(apiName, dataCollectForSfcEx.sfc, requestContent, opName, apiNameCreateFile, out code, out message);
        }
        public static void dataCollectForMoudleTest(string apiName, string opName, DataCollectForMoudleTest dataCollectForMoudleTest, out string code, out string message)
        {
            string apiNameCreateFile = "产品出站：dataCollectForMoudleTest";
            string parametricDataArrayStr = "";
            List<ParametricData> parametricDataArray = dataCollectForMoudleTest.parametricDataArray;
            for (int i = 0; i < parametricDataArray.Count; i++)
            {
                parametricDataArrayStr += $@"
                    <parametricDataArray>
                        <name>{parametricDataArray[i].name}</name>
                        <value>{parametricDataArray[i].value}</value>
                        <dataType>{parametricDataArray[i].dataType}</dataType>
                    </parametricDataArray>
                    ";
            }

            string requestContent = $@"
                <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:mac=""http://machine.ws.atlmes.com/"">
                   <soapenv:Header/>
                   <soapenv:Body>
                      <mac:dataCollectForModuleTest>
                         <DcForModuleTestRequest>
                            <site>{dataCollectForMoudleTest.site}</site>
                            <sfc>{dataCollectForMoudleTest.sfc}</sfc>
                            <dcGroup>{dataCollectForMoudleTest.dcGroup}</dcGroup>
                            <dcGroupRevision>{dataCollectForMoudleTest.dcGroupRevision}</dcGroupRevision>
                            <operation>{dataCollectForMoudleTest.operation}</operation>
                            <operationRevision>{dataCollectForMoudleTest.operationRevision}</operationRevision>
                            <resource>{dataCollectForMoudleTest.resource}</resource>
                            <user>{dataCollectForMoudleTest.user}</user>
                            <activityId>{dataCollectForMoudleTest.activityId}</activityId>
                            <modeProcessSfc>{dataCollectForMoudleTest.modeProcessSfc}</modeProcessSfc>
                            {parametricDataArrayStr}
                        </DcForModuleTestRequest>
                     </mac:dataCollectForModuleTest>
                   </soapenv:Body>
                </soapenv:Envelope>
                ";
            cmdApi(apiName, dataCollectForMoudleTest.sfc, requestContent, opName, apiNameCreateFile, out code, out message);
        }

        public static void sfcComplete(string apiName, string opName, SfcComplete sfcComplete, out string code, out string message)
        {
            string apiNameCreateFile = "产品出站：sfcComplete";
            string requestContent = $@"
                <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:mac=""http://machine.ws.atlmes.com/"">
                   <soapenv:Header/>
                   <soapenv:Body>
                      <mac:sfcComplete>
                         <CompleteSfcRequest>
                            <site>{sfcComplete.site}</site>
                            <user>{sfcComplete.user}</user>
                            <operation>{sfcComplete.operation}</operation>
                            <operationRevision>{sfcComplete.operationRevision}</operationRevision>
                            <resource>{sfcComplete.resource}</resource>
                            <sfcArray>{sfcComplete.sfcArray}</sfcArray>
                         </CompleteSfcRequest>
                      </mac:sfcComplete>
                   </soapenv:Body>
                </soapenv:Envelope>
                
            ";
            cmdApi(apiName, sfcComplete.sfcArray, requestContent, opName, apiNameCreateFile, out code, out message);

        }
        public static void miAssmebleAndCollectDataForSfc(string apiName, string opName, MiAssmebleAndCollectDataForSfc miAssmebleAndCollectDataForSfc, out string code, out string message)
        {
            string apiNameCreateFile = "物料装配：miAssmebleAndCollectDataForSfc";
            string inventoryArrayStr = "";
            List<InventoryItem> inventoryArray = miAssmebleAndCollectDataForSfc.inventoryArray;
            for (int i = 0; i < inventoryArray.Count; i++)
            {
                string assemblyDataFieldsStr = "";
                List<AssemblyDataField> assemblyDataFields = inventoryArray[i].assemblyDataFields;
                for (int j = 0; j < assemblyDataFields.Count; j++)
                {
                    assemblyDataFieldsStr += $@"
                        <assemblyDataFields>
                            <attribute>{assemblyDataFields[j].attribute}</attribute>
                            <value>{assemblyDataFields[j].value}</value>
                        </assemblyDataFields>
                    ";
                }
                inventoryArrayStr += $@"
                    <inventoryArray>
                    <inventory>{inventoryArray[i].inventory}</inventory>
                    <qty>{inventoryArray[i].qty}</qty>
                    {assemblyDataFieldsStr}
                    </inventoryArray>
                ";
            }

            string requestContent = $@"
                <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:mac=""http://machineintegration.ws.atlmes.com/"" xmlns:prod=""http://www.sap.com/me/production"">
                   <soapenv:Header/>
                   <soapenv:Body>
                      <mac:miAssmebleAndCollectDataForSfc>
                         <AssembleAndCollectDataForSfcRequest>
                            <site>{miAssmebleAndCollectDataForSfc.site}</site>
                            <sfc>{miAssmebleAndCollectDataForSfc.sfc}</sfc>
                            <operation>{miAssmebleAndCollectDataForSfc.operation}</operation>
                            <operationRevision>{miAssmebleAndCollectDataForSfc.operationRevision}</operationRevision>
                            <resource>{miAssmebleAndCollectDataForSfc.resource}</resource>
                            <user>{miAssmebleAndCollectDataForSfc.user}</user>
                            <activityId>{miAssmebleAndCollectDataForSfc.activityId}</activityId>
                            <modeProcessSFC>{miAssmebleAndCollectDataForSfc.modeProcessSFC}</modeProcessSFC>
                            <partialAssembly>{miAssmebleAndCollectDataForSfc.partialAssembly}</partialAssembly>
                            {inventoryArrayStr}
                         </AssembleAndCollectDataForSfcRequest>
                      </mac:miAssmebleAndCollectDataForSfc>
                   </soapenv:Body>
                </soapenv:Envelope>
                ";
            cmdApi(apiName, miAssmebleAndCollectDataForSfc.sfc, requestContent, opName, apiNameCreateFile, out code, out message);
        }
        
        public static void getAllLabelContents(string apiName, string opName, GetAllLabelContents getAllLabelContents, out string responseContent,out string code, out string message)
        {
            string apiNameCreateFile = "获取打印配置：getAllLabelContents";

            string requestContent = $@"
                <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:mig=""http://miGetAllLabelContentsBySfc.ws.atlmes.com/"">
                   <soapenv:Header/>
                   <soapenv:Body>
                      <mig:getAllLabelContents>
                         <GetAllLabelContentsBySfcRequest>
                            <site>{getAllLabelContents.site}</site>
                            <sfcList>{getAllLabelContents.sfcList}</sfcList>
                            <item>{getAllLabelContents.item}</item>
                            <languageCode>{getAllLabelContents.languageCode}</languageCode>
                            <Y>{getAllLabelContents.Y}</Y>
                            <activity>{getAllLabelContents.activity}</activity>
                         </GetAllLabelContentsBySfcRequest>
                      </mig:getAllLabelContents>
                   </soapenv:Body>
                </soapenv:Envelope>
                ";
            cmdApi(apiName, getAllLabelContents.sfcList, requestContent, opName, apiNameCreateFile, out responseContent, out code, out message);

        }
        
        public static void dataCollectForResourceInspect(string apiName, string opName, DataCollectForResourceInspect dataCollectForResourceInspect, out string code, out string message)
        {
            string apiNameCreateFile = "首件：dataCollectForResourceInspect";
            List<ParametricData> parametricDataArray = dataCollectForResourceInspect.parametricDataArray;
            string parametricDataArrayStr = "";
            for (int i = 0; i < parametricDataArray.Count; i++)
            {
                parametricDataArrayStr += $@"

                 <parametricDataArray>
                    <name>{parametricDataArray[i].name}</name>
                    <value>{parametricDataArray[i].value}</value>
                    <dataType>{parametricDataArray[i].dataType}</dataType>
                </parametricDataArray>

                ";
            }

            string requestContent = $@"
                 <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:dat=""http://datacollectforresourceinspect.ws.atlmes.com/"">
                   <soapenv:Header/>
                   <soapenv:Body>
                      <dat:dataCollectForResourceInspectTask>
                         <DataCollectForResourceInspectTaskRequest>
                            <site>{dataCollectForResourceInspect.site}</site>
                            <user>{dataCollectForResourceInspect.user}</user>
                            <dcMode>{dataCollectForResourceInspect.dcMode}</dcMode>
                            <executeMode>{dataCollectForResourceInspect.executeMode}</executeMode>
                            <resource>{dataCollectForResourceInspect.resource}</resource>
                            <operation>{dataCollectForResourceInspect.operation}</operation>
                            <operationRevision>{dataCollectForResourceInspect.operationRevision}</operationRevision>
                            <dcGroup>{dataCollectForResourceInspect.dcGroup}</dcGroup>
                            <dcGroupRevision>{dataCollectForResourceInspect.dcGroupRevision}</dcGroupRevision>
                            <dcSequence>{dataCollectForResourceInspect.dcSequence}</dcSequence>
                                {parametricDataArrayStr}
                         </DataCollectForResourceInspectTaskRequest>
                      </dat:dataCollectForResourceInspectTask>
                   </soapenv:Body>
                </soapenv:Envelope>

                ";
            cmdApi(apiName, "", requestContent, opName, apiNameCreateFile, out code, out message);
        }

        // 申请条码 返回sfc
        public static void cmdApi(string apiName, string requestContent, string opName, string apiNameCreateFile, out string code, out string message, out string sfc)
        {
        
            sfc = "";
            code = "9999999";
            message = "未知错误";

            string requestTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            string responseTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

            MisDataFun.GetApiAuth(apiName, out string Username, out string Password, out int timeout, out string url, out code, out message);
            if (code != "0") goto step100;

            // 创建 WebRequest
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "text/xml";
            request.Timeout = timeout;
            // 设置 Basic 认证头
            string authToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Username}:{Password}"));
            request.Headers.Add("Authorization", "Basic " + authToken);

            try
            {
                // 写入请求体
                byte[] requestBytes = Encoding.UTF8.GetBytes(requestContent);
                request.ContentLength = requestBytes.Length;
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(requestBytes, 0, requestBytes.Length);
                }

                // 发送请求并获取响应

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    string responseBody = reader.ReadToEnd();
                    responseTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                    XDocument doc = XDocument.Parse(responseBody);
                    foreach (var element in doc.Descendants())
                    {
                        if (element.Name.LocalName == "code")
                        {
                            code = element.Value;
                        }
                        if (element.Name.LocalName == "message")
                        {
                            message = element.Value;
                        }
                        if (element.Name.LocalName == "sfc")
                        {
                            //sfc.Add(element.Value);
                            sfc = element.Value;
                        }
                    }

                }
            }
            catch (WebException err)
            {
                responseTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                if (err.Response != null)
                {
                    using (var errorResponse = (HttpWebResponse)err.Response)
                    using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                    {
                        message = reader.ReadToEnd();
                        code = errorResponse.StatusCode.ToString();
                    }
                }
                else
                {
                    message = err.Message;
                }
            }

            step100:
            ND_Api.RecordApiLog(apiName,apiNameCreateFile, opName, sfc, requestContent, requestTime, code, message, responseTime);
        }
        public static void cmdApi(string apiName, string sfc, string requestContent, string opName, string apiNameCreateFile, out string code, out string message)
        {
            code = "9999999";
            message = "未知错误";

            string requestTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            string responseTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

            MisDataFun.GetApiAuth(apiName, out string Username, out string Password, out int timeout, out string url, out code, out message);
            if (code != "0") goto step100;

            // 创建 WebRequest
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "text/xml";
            request.Timeout = timeout;

            // 设置 Basic 认证头
            string authToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Username}:{Password}"));
            request.Headers.Add("Authorization", "Basic " + authToken);

            try
            {
                // 写入请求体
                byte[] requestBytes = Encoding.UTF8.GetBytes(requestContent);
                request.ContentLength = requestBytes.Length;
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(requestBytes, 0, requestBytes.Length);
                }

                // 发送请求并获取响应

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    string responseBody = reader.ReadToEnd();
                    responseTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                    XDocument doc = XDocument.Parse(responseBody);
                    foreach (var element in doc.Descendants())
                    {
                        if (element.Name.LocalName == "code")
                        {
                            code = element.Value;
                        }
                        if (element.Name.LocalName == "message")
                        {
                            message = element.Value;
                        }
                    }
                    //code = "0";
                    //message = "";
                }
            }
            catch (WebException err)
            {
                responseTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                if (err.Response != null)
                {
                    using (var errorResponse = (HttpWebResponse)err.Response)
                    using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                    {
                        code = errorResponse.StatusCode.ToString();
                        message = reader.ReadToEnd();
                    }
                }
                else
                {
                    message = err.Message;
                }
            }

            step100:
            ND_Api.RecordApiLog(apiName,apiNameCreateFile, opName, sfc, requestContent, requestTime, code, message, responseTime);
        }

        public static void miCheckBOMInventory(string apiName, string opName, MiCheckBOMInventory miCheckBOMInventory, out string code, out string message)
        {
            string apiNameCreateFile = "批次校验：miCheckBOMInventory";
            string requestContent = $@"
                 <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:mac=""http://machineintegration.ws.atlmes.com/"">
                   <soapenv:Header/>
                   <soapenv:Body>
                      <mac:miCheckBOMInventory>
                         <CheckBOMInventoryRequest>
                            <site>{miCheckBOMInventory.site}</site>
                            <operation>{miCheckBOMInventory.operation}</operation>
                            <operationRevision>{miCheckBOMInventory.operationRevision}</operationRevision>
                            <resource>{miCheckBOMInventory.resource}</resource>
                            <user>{miCheckBOMInventory.user}</user>
                            <activity>{miCheckBOMInventory.activity}</activity>
                            <sfc>{miCheckBOMInventory.sfc}</sfc>
                            <modeCheckOperation>{miCheckBOMInventory.modeCheckOperation}</modeCheckOperation>
                            <inventoryDataArray>
                               <inventory>{miCheckBOMInventory.inventory}</inventory>
                               <component>{miCheckBOMInventory.component}</component>
                            </inventoryDataArray>
                         </CheckBOMInventoryRequest>
                      </mac:miCheckBOMInventory>
                   </soapenv:Body>
                </soapenv:Envelope>
                ";
            cmdApi(apiName, miCheckBOMInventory.sfc, requestContent, opName, apiNameCreateFile, out code, out message);
        }

        public static void getSfcStatusAndOperation(string apiName, string opName, GetSfcStatusAndOperationParams getSfcStatusAndOperationParams, out string responseContent, out string code, out string message)
        {
            string apiNameCreateFile = "产品状态查询：getSfcStatusAndOperation";
            string requestContent = $@"
            <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:get=""http://GetSfcStatusAndOperation.ws.atlmes.com/"">
               <soapenv:Header/>
               <soapenv:Body>
                  <get:getSfcStatusAndOperation>
                     <!--Optional:-->
                     <getSfcStatusAndOperation>
                        <site>{getSfcStatusAndOperationParams.site}</site>
                        <barcode>{getSfcStatusAndOperationParams.barcode}</barcode>
                     </getSfcStatusAndOperation>
                  </get:getSfcStatusAndOperation>
               </soapenv:Body>
            </soapenv:Envelope>
            ";
            cmdApi(apiName, getSfcStatusAndOperationParams.barcode, requestContent, opName, apiNameCreateFile, out responseContent, out code, out message);
        }

        public static void cmdApi(string apiName, string sfc, string requestContent, string opName, string apiNameCreateFile, out string responseContent, out string code, out string message)
        {
            code = "9999999";
            message = "未知错误";
            responseContent = "";

            string requestTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            string responseTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");

            MisDataFun.GetApiAuth(apiName, out string Username, out string Password, out int timeout, out string url, out code, out message);
            if (code != "0") goto step100;

            // 创建 WebRequest
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = "text/xml";
            request.Timeout = timeout;

            // 设置 Basic 认证头
            string authToken = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Username}:{Password}"));
            request.Headers.Add("Authorization", "Basic " + authToken);

            try
            {
                // 写入请求体
                byte[] requestBytes = Encoding.UTF8.GetBytes(requestContent);
                request.ContentLength = requestBytes.Length;
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(requestBytes, 0, requestBytes.Length);
                }

                // 发送请求并获取响应

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    string responseBody = reader.ReadToEnd();
                    responseTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                    XDocument doc = XDocument.Parse(responseBody);
                    foreach (var element in doc.Descendants())
                    {
                        if (element.Name.LocalName == "code")
                        {
                            code = element.Value;
                        }
                        if (element.Name.LocalName == "message")
                        {
                            message = element.Value;
                        }
                    }
                    responseContent = responseBody;
                }
            }
            catch (WebException err)
            {
                responseTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                if (err.Response != null)
                {
                    using (var errorResponse = (HttpWebResponse)err.Response)
                    using (var reader = new StreamReader(errorResponse.GetResponseStream()))
                    {
                        code = errorResponse.StatusCode.ToString();
                        message = reader.ReadToEnd();
                    }
                }
                else
                {
                    message = err.Message;
                }
            }

        step100:
            ND_Api.RecordApiLog(apiName,apiNameCreateFile, opName, sfc, requestContent, requestTime, code, message, responseTime);
        }

        public static void RecordApiLog(string apiName, string apiNameCreateFile, string opName, string sfc, string requestContent, string requestTime, string responseCode, string responseMessage, string responseTime)
        {
            var now = DateTime.Now;
            string path1 = Path.Combine(LocalPath_Log, apiNameCreateFile);
            string fileName = $"{opName}_log_{now:yyyy-MM-dd}.txt";
            string fullPath = Path.Combine(path1, fileName);

            // 确保目录存在
            Directory.CreateDirectory(path1);

            // 计算耗时（假设时间格式为 yyyy/MM/dd HH:mm:ss.fff）
            TimeSpan duration = DateTime.Parse(responseTime) - DateTime.Parse(requestTime);
            string durationStr = $"耗时：{duration.TotalMilliseconds}ms";
            // 构建日志内容
            StringBuilder logContent = new StringBuilder();

            // 添加分隔线（如果不是新文件）
            if (File.Exists(fullPath))
            {
                logContent.AppendLine();
            }

            logContent.AppendLine($"{requestTime} 开始调用，sfc条码：{sfc}");
            logContent.AppendLine($"{requestTime} 开始调用，请求参数：{requestContent}");
            logContent.AppendLine($"{responseTime} 调用完成");
            logContent.AppendLine($"{responseTime} {durationStr}");
            logContent.AppendLine($"{responseTime} 返回代码:{responseCode}；返回信息:{responseMessage}");
            logContent.AppendLine(new string('-', 50)); // 分隔线
            // 写入文件（追加模式）
            File.AppendAllText(fullPath, logContent.ToString(), Encoding.UTF8);

            MisDataFun.RecordApiContent(apiName, opName, sfc, requestTime, requestContent, responseTime, duration.TotalMilliseconds.ToString(), responseCode, responseMessage);
        }


    }

}
