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 = SQLiteHelper<TrayRfidBinding>.Instance;

        private SerilogHelper _log = SerilogHelper.Instance;

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