using System;
using System.Collections.Generic;
namespace BRServer
{
    public class BRTagHandler:TagHandler
    {
        public override bool isThisTag(Tag tag)
        {
            if (!(tag is UploadTag))
            {
                return false;
            }

            UploadTag uploadTag = tag as UploadTag;

            return uploadTag.BizType == 19 ? true : false;//业务类型       
        }

        public override void execute(Tag tag,String devCode,CellTag cellTag,
            SystemDateTag systemDateTag,CasicSession session)
        {
            //TODO LIST:解析数据，保存数据
            UploadTag BRTag = tag as UploadTag;
            int itv = BRTag.CollectInter;
            String collecTime = BRTag.CollectTime;
            int len = BRTag.Len;
            String dataValue = BRTag.DataValue;

            session.Logger.Info("北燃轨道阀回讯装置数据上传TAG：oid：" + BRTag.Oid + " 采集间隔: " +
                itv + " 采集时间：" + collecTime + " 上传数值：" + dataValue);

            int num = len / 8;
            List<Model.BR> djs = new List<Model.BR>();

            DateTime baseTime = Convert.ToDateTime(systemDateTag.CollectDate + " " + collecTime);
            for (int i = 0; i < num; i++)
            {
                Model.BR BRInfo = new Model.BR();
                float opening = strHexToSingle(dataValue.Substring(i * 8, 8));

                //TODO LIST:电池电量
                BRInfo.CELL = (cellTag == null ? "" : cellTag.Cell);
                BRInfo.OPENING = opening;
                BRInfo.LOGTIME = DateTime.Now;
                BRInfo.UPTIME = baseTime.AddMinutes(i * itv);
                BRInfo.DEVCODE = devCode;
                djs.Add(BRInfo);
            }

            BLL.BR.getInstance().insert(djs);
            session.Logger.Info("北燃轨道阀回讯装置数据保存成功");
        }

        //网络序列转int
        private float strHexToSingle(String src)
        {
            if (src.Length != 8)
                return 0;

            byte[] lBt ={
                                   byte.Parse(src.Substring(0,2),System.Globalization.NumberStyles.HexNumber),
                                   byte.Parse(src.Substring(2,2),System.Globalization.NumberStyles.HexNumber),
                                   byte.Parse(src.Substring(4,2),System.Globalization.NumberStyles.HexNumber),
                                   byte.Parse(src.Substring(6,2),System.Globalization.NumberStyles.HexNumber)                          
                               };
            return BitConverter.ToSingle(lBt, 0);
        }
    }
}
