using DeviceRepair.DataAccess.Data;
using DeviceRepair.Models;
using DeviceRepair.Models.Enum;
using DeviceRepair.Models.History;
using DeviceRepair.Models.Logs;
using DeviceRepair.Models.Record;
using DeviceRepair.Utils;
using Newtonsoft.Json;
using NLog;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;

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

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

        }

        /// <summary>
        /// 获取单条保养记录
        /// </summary>
        /// <param name="dsDatas"></param>
        /// <returns></returns>
        public APIResponseData Get_Preserve_Single(out DataSet dsDatas)
        {
            dsDatas = new DataSet("Datas");
            try
            {
                int AutoID = base.GetParamInt("AutoID", "保养记录编号");
                MaintenanceRecordInfo Data = devMain.Queryable<MaintenanceRecordInfo>().First(x => x.AutoID == AutoID);
                if (Data == null)
                {
                    throw new ArgumentException("传入的数据不正确，获取保养记录信息失败！");
                }
                DataTable table = new List<MaintenanceRecordInfo> { Data }.ToDataTable();
                dsDatas.Tables.Add(table);
                return new APIResponseData { Code = 1, Message = "操作成功！" };
            }
            catch (SqlException sqlEx)
            {
                throw sqlEx;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }


        /// <summary>
        /// 获取单条保养记录
        /// </summary>
        /// <param name="dsDatas"></param>
        /// <returns></returns>
        public APIResponseData Get_Preserve_Single(int PlanAutoID, int EquipmentPrimaryID, int FormPrimaryID, out DataSet dsDatas)
        {
            dsDatas = new DataSet("Datas");
            try
            {
                if (EquipmentPrimaryID <= 0)
                    throw new Exception($"参数【设备表主键编号】不能为空！");

                if (FormPrimaryID <= 0)
                    throw new Exception($"参数【保养点检表主键编号】不能为空！");

                DriveMaintencePlanInfo plan = devMain.Queryable<DriveMaintencePlanInfo>().First(x => x.AutoID == PlanAutoID);
                if (plan == null)
                    return new APIResponseData { Code = -1, Message = $"当前计划不存在,请刷新后再试！" };

                List<MaintenanceRecordInfo> entity = devMain.Queryable<MaintenanceRecordInfo>()
                     .OrderBy(x => x.AutoID, OrderByType.Asc)
                     .Where(x => x.EquipmentPrimaryID == EquipmentPrimaryID //&& x.FormPrimaryID == FormPrimaryID
                     && x.MYear == plan.MaintenanceYear && x.PlanPrimaryID == plan.AutoID).ToList();

                if (entity == null || entity.Count == 0)
                    return new APIResponseData { Code = 1, Data = null };

                MaintenanceRecordInfo Item = entity[0];
                Models.Preserve.JsonData.ContentData content = JsonConvert.DeserializeObject<Models.Preserve.JsonData.ContentData>(Item.ContentData);

                for (int i = 1; i < entity.Count; i++)
                {
                    MaintenanceRecordInfo m = entity[i];
                    Models.Preserve.JsonData.ContentData data = JsonConvert.DeserializeObject<Models.Preserve.JsonData.ContentData>(m.ContentData);

                    foreach (SheetDataItem item in data.InstallationSite)
                    {
                        SheetDataItem j = content.InstallationSite.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                        if (j != null)
                            j.Value = item.Value;
                        else
                            content.InstallationSite.Add(item);
                    }

                    foreach (SheetDataItem item in data.EquipmentName)
                    {
                        SheetDataItem j = content.EquipmentName.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                        if (j != null)
                            j.Value = item.Value;
                        else
                            content.EquipmentName.Add(item);
                    }

                    foreach (SheetDataItem item in data.DeviceSpecification)
                    {
                        SheetDataItem j = content.DeviceSpecification.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                        if (j != null)
                            j.Value = item.Value;
                        else
                            content.DeviceSpecification.Add(item);
                    }

                    foreach (SheetDataItem item in data.EquipmentID)
                    {
                        SheetDataItem j = content.EquipmentID.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                        if (j != null)
                            j.Value = item.Value;
                        else
                            content.EquipmentID.Add(item);
                    }

                    foreach (SheetDataItem item in data.Year)
                    {
                        SheetDataItem j = content.Year.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                        if (j != null)
                            j.Value = item.Value;
                        else
                            content.Year.Add(item);
                    }

                    foreach (SheetDataItem item in data.Content)
                    {
                        SheetDataItem j = content.Content.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                        if (j != null)
                            j.Value = item.Value;
                        else
                            content.Content.Add(item);
                    }

                    foreach (SheetDataItem item in data.ExceptionDescription)
                    {
                        SheetDataItem j = content.ExceptionDescription.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                        if (j != null)
                            j.Value += Environment.NewLine + item.Value;
                        else
                            content.ExceptionDescription.Add(item);
                    }

                    foreach (SheetDataItem item in data.Operation)
                    {
                        SheetDataItem j = content.Operation.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                        if (j != null)
                            j.Value = item.Value;
                        else
                            content.Operation.Add(item);
                    }

                    foreach (SheetDataItem item in data.OperationDate)
                    {
                        SheetDataItem j = content.OperationDate.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                        if (j != null)
                            j.Value = item.Value;
                        else
                            content.OperationDate.Add(item);
                    }

                    foreach (SheetDataItem item in data.YearAndMonth)
                    {
                        SheetDataItem j = content.YearAndMonth.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                        if (j != null)
                            j.Value = item.Value;
                        else
                            content.YearAndMonth.Add(item);
                    }
                }
                Item.ContentData = JsonConvert.SerializeObject(content);

                DataTable table = new List<MaintenanceRecordInfo> { Item }.ToDataTable();
                dsDatas.Tables.Add(table);
                return new APIResponseData { Code = 1, Message = "操作成功！" };
            }
            catch (SqlException sqlEx)
            {
                throw sqlEx;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }


        /// <summary>
        /// 保养数据新增
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public APIResponseData Insert_PM_Preserve_Data(MaintenanceRecordSubmit entity)
        {
            APIResponseData apiResponseData = new APIResponseData { Code = -1, Message = $"获取数据失败！" };
            try
            {
                devMain.BeginTran();

                string OperationType = "新增";
                DateTime CurrentDate = DateTime.Now;
                int Identity = 0;
                int OperationID = base.GetParamInt("OPERATORAUTOID", "当前操作人");
                string Belong = base.GetParamString("Belong", "计划类型");

                if (Belong.ToUpper() != "AM" && Belong.ToUpper() != "PM")
                    throw new ArgumentException("传入的计划类型值不正确！");

                if (entity.Record.AutoID == 0)
                {
                    if (Belong.ToUpper() != "AM" && devMain.Queryable<MaintenanceRecordInfo>().Any(x => x.PlanPrimaryID == entity.Record.PlanPrimaryID))
                    {
                        throw new Exception("当前数据已被其他用户录入 ");
                    }

                    entity.Record.ModifyDate = CurrentDate;
                    entity.Record.ModifyBy = OperationID;
                    entity.Record.CreateDate = CurrentDate;
                    Identity = devMain.Insertable(entity.Record).ExecuteReturnIdentity();
                }
                else
                {
                    OperationType = "修改";

                    MaintenanceRecordHisInfo his = new MaintenanceRecordHisInfo
                    {

                        HisID = entity.Record.AutoID,
                        OperationBy = OperationID,
                        OperationDate = CurrentDate,
                        EquipmentPrimaryID = entity.Record.EquipmentPrimaryID,
                        EquipmentID = entity.Record.EquipmentID,
                        EquipmentName = entity.Record.EquipmentName,
                        Specification = entity.Record.Specification,
                        PlanPrimaryID = entity.Record.PlanPrimaryID,
                        PlanType = entity.Record.PlanType,
                        FormPrimaryID = entity.Record.FormPrimaryID,
                        FormVersionCode = entity.Record.FormVersionCode,
                        FormVersionRev = entity.Record.FormVersionRev,
                        FormName = entity.Record.FormName,
                        MYear = entity.Record.MYear,
                        ContentData = entity.Record.ContentData,
                        CreateBy = entity.Record.CreateBy,
                        CreateDate = entity.Record.CreateDate,
                        ModifyBy = entity.Record.ModifyBy,
                        ModifyDate = entity.Record.ModifyDate,
                        Description = entity.Record.Description
                    };
                    int count = devMain.Insertable(his).ExecuteCommand();
                    if (count > 0)
                    {
                        entity.Record.ModifyDate = CurrentDate;
                        entity.Record.ModifyBy = OperationID;

                        count = devMain.Updateable(entity.Record)
                            .UpdateColumns(x => new { x.ContentData, x.ModifyDate, x.ModifyBy })
                            .ExecuteCommand();

                        if (count > 0)
                        {
                            Identity = entity.Record.AutoID;
                        }
                        else
                        {
                            devMain.RollbackTran();
                            return new APIResponseData { Code = -1, Message = "操作失败！" };
                        }
                    }
                    else
                    {
                        devMain.RollbackTran();
                        return new APIResponseData { Code = -1, Message = "操作失败！" };
                    }
                }

                if (Identity > 0)
                {
                    //附件存放路径
                    string AttachmentDirectory = Path.Combine(DeviceRepair.Utils.Config.Configurations.Properties.AttachmentDirectory, DateTime.Today.ToString("yyyyMMdd"));
                    if (!Directory.Exists(AttachmentDirectory))
                        Directory.CreateDirectory(AttachmentDirectory);

                    List<AttachmentInfo> Attas = new List<AttachmentInfo>();

                    #region 附件写入

                    //附件写入
                    if (entity.Files == null || entity.Files.Count == 0)
                    {
                        int cCount = devMain.Updateable<AttachmentInfo>().UpdateColumns(x => new { x.Status })
                       .SetColumns(x => x.Status == false)
                       .Where(x => x.Module == "Attachment" && x.TableName == "MaintenanceRecord" && x.PrimaryKey == "AutoID" && x.PrimaryValue == Identity + "").ExecuteCommand();
                    }

                    foreach (var item in entity.Files)
                    {
                        if (item.AutoID != 0 && item.Datas == null)
                        {
                            continue;
                        }

                        AttachmentInfo atta = new AttachmentInfo
                        {
                            CreateBy = OperationID,
                            FileName = item.FileName,
                            Extension = item.Extension,
                            Module = "Attachment",
                            TableName = "MaintenanceRecord",
                            PrimaryValue = Identity + "",
                            PrimaryKey = "AutoID",
                            ValueType = "int",
                            FilePath = Path.Combine(AttachmentDirectory, $"{Guid.NewGuid()}{item.Extension}"),
                            CreateOn = CurrentDate,
                            Status = true
                        };
                        Attas.Add(atta);
                        File.WriteAllBytes(atta.FilePath, item.Datas);
                    }
                    #endregion

                    #region 图片写入
                    int[] NoneImg = entity.Imgs.Select(x => x.AutoID).Distinct().ToArray();
                    string PrimaryValue = entity.Record.AutoID.ToString();


                    var exp = Expressionable.Create<AttachmentInfo>()
                    .AndIF(NoneImg.Length > 0, x => !SqlFunc.ContainsArray(NoneImg, x.AutoID))
                    .And(x => x.Module == "Image")
                    .And(x => x.TableName == "MaintenanceRecord")
                    .And(x => x.PrimaryKey == "AutoID")
                    .And(x => x.PrimaryValue == PrimaryValue).ToExpression();

                    devMain.Updateable<AttachmentInfo>().UpdateColumns(x => new { x.Status })
                        .SetColumns(x => x.Status == false)
                        .Where(exp).ExecuteCommand();


                    List<int> ImgIds = new List<int>();
                    foreach (var item in entity.Imgs)
                    {
                        if (item.Datas == null && item.AutoID != 0)
                        {
                            ImgIds.Add(item.AutoID);
                            continue;
                        }

                        string FileName = $"{Guid.NewGuid()}.Jpeg";
                        AttachmentInfo atta = new AttachmentInfo
                        {
                            CreateBy = OperationID,
                            FileName = FileName,
                            Extension = ".Jpeg",
                            Module = "Image",
                            TableName = "MaintenanceRecord",
                            PrimaryValue = Identity + "",
                            PrimaryKey = "AutoID",
                            ValueType = "int",
                            FilePath = Path.Combine(AttachmentDirectory, $"{Guid.NewGuid()}.Jpeg"),
                            CreateOn = CurrentDate,
                            Status = true
                        };
                        Attas.Add(atta);
                        File.WriteAllBytes(atta.FilePath, item.Datas);
                    }
                    #endregion

                    //附件插入
                    if (Attas.Count > 0)
                    {
                        bool result = devMain.Insertable(Attas).ExecuteCommand() > 0;
                        if (!result)
                        {
                            devMain.RollbackTran();
                            return new APIResponseData { Code = -1, Message = "附件写入失败！" };
                        }
                    }
                    devMain.CommitTran();

                    apiResponseData.Code = 1;
                    apiResponseData.Message = "";

                    MaintenanceRecordInfo model = devMain.Queryable<MaintenanceRecordInfo>().First(x => x.AutoID == Identity);

                    DeviceMaintenanceLogInfo log = new DeviceMaintenanceLogInfo
                    {
                        EquipmentAutoID = model.EquipmentPrimaryID,
                        EquipmentID = model.EquipmentID,
                        EquipmentName = model.EquipmentName,
                        PlanID = model.PlanPrimaryID,
                        PlanType = model.PlanType,
                        OperationComputer = ApiParameters["CLIENTNAME"],
                        OperationUserName = ApiParameters["OPERATORNAME"],
                        OperationDate = CurrentDate,
                        OperationIP = ApiParameters["CLIENTIP"],
                        OperationType = OperationType,
                        OperationUser = OperationID
                    };
                    devLog.Insertable(log).ExecuteCommand();

                    return apiResponseData;
                }

                devMain.RollbackTran();
                return apiResponseData;
            }
            catch (SqlException sqlEx)
            {
                devMain.RollbackTran();
                throw sqlEx;
            }
            catch (Exception ex)
            {
                devMain.RollbackTran();
                log.Error(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取保养计划的全部保养记录
        /// </summary>
        /// <returns></returns>
        public APIResponseData Get_PreserveDetail_All(out DataSet dsDatas)
        {
            dsDatas = new DataSet("Datas");
            try
            {
                int PlanPrimaryKey = base.GetParamInt("AutoID", "保养记录编号");

                if (PlanPrimaryKey == 0)
                    throw new ArgumentException("未能获取到查询条件:保养计划主键ID等于0的数据");

                MaintenanceRecordSubmit model = new MaintenanceRecordSubmit();
                DriveMaintencePlanInfo plan = devMain.Queryable<DriveMaintencePlanInfo>().First(x => x.AutoID == PlanPrimaryKey);
                DeviceInformationInfo dev = devMain.Queryable<DeviceInformationInfo>().First(x => x.AutoID == plan.EquipmentID);

                List<MaintenanceRecordInfo> Datas = devMain.Queryable<MaintenanceRecordInfo>()
   .Where(x => x.PlanPrimaryID == plan.AutoID
   //&& x.FormPrimaryID == FormID
   ).ToList();

                if (Datas != null && Datas.Count > 0)
                {
                    MaintenanceRecordInfo last = Datas.OrderByDescending(x => x.CreateDate).Take(1).FirstOrDefault();
                    Datas = Datas.Where(x => x.FormPrimaryID == last.FormPrimaryID).ToList();

                    MaintenanceRecordInfo Item = Datas[0];
                    Models.Preserve.JsonData.ContentData content = JsonConvert.DeserializeObject<Models.Preserve.JsonData.ContentData>(Item.ContentData);

                    for (int i = 1; i < Datas.Count; i++)
                    {
                        MaintenanceRecordInfo m = Datas[i];
                        Models.Preserve.JsonData.ContentData data = JsonConvert.DeserializeObject<Models.Preserve.JsonData.ContentData>(m.ContentData);

                        foreach (SheetDataItem item in data.InstallationSite)
                        {
                            SheetDataItem j = content.InstallationSite.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                            if (j != null)
                                j.Value = item.Value;
                            else
                                content.InstallationSite.Add(item);
                        }

                        foreach (SheetDataItem item in data.EquipmentName)
                        {
                            SheetDataItem j = content.EquipmentName.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                            if (j != null)
                                j.Value = item.Value;
                            else
                                content.EquipmentName.Add(item);
                        }

                        foreach (SheetDataItem item in data.DeviceSpecification)
                        {
                            SheetDataItem j = content.DeviceSpecification.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                            if (j != null)
                                j.Value = item.Value;
                            else
                                content.DeviceSpecification.Add(item);
                        }

                        foreach (SheetDataItem item in data.EquipmentID)
                        {
                            SheetDataItem j = content.EquipmentID.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                            if (j != null)
                                j.Value = item.Value;
                            else
                                content.EquipmentID.Add(item);
                        }

                        foreach (SheetDataItem item in data.Year)
                        {
                            SheetDataItem j = content.Year.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                            if (j != null)
                                j.Value = item.Value;
                            else
                                content.Year.Add(item);
                        }

                        foreach (SheetDataItem item in data.Content)
                        {
                            SheetDataItem j = content.Content.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                            if (j != null)
                                j.Value = item.Value;
                            else
                                content.Content.Add(item);
                        }

                        foreach (SheetDataItem item in data.ExceptionDescription)
                        {
                            SheetDataItem j = content.ExceptionDescription.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                            if (j != null)
                                j.Value += Environment.NewLine + item.Value;
                            else
                                content.ExceptionDescription.Add(item);
                        }

                        foreach (SheetDataItem item in data.Operation)
                        {
                            SheetDataItem j = content.Operation.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                            if (j != null)
                                j.Value = item.Value;
                            else
                                content.Operation.Add(item);
                        }

                        foreach (SheetDataItem item in data.OperationDate)
                        {
                            SheetDataItem j = content.OperationDate.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                            if (j != null)
                                j.Value = item.Value;
                            else
                                content.OperationDate.Add(item);
                        }

                        foreach (SheetDataItem item in data.YearAndMonth)
                        {
                            SheetDataItem j = content.YearAndMonth.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                            if (j != null)
                                j.Value = item.Value;
                            else
                                content.YearAndMonth.Add(item);
                        }
                    }
                    Item.ContentData = JsonConvert.SerializeObject(content);

                    string[] recordIds = Datas.Select(x => x.AutoID.ToString()).ToArray();

                    List<AttachmentInfo> att = devMain.Queryable<AttachmentInfo>()
                        .Where(x => x.TableName == "MaintenanceRecord"
                 && x.PrimaryKey == "AutoID" && SqlFunc.ContainsArray(recordIds, x.PrimaryValue) && x.Status).ToList();

                    model.Record = Item;

                    DataTable table = Item.toDataTable();
                    dsDatas.Tables.Add(table);

                    if (att.Count > 0)
                    {
                        List<AttachmentInfo> fs = att.Where(x => x.Module == "Attachment").ToList();
                        foreach (AttachmentInfo item in fs)
                        {
                            model.Files.Add(new AttachmentSubmitModel
                            {
                                Datas = File.ReadAllBytes(item.FilePath),
                                Extension = item.Extension,
                                FileName = item.FileName,
                                Module = item.Module
                            });
                        }

                        if (fs.Count > 0)
                        {
                            DataTable table2 = ListToDataTable(fs);
                            table2.TableName = "Attachment";
                            dsDatas.Tables.Add(table2);
                        }

                        List<AttachmentInfo> im = att.Where(x => x.Module == "Image").ToList();
                        foreach (AttachmentInfo item in im)
                        {
                            model.Imgs.Add(new AttachmentSubmitModel
                            {
                                Datas = File.ReadAllBytes(item.FilePath),
                                Extension = item.Extension,
                                FileName = item.FileName,
                                Module = item.Module
                            });
                        }

                        if (im.Count > 0)
                        {
                            DataTable table3 = ListToDataTable(im);
                            table3.TableName = "Image";
                            dsDatas.Tables.Add(table3);
                        }
                    }

                    return new APIResponseData { Code = 1 };
                }

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



        /// <summary>
        /// 获取设备保养记录信息
        /// </summary>
        /// <param name="dsDatas"></param>
        /// <returns></returns>
        public APIResponseData GetRecordHisView(out DataSet dsDatas)
        {
            dsDatas = new DataSet("Datas");
            try
            {
                string Belong = "AM";
                if (ApiParameters.ContainsKey("Belong"))
                {
                    Belong = ApiParameters["Belong"]?.Trim();
                }

                int PlanID = 0;
                if (ApiParameters.ContainsKey("PlanID"))
                {
                    PlanID = Convert.ToInt32(ApiParameters["PlanID"]);
                }

                int EquipmentId = 0;
                if (ApiParameters.ContainsKey("EquipmentId"))
                {
                    EquipmentId = Convert.ToInt32(ApiParameters["EquipmentId"]);
                }

                string EquipmentName = "";
                if (ApiParameters.ContainsKey("EquipmentName"))
                {
                    EquipmentName = ApiParameters["EquipmentName"];
                }

                DateTime StartDate = DateTime.MinValue;
                if (ApiParameters.ContainsKey("StartDate"))
                {
                    StartDate = Convert.ToDateTime(ApiParameters["StartDate"]);
                }

                DateTime EndDate = DateTime.MaxValue;
                if (ApiParameters.ContainsKey("EndDate"))
                {
                    EndDate = Convert.ToDateTime(ApiParameters["EndDate"]);
                    EndDate = EndDate.AddDays(1).AddSeconds(-1);
                }

                EnumMaintenanceType EnumMaintenanceType = EnumMaintenanceType.None;
                if (ApiParameters.ContainsKey("MaintenanceType"))
                {
                    EnumMaintenanceType = (EnumMaintenanceType)Enum.Parse(typeof(EnumMaintenanceType), ApiParameters["MaintenanceType"]);
                }

                EnumMaintenanceBanciType EnumBanci = EnumMaintenanceBanciType.None;
                if (ApiParameters.ContainsKey("Banci"))
                {
                    EnumBanci = (EnumMaintenanceBanciType)Enum.Parse(typeof(EnumMaintenanceBanciType), ApiParameters["Banci"]);
                }

                var exp = Expressionable.Create<MaintenanceRecordHistoryModel>();
                exp.And(x => x.Belong == Belong);

                string MaintenanceType = EnumMaintenanceType.ToString();
                string Banci = EnumBanci.ToString();

                exp.AndIF(EquipmentId != 0, x => x.EquipmentPrimaryID == EquipmentId);
                exp.AndIF(StartDate != DateTime.MinValue, x => x.MaintenanceDate >= StartDate);
                exp.AndIF(EndDate != DateTime.MaxValue, x => x.MaintenanceDate <= EndDate);
                exp.AndIF(EnumMaintenanceType != EnumMaintenanceType.None, x => x.MaintenanceType == MaintenanceType);
                exp.AndIF(EnumBanci != EnumMaintenanceBanciType.None, x => x.Banci == Banci);
                exp.AndIF(!EquipmentName.IsNull(), x => x.EquipmentName.Contains(EquipmentName) || x.EquipmentID == EquipmentName);
                exp.AndIF(PlanID != 0, x => x.PlanID == PlanID);

                List<MaintenanceRecordHistoryModel> Datas = devMain.Queryable<MaintenanceRecordHistoryModel>()
                    .Where(exp.ToExpression()).ToList();

                DataTable table = Datas.ToDataTable();
                dsDatas.Tables.Add(Datas.ToDataTable());
                return new APIResponseData { Code = 1, Message = "操作成功！" };
            }
            catch (SqlException sqlEx)
            {
                throw sqlEx;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }
    }
}
