using SlnMesnac.Common;
using SlnMesnac.Model.domain;
using SlnMesnac.Repository.service.ScanLog;
using SlnMesnac.TouchSocket;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Text;

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2024 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：T14-GEN3-7895
* 命名空间：SlnMesnac.Business
* 唯一标识：1a936e54-f672-4d86-b9bd-2747b75d4732
*
* 创建者：WenJY
* 电子邮箱：
* 创建时间：2024-09-19 9:49:11
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.Business
{
    public class TagScanBusiness
    {
        private ApiServer apiServer;
        private IScanLogService scanLogService;

        public delegate void RefreshTagScanInfo(ScanLogModel scanLogModel);
        public event RefreshTagScanInfo? RefreshTagScanInfoEvent;

        public delegate void RefreshDeviceAlarmMessage(string message);
        public event RefreshDeviceAlarmMessage? RefreshDeviceAlarmMessageEvent;

        public delegate void RefreshDeviceStatus(bool rfidFlag,bool camFlag);
        public event RefreshDeviceStatus? RefreshDeviceStatusEvent;


        public TagScanBusiness(ApiServer apiServer, IScanLogService scanLogService)
        {
            this.apiServer = apiServer;
            this.scanLogService = scanLogService;

            this.RefreshScanInfo();
        }

        /// <summary>
        /// 扫描信息刷新
        /// </summary>
        private void RefreshScanInfo()
        {
            //扫描记录刷新
            apiServer.ScanLogSocketAction += scan =>
            {
                RefreshTagScanInfoEvent?.Invoke(scan);
            };

            //告警状态刷新
            apiServer.ScanStatusSocketAction += info =>
            {
                if (info != null && info.is_alarm == 1)
                {
                    if (info.status_txt != null)
                    {
                        foreach (var item in info.status_txt)
                        {
                            RefreshDeviceAlarmMessageEvent?.Invoke(item);
                        }

                        List<string> rfidList = new List<string>();
                        List<string> camList = new List<string>();

                        foreach (string str in info.device_status)
                        {
                            if (str.Length == 2)
                            {
                                if(str != "00")
                                {
                                    int number;
                                    bool isNumber = int.TryParse(str, out number);
                                    if (isNumber && str[0] == '1')
                                    {
                                        camList.Add(str);
                                        continue;
                                    }
                                    rfidList.Add(str);
                                }
                            }
                        }

                        RefreshDeviceStatusEvent?.Invoke(rfidList.Count > 0 ? true : false, camList.Count > 0 ? true : false);
                        
                    }
                }
                else
                {
                    RefreshDeviceStatusEvent?.Invoke(false, false);
                }
            };
        }

        /// <summary>
        /// 查询扫描记录 
        /// </summary>
        /// <param name="rfidStr"></param>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <param name="result"></param>
        public void QuerySacnInfo(string rfidStr,DateTime beginTime,DateTime endTime,out List<ScanLogModel> result)
        {
            //var info = scanLogService.Query(x => x.CreateTime >= beginTime && x.CreateTime <= endTime);
            Expression<Func<ScanLogModel, bool>> exp = s1 => true;
            if(beginTime != null)
            {
                exp = exp.And(x => x.CreateTime >= beginTime.Date);
            }

            if (endTime != null)
            {
                exp = exp.And(x => x.CreateTime <= endTime.Date);
            }

            if (!string.IsNullOrEmpty(rfidStr))
            {
                exp = exp.And(x => x.Rfid == rfidStr);
            }
            var list = scanLogService.Query(exp);

            result = list.OrderByDescending(x => x.CreateTime).ToList();
        }

        /// <summary>
        /// 扫描合格率计算
        /// </summary>
        public double TagScanPassRate()
        {

            Expression<Func<ScanLogModel, bool>> exp = s1 => true;
            exp = exp.And(x => x.CreateTime >= DateTime.Now.Date && x.CreateTime <= DateTime.Now.AddDays(1).Date);
            var tagScanList = scanLogService.Query(exp);

            if (tagScanList.Count > 0)
            {
                var isOkList = tagScanList.Where(x => x.IsOk == "Ok").ToList();

                double passRate = ((double)isOkList.Count / (double)tagScanList.Count)*100;

                double result = Math.Round(passRate, 2);

                return result;
            }

            return 0;

        }

    }
}
