using DeviceRepair.Models;
using DeviceRepair.Models.Tag;
using DeviceRepair.Utils;
using NLog;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TsSFCDevice.Client.Biz.Base.Service;
using TsSFCDevice.Client.Biz.Base.Utils;

namespace TsSFCDevice.Client.Biz.Impl
{
    public class TagRepository
    {
        private readonly Logger log;
        private static TagRepository 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 TagRepository Instance
        {
            get
            {
                if (manager == null)
                    manager = new TagRepository();
                return manager;
            }
        }

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

        internal string GetParameters(string cOperator = "", bool bFlag = true)
        {
            return ParametersObject.GetInstance(cOperator).GetJsonSerialized(m_ApiParameters);
        }

        public IList<TagRecordInfo> GetDatas(TagRecordFilter filter)
        {
            try
            {
                byte[] btResults = null;

                ApiParameters?.Clear();
                ApiParameters.Add("sDate", filter.sDate.ToString("yyyy-MM-dd HH:mm:ss"));
                ApiParameters.Add("eDate", filter.eDate.ToString("yyyy-MM-dd HH:mm:ss"));
                ApiParameters.Add("EquipmentDisPlayID", filter.EquipmentDisPlayID);
                ApiParameters.Add("TagFormStatus", filter.TagFormStatus);

                var Rtn = Utility.SfcBizService.CurrentSvc.GetDatas(DeviceSvc.SysModelType.Tag, GetParameters(), out btResults);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }

                DataSet dsResults = CompressionHelper.ExactDataSet(btResults);
                IList<TagRecordInfo> tags = DTOHelper<TagRecordInfo>.DataTableToList(dsResults.Tables[0]);

                if (tags != null && tags.Count > 0)
                {
                    // 此处去除掉没有权限操作的设备
                    int[] DevIds = Utility.SystemRuntimeInfo.CurrentDeviceCaches.Select(x => x.AutoID).ToArray();
                    tags = tags.Where(x => DevIds.Contains(x.EquipmentID)).ToList();
                }

                return tags;
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }


        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="tag"></param>
        /// <returns></returns>
        public APIResponseData Edit(TagRecordInfo tag, out TagRecordInfo tagRecordInfo)
        {
            try
            {
                ApiParameters?.Clear();
                ApiParameters.Add("OPERATORNAME", Utility.SystemRuntimeInfo.CurrentUser.UserName);

                DataTable dtData = null;
                var Rtn = Utility.SfcBizService.CurrentSvc.ADD_Tag_Data(GetParameters(), tag.toDataTable(), out dtData);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }

                tagRecordInfo = DTOHelper<TagRecordInfo>.DataTableToList(dtData)?.FirstOrDefault();
                return new APIResponseData { Code = 1, Message = Rtn.Message };
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }

        /// <summary>
        /// 接受/维修
        /// </summary>
        /// <param name="tag"></param>
        /// <returns></returns>
        public APIResponseData Receipt(TagRecordInfo tag, ApiOperationRtn OperationResult, out TagRecordInfo tagRecordInfo)
        {
            try
            {
                ApiParameters?.Clear();
                ApiParameters.Add("TagOperationDate", OperationResult.OperationDate.ToString("yyyy-MM-dd HH:mm:ss"));
                ApiParameters.Add("TagOperation", OperationResult.Operation + "");
                ApiParameters.Add("TagOperationName", OperationResult.OperationName);


                DataTable dtData = null;
                var Rtn = Utility.SfcBizService.CurrentSvc.Receipt_Tag_Data(GetParameters(), tag.toDataTable(), out dtData);
                if (Rtn.Code != 1)
                {
                    throw new Exception(Rtn.Message);
                }

                tagRecordInfo = DTOHelper<TagRecordInfo>.DataTableToList(dtData)?.FirstOrDefault();
                return new APIResponseData { Code = 1, Message = Rtn.Message };
            }
            catch (Exception ex)
            {
                log.Error(ex.Message, ex);
                throw ex;
            }
        }
    }
}
