using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Logging;
using SlnMesnac.Config;
using SlnMesnac.Model.domain;
using SlnMesnac.Repository.service;
using SlnMesnac.Repository.service.LogImpl;
using SlnMesnac.Repository.service.ScanLog;
using TouchSocket.Core;
using TouchSocket.Http;
using TouchSocket.Rpc;
using TouchSocket.WebApi;

namespace SlnMesnac.TouchSocket
{
    public  class ApiServer : RpcServer
    {
        private readonly IScanLogService _scanService;

        private readonly IBaseCodeService _baseCodeService;

        private readonly IBaseLogService _baseLogService;
        
        public Action<ScanLogModel>? ScanLogSocketAction;
        public Action<ScanStatusSocket>? ScanStatusSocketAction;

        private ILogger<ApiServer> _logger;

        private AppConfig _appConfig;


        public ApiServer(IScanLogService scanService, IBaseCodeService baseCodeService, IBaseLogService baseLogService, ILogger<ApiServer> logger,AppConfig appConfig)
        {
            _scanService = scanService;
            _baseCodeService = baseCodeService;
            _baseLogService = baseLogService;
            _logger=logger;
            _appConfig=appConfig;
        }




        [EnableCors("cors")]
        [WebApi(HttpMethodType.POST)]

        public string Test(IWebApiCallContext callContext)
        {
            //http内容
            var httpContext = callContext.HttpContext;

            //http请求
            var request = httpContext.Request;

            var str = request.GetBody();

          
            _logger.LogInformation("测试body{Data}", str);
            return str;
        }

        [EnableCors("cors")]
        [WebApi(HttpMethodType.POST)]

        public Back Back(Hk hk)
        {
            Back ba=new Back();
            _logger.LogInformation("==========================");
            _logger.LogInformation("{Data}", hk.ToJsonString());
            _logger.LogInformation("==========================");
            if (hk.data_type == 1)
            {
                BaseLog log = new BaseLog();
                log.LogLevel = "Info";
                log.ErrMsg = "";
                log.Content = hk.ToJsonString();
                try
                {
                    //标签处理逻辑算法
                    FilterBuffer(ref hk, out string result);

                    //复制共享图像到指定路径
                    CopyImageWithDateFolder(hk.url, result,out string destinationImagePath);

                    string isOk = string.Empty;

                    if(result != "多条码" && result != "noread" && result != "NoRead" && !string.IsNullOrEmpty(result))
                    {
                        isOk = "Ok";
                    }else if(result == "多条码")
                    {
                        isOk = "Mul";
                    }else
                    {
                        isOk = "Ng";
                    }

                    ScanLogSocket scan = new ScanLogSocket()
                    {
                        code = hk.code,
                        data_type = hk.data_type,
                        ocr = hk.ocr,
                        rfid = hk.rfid,
                        timestamp = hk.timestamp,
                        url = destinationImagePath,
                        isOk = isOk,
                        result = result
                    };
                    ba = ScanBack(scan);

                }
                catch (Exception e)
                {
                    _logger.LogError(e, e.Message);
                    log.LogLevel = "Error";
                    log.ErrMsg = e.Message;
                }
                _baseLogService.Insert(log);

            }
            else
            {
                if (hk.data_type == 2)
                {
                    ScanStatusSocket scan = new ScanStatusSocket()
                    {
                       
                        data_type = hk.data_type,
                        is_alarm = hk.is_alarm,
                        device_status = hk.device_status,
                        timestamp = hk.timestamp,
                       
                    };
                    ba = ScanStatus(scan);

                }
            }

            return ba;
        }


        /// <summary>
        /// 扫描的状态回传
        /// </summary>
        /// <param name="scanStatus"></param>
        /// <returns></returns>
        [EnableCors("cors")]
        [WebApi(HttpMethodType.POST)]
        public Back ScanStatus(ScanStatusSocket scanStatus)
        {
            //_logger.LogInformation("扫描的状态接口");
            //_logger.LogInformation("{Data}",scanStatus.ToJsonString());
            BaseLog log = new BaseLog
            {
                LogLevel = "Info",
                ErrMsg = "",
                Content = scanStatus.ToJsonString()
            };
            try
            {
                if (scanStatus.is_alarm == 1 && scanStatus.device_status != null && scanStatus.device_status.Count > 0)
                {
                    List<string> ls = new List<string>();
                    var baseCodes = _baseCodeService.QuListCache();
                    foreach (var baseCode in scanStatus.device_status)
                    {
                        var enBaseCode = baseCodes.FirstOrDefault(x => x.Code == baseCode);
                        if (enBaseCode != null)
                        {
                            ls.Add(enBaseCode.State);
                        }
                    }
                    scanStatus.status_txt = ls;
                }

                ScanStatusSocketAction?.Invoke(scanStatus);
               
            }
            catch (Exception e)
            {
                _logger.LogError(e,e.Message);
                log.LogLevel = "Error";
                log.ErrMsg=e.Message;
            }

            Task.Run(() =>
            {
                lock (string.Empty)
                {
                    _baseLogService.Insert(log);
                }
            });

             return new Back();

        }


        /// <summary>
        /// 扫描数据回传接口
        /// </summary>
        /// <param name="scanLog"></param>
        /// <returns></returns>
        [EnableCors("cors")]
        [WebApi(HttpMethodType.POST)]
        public Back ScanBack(ScanLogSocket scanLog)
        {

            //_logger.LogInformation("扫描数据回传接口");
            //_logger.LogInformation("{Data}", scanLog.ToJsonString());

            var model = new ScanLogModel()
            {
                CreateTime = scanLog.CreateTime,
                DataType = scanLog.data_type,
                Code = scanLog.code,
                Rfid = scanLog.rfid,
                Ocr = scanLog.ocr,
                Url = scanLog.url,
                IsOk = scanLog.isOk,
                Result = scanLog.result
            };

            ScanLogSocketAction?.Invoke(model);
            _scanService.Insert(model);

            return new Back();

        }

        private const string bufferStart = "0C1104";
        private const string bufferBody = "EE5EFB65";

        /// <summary>
        /// RFID信息解析
        /// </summary>
        /// <param name="rfidStr"></param>
        private void AnasysBuffer(ref string rfidStr)
        {
            if(rfidStr != "noread")
            {
                string bufferHex = rfidStr.Substring(bufferStart.Length, bufferBody.Length);
                long decimalValue = Convert.ToInt64(bufferHex, 16);

                rfidStr = decimalValue.ToString();
            }

        }

        /// <summary>
        /// 标签处理逻辑算法
        /// </summary>
        /// <param name="hk"></param>
        /// <param name="result"></param>
        /// <exception cref="InvalidOperationException"></exception>
        private void FilterBuffer(ref Hk hk,out string result)
        {
            try
            {
                result = string.Empty;

                if (hk.rfid == "noread" || string.IsNullOrEmpty(hk.rfid))
                {
                    if (!string.IsNullOrEmpty(hk.code) && hk.code != "NoRead")
                    {
                        result = hk.code;

                    }
                    else
                    {
                        result = hk.rfid;
                    }
                }
                else
                {

                    string[] buffer = hk.rfid.Split(",");

                    if (buffer.Length > 1)
                    {
                        hk.rfid = "多条码";
                        
                    }
                    else
                    {
                        string rfidStr = hk.rfid;
                        if (!string.IsNullOrEmpty(hk.rfid))
                        {
                            AnasysBuffer(ref rfidStr);

                            hk.rfid = rfidStr;

                            
                        }
                    }

                    if (hk.rfid != hk.code && !string.IsNullOrEmpty(hk.code) && hk.code != "NoRead")
                    {
                        result = hk.code;
                    }
                    else
                    {
                        result = hk.rfid;
                    }
                }

                //处理ATR数据
                if (string.IsNullOrEmpty(hk.code) || hk.code == "NoRead")
                {
                    if (hk.rfid != "多条码" && hk.rfid != "noread")
                    {
                        result = hk.rfid;
                    }else
                    {
                        

                        if(hk.rfid == "多条码")
                        {
                            result = hk.rfid;
                        }
                        else
                        {
                            result = hk.code;
                        }
                    }
                }
                else
                {
                    string[] buffer = hk.code.Split(",");

                    if (buffer.Length > 1)
                    {
                        hk.code = "多条码";
                        
                    }

                    if (hk.rfid == hk.code && !string.IsNullOrEmpty(hk.rfid) && hk.rfid != "NoRead" && hk.rfid != "多条码")
                    {
                        result = hk.rfid;
                    }
                    else
                    {
                        result = hk.code;
                    }
                }

            }
            catch(Exception ex)
            {
               throw new InvalidOperationException($"标签处理逻辑异常:{ex.Message}");
            }
        }

        /// <summary>
        /// 将全景图像复制到指定路径下
        /// </summary>
        /// <param name="sourceImagePath"></param>
        /// <param name="fileName"></param>
        private void CopyImageWithDateFolder(string sourceImagePath,string fileName,out string destinationImagePath)
        {
            try
            {
                if (string.IsNullOrEmpty(sourceImagePath))
                {
                    throw new ArgumentNullException("全景图像路径为空");
                }

                if (string.IsNullOrEmpty(fileName))
                {
                    throw new ArgumentNullException("自定义全景图像文件名称为空");
                }

                string destinationBasePath = _appConfig.imagePath;

                DateTime now = DateTime.Now;
                string dateFolder = now.Year + "-" + now.Month + "-" + now.Day;

                string destinationFolder = Path.Combine(destinationBasePath, dateFolder);
                if (!Directory.Exists(destinationFolder))
                {
                    Directory.CreateDirectory(destinationFolder);

                    // 创建 ok、ng、mul 文件夹
                    string okFolder = Path.Combine(destinationFolder, "ok");
                    string ngFolder = Path.Combine(destinationFolder, "ng");
                    string mulFolder = Path.Combine(destinationFolder, "mul");
                    Directory.CreateDirectory(okFolder);
                    Directory.CreateDirectory(ngFolder);
                    Directory.CreateDirectory(mulFolder);
                }

                string sourceFileName = Path.GetFileName(sourceImagePath);
                string extension = Path.GetExtension(sourceImagePath);

                string newFileName = now.ToString("HHmmssfff") + "-" + fileName + extension;

                string subFolder = DetermineSubFolder(fileName);
                destinationImagePath = Path.Combine(destinationFolder, subFolder, newFileName);

                File.Copy(sourceImagePath, destinationImagePath, true);

                //File.Delete(sourceImagePath);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"将全景图像复制到指定路径处理异常:{ex.Message}");
            }
        }

        private string DetermineSubFolder(string fileName)
        {
            if (fileName.Contains("ead"))
            {
                return "ng";
            }
            else if (fileName.Contains("多条码"))
            {
                return "mul";
            }
            else
            {
                return "ok";
            }
        }
    }
}



public class Hk
{
    public DateTime CreateTime
    {
        get
        {
            DateTimeOffset dateTimeOffset = DateTimeOffset.FromUnixTimeMilliseconds(timestamp);
            return dateTimeOffset.UtcDateTime;
        }
    }

    public long timestamp { get; set; }

    public int data_type { get; set; }

    public string rfid { get; set; }

    public string code { get; set; }

    public string ocr { get; set; }

    public string url { get; set; }



    public int is_alarm { get; set; }

    public List<string> device_status { get; set; }


    public List<string> status_txt { get; set; }
}
