using DeviceRepair.DataAccess.Data;
using DeviceRepair.DataAccess.Device;
using DeviceRepair.Models;
using DeviceRepair.Models.DeviceMaintenance;
using DeviceRepair.Models.DeviceRepair.ExportView;
using DeviceRepair.Models.SFC;
using DeviceRepair.Utils;
using NLog;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace DeviceRepair.DataAccess.Maintenance
{
    public class MaintenanceDa : BaseDa
    {
        private static readonly Logger log = LogManager.GetCurrentClassLogger();

        public MaintenanceDa(IDictionary<string, string> apiParams) : base(apiParams)
        {
        }

        public DataSet GetDatas()
        {
            DataSet dsDatas = new DataSet("Datas");
            try
            {
                Models.DeviceMaintenance.DeviceWarrantyRequestFormFilter filter =
                    new Models.DeviceMaintenance.DeviceWarrantyRequestFormFilter();
                if (ApiParameters.ContainsKey("EquipmentID"))
                {
                    filter.EquipmentID = ApiParameters["EquipmentID"].Trim();
                }

                if (ApiParameters.ContainsKey("Status"))
                {
                    filter.Status = (Models.DeviceMaintenance.DeviceWarrantyRequestFormStatus)Enum.Parse(
                        typeof(Models.DeviceMaintenance.DeviceWarrantyRequestFormStatus), ApiParameters["Status"]);
                }

                if (ApiParameters.ContainsKey("StartTime"))
                {
                    filter.StartTime = Convert.ToDateTime(ApiParameters["StartTime"]);
                }

                if (ApiParameters.ContainsKey("EndTime"))
                {
                    filter.EndTime = Convert.ToDateTime(ApiParameters["EndTime"]);
                }

                if (ApiParameters.ContainsKey("DownStatus"))
                {
                    filter.DownStatus = (Models.DeviceMaintenance.DeviceRunningStatus)Enum.Parse(
                        typeof(Models.DeviceMaintenance.DeviceRunningStatus), ApiParameters["DownStatus"]);
                }

                var exp = Expressionable.Create<DeviceWarrantyRequestFormInfo>();
                exp.AndIF(!string.IsNullOrWhiteSpace(filter.EquipmentID),
                    x => x.EquipmentID.Contains(filter.EquipmentID));
                exp.AndIF(filter.StartTime.HasValue, x => x.CreatOn >= filter.StartTime.Value);
                exp.AndIF(filter.EndTime.HasValue, x => x.CreatOn <= filter.EndTime.Value);
                exp.AndIF(filter.Status == Models.DeviceMaintenance.DeviceWarrantyRequestFormStatus.AwaitingRepair,
                    x => SqlFunc.Subqueryable<Models.DeviceMaintenance.DeviceWarrantyRequestMaintaionInfo>()
                        .Where(s => s.FormID == x.AutoID).NotAny());
                exp.AndIF(filter.Status == Models.DeviceMaintenance.DeviceWarrantyRequestFormStatus.AwaitingApproval,
                    x => SqlFunc.Subqueryable<Models.DeviceMaintenance.DeviceWarrantyRequestMaintaionInfo>()
                             .Where(s => s.FormID == x.AutoID && s.SubmitBy > 0).Any() &&
                         !SqlFunc.HasNumber(x.RestorationConfirmationBy));
                exp.AndIF(filter.Status == Models.DeviceMaintenance.DeviceWarrantyRequestFormStatus.BeComplate,
                    x => SqlFunc.Subqueryable<Models.DeviceMaintenance.DeviceWarrantyRequestMaintaionInfo>()
                             .Where(s => s.FormID == x.AutoID && s.SubmitBy > 0 && s.ValidateBy > 0).Any() &&
                         SqlFunc.HasNumber(x.RestorationConfirmationBy));

                bool isDown = filter.DownStatus == Models.DeviceMaintenance.DeviceRunningStatus.Stop;
                exp.AndIF(filter.DownStatus != Models.DeviceMaintenance.DeviceRunningStatus.All,
                    x => x.IsDown == isDown);

                List<DeviceWarrantyRequestFormInfo> Datas = devMain.Queryable<DeviceWarrantyRequestFormInfo>()
                    .With(SqlWith.NoLock).Where(exp.ToExpression())
                    .Select(x => new DeviceWarrantyRequestFormInfo
                    {
                        AutoID = x.AutoID,
                        EquipmentPK = x.EquipmentPK,
                        EquipmentID = x.EquipmentID,
                        EquipmentName = x.EquipmentName,
                        Location = x.Location,
                        LocationName = x.LocationName,
                        InProduction = x.InProduction,
                        Batch = x.Batch,
                        FaultSymptoms = x.FaultSymptoms,
                        ReceivingDep = x.ReceivingDep,
                        IsDown = x.IsDown,
                        FormVer = x.FormVer,
                        CreatOn = x.CreatOn,
                        CreatBy = x.CreatBy,
                        ModifyOn = x.ModifyOn,
                        ModifyBy = x.ModifyBy,
                        RestorationConfirmationBy = x.RestorationConfirmationBy,
                        RestorationConfirmationOn = x.RestorationConfirmationOn,
                    }).ToList();

                if (Datas == null || Datas.Count == 0)
                {
                    return dsDatas;
                }

                DataTable table = Datas.ToDataTable();
                table.TableName = "Form";
                dsDatas.Tables.Add(table);

                int[] FormIds = Datas.Select(x => x.AutoID).ToArray();
                List<Models.DeviceMaintenance.DeviceWarrantyRequestMaintaionInfo> Maintaion = devMain
                    .Queryable<Models.DeviceMaintenance.DeviceWarrantyRequestMaintaionInfo>()
                    .With(SqlWith.NoLock).Where(x => SqlFunc.ContainsArray(FormIds, x.FormID))?.ToList();

                DataTable table2 = Maintaion.ToDataTable();
                table2.TableName = "Maintaion";
                dsDatas.Tables.Add(table2);

                List<Models.DeviceMaintenance.DeviceWarrantyEvaluatorInfo> Evals = devMain
                    .Queryable<Models.DeviceMaintenance.DeviceWarrantyEvaluatorInfo>()
                    .With(SqlWith.NoLock).Where(x => SqlFunc.ContainsArray(FormIds, x.FormID))?.ToList();
                DataTable table3 = Evals.ToDataTable();
                table3.TableName = "Eval";
                dsDatas.Tables.Add(table3);

                return dsDatas;
            }
            catch (SqlException sqlEx)
            {
                throw sqlEx;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 判断当前账户是否PE QE
        /// </summary>
        /// <returns></returns>
        public int CurrentIsManager()
        {
            DataSet dsDatas = new DataSet("Datas");
            try
            {
                string UserCode = string.Empty;
                if (ApiParameters.ContainsKey("UserCode"))
                {
                    UserCode = ApiParameters["UserCode"].Trim();
                }

                List<PostsInfo> Datas = sfcAddOn.Queryable<UserPostsInfo, PostsInfo>((t1, t2) => new object[]
                    {
                        JoinType.Left, t1.Post == t2.Guid
                    }).Where((t1, t2) =>
                        t1.UserCode.Equals(UserCode, StringComparison.CurrentCultureIgnoreCase) && t2.Status == "A")
                    .Select((t1, t2) => t2).ToList();

                int PostType = -1;

                if (Datas.Any(x => x.PostName == "OEM-QE"))
                    PostType = 0;

                if (Datas.Any(x => x.PostName == "OEM-PE"))
                    PostType = 1;

                return PostType;
            }
            catch (SqlException sqlEx)
            {
                throw sqlEx;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取维修单的配件
        /// </summary>
        /// <returns></returns>
        public DataSet GetFormAccessories()
        {
            DataSet dsDatas = new DataSet("Datas");
            try
            {
                int MaintaionID = 0;
                if (!ApiParameters.ContainsKey("MaintaionID") ||
                    !int.TryParse(ApiParameters["MaintaionID"], out MaintaionID))
                {
                    throw new ArgumentException("传入的维修单格式不正确！");
                }

                List<Models.DeviceMaintenance.DeviceWarrantyRequestAccessoriesInfo> Datas = devMain
                    .Queryable<Models.DeviceMaintenance.DeviceWarrantyRequestAccessoriesInfo>()
                    .Where(x => x.MaintaionID == MaintaionID).ToList();

                DataTable table = Datas.ToDataTable();
                dsDatas.Tables.Add(table);
                return dsDatas;
            }
            catch (SqlException sqlEx)
            {
                throw sqlEx;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 设备维修单设备状态修改
        /// </summary>
        /// <returns></returns>
        public APIResponseData ChangeFormStatus()
        {
            try
            {
                DateTime CurrentDate = DateTime.Now;
                int FormID = 0;
                if (!ApiParameters.ContainsKey("FormID") || !int.TryParse(ApiParameters["FormID"].Trim(), out FormID))
                {
                    throw new ArgumentException("传入的设备维修单编号参数不正确,对象类型不正确！");
                }

                if (FormID == 0)
                    throw new ArgumentException("传入的设备维修单编号参数不正确,对象不能为空！");

                if (!ApiParameters.ContainsKey("OPERATORAUTOID"))
                    throw new ArgumentException("传入的操作员对象参数不正确,操作员不能为空！");

                int Operation = 0;
                if (!int.TryParse(ApiParameters["OPERATORAUTOID"], out Operation))
                    throw new ArgumentException("传入的操作员对象参数不正确！");

                bool Status = false;
                if (!ApiParameters.ContainsKey("FormStatus") ||
                    !bool.TryParse(ApiParameters["FormStatus"].Trim(), out Status))
                {
                    throw new ArgumentException("传入的设备维修单设备停机状态,对象类型不正确！");
                }

                devMain.BeginTran();
                if (devMain.Queryable<Models.DeviceMaintenance.DeviceWarrantyRequestMaintaionInfo>()
                    .Any(x => x.FormID == FormID && x.SubmitBy > 0))
                {
                    throw new Exception("数据已被其他人修改！");
                }

                DeviceWarrantyRequestForm Entity =
                    devMain.Queryable<DeviceWarrantyRequestForm>().First(x => x.AutoID == FormID);
                if (Entity == null)
                {
                    throw new Exception("待处理的停机单主键编号无效！");
                }

                Entity.IsDown = Status;
                if (devMain.Updateable(Entity).UpdateColumns(it => new { it.IsDown }).ExecuteCommand() > 0)
                {
                    devMain.CommitTran();
                    return new APIResponseData { Code = 1 };
                }
                else
                {
                    throw new Exception("设备维修单设备停机状态修改失败,请重试！");
                }
            }
            catch (SqlException sqlEx)
            {
                devMain.RollbackTran();
                throw sqlEx;
            }
            catch (Exception ex)
            {
                devMain.RollbackTran();
                log.Error(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 列表导出
        /// </summary>
        /// <returns></returns>
        public APIResponseData Get_Xlsx_Data(out DataSet dsDatas)
        {
            dsDatas = new DataSet("Datas");
            try
            {
                Models.DeviceMaintenance.DeviceWarrantyRequestFormFilter FilterInfo =
                    new Models.DeviceMaintenance.DeviceWarrantyRequestFormFilter();
                if (ApiParameters.ContainsKey("EquipmentID"))
                {
                    FilterInfo.EquipmentID = ApiParameters["EquipmentID"].Trim();
                }

                if (ApiParameters.ContainsKey("Status"))
                {
                    FilterInfo.Status = (Models.DeviceMaintenance.DeviceWarrantyRequestFormStatus)Enum.Parse(
                        typeof(Models.DeviceMaintenance.DeviceWarrantyRequestFormStatus), ApiParameters["Status"]);
                }

                if (ApiParameters.ContainsKey("StartTime"))
                {
                    FilterInfo.StartTime = Convert.ToDateTime(ApiParameters["StartTime"]);
                }

                if (ApiParameters.ContainsKey("EndTime"))
                {
                    FilterInfo.EndTime = Convert.ToDateTime(ApiParameters["EndTime"]);
                }

                if (ApiParameters.ContainsKey("DownStatus"))
                {
                    FilterInfo.DownStatus =
                        (Models.DeviceMaintenance.DeviceRunningStatus)Enum.Parse(
                            typeof(Models.DeviceMaintenance.DeviceRunningStatus), ApiParameters["DownStatus"]);
                }

                var exp = Expressionable.Create<DeviceWarrantyRequestForm>();
                if (FilterInfo != null)
                {
                    exp.AndIF(!string.IsNullOrWhiteSpace(FilterInfo.EquipmentID),
                        x => x.EquipmentID.Contains(FilterInfo.EquipmentID));
                    exp.AndIF(FilterInfo.StartTime.HasValue, x => x.CreatOn >= FilterInfo.StartTime.Value);
                    exp.AndIF(FilterInfo.EndTime.HasValue, x => x.CreatOn <= FilterInfo.EndTime.Value);
                    exp.AndIF(
                        FilterInfo.Status == Models.DeviceMaintenance.DeviceWarrantyRequestFormStatus.AwaitingRepair,
                        x => SqlFunc.Subqueryable<Models.DeviceMaintenance.DeviceWarrantyRequestMaintaionInfo>()
                            .Where(s => s.FormID == x.AutoID).NotAny());
                    exp.AndIF(
                        FilterInfo.Status == Models.DeviceMaintenance.DeviceWarrantyRequestFormStatus.AwaitingApproval,
                        x => SqlFunc.Subqueryable<Models.DeviceMaintenance.DeviceWarrantyRequestMaintaionInfo>()
                                 .Where(s => s.FormID == x.AutoID && s.SubmitBy > 0).Any() &&
                             !SqlFunc.HasNumber(x.RestorationConfirmationBy));
                    exp.AndIF(FilterInfo.Status == Models.DeviceMaintenance.DeviceWarrantyRequestFormStatus.BeComplate,
                        x => SqlFunc.Subqueryable<Models.DeviceMaintenance.DeviceWarrantyRequestMaintaionInfo>()
                                 .Where(s => s.FormID == x.AutoID && s.SubmitBy > 0 && s.ValidateBy > 0).Any() &&
                             SqlFunc.HasNumber(x.RestorationConfirmationBy));

                    bool isDown = FilterInfo.DownStatus == Models.DeviceMaintenance.DeviceRunningStatus.Stop;
                    exp.AndIF(FilterInfo.DownStatus != Models.DeviceMaintenance.DeviceRunningStatus.All,
                        x => x.IsDown == isDown);
                }

                List<DeviceWarrantyRequestForm> Datas = devMain.Queryable<DeviceWarrantyRequestForm>()
                    .With(SqlWith.NoLock).Where(exp.ToExpression()).ToList();
                Dictionary<int, FieldsInfo> Fields = devMain.Queryable<FieldsInfo>().With(SqlWith.NoLock).ToList()
                    .ToDictionary(x => x.AutoID, x => x);
                Dictionary<int, string> RootIds = devMain.Ado
                    .SqlQuery<DeviceRouteInfo>(@"select AutoID,RootName as Name from dbo.View_DeviceRoot")
                    .ToDictionary(x => x.AutoID, x => x.Name);

                DeviceDa ddCmd = new DeviceDa(ApiParameters);
                DataSet ds = ddCmd.Get_DEVICE_Datas();
                Dictionary<int, DeviceInformationInfo> devs = DTOHelper<DeviceInformationInfo>
                    .DataTableToList(ds.Tables[0])?.ToList()?.ToDictionary(x => x.AutoID, x => x);

                SFC.UserDa cmd = new SFC.UserDa(ApiParameters);
                ds = cmd.Get_User_Datas();
                Dictionary<int, TsSFCUserInfo> Users = DTOHelper<TsSFCUserInfo>.DataTableToList(ds.Tables[0])?.ToList()
                    ?.ToDictionary(x => x.Id, x => x);

                int i = 1;
                List<MaintainOrderView> views = new List<MaintainOrderView>();
                foreach (DeviceWarrantyRequestForm item in Datas)
                {
                    int Plant = RootIds[item.EquipmentPK] == "KH" ? 1303 : 9997;
                    MaintainOrderView view = new MaintainOrderView
                    {
                        AutoNumber = i,
                        Plant = Plant,
                        AutoID = item.AutoID,
                        EquipmentID = item.EquipmentID,
                        EquipmentName = item.EquipmentName,
                        FormCreatOnDate = item.CreatOn.Value.ToString("yyyy-M-dd"),
                        FormCreatOnTime = item.CreatOn.Value.ToString("HH:mm:ss"),
                        ReferenceOnDate = "",
                        ReferenceOnTime = "",
                        FaultSymptoms = item.FaultSymptoms,
                    };

                    if (item.RestorationConfirmationBy > 0)
                    {
                        view.ComplateDate = item.RestorationConfirmationOn.Value.ToString("yyyy-M-dd");
                        view.ComplateTime = item.RestorationConfirmationOn.Value.ToString("HH:mm:ss");
                        view.ComplateBy = item.RestorationConfirmationOnName;
                    }

                    if (item.MaintaionItems != null && item.MaintaionItems.SubmitBy > 0)
                    {
                        Models.DeviceWarrantyRequestMaintaionInfo repair = item.MaintaionItems;
                        view.RepairPersonnel = Users[repair.SubmitBy].UserName;
                        view.RepairStartDate = repair.MaintainStartTime.ToString("yyyy-M-dd");
                        view.RepairFinishDate = repair.MaintainEndTime.ToString("yyyy-M-dd");
                        view.MaintainCause = repair.MaintainCause;
                        view.MaintainContent = repair.MaintainContent;

                        if (repair.AccessoriesItems == null || repair.AccessoriesItems.Count == 0)
                        {
                            view.Accessories = "N/A";
                        }
                        else
                        {
                            view.Accessories = string.Join(",",
                                repair.AccessoriesItems.Select(x => x.FieldName).ToArray());
                        }

                        TimeSpan Downtime = repair.MaintainEndTime - item.CreatOn.Value;
                        view.Downtime = Convert.ToDecimal(Math.Round(Downtime.TotalHours, 2));

                        TimeSpan RepairDuration = repair.MaintainEndTime - repair.MaintainStartTime;
                        view.RepairDuration = Convert.ToDecimal(Math.Round(RepairDuration.TotalHours));

                        view.Maintenance = Fields[repair.Maintenance].FieldText;
                        view.SymptomlDistinction = Fields[repair.SymptomlDistinction].FieldText;
                        view.ValidateNo = repair.BeValidate ? repair.ValidateNo : "N/A";
                    }

                    views.Add(view);
                    i++;
                }

                DataTable table = views.ToDataTable();
                dsDatas.Tables.Add(table);
                return new APIResponseData { Code = 1 };
            }
            catch (SqlException sqlEx)
            {
                throw sqlEx;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 设备维修单是否已提交
        /// </summary>
        /// <param name="FormAutoId"></param>
        /// <returns></returns>
        public APIResponseData DataBeSubmit(out bool BeSubmit)
        {
            try
            {
                int FormID = 0;
                if (!ApiParameters.ContainsKey("FormID"))
                    throw new ArgumentException("查询出错：缺少传入参数设备维修单编号！");

                if (!int.TryParse(ApiParameters["FormID"].Trim(), out FormID))
                    throw new ArgumentException("传入的设备维修单编号参数不正确,对象类型不正确！");

                int Count = devMain.Queryable<Models.DeviceWarrantyRequestMaintaionInfo>().With(SqlWith.NoLock)
                    .Count(x => x.FormID == FormID && x.SubmitBy > 0);
                BeSubmit = Count > 0;

                return new APIResponseData { Code = 1 };
            }
            catch (SqlException sqlEx)
            {
                throw sqlEx;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 设备维修单 - 维修操作
        /// </summary>
        /// <param name="DataContent"></param>
        /// <returns></returns>
        public APIResponseData Insert(DataSet DataContent)
        {
            try
            {
                if (DataContent == null || DataContent.Tables.Count != 2)
                    throw new ArgumentException("传入的维修单数据不正确!");

                if (!DataContent.Tables.Contains("Maintaion") || !DataContent.Tables.Contains("Accessories"))
                    throw new ArgumentException("传入的维修单数据有缺失,操作失败!");

                if (!ApiParameters.ContainsKey("OPERATORAUTOID"))
                    throw new ArgumentException("传入的操作员对象参数不正确,操作员不能为空！");

                int Operation = 0;
                if (!int.TryParse(ApiParameters["OPERATORAUTOID"], out Operation))
                    throw new ArgumentException("传入的操作员对象参数不正确！");

                bool IsSubmit = false;
                if (ApiParameters.ContainsKey("IsSubmit"))
                {
                    if (!bool.TryParse(ApiParameters["IsSubmit"], out IsSubmit))
                        throw new ArgumentException("传入的维修单提交状态数据参数格式不正确,操作失败!");
                }

                /* 维修单表单数据 */
                Models.DeviceWarrantyRequestMaintaionInfo Entity = DTOHelper<Models.DeviceWarrantyRequestMaintaionInfo>
                    .DataTableToList(DataContent.Tables["Maintaion"])?.FirstOrDefault();

                /* 维修配件 */
                IList<Models.DeviceWarrantyRequestAccessoriesInfo> AccessoriesItems =
                    DTOHelper<Models.DeviceWarrantyRequestAccessoriesInfo>.DataTableToList(
                        DataContent.Tables["Accessories"]);

                if (Entity == null)
                    throw new ArgumentException("待插入的数据库对象不能为空！");

                DateTime CurrentTime = DateTime.Now;
                if (Entity.AutoID > 0)
                {
                    /// 修改
                    Entity.ModifyBy = Operation;
                    Entity.ModifyOn = CurrentTime;
                }
                else
                {
                    /// 新增
                    Entity.CreatOn = CurrentTime;
                    Entity.CreateBy = Operation;
                    Entity.Guid = Guid.NewGuid();
                }

                if (IsSubmit)
                {
                    Entity.SubmitBy = Operation;
                    Entity.SubmitOn = CurrentTime;
                }

                devMain.BeginTran();
                if (devMain.Queryable<Models.DeviceWarrantyRequestMaintaionInfo>().With(SqlWith.NoLock)
                    .Any(x => x.FormID == Entity.AutoID && x.SubmitBy > 0))
                    throw new Exception($"当前数据已被处理，请刷新后再试!");

                Models.DeviceWarrantyRequestMaintaionInfo
                    MaintaionInfo = devMain.Saveable(Entity).ExecuteReturnEntity();
                if (MaintaionInfo != null)
                {
                    bool IsSuccess = true;
                    if (AccessoriesItems != null && AccessoriesItems.Count > 0)
                    {
                        foreach (var item in AccessoriesItems)
                        {
                            item.Guid = Guid.NewGuid();
                            item.MaintaionID = MaintaionInfo.AutoID;
                            item.CreatBy = Operation;
                            item.CreatOn = CurrentTime;
                        }

                        IsSuccess = devMain.Saveable(AccessoriesItems.ToList()).ExecuteCommand() ==
                                    AccessoriesItems.Count;
                    }

                    if (IsSuccess)
                    {
                        devMain.CommitTran();
                        return new APIResponseData { Code = 1 };
                    }

                    return new APIResponseData { Code = -1, Message = "设备维修单保存失败！" };
                }
                else
                {
                    devMain.RollbackTran();
                    return new APIResponseData { Code = -1, Message = "设备维修单保存失败！" };
                }
            }
            catch (SqlException sqlEx)
            {
                devMain.RollbackTran();
                throw sqlEx;
            }
            catch (Exception ex)
            {
                devMain.RollbackTran();
                log.Error(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 设备恢复确认
        /// </summary>
        /// <returns></returns>
        public APIResponseData ValidateMaintenance()
        {
            try
            {
                DateTime CurrentDate = DateTime.Now;
                int FormID = 0;
                if (!ApiParameters.ContainsKey("FormID") || !int.TryParse(ApiParameters["FormID"].Trim(), out FormID))
                {
                    throw new ArgumentException("传入的设备维修单编号参数不正确,对象类型不正确！");
                }

                if (FormID == 0)
                    throw new ArgumentException("传入的设备维修单编号参数不正确,对象不能为空！");

                if (!ApiParameters.ContainsKey("OPERATORAUTOID"))
                    throw new ArgumentException("传入的操作员对象参数不正确,操作员不能为空！");

                int Operation = 0;
                if (!int.TryParse(ApiParameters["OPERATORAUTOID"], out Operation))
                    throw new ArgumentException("传入的操作员对象参数不正确！");

                int t = 0;
                if (!ApiParameters.ContainsKey("t") || !int.TryParse(ApiParameters["t"], out t))
                    throw new ArgumentException("传入的校验类型不正确！");

                devMain.BeginTran();
                Models.DeviceMaintenance.DeviceWarrantyRequestMaintaionInfo Entity = devMain
                    .Queryable<Models.DeviceMaintenance.DeviceWarrantyRequestMaintaionInfo>()
                    .First(x => x.FormID == FormID && x.SubmitBy > 0);
                if (Entity == null)
                    throw new Exception("传入的设备维修单编号参数不正确！");

                if (t == 1)
                {
                    if (Entity.ValidateBy > 0)
                        throw new Exception("当前设备维修单数据已被处理，请刷新后再试！");

                    Entity.ValidateBy = Operation;
                    Entity.ValidateOn = CurrentDate;
                }
                else if (t == 2)
                {
                    if (Entity.Validate2By > 0)
                        throw new Exception("当前设备维修单数据已被处理，请刷新后再试！");

                    Entity.Validate2By = Operation;
                    Entity.Validate2On = CurrentDate;
                }

                if (devMain.Updateable(Entity).ExecuteCommand() > 0)
                {
                    devMain.CommitTran();
                    return new APIResponseData { Code = 1 };
                }
                else
                {
                    throw new Exception("设备维修单设备恢复确认失败,请重试！");
                }
            }
            catch (SqlException sqlEx)
            {
                devMain.RollbackTran();
                throw sqlEx;
            }
            catch (Exception ex)
            {
                devMain.RollbackTran();
                log.Error(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 停机单新增
        /// </summary>
        /// <param name="DataContent"></param>
        /// <param name="ID"></param>
        /// <returns></returns>
        public APIResponseData ADD_DeviceDownForm_DATA(DataTable DataContent, out int ID)
        {
            ID = 0;
            try
            {
                DateTime CurrentTime = DateTime.Now;

                if (DataContent == null && DataContent.Rows.Count == 0)
                    throw new ArgumentException("传入的维修单数据不能为空!");

                if (!ApiParameters.ContainsKey("OPERATORAUTOID"))
                    throw new ArgumentException("传入的操作员对象参数不正确,操作员不能为空！");

                int Operation = 0;
                if (!int.TryParse(ApiParameters["OPERATORAUTOID"], out Operation))
                    throw new ArgumentException("传入的操作员对象参数不正确！");

                /* 维修单表单数据 */
                Models.DeviceWarrantyRequestForm Form = DTOHelper<Models.DeviceWarrantyRequestForm>
                    .DataTableToList(DataContent)?.FirstOrDefault();
                Form.GUID = Guid.NewGuid();
                Form.CreatBy = Operation;
                Form.CreatorName = ApiParameters["OPERATORNAME"];
                Form.CreatOn = CurrentTime;

                devMain.BeginTran();
                int AutoID = devMain.Saveable(Form).ExecuteReturnEntity()?.AutoID ?? 0;
                if (AutoID > 0)
                {
                    devMain.CommitTran();
                    ID = AutoID;
                    return new APIResponseData { Code = 1 };
                }
                else
                {
                    devMain.RollbackTran();
                    return new APIResponseData { Code = -1, Message = "操作失败！" };
                }
            }
            catch (SqlException sqlEx)
            {
                devMain.RollbackTran();
                throw sqlEx;
            }
            catch (Exception ex)
            {
                devMain.RollbackTran();
                log.Error(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 停机单 - 评估
        /// </summary>
        /// <param name="DataContent"></param>
        /// <returns></returns>
        public APIResponseData DownFormAssessment(DataTable DataContent)
        {
            try
            {
                DateTime CurrentTime = DateTime.Now;
                devMain.BeginTran();

                if (DataContent == null && DataContent.Rows.Count == 0)
                    throw new ArgumentException("传入的维修单数据不能为空!");

                if (!ApiParameters.ContainsKey("OPERATORAUTOID"))
                    throw new ArgumentException("传入的操作员对象参数不正确,操作员不能为空！");

                int Operation = 0;
                if (!int.TryParse(ApiParameters["OPERATORAUTOID"], out Operation))
                    throw new ArgumentException("传入的操作员对象参数不正确！");

                Models.DeviceWarrantyEvaluatorInfo Evaluator = DTOHelper<Models.DeviceWarrantyEvaluatorInfo>
                    .DataTableToList(DataContent)?.FirstOrDefault();

                devMain.BeginTran();
                Models.DeviceWarrantyRequestForm Entity = devMain.Queryable<Models.DeviceWarrantyRequestForm>()
                    .First(x => x.AutoID == Evaluator.FormID);
                if (Entity == null)
                {
                    throw new Exception("待处理的停机单主键编号无效！");
                }

                if (Evaluator.EvaluatorCode.ToUpper() != "QE" && Evaluator.EvaluatorCode.ToUpper() != "PE")
                {
                    throw new Exception($"程序出错，未知的评估编码：{Evaluator.EvaluatorCode.ToUpper()}！");
                }

                if (devMain.Queryable<Models.DeviceWarrantyEvaluatorInfo>().Any(x =>
                        x.FormID == Evaluator.FormID && x.EvaluatorCode == Evaluator.EvaluatorCode))
                    throw new Exception("当前停机单已被他人处理，请刷新后再试！");

                Evaluator.CreatorName = ApiParameters["OPERATORNAME"];
                Evaluator.CreateBy = Operation;
                Evaluator.CreatOn = CurrentTime;
                Evaluator.Guid = Guid.NewGuid();

                if (devMain.Insertable(Evaluator).ExecuteCommand() > 0)
                {
                    devMain.CommitTran();
                    return new APIResponseData { Code = 1 };
                }
                else
                {
                    return new APIResponseData { Code = -1, Message = "操作失败！" };
                }
            }
            catch (SqlException sqlEx)
            {
                devMain.RollbackTran();
                throw sqlEx;
            }
            catch (Exception ex)
            {
                devMain.RollbackTran();
                log.Error(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 生产部门 - 设备恢复确认
        /// </summary>
        /// <returns></returns>
        public APIResponseData DeviceResumptionComfirm()
        {
            try
            {
                int AutoID = 0;
                DateTime CurrentTime = DateTime.Now;
                if (!ApiParameters.ContainsKey("AutoID"))
                    throw new ArgumentException("查询出错：缺少传入参数设备维修单编号！");

                if (!int.TryParse(ApiParameters["AutoID"].Trim(), out AutoID))
                    throw new ArgumentException("传入的设备维修单编号参数不正确,对象类型不正确！");

                if (!ApiParameters.ContainsKey("OPERATORAUTOID"))
                    throw new ArgumentException("传入的操作员对象参数不正确,操作员不能为空！");

                int Operation = 0;
                if (!int.TryParse(ApiParameters["OPERATORAUTOID"], out Operation))
                    throw new ArgumentException("传入的操作员对象参数不正确！");

                Models.DeviceWarrantyRequestForm Entity = devMain.Queryable<Models.DeviceWarrantyRequestForm>()
                    .First(x => x.AutoID == AutoID);
                if (Entity == null)
                {
                    throw new Exception("待处理的停机单主键编号无效！");
                }

                if (Entity.MaintaionItems != null && Entity.MaintaionItems.SubmitBy > 0 &&
                    ((Entity.InProduction && Entity.EvaluatorItems?.Count == 2) || !Entity.InProduction) &&
                    ((Entity.MaintaionItems.BeValidate && Entity.MaintaionItems.Validate2By > 0 &&
                      Entity.MaintaionItems.ValidateBy > 0) || !Entity.MaintaionItems.BeValidate)
                    && Entity.RestorationConfirmationBy == 0
                   )
                {
                    Entity.RestorationConfirmationOn = CurrentTime;
                    Entity.RestorationConfirmationBy = Operation;
                    Entity.RestorationConfirmationOnName = ApiParameters["OPERATORNAME"];

                    if (devMain.Updateable(Entity).ExecuteCommand() > 0)
                    {
                        return new APIResponseData { Code = 1 };
                    }
                    else
                    {
                        return new APIResponseData { Code = -1, Message = "操作失败！" };
                    }
                }
                else
                {
                    throw new Exception("待处理的停机单状态不正确，或已被其他用户处理，请重试！");
                }
            }
            catch (SqlException sqlEx)
            {
                devMain.RollbackTran();
                throw sqlEx;
            }
            catch (Exception ex)
            {
                devMain.RollbackTran();
                log.Error(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取当前批次的QE PE邮箱
        /// </summary>
        /// <returns></returns>
        public DataSet CurrentBatchManagerEmail()
        {
            DataSet dsDatas = new DataSet("Datas");
            try
            {
                string Batch = string.Empty;
                if (!ApiParameters.ContainsKey("Batch"))
                {
                    throw new ArgumentException("参数批次号不能为空！");
                }

                Batch = ApiParameters["Batch"].Trim();

                List<string> Emails = new List<string>();
                InspBatchInfo BatchInfo = sfcData.Queryable<InspBatchInfo>().With(SqlWith.NoLock)
                    .First(x => x.Batch.ToUpper().Equals(Batch.ToUpper()));
                if (BatchInfo != null)
                {
                    List<ResourceAllocationsInfo> allocationsInfos = sfcAddOn.Queryable<ResourceAllocationsInfo>()
                        .With(SqlWith.NoLock).Where(x => x.Product.Trim().Equals(BatchInfo.Product.ToUpper()) &&
                                                         x.Technology.Trim().ToUpper() ==
                                                         BatchInfo.Technology.Trim().ToUpper()).ToList();

                    if (allocationsInfos != null)
                    {
                        Guid[] guids = allocationsInfos.Select(x => x.Staff).ToArray();
                        List<StaffsInfo> staffs = sfcAddOn.Queryable<StaffsInfo>().Where(x =>
                            SqlFunc.ContainsArray(guids, x.Guid) && (x.Post == "0" || x.Post == "1")).ToList();
                        if (staffs != null && staffs.Count > 0)
                        {
                            Emails.AddRange(staffs.Select(x => x.EMail).ToArray());
                        }
                    }
                }

                DataTable table = new DataTable();
                table.Columns.Add("email");

                foreach (string item in Emails)
                {
                    DataRow dr = table.NewRow();
                    dr["email"] = item;
                    table.Rows.Add(dr);
                }

                dsDatas.Tables.Add(table);
                return dsDatas;
            }
            catch (SqlException sqlEx)
            {
                throw sqlEx;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }
    }
}