using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Common;
using Domain;
using RCUHost.Protocols;
using Dao;
using System.Threading.Tasks;

namespace RCUHost.Implement
{
    /// <summary>
    /// RCU文字上报处理
    /// </summary>
    public class WordsReportReceiver : GenericReceiverBase
    {
        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(WordsReportReceiver));
        public IHostRepository HostRepository { get; set; }
        public IHostWordsReportRepository HostWordsReportRepository { get; set; }

        public override void Process(ReceiverContext context)
        {
            //AA 55 24 00 54 33 53 41 14 67 80 2E 04 01 24 13 00 00 00 02 0C 00 D1 EB CA D3 B2 C6 BE AD C6 B5 B5 C0 93 A1
            //AA552400543353411467802E04012413000000020C00D1EBCAD3B2C6BEADC6B5B5C093A1
            Reply(context);
            Host host = HostRepository.GetByHostNumber(context.SystemHeader.Value.HostNumber.ToString());
            if (host != null)
            {
                int offset = StructConverter.SizeOf(context.SystemHeader);
                int length = context.Data.Length - offset - 2;
                try
                {
                    //启动任务更新数据库
                    Task.Factory.StartNew(() =>
                    {
                        using (MemoryStream stream = new MemoryStream(context.Data, offset, length))
                        {
                            using (BinaryReader reader = new BinaryReader(stream))
                            {
                                string faultNo = new DeviceAddress(reader.ReadBytes(4)).ToString();//设备类型1、设备地址1、回路地址2
                                int wordType = reader.ReadByte();//文字类型：01客需服务，02电视控制，03RCU异常信息
                                int sentenceLength = Tools.ByteToInt(reader.ReadBytes(2));//文字长度
                                string sentence;
                                if (wordType == 3)
                                {
                                    sentence = Encoding.UTF8.GetString(reader.ReadBytes(sentenceLength));//文字内容
                                }
                                else
                                {
                                    sentence = Encoding.GetEncoding("gb2312").GetString(reader.ReadBytes(sentenceLength));//文字内容
                                }
                                HostWordsReportRepository.Save(new HostWordsReport()
                                {
                                    HostID = host.ID,
                                    HotelID = host.SysHotel.ID,
                                    ModalAddress = faultNo,
                                    Type = wordType,
                                    Sentence = sentence,
                                    CreatedDate = DateTime.Now
                                });
                                if (wordType == 2)//电视控制的时候上报给IPTV
                                {
                                    Common.TVOperation.ReportIPTV(host.SysHotel.TVControlToken, host.SysHotel.TVControlUrl, host.SysHotel.Code, host.RoomNumber, sentence);//推送给IPTV电视
                                }
                            }
                        }
                    }, System.Threading.CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
                }
                catch (Exception ex)
                {
                    logger.Error(string.Format("更新客房({0}:{1})文字服务出错。", host.SysHotel.Name, host.RoomNumber), ex);
                }
            }
        }

        public override CommandType CommandType
        {
            get { return CommandType.WordsReport; }
        }
    }
}
