using CatLib;
using Highway.Assemble.common;
using Highway.Assemble.Common;
using Highway.Assemble.EquipClient;
using Highway.Assemble.Sql;
using Highway.Assemble.SqlSugar.serviceImpl;
using log4net;
using Mesnac.DeviceAdapter;
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;
using static System.Windows.Forms.AxHost;

namespace HighWayAssemble.Protocol
{
    [Router("/[api]/[action]")]
    public class ApiServer : SingletonRpcServer
    {
        IEquipClient m_EquipClient = null;
        ISql Sql = null;
        public ApiServer()
        {
            m_EquipClient = App.Make<IEquipClient>();
            Sql = App.Make<ISql>(System.Configuration.ConfigurationManager.AppSettings["SqlString"]);
        }
        /// <summary>
        /// 测试
        /// </summary>
        /// <param name="mesParaData"></param>
        /// <returns></returns>
        [Router("/[action]")]
        [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<RFIDDeviceInfo>> basedata(string Requesttime)
        {
           List<RFIDDeviceInfo> rFIDDeviceInfos =  Sql.GetRFIDEquipList();
            return new RFIDDeviceApiResponse<RFIDDeviceInfo>
            {
                Code = 200,
                Data = rFIDDeviceInfos,
                Msg = "sucess",
            };

        }

        /// <summary>
        /// MES主动请求读取标签
        /// </summary>
        /// <param name="EQUID"></param>
        /// <param name="requesttime"></param>
        /// <returns></returns>
        [WebApi(Method = HttpMethodType.Post)]
        public async Task<ApiResponse<MesReadRespon>> readAsync(MesReadPara mesReadPara)
        {
            ApiResponse<MesReadRespon> response = new ApiResponse<MesReadRespon>();
            int code = 400;
            string Msg = "error";
            FrmDisplayView.LogInfo.InfoFormat("接收MES主动读取指令{0}", JsonSerializer.Serialize(mesReadPara));
            //FrmDisplayView.LogInfo.InfoFormat("接收MES主动读取指令{0},{1}",mesReadPara.EQUID ,mesReadPara.requesttime);
            MesReadRespon mesReadRespon = new MesReadRespon();
            List<TagInfo> rfid = m_EquipClient.ReadRFID(mesReadPara.EQUID);

            if (rfid != null && rfid.Count > 0)
            {
                if (rfid.Count > 1)
                {
                    if (rfid != null && rfid.Any())
                    {
                        mesReadRespon.EPCID = string.Join(",", rfid.Select(item => item.EPCstring));
                        Msg = "multiple EPC";
                    }
                }
                else
                {
                    mesReadRespon.EPCID = rfid[0].EPCstring;
                    code = 200;
                    Msg = "sucess";
                }
               
                mesReadRespon.Respontime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }
            else
            {
                Msg = "nodata";
            }
            response = new ApiResponse<MesReadRespon>()
            {
                Code = code,
                Data = mesReadRespon,
                Msg = Msg,
            };
            FrmDisplayView.LogInfo.InfoFormat("发送MES主动读取指令{0}", JsonSerializer.Serialize(response));
            InsertRealMesData(mesReadPara.EQUID.ToString(), JsonSerializer.Serialize(mesReadPara), JsonSerializer.Serialize(response), 0);
            return response;
            //return new ApiResponse<MesReadRespon>
            //{
            //    Code = code,
            //    Data = mesReadRespon,
            //    Msg = Msg,
            //};
        }


        /// <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>();

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

            //FrmDisplayView.LogInfo.InfoFormat("接收MES控制报警灯指令{0},{1},{2}", mesAlarmLightPara.EQUID, mesAlarmLightPara.Sendtime, mesAlarmLightPara.Code);

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

            m_EquipClient.WriteAlarmLight(mesAlarmLightPara.EQUID, mesAlarmLightPara.Code);

            response = new ApiResponse<MesParaData>()
            {
                Code = 200,
                Data = null,
                Msg = "sucess",
            };
            FrmDisplayView.LogInfo.InfoFormat("发送MES控制报警灯指令{0}", JsonSerializer.Serialize(response));
            InsertRealMesData(mesAlarmLightPara.EQUID.ToString(), JsonSerializer.Serialize(mesAlarmLightPara), JsonSerializer.Serialize(response), 1);
            return response;

            //return new ApiResponse<MesParaData>
            //{
            //    Code = 200,
            //    Data = null,
            //    Msg = "sucess",
            //};
        }
        public bool InsertRealMesData(string CombID, string data, string response, int type)
        {
            try
            {
                RealMesdata realWorkdata = new RealMesdata();
                realWorkdata.Combineid = CombID.ToString();
                realWorkdata.Data = data;
                realWorkdata.Response = response;
                realWorkdata.Reportmode = type;
                realWorkdata.Tm = DateTime.Now;
                realWorkdata.Edittime = DateTime.Now;
                realWorkdata.Deleteflag = 0;
                var MaterialTypeList = new BaseServices<RealMesdata>().Add1(realWorkdata);
                return true;
            }
            catch (Exception ex)
            {
                FrmDisplayView.LogInfo.Fatal("插入数据失败" + ex.ToString());
                return false;
            }
        }
    }
}
