using DeviceRepair.DataAccess.Data;
using DeviceRepair.Models;
using DeviceRepair.Models.Device;
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.Device
{
    public class DeviceDa : BaseDa
    {
        private static readonly Logger log = LogManager.GetCurrentClassLogger();

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

        /// <summary>
        /// 根据权限获取设备信息
        /// </summary>
        /// <returns></returns>
        public DataSet Get_DEVICE_Datas()
        {
            DataSet dsDatas = new DataSet("Datas");
            try
            {
                if (!ApiParameters.ContainsKey("Auths"))
                {
                    return dsDatas;
                }

                var AuthString = GetParamString("Auths", "权限");
                var auths = AuthString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                var devIds = devMain.Ado
                    .SqlQuery<int>("SELECT AutoID FROM dbo.View_DeviceRoot WHERE RootName IN (@RootName)",
                        new { RootName = auths }).ToArray();
                var Datas = devMain.Queryable<DeviceInformationInfo>()
                    .Where(x => SqlFunc.ContainsArray(devIds, x.AutoID)).ToList();

                var 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 Get_DEVICE_TreeDatas(out DataSet dsDatas)
        {
            dsDatas = new DataSet("Datas");
            try
            {
                if (!ApiParameters.ContainsKey("Auths"))
                {
                    return new APIResponseData { Code = -1, Message = "没有设备信息查看权限！" };
                }

                var AuthString = GetParamString("Auths", "权限");

                var FilterValue = string.Empty;
                if (ApiParameters.ContainsKey("FilterValue"))
                    FilterValue = GetParamString("FilterValue", "检索条件");

                var Datas2 = devMain.Ado.UseStoredProcedure().GetDataTable("Proc_DeviceTreeViews", new { RootName = AuthString });
                var Datas = Datas2.ToList<DeviceInformationInfoTree>();

                if (!FilterValue.IsNull())
                {
                    Datas = Datas.Where(x => x.EquipmentID == FilterValue).ToList();
                }

                var table = Datas.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_DEVICE_Route(out DataSet dsDatas)
        {
            dsDatas = new DataSet("Datas");
            try
            {
                if (!ApiParameters.ContainsKey("Auths"))
                {
                    return new APIResponseData { Code = -1, Message = "没有设备信息查看权限！" };
                }

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

                string AuthString = ApiParameters["Auths"];
                string[] auths = AuthString.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                /* 获取权限分组 */
                List<DeviceRouteInfo> route = devMain.Ado.SqlQuery<DeviceRouteInfo>(@";WITH cte
                                AS (SELECT AutoID,
                                           Name
                                    FROM dbo.DeviceRoute
                                    WHERE (ParentID = 0)
                                    UNION ALL
                                    SELECT dr.AutoID,
                                           cte_1.Name
                                    FROM dbo.DeviceRoute AS dr
                                        INNER JOIN cte AS cte_1
                                            ON dr.ParentID = cte_1.AutoID)
                                SELECT DeviceRoute.*
                                FROM dbo.DeviceRoute
								INNER JOIN cte ON cte.AutoID = DeviceRoute.AutoID WHERE cte.Name IN (@Name) AND Status = 1",
                    new { Name = auths }).ToList();

                int[] routeIds = route.Select(x => x.AutoID).ToArray();
                List<DeviceRouteInfo> Data = devMain.Queryable<DeviceRouteInfo>()
                    .Where(x => x.Status && SqlFunc.ContainsArray(routeIds, x.AutoID)).ToList();

                DataTable table = 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>
        /// 判断设备是否存在
        /// 1 存在
        /// 0 不存在
        /// </summary>
        /// <param name="Equipment"></param>
        /// <returns></returns>
        public int Get_DEVICE_EXISTS(string Equipment)
        {
            try
            {
                if (Equipment.IsNull())
                    throw new ArgumentException("传入的设备编号不能为空！");

                Equipment = Equipment.Trim();

                if (Equipment.Length > 50)
                    throw new ArgumentException("传入的设备编号长度不允许超过50！");


                return devMain.Queryable<DeviceInformationInfo>().Any(x => x.EquipmentID == Equipment) ? 1 : 0;
            }
            catch (SqlException sqlEx)
            {
                throw sqlEx;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 设备新增
        /// </summary>
        /// <param name="Data"></param>
        /// <param name="dsDatas"></param>
        /// <returns></returns>
        public APIResponseData Insert_DEVICE_Data(DeviceInformationInfo Data, out DataSet dsDatas)
        {
            dsDatas = new DataSet("Datas");
            try
            {
                if (Data == null)
                    throw new ArgumentException("传入的设备对象参数不正确,对象不能为空！");

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

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

                DateTime CurrentDate = DateTime.Now;

                Data.CreatUser = Operation;
                Data.CreatDate = CurrentDate;

                DeviceInformationInfo Result = devMain.Insertable(Data).ExecuteReturnEntity();

                DataTable table = new List<DeviceInformationInfo> { Result }.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="Data"></param>
        /// <param name="OperationTime"></param>
        /// <returns></returns>
        public APIResponseData Updata_DEVICE_Data(DeviceInformationInfo Data, out DateTime OperationTime)
        {
            try
            {
                DateTime CurrentDate = DateTime.Now;
                OperationTime = CurrentDate;

                if (Data == null)
                    throw new ArgumentException("传入的设备对象参数不正确,对象不能为空！");

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

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

                devMain.BeginTran();
                DeviceInformationInfo Item = devMain.Queryable<DeviceInformationInfo>()
                    .First(x => x.AutoID == Data.AutoID);
                if (Item == null)
                    throw new ArgumentException($"没有获取到设备编号为：【{Data.EquipmentID}】的设备信息！");

                Item.EquipmentID = Data.EquipmentID;
                Item.EquipmentName = Data.EquipmentName;
                Item.Specification = Data.Specification;
                Item.Manufacturer = Data.Manufacturer;
                Item.SerialNumber = Data.SerialNumber;
                Item.UsingDate = Data.UsingDate;
                Item.Totalcapacity = Data.Totalcapacity;
                Item.Weight = Data.Weight;
                Item.EquipmentCategory = Data.EquipmentCategory;
                Item.EquipmentOriginalvalue = Data.EquipmentOriginalvalue;
                Item.EquipmentStatus = Data.EquipmentStatus;
                Item.WarrantyPeriod = Data.WarrantyPeriod;
                Item.InstallationLocation = Data.InstallationLocation;
                Item.OwningUnit = Data.OwningUnit;
                Item.OperatingParameters = Data.OperatingParameters;
                Item.MaintenanceFormVersion = Data.MaintenanceFormVersion;
                Item.MaintenanceAMFormVersion = Data.MaintenanceAMFormVersion;
                Item.Route = Data.Route;
                Data.ChangeDate = CurrentDate;
                Data.ChangeUser = Operation;
                Item.Remarks = Data.Remarks;

                if (devMain.Updateable(Item).ExecuteCommand() > 0)
                {
                    devMain.CommitTran();
                    return new APIResponseData { Code = 1 };
                }
                else
                {
                    devMain.RollbackTran();
                    return new APIResponseData { Code = -1 };
                }
            }
            catch (SqlException sqlEx)
            {
                devMain.RollbackTran();
                throw sqlEx;
            }
            catch (Exception ex)
            {
                devMain.RollbackTran();
                log.Error(ex);
                throw ex;
            }
        }

        /// <summary>
        /// 修改设备状态
        /// </summary>
        /// <param name="AutoID"></param>
        /// <param name="OperationTime"></param>
        /// <returns></returns>
        public APIResponseData Update_DEVICE_Status(int AutoID, out DateTime OperationTime)
        {
            try
            {
                DateTime CurrentDate = DateTime.Now;
                OperationTime = CurrentDate;

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

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

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

                devMain.BeginTran();
                DeviceInformationInfo Item = devMain.Queryable<DeviceInformationInfo>().First(x => x.AutoID == AutoID);
                if (Item == null)
                    throw new ArgumentException($"没有获取到设备主键编号为：【{AutoID}】的设备信息！");

                Item.EquipmentStatus = Item.EquipmentStatus == 1 ? 0 : 1;
                Item.ChangeDate = CurrentDate;
                Item.ChangeUser = Operation;

                if (devMain.Updateable(Item).ExecuteCommand() > 0)
                {
                    devMain.CommitTran();
                    return new APIResponseData { Code = 1 };
                }
                else
                {
                    devMain.RollbackTran();
                    return new APIResponseData { Code = -1 };
                }
            }
            catch (SqlException sqlEx)
            {
                throw sqlEx;
            }
            catch (Exception ex)
            {
                log.Error(ex);
                throw ex;
            }
        }
    }
}