using DeviceRepair.Api.Common;
using DeviceRepair.Api.CustomAttribute;
using DeviceRepair.DataAccess;
using DeviceRepair.Models;
using DeviceRepair.Models.Common;
using DeviceRepair.Utils;
using System;
using System.Data;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Xml;

namespace DeviceRepair.Api.Controllers
{
    /// <summary>
    /// 设备维修
    /// </summary>
    [RoutePrefix("Api/Maintenance")]
    public class MaintenanceController : CFController
    {
        /// <summary>
        /// 查询设备维修单
        /// </summary>
        /// <param name="Code"></param>
        /// <returns></returns>
        [HttpPost, HttpAuthorize, Route("GetDatas")]
        public APIResponseData GetDatas(DeviceWarrantyRequestFormFilter FilterInfo)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "操作失败！" };
            try
            {
                return MaintenanceAccess.Instance.GetDatas(FilterInfo);
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 设备维修
        /// </summary>
        /// <param name="Entity"></param>
        /// <returns></returns>
        [HttpPost, HttpAuthorize, Route("DeviceMaintion")]
        public APIResponseData DeviceMaintion(DeviceWarrantyRequestMaintaionView Entity)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "操作失败！" };
            try
            {
                base.GetParams();
                return MaintenanceAccess.Instance.DeviceMaintion(Entity.TodbModel(), Entity.AccessoriesItems, OperationInfo);
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 停机单申请
        /// </summary>
        /// <param name="Form"></param>
        /// <returns></returns>
        [HttpPost, HttpAuthorize, Route("DeviceDownFormAdd")]
        public APIResponseData DeviceDownFormAdd(DeviceWarrantyRequestForm Form)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "操作失败！" };
            try
            {
                base.GetParams();
                return MaintenanceAccess.Instance.DeviceDownFormAdd(Form, OperationInfo);
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 停机单 - 评估
        /// </summary>
        /// <param name="AuotID"></param>
        /// <param name="AssessmentCode"></param>
        /// <returns></returns>
        [HttpPost, HttpAuthorize, Route("DownFormAssessment")]
        public APIResponseData DownFormAssessment(DeviceWarrantyEvaluatorInfo Evaluator)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "操作失败！" };
            try
            {
                base.GetParams();
                return MaintenanceAccess.Instance.DownFormAssessment(Evaluator, OperationInfo);
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 修改停机单 停机状态
        /// </summary>
        /// <param name="AutoID"></param>
        /// <param name="Status"></param>
        /// <returns></returns>
        [HttpPost, HttpAuthorize, Route("ChangeDownStatus")]
        public APIResponseData ChangeDownStatus(int AutoID, int Status)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "操作失败！" };
            try
            {
                base.GetParams();
                return MaintenanceAccess.Instance.ChangeDownStatus(AutoID, Status > 0, OperationInfo);
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 双重确认
        /// </summary>
        /// <param name="AutoID"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        [HttpPost, HttpAuthorize, Route("ValidateMaintenance")]
        public APIResponseData ValidateMaintenance(int AutoID, int t)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "操作失败！" };
            try
            {
                base.GetParams();
                return MaintenanceAccess.Instance.ValidateMaintenance(AutoID, t, OperationInfo);
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 生产部门设备恢复确认
        /// </summary>
        /// <param name="AutoID"></param>
        /// <returns></returns>
        [HttpPost, HttpAuthorize, Route("DeviceResumptionComfirm")]
        public APIResponseData DeviceResumptionComfirm(int AutoID)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "操作失败！" };
            try
            {
                base.GetParams();
                return MaintenanceAccess.Instance.DeviceResumptionComfirm(AutoID, OperationInfo);
            }
            catch (Exception ex)
            {
                apiResponseData.Code = -1;
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 获取生产批号信息
        /// </summary>
        /// <param name="Batch"></param>
        /// <returns></returns>
        [HttpPost, HttpAuthorize, Route("GetBatchInfoToStaff")]
        public APIResponseData GetBatchInfoToStaff(SfcParams Params)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "获取失败！" };
            try
            {
                string SFCWebServiceUrl = Utils.Config.Configurations.Properties.SFCWebServiceUrl;
                bool isSuccess = false;
                byte[] password = Encoding.Unicode.GetBytes(Params.LoginCode);
                Array.Reverse(password);
                string pass64 = Convert.ToBase64String(password);
                if (pass64.Length < 10)
                    pass64 += "YeT+=fue";

                StringBuilder builder = new StringBuilder();
                builder.AppendLine($"<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                builder.AppendLine($"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
                builder.AppendLine($"  <soap:Header>");
                builder.AppendLine($"   <SvcAuthentication xmlns=\"http://www.TechScan.cn/\">");
                builder.AppendLine($"       <Password>{pass64}</Password>");
                builder.AppendLine($"       <Username>{Params.LoginCode}</Username>");
                builder.AppendLine($"   </SvcAuthentication>");
                builder.AppendLine($"   </soap:Header>");
                builder.AppendLine($"   <soap:Body>");
                builder.AppendLine($"      <GetBatchInfoToStaff xmlns=\"http://www.TechScan.cn/\">");
                builder.AppendLine($"         <inParams>{Params.inParams}</inParams>");
                builder.AppendLine($"      </GetBatchInfoToStaff>");
                builder.AppendLine($"   </soap:Body>");
                builder.AppendLine($"</soap:Envelope>");

                using (var client = new HttpClient())
                {
                    var content = new StringContent(builder.ToString(), Encoding.UTF8, "text/xml");
                    var request = new HttpRequestMessage(HttpMethod.Post, $"{SFCWebServiceUrl}/SfcService.asmx");
                    request.Content = content;

                    var response = client.SendAsync(request).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        string stringRtn = response.Content.ReadAsStringAsync().Result;

                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(stringRtn);
                        XmlNode Node = doc.DocumentElement["soap:Body"]["GetBatchInfoToStaffResponse"]["GetBatchInfoToStaffResult"]["Code"].LastChild;

                        if (Node.Value == "0")
                        {
                            Node = doc.DocumentElement["soap:Body"]["GetBatchInfoToStaffResponse"]["btResults"].LastChild;
                            byte[] bytes = Convert.FromBase64String(Node.Value);
                            DataSet ds = bytes.ExactDataSet();
                            isSuccess = ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0;

                            if (isSuccess)
                                return new APIResponseData { Code = 1, Data = ds };
                        }
                        else
                        {
                            Node = doc.DocumentElement["soap:Body"]["GetBatchInfoToStaffResponse"]["GetBatchInfoToStaffResult"]["Msg"].LastChild;
                            return new APIResponseData { Code = -1, Message = Node.Value };
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }

        /// <summary>
        /// 获取PE QE 信息
        /// </summary>
        /// <param name="Batch"></param>
        /// <returns></returns>
        [HttpPost, HttpAuthorize, Route("ProductResourceAllocationsGet")]
        public APIResponseData ProductResourceAllocationsGet(SfcParams Params)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = "获取失败！" };
            try
            {
                string SFCWebServiceUrl = Utils.Config.Configurations.Properties.SFCWebServiceUrl;
                bool isSuccess = false;
                byte[] password = Encoding.Unicode.GetBytes(Params.LoginCode);
                Array.Reverse(password);
                string pass64 = Convert.ToBase64String(password);
                if (pass64.Length < 10)
                    pass64 += "YeT+=fue";

                StringBuilder builder = new StringBuilder();
                builder.AppendLine($"<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                builder.AppendLine($"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
                builder.AppendLine($"  <soap:Header>");
                builder.AppendLine($"   <SvcAuthentication xmlns=\"http://www.TechScan.cn/\">");
                builder.AppendLine($"       <Password>{pass64}</Password>");
                builder.AppendLine($"       <Username>{Params.LoginCode}</Username>");
                builder.AppendLine($"   </SvcAuthentication>");
                builder.AppendLine($"   </soap:Header>");
                builder.AppendLine($"   <soap:Body>");
                builder.AppendLine($"      <ProductResourceAllocationsGet xmlns=\"http://www.TechScan.cn/\">");
                builder.AppendLine($"         <inParams>{Params.inParams}</inParams>");
                builder.AppendLine($"      </ProductResourceAllocationsGet>");
                builder.AppendLine($"   </soap:Body>");
                builder.AppendLine($"</soap:Envelope>");

                using (var client = new HttpClient())
                {
                    var content = new StringContent(builder.ToString(), Encoding.UTF8, "text/xml");
                    var request = new HttpRequestMessage(HttpMethod.Post, $"{SFCWebServiceUrl}/SfcAddon.asmx");
                    request.Content = content;

                    var response = client.SendAsync(request).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        string stringRtn = response.Content.ReadAsStringAsync().Result;

                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(stringRtn);
                        XmlNode Node = doc.DocumentElement["soap:Body"]["ProductResourceAllocationsGetResponse"]["ProductResourceAllocationsGetResult"]["Code"].LastChild;

                        if (Node.Value == "0")
                        {
                            Node = doc.DocumentElement["soap:Body"]["ProductResourceAllocationsGetResponse"]["btResults"].LastChild;
                            byte[] bytes = Convert.FromBase64String(Node.Value);
                            DataSet ds = bytes.ExactDataSet();
                            isSuccess = ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0;

                            if (isSuccess)
                                return new APIResponseData { Code = 1, Data = ds };
                        }
                        else
                        {
                            Node = doc.DocumentElement["soap:Body"]["ProductResourceAllocationsGetResponse"]["ProductResourceAllocationsGetResult"]["Msg"].LastChild;
                            return new APIResponseData { Code = -1, Message = Node.Value };
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                apiResponseData.Message = ex.Message;
            }
            return apiResponseData;
        }
    }
}
