using DeviceRepair.Models;
using DeviceRepair.Models.DeviceMaintenance;
using DeviceRepair.Models.DeviceRepair.ExportView;
using DeviceRepair.Models.SFC;
using DeviceRepair.Utils;
using NLog;
using NLog.Filters;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using TsSFCDevice.Client.Biz.Base.Service;
using TsSFCDevice.Client.Biz.Base.Utils;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace TsSFCDevice.Client.Biz.Impl
{
    /// <summary>
    /// 设备维修
    /// </summary>
    public class MaintenanceRepository
    {
        private readonly Logger log;
        private static MaintenanceRepository manager;

        private IDictionary<string, string> m_ApiParameters;
        /// <summary>
        /// API输入参数
        /// </summary>
        public IDictionary<string, string> ApiParameters
        {
            get
            {
                return m_ApiParameters;
            }
            set
            {
                m_ApiParameters = value;
            }
        }

        public static MaintenanceRepository Instance
        {
            get
            {
                if (manager == null)
                    manager = new MaintenanceRepository();
                return manager;
            }
        }

        public MaintenanceRepository()
        {
            log = LogManager.GetCurrentClassLogger();
            m_ApiParameters = new Dictionary<string, string>();
        }

        internal string GetParameters(string cOperator = "", bool bFlag = true)
        {

            return ParametersObject.GetInstance(cOperator).GetJsonSerialized(m_ApiParameters);
        }

        /// <summary>
        /// 设备维修数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public IList<DeviceWarrantyRequestFormView> GetDatas(DeviceRepair.Models.DeviceWarrantyRequestFormFilter filter)
        {
            try
            {
                byte[] btResults = null;
                int[] EquipmentIds = Utility.SystemRuntimeInfo.CurrentDeviceCaches?.Select(x => x.AutoID)?.ToArray();
                if (EquipmentIds == null || EquipmentIds.Length == 0)
                {
                    return new List<DeviceWarrantyRequestFormView>();
                }

                ApiParameters?.Clear();
                ApiParameters.Add("EquipmentID", filter.EquipmentID);
                ApiParameters.Add("Status", ((int)filter.Status) + "");
                ApiParameters.Add("DownStatus", ((int)filter.DownStatus) + "");
                if (filter.StartTime.HasValue)
                {
                    ApiParameters.Add("StartTime", filter.StartTime.Value.ToString("yyyy-MM-dd hh:mm:ss"));
                }

                if (filter.EndTime.HasValue)
                {
                    ApiParameters.Add("EndTime", filter.EndTime.Value.ToString("yyyy-MM-dd hh:mm:ss"));
                }

                var Rtn = Utility.SfcBizService.CurrentSvc.GetDatas(DeviceSvc.SysModelType.Maintenance, GetParameters(), out btResults);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }
                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                if (dsResults.Tables["Form"] == null)
                {
                    return new List<DeviceWarrantyRequestFormView>();
                }

                IList<DeviceWarrantyRequestFormView> Datas = DTOHelper<DeviceWarrantyRequestFormView>.DataTableToList(dsResults.Tables["Form"]);
                Datas = Datas.Where(x => EquipmentIds.Contains(x.EquipmentPK))?.ToList();

                IList<DeviceWarrantyRequestMaintaionView> Maintaion = DTOHelper<DeviceWarrantyRequestMaintaionView>.DataTableToList(dsResults.Tables["Maintaion"]);
                IList<DeviceRepair.Models.DeviceWarrantyEvaluatorInfo> Evals = DTOHelper<DeviceRepair.Models.DeviceWarrantyEvaluatorInfo>.DataTableToList(dsResults.Tables["Eval"]);

                Dictionary<int, string> dictUser = Utility.SystemRuntimeInfo.CurrentUsersCaches?.ToDictionary(x => x.Id, x => x.UserName);

                foreach (DeviceWarrantyRequestFormView item in Datas)
                {
                    if (item.CreatBy.HasValue && dictUser.ContainsKey(item.CreatBy.Value))
                    {
                        item.CreatorName = dictUser[item.CreatBy.Value];
                    }

                    if (item.ModifyBy.HasValue && dictUser.ContainsKey(item.ModifyBy.Value))
                    {
                        item.ModifyByName = dictUser[item.ModifyBy.Value];
                    }
                    //item.RestorationConfirmationBy
                    if (item.RestorationConfirmationBy > 0 && dictUser.ContainsKey(item.RestorationConfirmationBy))
                    {
                        item.RestorationConfirmationOnName = dictUser[item.RestorationConfirmationBy];
                    }

                    item.MaintaionItems = Maintaion.FirstOrDefault(x => x.FormID == item.AutoID);
                    item.EvaluatorItems = Evals.Where(x => x.FormID == item.AutoID)?.ToList();
                }

                return Datas.Where(x => Utility.SystemRuntimeInfo.CurrentDeviceAutoIDCaches.Contains(x.EquipmentPK)).ToList();
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 获取当前批次的QE PE邮箱
        /// </summary>
        /// <returns></returns>
        public IList<string> SFC_Batch_PE_QE_Email(string Batch)
        {
            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();
                ApiParameters.Add("Batch", Batch);
                var Rtn = Utility.SfcBizService.CurrentSvc.GetDatas(DeviceSvc.SysModelType.SFC_Batch_PE_QE_Email, GetParameters(), out btResults);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }
                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                IList<string> Datas = dsResults.Tables[0].Rows.Cast<DataRow>().Select(x => x[0] + "").ToList<string>();
                //IList<string> Datas = dsResults.Tables[0].ToList<string>(); DTOHelper<string>.DataTableToList(dsResults.Tables[0]);
                return Datas;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 获取维修单 维修配件列表
        /// </summary>
        /// <param name="MaintaionID"></param>
        /// <returns></returns>
        public IList<DeviceRepair.Models.DeviceWarrantyRequestAccessoriesInfo> GetFormAccessories(int MaintaionID)
        {
            try
            {
                byte[] btResults = null;

                ApiParameters?.Clear();
                ApiParameters.Add("MaintaionID", MaintaionID + "");

                var Rtn = Utility.SfcBizService.CurrentSvc.GetDatas(DeviceSvc.SysModelType.MaintenanceAccessories, GetParameters(), out btResults);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }
                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                IList<DeviceRepair.Models.DeviceWarrantyRequestAccessoriesInfo> Datas = DTOHelper<DeviceRepair.Models.DeviceWarrantyRequestAccessoriesInfo>.DataTableToList(dsResults.Tables[0]);
                return Datas;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 设备维修单 - 设备停机状态修改
        /// </summary>
        /// <returns></returns>
        public APIResponseData Update_Maintenance_Status(int FormID, bool Status)
        {
            try
            {
                ApiParameters?.Clear();
                ApiParameters.Add("FormID", FormID + "");
                ApiParameters.Add("FormStatus", Status + "");

                var Rtn = Utility.SfcBizService.CurrentSvc.Update_Maintenance_Status(GetParameters());
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }
                return new APIResponseData { Code = 1, Message = Rtn.Message };
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 双重确认
        /// </summary>
        /// <param name="FormID"></param>
        /// <param name="PostID">1:技术人员确认  2:工程师或维修主管确认</param>
        /// <returns></returns>
        public APIResponseData ValidateMaintenance(int FormID, int PostID)
        {
            try
            {
                ApiParameters?.Clear();
                ApiParameters.Add("FormID", FormID + "");
                ApiParameters.Add("t", PostID + "");

                var Rtn = Utility.SfcBizService.CurrentSvc.ADD_Maintenance_DoubleValidate(GetParameters());
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }
                return new APIResponseData { Code = 1, Message = Rtn.Message };
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 设备维修单列表导出
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public IList<MaintainOrderView> Get_Maintenance_Xlsx_Datas(DeviceRepair.Models.DeviceWarrantyRequestFormFilter filter)
        {
            try
            {
                byte[] btResults = null;
                ApiParameters?.Clear();
                ApiParameters.Add("EquipmentID", filter.EquipmentID);
                ApiParameters.Add("Status", ((int)filter.Status) + "");
                ApiParameters.Add("DownStatus", ((int)filter.DownStatus) + "");
                List<string> auths = new List<string>();
                if (Utility.SystemRuntimeInfo.AuthValidate(Utility.SystemRuntimeInfo.DEVICE_OEM))
                    auths.Add("OEM");
                if (Utility.SystemRuntimeInfo.AuthValidate(Utility.SystemRuntimeInfo.DEVICE_KH))
                    auths.Add("KH");
                ApiParameters.Add("Auths", string.Join(",", auths));

                if (filter.StartTime.HasValue)
                {
                    ApiParameters.Add("StartTime", filter.StartTime.Value.ToString("yyyy-MM-dd hh:mm:ss"));
                }

                if (filter.EndTime.HasValue)
                {
                    ApiParameters.Add("EndTime", filter.EndTime.Value.ToString("yyyy-MM-dd hh:mm:ss"));
                }
                var Rtn = Utility.SfcBizService.CurrentSvc.Get_Maintenance_Xlsx_Datas(GetParameters(), out btResults);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }
                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                IList<MaintainOrderView> Datas = DTOHelper<MaintainOrderView>.DataTableToList(dsResults.Tables[0]);
                return Datas;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 设备维修单是否已提交
        /// </summary>
        /// <param name="FormID"></param>
        /// <returns></returns>
        public bool DataBeSubmit(int FormID)
        {
            try
            {
                bool BeSubmit = false;

                ApiParameters?.Clear();
                ApiParameters.Add("FormID", FormID + "");

                var Rtn = Utility.SfcBizService.CurrentSvc.Get_Maintenance_BeSubmit(GetParameters(), out BeSubmit);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }
                return BeSubmit;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 保养数据新增
        /// </summary>
        /// <param name="Entity"></param>
        /// <param name="AccessoriesItems"></param>
        /// <returns></returns>
        public APIResponseData Insert(DeviceRepair.Models.DeviceMaintenance.DeviceWarrantyRequestMaintaionInfo Entity, List<DeviceRepair.Models.DeviceWarrantyRequestAccessoriesInfo> AccessoriesItems, bool beSubmit = false)
        {
            try
            {
                ApiParameters?.Clear();
                ApiParameters.Add("IsSubmit", beSubmit + "");

                DataSet DataContent = new DataSet();
                DataTable table = (new List<DeviceRepair.Models.DeviceMaintenance.DeviceWarrantyRequestMaintaionInfo> { Entity }).ToDataTable();
                table.TableName = "Maintaion";

                DataTable table2 = AccessoriesItems.ToDataTable();
                table2.TableName = "Accessories";

                DataContent.Tables.Add(table);
                DataContent.Tables.Add(table2);

                var apiResponseData = Utility.SfcBizService.CurrentSvc.Insert_Maintenance_Data(GetParameters(), DataContent);
                if (apiResponseData.Code != 1)
                {
                    return new APIResponseData { Code = -1, Message = apiResponseData.Message };
                }

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

        /// <summary>
        /// 判断当前账户是否PE QE
        /// </summary>
        /// <returns></returns>
        public int CurrentIsManager()
        {
            try
            {
                ApiParameters?.Clear();
                ApiParameters.Add("UserCode", Utility.SystemRuntimeInfo.CurrentUser.UserCode);
                int PostType = -1;
                var Rtn = Utility.SfcBizService.CurrentSvc.Get_CurrentIsManager(GetParameters(), out PostType);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }
                return PostType;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 停机单 - 评估
        /// </summary>
        /// <param name="Evaluator"></param>
        /// <returns></returns>
        public APIResponseData DownFormAssessment(DeviceRepair.Models.DeviceWarrantyEvaluatorInfo Evaluator)
        {
            try
            {
                ApiParameters?.Clear();
                ApiParameters.Add("OPERATORNAME", Utility.SystemRuntimeInfo.CurrentUser.UserName);

                DataTable table = (new List<DeviceRepair.Models.DeviceWarrantyEvaluatorInfo> { Evaluator }).ToDataTable();

                var apiResponseData = Utility.SfcBizService.CurrentSvc.ADD_DownFormAssessment(GetParameters(), table);
                if (apiResponseData.Code != 1)
                {
                    return new APIResponseData { Code = -1, Message = apiResponseData.Message };
                }

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

        /// <summary>
        /// 生产部门 - 设备恢复确认
        /// </summary>
        /// <param name="AutoID"></param>
        /// <returns></returns>
        public APIResponseData DeviceResumptionComfirm(int AutoID)
        {
            try
            {
                ApiParameters?.Clear();
                ApiParameters.Add("AutoID", AutoID + "");
                ApiParameters.Add("OPERATORNAME", Utility.SystemRuntimeInfo.CurrentUser.UserName);

                var apiResponseData = Utility.SfcBizService.CurrentSvc.DeviceResumptionComfirm(GetParameters());
                if (apiResponseData.Code != 1)
                {
                    return new APIResponseData { Code = -1, Message = apiResponseData.Message };
                }

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

        /// <summary>
        /// 停机单新增
        /// </summary>
        /// <param name="Form"></param>
        /// <param name="AutoID"></param>
        /// <returns></returns>
        public APIResponseData ADD_DeviceDownForm_DATA(DeviceWarrantyRequestFormInfo Form, out int AutoID)
        {
            AutoID = 0;
            try
            {
                ApiParameters?.Clear();
                ApiParameters.Add("OPERATORNAME", Utility.SystemRuntimeInfo.CurrentUser.UserName);

                DataTable table = (new List<DeviceWarrantyRequestFormInfo> { Form }).ToDataTable();

                var apiResponseData = Utility.SfcBizService.CurrentSvc.ADD_DeviceDownForm_DATA(GetParameters(), table, out AutoID);
                if (apiResponseData.Code != 1)
                {
                    return new APIResponseData { Code = -1, Message = apiResponseData.Message };
                }

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

    }
}
