
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Models;
using Nancy;
using SlnMesnac.Model.AirportApiEntity;
using SlnMesnac.Model.domain;
using SlnMesnac.Model.dto;
using SlnMesnac.Repository.service;
using SlnMesnac.Repository.service.@base;
using SlnMesnac.Rfid;
using SlnMesnac.Rfid.Factory;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using TouchSocket.Rpc;
using TouchSocket.WebApi;

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2024 WenJY 保留所有权利。
* CLR版本：4.0.30319.42000
* 机器名称：T14-GEN3-7895
* 命名空间：SlnMesnac.TouchSocket
* 唯一标识：649766cc-308e-4bf3-8d69-dea48ec40642
*
* 创建者：WenJY
* 电子邮箱：
* 创建时间：2024-09-04 10:51:54
* 版本：V1.0.0
* 描述：
*
*--------------------------------------------------------------------
* 修改人：
* 时间：
* 修改说明：
*
* 版本：V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.TouchSocket
{
    public class ApiServer: RpcServer
    {
        private ILogger<ApiServer> _logger;
        private List<RfidAbsractFactory> rfidAbsractFactory;
        private List<Base_sensor_info> base_Sensor_Infos;
        public static Action<string> _RefreshLogMessageAction;
        public static Action<string, string> RefreshStateEvent;
        private IReal_mesdataService _real_MesdataService;
        private IReal_workdataService _real_WorkdataService;

        public ApiServer(ILogger<ApiServer> logger, List<RfidAbsractFactory> rfidAbsractFactory, IReal_mesdataService real_MesdataService, IReal_workdataService real_WorkdataService)
        {
            _logger = logger;
            this.rfidAbsractFactory = rfidAbsractFactory;
            _real_MesdataService = real_MesdataService;
            _real_WorkdataService = real_WorkdataService;
        }
        /// <summary>
        /// 测试
        /// </summary>
        /// <param name="mesParaData"></param>
        /// <returns></returns>
        [WebApi(Method = HttpMethodType.POST)]
        public async Task<ApiResponse<MesParaData>> autoread()
        {

            return new ApiResponse<MesParaData>
            {
                Code = 200,
                Data = null,
                Msg = "sucess",
            };

        }
        /// <summary>
        /// 查询设备信息
        /// </summary>
        /// <param name="Requesttime"></param>
        /// <returns></returns>
        [WebApi(Method = HttpMethodType.POST)]
        public async Task<RFIDDeviceApiResponse<DeviceInfo>> basedata(string Requesttime)
        {
            List<DeviceInfo> rFIDDeviceInfos = _real_WorkdataService.GetDeviceInfos();
            return new RFIDDeviceApiResponse<DeviceInfo>
            {
                Code = 200,
                Data = rFIDDeviceInfos,
                Msg = "sucess",
            };

        }
        private bool iFlag = false;
        /// <summary>
        /// MES主动请求读取标签
        /// </summary>
        /// <param name="EQUID"></param>
        /// <param name="requesttime"></param>
        /// <returns></returns>
        [WebApi(Method = HttpMethodType.POST)]
        public async Task<ApiResponse<MesReadRespon>> read(MesReadPara mesReadPara)
        {
            ApiResponse<MesReadRespon> response = new ApiResponse<MesReadRespon>();
            int code = 400;
            string Msg = "error";
            MesReadRespon mesReadRespon = new MesReadRespon();
            try
            {
                if (iFlag)
                {
                    response = new ApiResponse<MesReadRespon>()
                    {
                        Code = code,
                        Data = mesReadRespon,
                        Msg = Msg,
                    };
                    return response;
                }
                // 设置标志位为 true，表示方法正在执行
                iFlag = true;
                _RefreshLogMessageAction?.Invoke("接收MES主动读取指令" + JsonSerializer.Serialize(mesReadPara));
                _logger.LogInformation("接收MES主动读取指令{0}", JsonSerializer.Serialize(mesReadPara));

                string FilterData = rfidAbsractFactory.Find(x => x.ConfigKey == mesReadPara.EQUID).FilterData;
                List<TagInfo> rfid = await rfidAbsractFactory.Find(x => x.ConfigKey == mesReadPara.EQUID).GetRFIDAsync();
                rfid = rfid.Where((x, i) => rfid.FindIndex(z => z.EPCstring == x.EPCstring) == i).ToList();
                //新增工位过滤
                if (!string.IsNullOrEmpty(FilterData))
                {
                    rfid = FilterByEPCString(rfid, FilterData);
                }
                if (rfid != null && rfid.Count > 0)
                {

                    if (rfid.Count > 1)
                    {
                        if (rfid != null && rfid.Any())
                        {
                            mesReadRespon.EPCID = string.Join(",", rfid.Select(item => item.EPCstring));
                            //mesReadRespon.EPCID = "MORE";
                            Msg = "multiple EPC";
                        }
                    }
                    else
                    {
                        mesReadRespon.EPCID = rfid[0].EPCstring;
                        code = 200;
                        Msg = "sucess";
                    }

                    mesReadRespon.Respontime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    Real_workdata real_Workdata = new Real_workdata()
                    {
                        Combineid = mesReadPara.EQUID.ToString(),
                        Data = mesReadRespon.EPCID,
                        Tm = DateTime.Now,
                        Deleteflag = 0,
                        Reportmode = 0,
                        Edittime = DateTime.Now,
                    };
                    await _real_WorkdataService.AddAsync(real_Workdata);

                }
                else
                {
                    Msg = "nodata";
                }
                response = new ApiResponse<MesReadRespon>()
                {
                    Code = code,
                    Data = mesReadRespon,
                    Msg = Msg,
                };
                _RefreshLogMessageAction?.Invoke("发送MES主动读取指令" + JsonSerializer.Serialize(response));
                _logger.LogInformation("发送MES主动读取指令{0}", JsonSerializer.Serialize(response));
                Real_mesdata real_Mesdata = new Real_mesdata()
                {
                    Combineid = mesReadPara.EQUID.ToString(),
                    Data = JsonSerializer.Serialize(mesReadPara),
                    Response = JsonSerializer.Serialize(response),
                    Reportmode = 0,
                    Edittime = DateTime.Now,
                    Tm = DateTime.Now,
                    Deleteflag = 0,
                };


                //InsertRealMesData(mesReadPara.EQUID.ToString(), JsonSerializer.Serialize(mesReadPara), JsonSerializer.Serialize(response), 0);
                RefreshStateEvent?.Invoke(mesReadPara.EQUID, mesReadRespon.EPCID);
                await _real_MesdataService.AddAsync(real_Mesdata);
                return response;
            }
            catch (Exception ex)
            {
                _logger.LogInformation("read接口异常" + ex.ToString());
                return response;
            }
            finally
            {
                iFlag = false;
            }
            
        }
        private static List<TagInfo> FilterByEPCString(List<TagInfo> tagList, string searchText)
        {
            return tagList
                .Where(tag => tag.EPCstring != null && tag.EPCstring.Contains(searchText))
                .ToList();
        }


        /// <summary>
        /// MES主动回复处理结果，控制报警灯
        /// </summary>
        /// <param name="EQUID"></param>
        /// <param name="requesttime"></param>
        /// <returns></returns>
        [WebApi(Method = HttpMethodType.POST)]
        public async Task<ApiResponse<MesParaData>> revresult(MesAlarmLightPara mesAlarmLightPara)
        {
            ApiResponse<MesParaData> response = new ApiResponse<MesParaData>();
            _RefreshLogMessageAction?.Invoke("接收MES控制报警灯指令" + JsonSerializer.Serialize(mesAlarmLightPara));

            _logger.LogInformation("接收MES控制报警灯指令{0}", JsonSerializer.Serialize(mesAlarmLightPara));

            if (mesAlarmLightPara.Code == "0")
            {
                mesAlarmLightPara.Code = "2";
            }
            else if (mesAlarmLightPara.Code == "1")
            {
                mesAlarmLightPara.Code = "3";
            }
            else
            {
                mesAlarmLightPara.Code = "1";
            }

            await rfidAbsractFactory.Find(x => x.ConfigKey == mesAlarmLightPara.EQUID).WriteAlarmLight(int.Parse(mesAlarmLightPara.Code),10000);
            //m_EquipClient.WriteAlarmLight(mesAlarmLightPara.EQUID, mesAlarmLightPara.Code);

            response = new ApiResponse<MesParaData>()
            {
                Code = 200,
                Data = null,
                Msg = "sucess",
            };
            _RefreshLogMessageAction?.Invoke("发送MES控制报警灯指令" + JsonSerializer.Serialize(response));
            _logger.LogInformation("发送MES控制报警灯指令{0}", JsonSerializer.Serialize(response));
            Real_mesdata real_Mesdata = new Real_mesdata()
            {
                Combineid = mesAlarmLightPara.EQUID.ToString(),
                Data = JsonSerializer.Serialize(mesAlarmLightPara),
                Response = JsonSerializer.Serialize(response),
                Reportmode = 1,
                Edittime = DateTime.Now,
                Tm = DateTime.Now,
                Deleteflag = 0,
            };
            await _real_MesdataService.AddAsync(real_Mesdata);
            //InsertRealMesData(mesAlarmLightPara.EQUID.ToString(), JsonSerializer.Serialize(mesAlarmLightPara), JsonSerializer.Serialize(response), 1);
            return response;
        }
    }

}
