using Sln.Iot.Repository.dao;
using Sln.Iot.Serilog;
using SQLitePCL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sln.Iot.Repository.service
{
    /// <summary>
    /// 托盘绑定服务类
    /// </summary>
    public class TrayBindingService
    {
        private static readonly Lazy<TrayBindingService> lazy = new Lazy<TrayBindingService>(() => new TrayBindingService());

        public static TrayBindingService Instance
        {
            get
            {
                return lazy.Value;
            }
        }

        private SQLiteHelper<TrayRfidBinding> _helper = new SQLiteHelper<TrayRfidBinding>();

        private SerilogHelper _log = SerilogHelper.Instance;

        /// <summary>
        /// 获取托盘绑定的产品码
        /// </summary>
        /// <param name="trayCode"></param>
        /// <returns></returns>
        public string[] ProdCodeGet(string trayCode)
        {
            try
            {
                string[] res = _helper.Query(t => t.TrayCode == trayCode).Select(x => x.ProductionCode).ToArray();
                return res;
            }
            catch(Exception ex)
            {
                _log.Error("托盘绑定产品码获取错误", ex);
                return Array.Empty<string>();
            }
        }

        /// <summary>
        /// 获取托盘绑定的产品码(获取第一个)
        /// </summary>
        /// <param name="trayCode"></param>
        /// <returns></returns>
        public string TidGet()
        {
            try
            {
                var res = _helper.QuerySingle();
                if(res == null)
                {
                    return string.Empty;
                }
                return res.TransactionID ?? string.Empty;
            }
            catch(Exception ex)
            {
                _log.Error("托盘绑定产品码获取错误", ex);
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取托盘绑定的产品码
        /// </summary>
        /// <param name="trayCode"></param>
        /// <returns></returns>
        public string TidGet(string trayCode)
        {
            try
            {
                var res = _helper.Query(t => t.TrayCode == trayCode).FirstOrDefault();
                if (res == null)
                {
                    return string.Empty;
                }
                return res.TransactionID ?? string.Empty;
            }
            catch (Exception ex)
            {
                _log.Error("托盘绑定产品码获取错误", ex);
                return string.Empty;
            }
        }

        /// <summary>
        /// 绑定信息根据托盘号删除
        /// </summary>
        /// <returns></returns>
        public bool TrayCodeDelete(string trayCode)
        {
            try
            {
                int res = _helper.DeleteTrayRange(trayCode);
                return res != 0;
            }
            catch (Exception ex)
            {
                _log.Error("托盘码删除错误", ex);
                return false;
            }
        }

        /// <summary>
        /// 托盘二维码重新绑定
        /// </summary>
        /// <param name="trayCode">托盘码</param>
        /// <param name="prodCode">产品码</param>
        /// <returns></returns>
        public bool TrayBindingRefresh(Guid tid, string trayCode, string[] prodCode)
        {
            try
            {
                //先删除原来的
                _helper.DeleteTrayRange(trayCode);
                //再绑定（插入）新的
                var entities = new List<TrayRfidBinding>();
                foreach (string code in prodCode)
                {
                    if (string.IsNullOrWhiteSpace(code))
                    {
                        continue;
                    }
                    TrayRfidBinding entity = new TrayRfidBinding()
                    {
                        GUID = Guid.NewGuid().ToString("N"),
                        TrayCode = trayCode,
                        ProductionCode = code,
                        TransactionID = tid.ToString(),
                    };
                    entities.Add(entity);
                }
                if(entities.Count == 0 || entities == null)
                {
                    return false;
                }
                _helper.InsertRange(entities);
                return true;
            }
            catch (Exception ex)
            {
                _log.Error("托盘二维码重新绑定错误", ex);
                return false;
            }
        }

        /// <summary>
        /// 存储对应托盘码的时间节点
        /// </summary>
        /// <param name="timeString">时间字符串</param>
        /// <param name="trayCode">托盘码</param>
        /// <param name="timeCount">时间参数编号</param>
        /// <returns></returns>
        public bool UpDateTime(string timeString, string trayCode, string timeCount)
        {
            try
            {
                int res = _helper.SqlExcute($@"update TrayRfidBinding set time{timeCount} = '{timeString}' where TrayCode = '{trayCode}' ");
                if (res <= 0 || res > 6)
                {
                    return false;
                }
                return true;
            }
            catch (Exception ex)
            {
                _log.Error("时间更新错误", ex);
                return false;
            }
        }

        /// <summary>
        /// 获取一个时间
        /// </summary>
        /// <param name="trayCode"></param>
        /// <returns></returns>
        public string GetTime2ByTrayCode(string trayCode)
        {
            string time2 = string.Empty;
            try
            {
                var res = _helper.Query(t => t.TrayCode == trayCode).FirstOrDefault();
                if (res != null)
                {
                    time2 = res.Time2;
                }
                return time2;
            }
            catch (Exception ex)
            {
                _log.Error("根据托盘码获取time2错误", ex);
                return time2;
            }
        }

        /// <summary>
        /// 根据时间字段索引获取时间值
        /// </summary>
        public string GetTimeByTrayCode(string trayCode, string timeField)
        {
            try
            {
                var res = _helper.Query(t => t.TrayCode == trayCode).FirstOrDefault();
                if (res == null) return string.Empty;

                return timeField switch
                {
                    "1" => res.Time1 ?? string.Empty,
                    "2" => res.Time2 ?? string.Empty,
                    "3" => res.Time3 ?? string.Empty,
                    "4" => res.Time4 ?? string.Empty,
                    _ => string.Empty
                };
            }
            catch (Exception ex)
            {
                _log.Error($"根据托盘码获取time{timeField}错误", ex);
                return string.Empty;
            }
        }
    }
}
