HDL Home App 第二版本 旧平台金堂用 正在使用
chenqiyang
2022-06-22 dc0309e64f02227d8e1468b7326c07955f804612
ZigbeeApp/Shared/Phone/UserCenter/CommonBase/Logic/HdlSafeguardLogic.cs
old mode 100755 new mode 100644
@@ -1,2366 +1,2406 @@
using Newtonsoft.Json;
using Shared.Common;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using ZigBee.Device;
namespace Shared.Phone.UserCenter
{
    /// <summary>
    /// <para>安防本地缓存(代码使用)</para>
    /// <para>防区ID(ZoneId):</para>
    /// <para>1:24小时防区  2:24小时静音防区  3:出入防区  4:内部防区  5:周界防区</para>
    /// <para>防区模式ID(ActionType -> 防区ID换算:ZoneId=3,4,5都当做3处理):</para>
    /// <para>1:24小时防区  2:静音防区  3:其他防区(出入防区、内部防区、周界防区)</para>
    /// <para>布防模式ID(GarrisonMode):</para>
    /// <para>1:在家布防 或者 布防(内部防区没有设置的时候)  2:离家布防</para>
    /// </summary>
    public class HdlSafeguardLogic
    {
        #region ■ 变量声明___________________________
        /// <summary>
        /// 本地安防数据
        /// </summary>
        private static HdlSafeguardLogic m_Current = null;
        /// <summary>
        /// 本地安防数据
        /// </summary>
        public static HdlSafeguardLogic Current
        {
            get
            {
                if (m_Current == null)
                {
                    m_Current = new HdlSafeguardLogic();
                }
                return m_Current;
            }
            set
            {
                m_Current = value;
            }
        }
        /// <summary>
        /// 当前的布防模式(注意,这个东西只给安防主界面初始化的时候使用!!)
        /// </summary>
        public GarrisonMode NowGarrisonMode = GarrisonMode.None;
        /// <summary>
        /// 用户密码的缓存
        /// </summary>
        private string UserPassword = null;
        /// <summary>
        /// 安防数据缓存
        /// </summary>
        private Dictionary<int, SafeguardZoneInfo> dicAllZoneInfo = new Dictionary<int, SafeguardZoneInfo>();
        #endregion
        #region ■ 刷新安防___________________________
        /// <summary>
        /// 从新从网关那里获取数据(失败时会弹出信息框)
        /// </summary>
        /// <returns></returns>
        public async Task<bool> ReFreshByGateway()
        {
            //先清空
            this.dicAllZoneInfo.Clear();
            var mainGateway = ZbGateway.MainGateWay;
            if (mainGateway == null)
            {
                //错误:网关对象丢失
                string msg = Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg);
                this.ShowTipMsg(msg);
                return false;
            }
            var mainWayId = HdlGatewayLogic.Current.GetGatewayId(mainGateway);
            //主题数固定5+3+1
            int topicCount = 9;
            //错误
            bool error = false;
            //防区设备信息
            var listDevice = new List<Safeguard.GetZoneDeviceListByIdResponData>();
            //报警目标
            var listAlarm = new List<Safeguard.CatZoneActionResponseData>();
            //安防模式
            var listMode = new List<Safeguard.GetModeUsingResponseData>();
            Action<string, string> action = (topic, message) =>
            {
                var gatewayID = topic.Split('/')[0];
                if (gatewayID != mainWayId)
                {
                    return;
                }
                //检测共通错误
                if (topic == gatewayID + "/" + "Error_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                    if (temp != null)
                    {
                        string msg = HdlCheckLogic.Current.CheckCommonErrorCode(temp.Error);
                        if (msg != null)
                        {
                            this.ShowTipMsg(msg);
                        }
                    }
                    error = true;
                }
                //防区设备信息
                if (topic == gatewayID + "/Security/GetZoneDeviceList_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    var result = JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString());
                    if (result == 0)
                    {
                        var data = JsonConvert.DeserializeObject<Safeguard.GetZoneDeviceListByIdResponData>(jobject["Data"].ToString());
                        if (data != null)
                        {
                            //将防区传感器设备列表加入缓存
                            listDevice.Add(data);
                            topicCount--;
                            return;
                        }
                    }
                    error = true;
                }
                //防区报警目标
                if (topic == gatewayID + "/Security/GetZoneAction_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    var result = JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString());
                    if (result == 0)
                    {
                        var data = JsonConvert.DeserializeObject<Safeguard.CatZoneActionResponseData>(jobject["Data"].ToString());
                        if (data != null)
                        {
                            //将防区报警目标加入缓存
                            listAlarm.Add(data);
                            topicCount--;
                            return;
                        }
                    }
                    error = true;
                }
                //当前布防模式
                if (topic == gatewayID + "/Security/GetCurrentMode_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    var result = JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString());
                    if (result != 0)
                    {
                        //当前没有模仿模式
                        this.NowGarrisonMode = GarrisonMode.None;
                    }
                    else
                    {
                        var data = JsonConvert.DeserializeObject<Safeguard.GetModeUsingResponseData>(jobject["Data"].ToString());
                        if (data != null)
                        {
                            //设置当前模仿模式
                            this.NowGarrisonMode = (GarrisonMode)data.ModeId;
                        }
                    }
                    topicCount--;
                }
            };
            mainGateway.Actions += action;
            try
            {
                var jObject = new Newtonsoft.Json.Linq.JObject() { { "Cluster_ID", 0 }, { "Command", 4036 } };
                mainGateway.Send("Security/GetSecurityInfo", jObject.ToString());
            }
            catch { }
            var dateTime = DateTime.Now;
            while ((DateTime.Now - dateTime).TotalMilliseconds < 3000)
            {
                if (topicCount <= 0 || error == true)
                {
                    //9次主题全部接收完成
                    break;
                }
                await Task.Delay(50);
            }
            mainGateway.Actions -= action;
            if (topicCount > 0)
            {
                //获取防区信息失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetSafetyInfoFail);
                this.ShowTipMsg(msg);
                return false;
            }
            //将防区传感器设备列表加入缓存
            foreach (var data in listDevice)
            {
                this.SetZoneSensorDeviceToMemory(data);
            }
            //将防区报警目标加入缓存
            foreach (var data in listAlarm)
            {
                this.SetAlarmTargetDeviceToMemory(data);
            }
            return true;
        }
        /// <summary>
        /// 将防区设备(传感器)列表加入缓存
        /// </summary>
        /// <param name="allData">防区数据</param>
        private void SetZoneSensorDeviceToMemory(Safeguard.GetZoneDeviceListByIdResponData allData)
        {
            if (this.dicAllZoneInfo.ContainsKey(allData.ZoneId) == false)
            {
                this.dicAllZoneInfo[allData.ZoneId] = new SafeguardZoneInfo();
            }
            //设置基本信息
            SafeguardZoneInfo zoneInfo = this.dicAllZoneInfo[allData.ZoneId];
            zoneInfo.ZoneId = allData.ZoneId;
            zoneInfo.ZoneName = allData.ZoneName;
            //处理设备
            foreach (var data2 in allData.DeviceList)
            {
                string mainKey = LocalDevice.Current.GetDeviceMainKeys(data2.MacAddr, data2.Epoint);
                //传感器设备信息
                var Deviceinfo = new Safeguard.ZoneDeviceListData();
                Deviceinfo.IsBypass = data2.IsBypass;
                Deviceinfo.MomentStatus = data2.MomentStatus;
                Deviceinfo.TriggerZoneStatus = data2.TriggerZoneStatus;
                Deviceinfo.MacAddr = data2.MacAddr;
                Deviceinfo.Epoint = data2.Epoint;
                zoneInfo.dicSensor[mainKey] = Deviceinfo;
                //本地是否有这个设备
                CommonDevice device = LocalDevice.Current.GetDevice(mainKey);
                if (device != null)
                {
                    //全部设备
                    zoneInfo.dicAllDevice[mainKey] = device.FilePath;
                }
                else
                {
                    //全部设备(缺失的未知设备)
                    var tempDevice = new CommonDevice();
                    tempDevice.DeviceAddr = data2.MacAddr;
                    tempDevice.DeviceEpoint = data2.Epoint;
                    zoneInfo.dicAllDevice[mainKey] = tempDevice.FilePath;
                }
            }
        }
        /// <summary>
        /// 将报警目标列表加入缓存
        /// </summary>
        /// <param name="resData">
        /// <para>1:24小时防区触发动作</para>
        /// <para>2:24小时静音防区触发动作</para>
        /// <para>3:其他防区(出入防区、内部防区、周界防区)触发动作</para>
        /// </param>
        /// <param name="mode">是否显示错误</param>
        /// <returns></returns>
        private void SetAlarmTargetDeviceToMemory(Safeguard.CatZoneActionResponseData resData, ShowErrorMode mode = ShowErrorMode.NO)
        {
            int ActionType = resData.ActionType;
            if (this.dicAllZoneInfo.ContainsKey(ActionType) == false)
            {
                this.dicAllZoneInfo[ActionType] = new SafeguardZoneInfo();
                //设置基本信息
                this.dicAllZoneInfo[ActionType].ZoneId = ActionType;
            }
            SafeguardZoneInfo zoneInfo = this.dicAllZoneInfo[ActionType];
            zoneInfo.dicAlarmDevice.Clear();
            zoneInfo.dicScenes.Clear();
            //信息推送
            zoneInfo.InformationPush = resData.IsDisablePushMessage;
            foreach (var data in resData.Actions)
            {
                //设备
                if (data.Type == 0)
                {
                    //本地是否有这个设备
                    string mainKey = LocalDevice.Current.GetDeviceMainKeys(data.DeviceAddr, data.Epoint);
                    //报警信息
                    zoneInfo.dicAlarmDevice[mainKey] = data;
                    CommonDevice device = LocalDevice.Current.GetDevice(mainKey);
                    if (device != null)
                    {
                        //全部设备
                        zoneInfo.dicAllDevice[mainKey] = device.FilePath;
                    }
                    else
                    {
                        //全部设备(缺失的未知设备)
                        var tempDevice = new CommonDevice();
                        tempDevice.DeviceAddr = data.DeviceAddr;
                        tempDevice.DeviceEpoint = data.Epoint;
                        zoneInfo.dicAllDevice[mainKey] = tempDevice.FilePath;
                    }
                }
                //场景
                else if (data.Type == 1)
                {
                    //场景
                    zoneInfo.dicScenes[data.ScenesId] = data.ESName;
                }
            }
        }
        #endregion
        #region ■ 获取设备___________________________
        /// <summary>
        /// 获取指定防区的所有传感器设备的信息
        /// </summary>
        /// <param name="zoonId">防区ID(它似乎是唯一主键)</param>
        /// <returns></returns>
        public List<Safeguard.ZoneDeviceListData> GetSensorDevicesInfoByZoonID(int zoonId)
        {
            var list = new List<Safeguard.ZoneDeviceListData>();
            if (this.dicAllZoneInfo.ContainsKey(zoonId) == false)
            {
                return list;
            }
            SafeguardZoneInfo info = this.dicAllZoneInfo[zoonId];
            foreach (var data in info.dicSensor.Values)
            {
                list.Add(data);
            }
            return list;
        }
        /// <summary>
        /// 获取全部的传感器设备的信息(按防区分组)
        /// </summary>
        /// <returns></returns>
        public Dictionary<int, List<Safeguard.ZoneDeviceListData>> GetAllSensorDeviceInfo()
        {
            var dic = new Dictionary<int, List<Safeguard.ZoneDeviceListData>>();
            foreach (int ZoonId in this.dicAllZoneInfo.Keys)
            {
                List<Safeguard.ZoneDeviceListData> list = this.GetSensorDevicesInfoByZoonID(ZoonId);
                if (list.Count > 0)
                {
                    dic[ZoonId] = list;
                }
            }
            return dic;
        }
        /// <summary>
        /// 根据防区ID获取本地报警目标
        /// </summary>
        /// <param name="ZoneId">防区ID</param>
        /// <returns></returns>
        public List<Safeguard.CatActionResponseObj> GetLocalAlarmTargetInfoByZoneId(int ZoneId)
        {
            if (ZoneId > 3)
            {
                ZoneId = 3;
            }
            if (this.dicAllZoneInfo.ContainsKey(ZoneId) == false)
            {
                return new List<Safeguard.CatActionResponseObj>();
            }
            SafeguardZoneInfo zoneInfo = this.dicAllZoneInfo[ZoneId];
            //优先场景吧
            var list = new List<Safeguard.CatActionResponseObj>();
            foreach (int sceneId in zoneInfo.dicScenes.Keys)
            {
                var objData = new Safeguard.CatActionResponseObj();
                objData.Type = 1;
                objData.ScenesId = sceneId;
                objData.ESName = zoneInfo.dicScenes[sceneId];
                list.Add(objData);
            }
            foreach (var data in zoneInfo.dicAlarmDevice.Values)
            {
                list.Add(data);
            }
            return list;
        }
        /// <summary>
        /// 获取指定传感器所处的防区ID(不存在则返回-1)
        /// </summary>
        /// <param name="device">指定传感器设备</param>
        /// <returns></returns>
        public int GetZoneIdByIASZone(CommonDevice device)
        {
            string mainkey = this.GetDeviceMainKeys(device);
            foreach (SafeguardZoneInfo info in this.dicAllZoneInfo.Values)
            {
                if (info.dicSensor.ContainsKey(mainkey) == true)
                {
                    return info.ZoneId;
                }
            }
            return -1;
        }
        #endregion
        #region ■ 添加传感器_________________________
        /// <summary>
        /// 添加传感器设备到防区(失败时会弹出信息框)
        /// </summary>
        /// <param name="zoonId">防区ID(它似乎是唯一主键)</param>
        /// <param name="listdevice">设备列表</param>
        public async Task<bool> AddSensorDevice(int zoonId, List<CommonDevice> listdevice)
        {
            //现获取当前的布防模式
            var safetyMode = await this.GetSafetyMode();
            if (safetyMode != null)
            {
                //当前正处于布防模式,无法添加设备
                string msg = Language.StringByID(R.MyInternationalizationString.uCanNotAddDeviceInGarrisonMode);
                this.ShowErrorMsg(msg);
                return false;
            }
            //校验密码
            bool result = await this.ShowSafetyAdminValidatedDialog();
            if (result == false)
            {
                return false;
            }
            if (listdevice.Count == 0)
            {
                return true;
            }
            List<int> listMomentStatus = new List<int>();
            List<int> listTriggerStatus = new List<int>();
            foreach (var device in listdevice)
            {
                int MomentStatus = 1;
                int TriggerZoneStatus = 1;
                //获取安防传感器的瞬间状态设定值
                this.GetSafeguardSensorMomentStatus(device, ref MomentStatus, ref TriggerZoneStatus);
                listMomentStatus.Add(MomentStatus);
                listTriggerStatus.Add(TriggerZoneStatus);
            }
            //添加设备到网关
            List<string> listSuccess = await this.AddSensorDeviceToGateway(zoonId, listdevice, listMomentStatus, listTriggerStatus);
            if (listSuccess == null)
            {
                return false;
            }
            //修改缓存
            if (this.dicAllZoneInfo.ContainsKey(zoonId) == false)
            {
                this.dicAllZoneInfo[zoonId] = new SafeguardZoneInfo();
            }
            SafeguardZoneInfo info = this.dicAllZoneInfo[zoonId];
            for (int i = 0; i < listdevice.Count; i++)
            {
                CommonDevice device = listdevice[i];
                string mainkey = this.GetDeviceMainKeys(device);
                if (listSuccess.Contains(mainkey) == false)
                {
                    //没有添加成功
                    continue;
                }
                Safeguard.ZoneDeviceListData sensorInfo = null;
                if (info.dicSensor.ContainsKey(mainkey) == true)
                {
                    sensorInfo = info.dicSensor[mainkey];
                }
                else
                {
                    sensorInfo = new Safeguard.ZoneDeviceListData();
                    info.dicSensor[mainkey] = sensorInfo;
                    sensorInfo.Epoint = device.DeviceEpoint;
                    sensorInfo.MacAddr = device.DeviceAddr;
                    sensorInfo.IsBypass = 0;
                }
                info.dicAllDevice[mainkey] = device.FilePath;
                //设备信息
                sensorInfo.MomentStatus = listMomentStatus[0];
                sensorInfo.TriggerZoneStatus = listTriggerStatus[0];
            }
            return true;
        }
        /// <summary>
        /// 添加传感器设备到网关(失败时会弹出信息框)
        /// </summary>
        /// <param name="zoonId">防区ID(它似乎是唯一主键)</param>
        /// <param name="listdevice">设备列表</param>
        /// <param name="listMomentStatus">设备上报的状态是否为瞬间状态</param>
        /// <param name="listTriggerStatus">我也不知道这个是什么东西</param>
        /// <returns></returns>
        private async Task<List<string>> AddSensorDeviceToGateway(int zoonId, List<CommonDevice> listdevice, List<int> listMomentStatus, List<int> listTriggerStatus)
        {
            var addData = new Safeguard.AddDeviceToZoneData();
            addData.ZoneId = zoonId;
            addData.LoginToken = this.GetLoginToken();
            for (int i = 0; i < listdevice.Count; i++)
            {
                CommonDevice device = listdevice[i];
                //数据组装
                var deviceData = new Safeguard.DeviceListObj();
                deviceData.Epoint = device.DeviceEpoint;
                deviceData.MacAddr = device.DeviceAddr;
                deviceData.MomentStatus = listMomentStatus[i];
                deviceData.TriggerZoneStatus = listTriggerStatus[i];
                addData.DeviceList.Add(deviceData);
            }
            //没有数据
            if (addData.DeviceList.Count == 0)
            {
                return new List<string>();
            }
            //添加到网关
            var returnData = await Safeguard.AddDeviceToZoneAsync(addData);
            if (returnData == null || returnData.addDeviceToPartResponseData == null || returnData.addDeviceToPartResponseData.Result == 1)
            {
                //向防区添加设备失败
                string msg = Language.StringByID(R.MyInternationalizationString.uAddDeviceToZoneFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, returnData);
                this.ShowErrorMsg(msg);
                return null;
            }
            List<string> listSuccess = new List<string>();
            foreach (var data in returnData.addDeviceToPartResponseData.DeviceList)
            {
                //一批设备里面,成功添加的
                if (data.Status == 0)
                {
                    listSuccess.Add(LocalDevice.Current.GetDeviceMainKeys(data.MacAddr, data.Epoint));
                }
                else if (data.Status == 1)
                {
                    var device = Common.LocalDevice.Current.GetDevice(data.MacAddr, data.Epoint);
                    string msg = Common.LocalDevice.Current.GetDeviceEpointName(device) + "\r\n";
                    //目标设备不存在
                    msg += Language.StringByID(R.MyInternationalizationString.uTargetDeviceIsNotExsit);
                    this.ShowTipMsg(msg);
                }
                else if (data.Status == 2)
                {
                    var device = Common.LocalDevice.Current.GetDevice(data.MacAddr, data.Epoint);
                    string msg = Common.LocalDevice.Current.GetDeviceEpointName(device) + "\r\n";
                    //设备已加入其它防区
                    msg += Language.StringByID(R.MyInternationalizationString.uDeviceHadAddToTheOtherGarrison);
                    this.ShowTipMsg(msg);
                }
            }
            return listSuccess;
        }
        /// <summary>
        /// 获取安防传感器的瞬间状态设定值(添加传感器到安防时,需要调用此方法来初始化参数)
        /// </summary>
        /// <param name="device">设备对象</param>
        /// <param name="MomentStatus">设备上报的状态是否为瞬间状态</param>
        /// <param name="TriggerZoneStatus">我也不知道这个是什么东西</param>
        public void GetSafeguardSensorMomentStatus(CommonDevice device, ref int MomentStatus, ref int TriggerZoneStatus)
        {
            //运动传感器
            if (device.IasDeviceType == 13)
            {
                MomentStatus = 1;
                TriggerZoneStatus = 1;
            }
            //烟雾传感器
            else if (device.IasDeviceType == 40)
            {
                MomentStatus = 1;
                TriggerZoneStatus = 1;
            }
            //水侵传感器
            else if (device.IasDeviceType == 42)
            {
                MomentStatus = 1;
                TriggerZoneStatus = 1;
            }
            //燃气传感器
            else if (device.IasDeviceType == 43)
            {
                MomentStatus = 1;
                TriggerZoneStatus = 1;
            }
            //紧急按钮
            else if (device.IasDeviceType == 44)
            {
                MomentStatus = 1;
                TriggerZoneStatus = 1;
            }
            //钥匙扣
            else if (device.IasDeviceType == 277)
            {
                MomentStatus = 1;
                TriggerZoneStatus = 1;
            }
            //门窗传感器
            else if (device.IasDeviceType == 21 || device.IasDeviceType == 22)
            {
                MomentStatus = 0;
                TriggerZoneStatus = 1;
            }
            //如果是虚拟设备,则这个东西永恒为0
            if (device.DriveCode > 0)
            {
                MomentStatus = 0;
            }
        }
        #endregion
        #region ■ 删除设备___________________________
        /// <summary>
        /// 删除传感器设备
        /// </summary>
        /// <param name="zoonId">防区ID(它似乎是唯一主键)</param>
        /// <param name="listdevice">传感器设备对象</param>
        public async Task<bool> DeleteSensorDevice(int zoonId, List<CommonDevice> listdevice)
        {
            //现获取当前的布防模式
            var safetyMode = await this.GetSafetyMode();
            if (safetyMode != null)
            {
                //当前正处于布防模式,无法删除设备
                string msg = Language.StringByID(R.MyInternationalizationString.uCanNotDeleteDeviceInGarrisonMode);
                this.ShowErrorMsg(msg);
                return false;
            }
            //校验密码
            bool result = await this.ShowSafetyAdminValidatedDialog();
            if (result == false)
            {
                return false;
            }
            if (listdevice.Count == 0)
            {
                return true;
            }
            //从网关那里删除设备
            List<string> listKeys = await this.DeleteSensorDeviceFromGateway(zoonId, listdevice);
            if (listKeys == null)
            {
                return false;
            }
            //修改缓存
            if (this.dicAllZoneInfo.ContainsKey(zoonId) == false)
            {
                return true;
            }
            SafeguardZoneInfo info = this.dicAllZoneInfo[zoonId];
            foreach (CommonDevice device in listdevice)
            {
                string mainkey = this.GetDeviceMainKeys(device);
                if (info.dicSensor.ContainsKey(mainkey) == true
                    && listKeys.Contains(mainkey) == true)
                {
                    info.dicSensor.Remove(mainkey);
                    info.dicAllDevice.Remove(mainkey);
                }
            }
            return true;
        }
        /// <summary>
        /// 从网关那里删除传感器设备
        /// </summary>
        /// <param name="zoonId">防区ID(它似乎是唯一主键)</param>
        /// <param name="listdevice">设备对象</param>
        /// <returns></returns>
        private async Task<List<string>> DeleteSensorDeviceFromGateway(int zoonId, List<CommonDevice> listdevice)
        {
            var deteleData = new Safeguard.RemoveEqToZoneData();
            deteleData.ZoneId = zoonId;
            deteleData.LoginToken = this.GetLoginToken();
            foreach (CommonDevice device in listdevice)
            {
                //组装数据
                var removeData = new Safeguard.RemoveDeviceListObj();
                removeData.MacAddr = device.DeviceAddr;
                removeData.Epoint = device.DeviceEpoint;
                deteleData.RemoveDeviceList.Add(removeData);
            }
            //没有数据
            if (deteleData.RemoveDeviceList.Count == 0)
            {
                return new List<string>();
            }
            //从网关中移除
            var returnData = await Safeguard.RemoveDeviceToZoneAsync(deteleData);
            if (returnData == null || returnData.removeDeviceToZoneResponseData == null || returnData.removeDeviceToZoneResponseData.Result == 1)
            {
                //设备删除失败
                string msg = Language.StringByID(R.MyInternationalizationString.uDeviceDeleteFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, returnData);
                this.ShowErrorMsg(msg);
                return null;
            }
            List<string> listKeys = new List<string>();
            foreach (var data in returnData.removeDeviceToZoneResponseData.RemoveDeviceList)
            {
                if (data.Status == 0)
                {
                    listKeys.Add(LocalDevice.Current.GetDeviceMainKeys(data.MacAddr, data.Epoint));
                }
            }
            return listKeys;
        }
        #endregion
        #region ■ 存在检测___________________________
        /// <summary>
        /// 指定传感器设备是否存在于安防网关
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        public bool IsSensorDeviceExist(CommonDevice device)
        {
            string mainkey = this.GetDeviceMainKeys(device);
            foreach (SafeguardZoneInfo info in this.dicAllZoneInfo.Values)
            {
                if (info.dicSensor.ContainsKey(mainkey) == true)
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 指定传感器设备是否存在于安防网关
        /// </summary>
        /// <param name="ZoneId">防区ID</param>
        /// <param name="device"></param>
        /// <returns></returns>
        public bool IsSensorDeviceExist(int ZoneId, CommonDevice device)
        {
            if (this.dicAllZoneInfo.ContainsKey(ZoneId) == false)
            {
                return false;
            }
            string mainkey = this.GetDeviceMainKeys(device);
            SafeguardZoneInfo info = this.dicAllZoneInfo[ZoneId];
            if (info.dicSensor.ContainsKey(mainkey) == true)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 指定报警设备是否存在于安防网关
        /// </summary>
        /// <param name="ZoneId">防区ID</param>
        /// <param name="device"></param>
        /// <returns></returns>
        public bool IsAlarmDeviceExist(int ZoneId, CommonDevice device)
        {
            if (ZoneId < 3)
            {
                if (this.dicAllZoneInfo.ContainsKey(ZoneId) == false)
                {
                    return false;
                }
                string mainkey = this.GetDeviceMainKeys(device);
                SafeguardZoneInfo info = this.dicAllZoneInfo[ZoneId];
                if (info.dicAlarmDevice.ContainsKey(mainkey) == true)
                {
                    return true;
                }
            }
            else
            {
                string mainkey = this.GetDeviceMainKeys(device);
                for (int i = 3; i <= 5; i++)
                {
                    if (this.dicAllZoneInfo.ContainsKey(i) == false)
                    {
                        continue;
                    }
                    SafeguardZoneInfo info = this.dicAllZoneInfo[i];
                    if (info.dicAlarmDevice.ContainsKey(mainkey) == true)
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        /// <summary>
        /// 指定布防是否存在于安防网关
        /// </summary>
        /// <param name="zoonId">防区ID(它似乎是唯一主键)</param>
        /// <returns></returns>
        public bool IsZoonExist(int zoonId)
        {
            return this.dicAllZoneInfo.ContainsKey(zoonId);
        }
        /// <summary>
        /// 是否设置有内部防区
        /// </summary>
        /// <returns></returns>
        public bool IsHadInternalDefenseArea()
        {
            foreach (SafeguardZoneInfo info in this.dicAllZoneInfo.Values)
            {
                //存在第四防区
                if (info.ZoneId == 4)
                {
                    //里面有没有设备
                    if (info.dicSensor.Count > 0)
                    {
                        return true;
                    }
                    //不再往下循环
                    return false;
                }
            }
            return false;
        }
        #endregion
        #region ■ 安防登陆___________________________
        /// <summary>
        /// 主用户登陆  0:密码错误  1:正常  -1:异常
        /// </summary>
        /// <param name="password"></param>
        /// <param name="showMode"></param>
        public async Task<int> AdminLogin(string password, ShowErrorMode showMode = ShowErrorMode.YES)
        {
            //尝试登陆
            var resultData = await ZigBee.Device.Safeguard.AdminLoginResponAsync(password, this.GetLoginToken());
            if (resultData == null)
            {
                return -1;
            }
            if (resultData != null && resultData.Result != 0)
            {
                if (showMode == ShowErrorMode.YES)
                {
                    //管理员密码错误
                    string msg = Language.StringByID(R.MyInternationalizationString.uAdministratorPasswordIsError);
                    this.ShowErrorMsg(msg);
                }
                return 0;
            }
            return 1;
        }
        /// <summary>
        /// 获取指定用户的密码,如果用户不存在,则返回null(错误不会弹出信息)
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<string> GetUserPassword(int userId)
        {
            //先获取密码
            var nowPw = await Safeguard.CatUserPasswordAsync(this.GetLoginToken());
            if (nowPw == null || nowPw.catUserPasswordResponseData == null)
            {
                return null;
            }
            foreach (var pw in nowPw.catUserPasswordResponseData.UserPasswordList)
            {
                if (pw.UserId == userId)
                {
                    return pw.Password;
                }
            }
            return null;
        }
        /// <summary>
        /// 获取全部用户的密码(错误会弹出信息)
        /// </summary>
        /// <param name="mode">是否显示错误</param>
        /// <returns></returns>
        public async Task<List<Safeguard.UserPasswordListObj>> GetAllUserPassword(ShowErrorMode mode = ShowErrorMode.YES)
        {
            //先获取密码
            var nowPw = await Safeguard.CatUserPasswordAsync(this.GetLoginToken());
            if (nowPw == null || nowPw.catUserPasswordResponseData == null)
            {
                //获取安防密码失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetSafetyPasswordFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, nowPw);
                if (mode == ShowErrorMode.YES)
                {
                    this.ShowErrorMsg(msg);
                }
                return null;
            }
            return nowPw.catUserPasswordResponseData.UserPasswordList;
        }
        /// <summary>
        /// 修改用户密码(不存在时,则新建)
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="password">密码</param>
        /// <param name="passWordTips">密码提示</param>
        /// <returns></returns>
        public async Task<bool> ChangedUserPassword(int userId, string password, string passWordTips)
        {
            //创建新用户
            var result = await Safeguard.SetUserPasswordAsync(userId, password, passWordTips, this.GetLoginToken());
            if (result == null || result.setUserPasswordResponseData == null)
            {
                if (userId != 5)
                {
                    //修改用户密码失败
                    string msg = Language.StringByID(R.MyInternationalizationString.uChangedUserPasswordFail);
                    //拼接上【网关回复超时】的Msg
                    msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                    this.ShowErrorMsg(msg);
                    return false;
                }
                else
                {
                    //修改胁迫密码失败
                    string msg = Language.StringByID(R.MyInternationalizationString.uChangedCoercePasswordFail);
                    this.ShowErrorMsg(msg);
                    return false;
                }
            }
            if (result.setUserPasswordResponseData.Result == 1)
            {
                //用户密码数已满(最大4个)
                string msg = Language.StringByID(R.MyInternationalizationString.uUserPasswordCountIsMax);
                this.ShowErrorMsg(msg);
                return false;
            }
            if (result.setUserPasswordResponseData.Result == 2)
            {
                //密码长度不正确
                string msg = Language.StringByID(R.MyInternationalizationString.uPasswordLengthIsError);
                this.ShowErrorMsg(msg);
                return false;
            }
            if (result.setUserPasswordResponseData.Result == 3)
            {
                //用户密码重复
                string msg = Language.StringByID(R.MyInternationalizationString.uUserPasswordIsRepeat);
                this.ShowErrorMsg(msg);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 显示校验管理员密码的窗口
        /// </summary>
        /// <returns></returns>
        public async Task<bool> ShowSafetyAdminValidatedDialog()
        {
            //式样变更,不再弹出输入管理员密码框,直接取默认密码admin
            //0:密码错误  1:正常 - 1:异常
            var result = await this.AdminLogin("admin", ShowErrorMode.NO);
            if (result != 1)
            {
                //获取执行权限失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetActionAuthorityFail);
                this.ShowTipMsg(msg);
                if (result == 0)
                {
                    //重置密码
                    await DoResetAdministratorPsw("admin");
                }
            }
            return result == 1;
        }
        /// <summary>
        /// 检测是否已经配置有用户密码(内部会弹出错误信息,-1:异常 0:没有配置 1:已经配置)
        /// </summary>
        /// <returns></returns>
        public async Task<int> CheckHadConfigureUserPsw()
        {
            var pswInfo = await this.GetAllUserPassword(ShowErrorMode.NO);
            if (pswInfo == null)
            {
                //出现未知错误,请稍后再试
                string msg = Language.StringByID(R.MyInternationalizationString.uUnKnowErrorAndResetAgain);
                this.ShowTipMsg(msg);
                return -1;
            }
            foreach (var data in pswInfo)
            {
                //4个用户密码
                if (data.UserId >= 1 && data.UserId <= 4)
                {
                    return 1;
                }
            }
            return 0;
        }
        /// <summary>
        /// 添加密码的备注
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="password">网关说需要原来的密码,也不知道为什么</param>
        /// <param name="passWordTips">密码备注</param>
        /// <returns></returns>
        public async Task<bool> AddPassWordTips(int userId, string password, string passWordTips)
        {
            var result = await Safeguard.SetPassWordTipsAsync(userId, password, passWordTips, this.GetLoginToken());
            if (result == null || result.setUserPasswordResponseData == null)
            {
                //修改备注信息失败
                string msg = Language.StringByID(R.MyInternationalizationString.uEditorNoteInformationFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return false;
            }
            if (result.setUserPasswordResponseData.Result != 0)
            {
                //修改备注信息失败
                string msg = Language.StringByID(R.MyInternationalizationString.uEditorNoteInformationFail);
                this.ShowErrorMsg(msg);
                return false;
            }
            return true;
        }
        #endregion
        #region ■ 报警目标___________________________
        /// <summary>
        /// 添加报警目标到安防
        /// </summary>
        /// <param name="ZoneId">防区ID</param>
        /// <param name="listAction">添加的目标</param>
        /// <returns></returns>
        public async Task<bool> AddAlarmTagetToSafety(int ZoneId, List<Safeguard.AlarmActionObj> listAction)
        {
            //现获取当前的布防模式
            var safetyMode = await this.GetSafetyMode();
            if (safetyMode != null)
            {
                //当前正处于布防模式,无法添加设备
                string msg = Language.StringByID(R.MyInternationalizationString.uCanNotAddDeviceInGarrisonMode);
                this.ShowErrorMsg(msg);
                return false;
            }
            //验证身份
            bool login = await this.ShowSafetyAdminValidatedDialog();
            if (login == false)
            {
                return false;
            }
            if (ZoneId > 3)
            {
                ZoneId = 3;
            }
            var saveData = new Safeguard.AddZoneActionData();
            saveData.ActionType = ZoneId;
            saveData.Actions = listAction;
            saveData.LoginToken = this.GetLoginToken();
            //添加报警目标到安防
            var result = await Safeguard.AddZoneActionAsync(saveData);
            if (result == null || result.addZoneActionResponseData == null || result.addZoneActionResponseData.Result == 1)
            {
                //添加报警目标失败
                string msg = Language.StringByID(R.MyInternationalizationString.uAddAlarmTargetFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return false;
            }
            foreach (var data in result.addZoneActionResponseData.Actions)
            {
                if (data.Status == "1")
                {
                    if (data.Type == "0")
                    {
                        var device = Common.LocalDevice.Current.GetDevice(data.DeviceAddr, data.Epoint);
                        string msg = Common.LocalDevice.Current.GetDeviceEpointName(device) + "\r\n";
                        //目标设备不存在
                        msg += Language.StringByID(R.MyInternationalizationString.uTargetDeviceIsNotExsit);
                        this.ShowTipMsg(msg);
                    }
                    else if (data.Type == "1")
                    {
                        var scene = HdlSceneLogic.Current.GetSceneUIBySceneId(data.ScenesId);
                        if (scene != null)
                        {
                            string msg = scene.Name + "\r\n";
                            //目标场景不存在
                            msg += Language.StringByID(R.MyInternationalizationString.uTargetSceneIsNotExsit);
                            this.ShowTipMsg(msg);
                        }
                    }
                }
            }
            //将报警目标列表加入缓存(从新从网关那里获取新追加的设备)
            var resultData = await Safeguard.CatZoneActionAsync(ZoneId);
            if (resultData == null
                || resultData.catZoneActionResponseData == null
                || resultData.catZoneActionResponseData.Result == 1)
            {
                //获取报警目标列表失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetAlarmTargetListFail);
                this.ShowTipMsg(msg);
                return false;
            }
            this.SetAlarmTargetDeviceToMemory(resultData.catZoneActionResponseData, ShowErrorMode.YES);
            return true;
        }
        /// <summary>
        /// 删除报警目标
        /// </summary>
        /// <param name="ZoneId">防区ID</param>
        /// <param name="listActions">删除的目标</param>
        /// <returns></returns>
        public async Task<bool> DeleteAlarmTaget(int ZoneId, List<Safeguard.DelAlarmActionObj> listActions)
        {
            //现获取当前的布防模式
            var safetyMode = await this.GetSafetyMode();
            if (safetyMode != null)
            {
                //当前正处于布防模式,无法删除设备
                string msg = Language.StringByID(R.MyInternationalizationString.uCanNotDeleteDeviceInGarrisonMode);
                this.ShowErrorMsg(msg);
                return false;
            }
            //验证身份
            bool login = await this.ShowSafetyAdminValidatedDialog();
            if (login == false)
            {
                return false;
            }
            if (ZoneId > 3)
            {
                ZoneId = 3;
            }
            //参数
            var Pra = new Safeguard.DelZoneActionData();
            Pra.ActionType = ZoneId;
            Pra.Actions = listActions;
            Pra.LoginToken = this.GetLoginToken();
            //执行删除
            var result = await Safeguard.DelZoneActionAsync(Pra);
            if (result == null || result.delZoneActionResponseData == null || result.delZoneActionResponseData.Result == 1)
            {
                //删除报警目标失败
                string msg = Language.StringByID(R.MyInternationalizationString.uDeleteAlarmTargetFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return false;
            }
            //获取本地缓存
            if (this.dicAllZoneInfo.ContainsKey(ZoneId) == false)
            {
                return true;
            }
            SafeguardZoneInfo zoneInfo = this.dicAllZoneInfo[ZoneId];
            //修改缓存
            foreach (var device in result.delZoneActionResponseData.Actions)
            {
                //删除失败
                if (device.Status == "1")
                {
                    continue;
                }
                //设备
                if (device.Type == "0")
                {
                    //删除报警设备
                    string mainkeys = Common.LocalDevice.Current.GetDeviceMainKeys(device.DeviceAddr, device.Epoint);
                    if (zoneInfo.dicAlarmDevice.ContainsKey(mainkeys) == false)
                    {
                        continue;
                    }
                    zoneInfo.dicAlarmDevice.Remove(mainkeys);
                    zoneInfo.dicAllDevice.Remove(mainkeys);
                }
                //场景
                else if (device.Type == "1")
                {
                    //删除场景
                    if (zoneInfo.dicScenes.ContainsKey(device.ScenesId) == true)
                    {
                        zoneInfo.dicScenes.Remove(device.ScenesId);
                    }
                }
            }
            return true;
        }
        #endregion
        #region ■ 获取场景___________________________
        /// <summary>
        /// 根据防区ID获取本地的场景
        /// </summary>
        /// <param name="ZoneId">防区ID</param>
        /// <returns></returns>
        public Dictionary<int, string> GetLocalSceneByZoneID(int ZoneId)
        {
            if (ZoneId > 3)
            {
                ZoneId = 3;
            }
            if (this.dicAllZoneInfo.ContainsKey(ZoneId) == false)
            {
                return new Dictionary<int, string>();
            }
            var infoData = this.dicAllZoneInfo[ZoneId];
            return infoData.dicScenes;
        }
        #endregion
        #region ■ 旁路设置___________________________
        /// <summary>
        /// 旁路状态设置
        /// </summary>
        /// <param name="zoneId">防区ID</param>
        /// <param name="device">传感器设备</param>
        /// <param name="statu">旁路状态 -> 0:不旁路  1:旁路</param>
        /// <returns></returns>
        public async Task<bool> SetByPassStatuToSafety(int zoneId, CommonDevice device, int statu)
        {
            //验证
            bool flage = await this.ShowSafetyAdminValidatedDialog();
            if (flage == false)
            {
                return false;
            }
            //参数
            var Pra = new Safeguard.EqByPassData();
            Pra.ZoneId = zoneId;
            Pra.MacAddr = device.DeviceAddr;
            Pra.Epoint = device.DeviceEpoint;
            Pra.IsByPass = statu;
            Pra.LoginToken = this.GetLoginToken();
            var result = await Safeguard.EqByPassAllDataAsync(Pra);
            if (result == null || result.eqByPassResponseData != null && result.eqByPassResponseData.Result == 3)
            {
                //设置失败,系统当前处于撤防状态
                string msg2 = Language.StringByID(R.MyInternationalizationString.uByPassFailAndSystemInWithdrawGarrisonStatu);
                this.ShowErrorMsg(msg2);
                return false;
            }
            //其他错误
            if (result.eqByPassResponseData == null || result.eqByPassResponseData.Result != 0)
            {
                //旁路状态设置失败
                string msg = Language.StringByID(R.MyInternationalizationString.uSetByPassStatuFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return false;
            }
            return true;
        }
        #endregion
        #region ■ 布防撤防___________________________
        /// <summary>
        /// 设置安防的布防模式,成功时,内部不会提示信息(不要调用此方法来实现【撤防】)
        /// </summary>
        /// <param name="garrison">布防模式</param>
        /// <returns>网关现在实行的布防模式</returns>
        public async Task<GarrisonMode> SetSafetyGarrisonByModel(GarrisonMode garrison)
        {
            //检测其他防区里面有没有配置有传感器
            if (this.CheckHadInteriorSectorsSensor() == false)
            {
                //其他防区里没有配置传感器设备
                string msg = Language.StringByID(R.MyInternationalizationString.uNotSensorInOtherSectors);
                this.ShowErrorMsg(msg);
                return GarrisonMode.None;
            }
            if (this.UserPassword == null)
            {
                var data = Global.ReadFileByDirectory(DirNameResourse.LocalMemoryDirectory, DirNameResourse.SafeguardUserPassword);
                if (data != null)
                {
                    this.UserPassword = System.Text.Encoding.UTF8.GetString(data);
                }
            }
            if (string.IsNullOrEmpty(this.UserPassword) == true)
            {
                //输入密码
                string password = await this.ShowInputUserPasswordForm();
                if (string.IsNullOrEmpty(password) == true)
                {
                    return GarrisonMode.None;
                }
                var result = await this.SetSafetyGarrisonByModel(garrison, false);
                if (result != GarrisonMode.None && result != GarrisonMode.RemoveGarrison)
                {
                    //保存加密的密码到本地
                    Global.WriteFileToDirectoryByBytes(DirNameResourse.LocalMemoryDirectory, DirNameResourse.SafeguardUserPassword, System.Text.Encoding.UTF8.GetBytes(this.UserPassword));
                }
                return result;
            }
            else
            {
                return await this.SetSafetyGarrisonByModel(garrison, true);
            }
        }
        /// <summary>
        /// 设置安防的布防模式,成功时,内部不会提示信息(不要调用此方法来实现【撤防】)
        /// </summary>
        /// <param name="garrison">布防模式</param>
        /// <param name="showPswForm">用户密码错误时,是否允许弹出输入用户密码的窗口</param>
        /// <returns>网关现在实行的布防模式</returns>
        private async Task<GarrisonMode> SetSafetyGarrisonByModel(GarrisonMode garrison, bool showPswForm)
        {
            //先把当前的模式给移除掉
            var flage = await this.RemoveSafetyGarrison(garrison, showPswForm);
            if (flage == -1)
            {
                return GarrisonMode.None;
            }
            //判断有没有其他逻辑去修改了布防模式
            //所以再次获取模式
            var safetyMode = await this.GetSafetyMode();
            if (safetyMode != null)
            {
                return GarrisonMode.None;
            }
            //参数
            var Pra = new Safeguard.EnableModeData();
            //模式ID
            Pra.ModeId = (int)garrison;
            //检查防区设备最近上报的安防信息状态进行布防
            Pra.CheckIASStatus = 1;
            //永久布防,直到撤防
            Pra.Setting = 1;
            //用户密码
            Pra.UserPassword = this.UserPassword;
            //执行布防
            var result = await Safeguard.EnableModeAsync(Pra);
            if (result == null || result.enableModeResponseData == null)
            {
                //布防设置失败
                string msg = Language.StringByID(R.MyInternationalizationString.uSetGarrisonFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return GarrisonMode.RemoveGarrison;
            }
            //错误检测
            if (result.enableModeResponseData.Result == 1)
            {
                //布防模式不存在
                string msg = Language.StringByID(R.MyInternationalizationString.uGarrisonModeIsNotEsixt);
                this.ShowErrorMsg(msg);
                return GarrisonMode.RemoveGarrison;
            }
            else if (result.enableModeResponseData.Result == 2)
            {
                //清空密码缓存
                this.UserPassword = null;
                if (showPswForm == false)
                {
                    //用户密码错误或未设置用户密码
                    string msg = Language.StringByID(R.MyInternationalizationString.uUserPasswordIsError);
                    this.ShowErrorMsg(msg);
                    return GarrisonMode.RemoveGarrison;
                }
                else
                {
                    //重新显示输入用户密码的窗口
                    string password = await this.ShowInputUserPasswordForm();
                    if (string.IsNullOrEmpty(password) == true)
                    {
                        return GarrisonMode.RemoveGarrison;
                    }
                    var result2 = await this.SetSafetyGarrisonByModel(garrison, false);
                    if (result2 != GarrisonMode.None && result2 != GarrisonMode.RemoveGarrison)
                    {
                        //保存加密密码到本地
                        Global.WriteFileToDirectoryByBytes(DirNameResourse.LocalMemoryDirectory, DirNameResourse.SafeguardUserPassword, System.Text.Encoding.UTF8.GetBytes(this.UserPassword));
                    }
                    return result2;
                }
            }
            else if (result.enableModeResponseData.Result == 3)
            {
                //安防设备未就绪
                string msg = Language.StringByID(R.MyInternationalizationString.uSafetyDeviceDoNotReady);
                msg += "(" + result.enableModeResponseData.IASName + ")";
                this.ShowErrorMsg(msg);
                return GarrisonMode.RemoveGarrison;
            }
            else if (result.enableModeResponseData.Result == 4)
            {
                //其他布防模式正在启用中
                string msg = Language.StringByID(R.MyInternationalizationString.uOtherGarrisonIsActtion);
                this.ShowErrorMsg(msg);
                return (GarrisonMode)result.enableModeResponseData.ModeIdBeUsing;
            }
            else if (result.enableModeResponseData.Result == 5)
            {
                //模式属性不允许失能
                string msg = Language.StringByID(R.MyInternationalizationString.uGarrisonModeElementCanNotLostFunction);
                this.ShowErrorMsg(msg);
                return GarrisonMode.RemoveGarrison;
            }
            return garrison;
        }
        /// <summary>
        /// 移除当前正在运行的布防模式(成功时,内部不会提示信息)
        /// </summary>
        /// <param name="garrison">布防模式(这个变量只是为了变更提示错误信息,当不是撤防时,错误提示信息会改变)</param>
        /// <param name="showPswForm">用户密码错误时,是否允许弹出输入用户密码的窗口</param>
        /// <returns></returns>
        public async Task<int> RemoveSafetyGarrison(GarrisonMode garrison, bool showPswForm)
        {
            //现获取当前的布防模式
            var safetyMode = await this.GetSafetyMode();
            if (safetyMode == null)
            {
                //如果是撤防的话
                if (garrison == GarrisonMode.RemoveGarrison)
                {
                    //当前不存在布防
                    string msg = Language.StringByID(R.MyInternationalizationString.uNowDoNotHadGarrison);
                    this.ShowErrorMsg(msg);
                    return -1;
                }
                //并没有设置布防,也就不谈什么撤防了
                return 0;
            }
            //撤防的时候,无条件弹出输入密码框
            if (garrison == GarrisonMode.RemoveGarrison)
            {
                string psw = await this.ShowInputUserPasswordForm();
                if (string.IsNullOrEmpty(psw) == true)
                {
                    return -1;
                }
            }
            //撤防
            var result = await Safeguard.WithdrawModeAsync(this.UserPassword);
            if (result == null || result.withdrawModeResponseData == null)
            {
                //执行撤防操作的时候
                if (garrison == GarrisonMode.RemoveGarrison)
                {
                    //撤防失败
                    string msg = Language.StringByID(R.MyInternationalizationString.uRemoveGarrisonFail);
                    //拼接上【网关回复超时】的Msg
                    msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                    this.ShowErrorMsg(msg);
                }
                else
                {
                    //布防模式变更失败
                    string msg = Language.StringByID(R.MyInternationalizationString.uChangedGarrisonModeFail);
                    //拼接上【网关回复超时】的Msg
                    msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                    this.ShowErrorMsg(msg);
                }
                return -1;
            }
            if (result.withdrawModeResponseData.Result == 2)
            {
                //清空密码缓存
                this.UserPassword = null;
                if (showPswForm == false || garrison == GarrisonMode.RemoveGarrison)
                {
                    //用户密码错误或未设置用户密码
                    string msg = Language.StringByID(R.MyInternationalizationString.uUserPasswordIsError);
                    this.ShowErrorMsg(msg);
                    return -1;
                }
                else
                {
                    //重新显示输入用户密码的窗口
                    string password = await this.ShowInputUserPasswordForm();
                    if (string.IsNullOrEmpty(password) == true)
                    {
                        return -1;
                    }
                    var result2 = await this.RemoveSafetyGarrison(garrison, false);
                    if (result2 != -1)
                    {
                        //保存到加密密码本地
                        Global.WriteFileToDirectoryByBytes(DirNameResourse.LocalMemoryDirectory, DirNameResourse.SafeguardUserPassword, System.Text.Encoding.UTF8.GetBytes(this.UserPassword));
                    }
                    return result2;
                }
            }
            else if (result.withdrawModeResponseData.Result == 3 && garrison == GarrisonMode.RemoveGarrison)
            {
                //当前模式不可撤防
                string msg = Language.StringByID(R.MyInternationalizationString.uNowGarrisonCanNotRemove);
                this.ShowErrorMsg(msg);
                return -1;
            }
            return 1;
        }
        /// <summary>
        /// 获取当前安防的模式(在家,离家等等),如果没有布防,则返回null
        /// </summary>
        public async Task<Safeguard.GetModeUsingResponseData> GetSafetyMode()
        {
            var result = await Safeguard.GetModeUsingAsync();
            if (result == null || result.getModeUsingResponseData == null)
            {
                return null;
            }
            if (result.getModeUsingResponseData.Result == 1)
            {
                return null;
            }
            return result.getModeUsingResponseData;
        }
        /// <summary>
        /// 显示输入用户密码的界面(返回null时代表出错或者取消)
        /// </summary>
        public async Task<string> ShowInputUserPasswordForm()
        {
            NumberPswInputDialogForm Dialogform = null;
            bool isShowingProgressBar = false;
            string ProgressBarText = string.Empty;
            string pasword = null;
            HdlThreadLogic.Current.RunMain(() =>
            {
                isShowingProgressBar = CommonPage.Loading.Visible;
                ProgressBarText = CommonPage.Loading.Text;
                if (isShowingProgressBar == true)
                {
                    //如果在弹出校验密码框的时候,显示着进度条的话,先暂时关闭进度条
                    CommonPage.Loading.Hide();
                }
                Dialogform = new NumberPswInputDialogForm();
                Dialogform.AddForm(Language.StringByID(R.MyInternationalizationString.uPleaseInputUserPassword), 4);
                //确认按钮
                Dialogform.FinishInputEvent += ((textValue) =>
                {
                    Dialogform.CloseForm();
                    //用户密码
                    pasword = textValue;
                    //加密密码
                    this.UserPassword = pasword;
                });
            });
            while (pasword == null)
            {
                if (Dialogform != null && Dialogform.Parent == null)
                {
                    break;
                }
                await Task.Delay(500);
            }
            //恢复进度条
            if (isShowingProgressBar == true)
            {
                Application.RunOnMainThread(() =>
                {
                    CommonPage.Loading.Start(ProgressBarText);
                });
            }
            return pasword;
        }
        /// <summary>
        /// 检测其他防区里面有没有配置有传感器(布防使用)
        /// </summary>
        /// <returns></returns>
        private bool CheckHadInteriorSectorsSensor()
        {
            for (int i = 3; i <= 5; i++)
            {
                if (dicAllZoneInfo.ContainsKey(i) == true
                    && dicAllZoneInfo[i].dicSensor.Count > 0)
                {
                    return true;
                }
            }
            return false;
        }
        #endregion
        #region ■ 信息推送___________________________
        /// <summary>
        /// 设置指定防区的信息推送状态
        /// </summary>
        /// <param name="zoneId">防区ID</param>
        /// <param name="statu">状态  0:推送  1:不推送</param>
        /// <returns></returns>
        public async Task<bool> SetGarrisonInformationPushStatu(int zoneId, int statu)
        {
            //校验密码
            bool flage = await this.ShowSafetyAdminValidatedDialog();
            if (flage == false)
            {
                return false;
            }
            if (zoneId > 3)
            {
                zoneId = 3;
            }
            //状态变更
            var result = await Safeguard.DisablePushMessageAsync(zoneId, statu);
            if (result == null || result.disablePushMessageResponseData == null || result.disablePushMessageResponseData.Result == 1)
            {
                //设置信息推送失败
                string msg = Language.StringByID(R.MyInternationalizationString.uSetInformationPushFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return false;
            }
            if (this.dicAllZoneInfo.ContainsKey(zoneId) == false)
            {
                return true;
            }
            SafeguardZoneInfo zoneInfo = this.dicAllZoneInfo[zoneId];
            zoneInfo.InformationPush = statu;
            return true;
        }
        /// <summary>
        /// 获取当前防区的信息推送状态
        /// </summary>
        /// <param name="zoneId">防区ID</param>
        /// <returns>0:推送  1:不推送</returns>
        public int GetGarrisonInformationPushStatu(int zoneId)
        {
            if (zoneId > 3)
            {
                zoneId = 3;
            }
            if (this.dicAllZoneInfo.ContainsKey(zoneId) == false)
            {
                return 1;
            }
            SafeguardZoneInfo zoneInfo = this.dicAllZoneInfo[zoneId];
            return zoneInfo.InformationPush;
        }
        #endregion
        #region ■ 延迟设置___________________________
        /// <summary>
        /// 获取防区的延迟时间(仅限出入防区),出错时返回null
        /// </summary>
        /// <returns></returns>
        public async Task<Safeguard.CatDelayTimeResponseData> GetGarrisonDelayTime()
        {
            //获取
            var result = await Safeguard.CatDelayTimeAsync();
            if (result == null || result.catDelayTimeResponseData == null)
            {
                //获取延时时间失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetDelayTimeFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return null;
            }
            return result.catDelayTimeResponseData;
        }
        /// <summary>
        /// 设置防区的进出延迟时间 (仅限出入防区),现接口不支持单个修改
        /// </summary>
        /// <param name="enterDelayTime">进入延时(秒)</param>
        /// <param name="goOutDelayTime">外出延时(秒)</param>
        /// <returns></returns>
        public async Task<bool> SetGarrisonDelayTime(int enterDelayTime, int goOutDelayTime)
        {
            //校验密码
            bool flage = await this.ShowSafetyAdminValidatedDialog();
            if (flage == false)
            {
                return false;
            }
            //更改时间
            var result = await Safeguard.SetDelayTimeAsync(enterDelayTime, goOutDelayTime, this.GetLoginToken());
            if (result == null || result.setDelayTimeResponseData == null)
            {
                //设置延时时间失败
                string msg = Language.StringByID(R.MyInternationalizationString.uSetDelayTimeFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return false;
            }
            return true;
        }
        #endregion
        #region ■ 胁迫设置___________________________
        /// <summary>
        /// 获取胁迫的电话联系方式(获取失败时会返回null)
        /// </summary>
        /// <returns></returns>
        public async Task<Safeguard.CheckCoercePhoneNumberResponseData> GetCoercePhoneNumber()
        {
            //获取
            var result = await Safeguard.CheckCoercePhoneNumberAsync();
            if (result == null || result.checkCoercePhoneNumberResponseData == null)
            {
                //获取胁迫联系方式信息失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetCoercePhoneNumberFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return null;
            }
            //没有数据
            if (result.checkCoercePhoneNumberResponseData.Result == 1)
            {
                return null;
            }
            return result.checkCoercePhoneNumberResponseData;
        }
        /// <summary>
        /// 设置胁迫的联系人方式
        /// </summary>
        /// <param name="listPhone">地区码-联系方式</param>
        /// <param name="listNote">联系人备注</param>
        /// <param name="addPhone">是否是新建联系人,false的时候,只改备注</param>
        /// <returns></returns>
        public async Task<bool> SetCoercePhoneNumber(List<string> listPhone, List<string> listNote, bool addPhone = true)
        {
            if (addPhone == true)
            {
                var Pra = new Safeguard.SetCoercePhoneNumberData();
                var Actonobj = new Safeguard.PushTargetActionObj();
                Actonobj.Type = 2;
                Pra.Actions.Add(Actonobj);
                Pra.LoginToken = this.GetLoginToken();
                for (int i = 0; i < listPhone.Count; i++)
                {
                    var phoneInfo = new Safeguard.PushTargetInfo();
                    Actonobj.PushTarget.Add(phoneInfo);
                    //电话号码
                    phoneInfo.PushNumber = listPhone[i];
                }
                var result = await Safeguard.SetCoercePhoneNumberAsync(Pra);
                if (result == null || result.setCoercePhoneNumberResponseData == null || result.setCoercePhoneNumberResponseData.Result != 0)
                {
                    //修改胁迫联系方式失败
                    string msg = Language.StringByID(R.MyInternationalizationString.uChangedCoercePhoneNumberFail);
                    //拼接上【网关回复超时】的Msg
                    msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                    this.ShowErrorMsg(msg);
                    return false;
                }
            }
            for (int i = 0; i < listNote.Count; i++)
            {
                var result = await Safeguard.SetCoercePhoneNumberNoteAsync(listPhone[i], listNote[i]);
                if (result == null)
                {
                    //修改备注信息失败
                    string msg = Language.StringByID(R.MyInternationalizationString.uEditorNoteInformationFail);
                    //拼接上【网关回复超时】的Msg
                    msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "回复超时");
                    this.ShowErrorMsg(msg);
                    return false;
                }
                if (result.Result == -2)
                {
                    //错误:网关对象丢失
                    string msg = Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg);
                    this.ShowErrorMsg(msg);
                    return false;
                }
                if (result.Result != 0)
                {
                    //修改备注信息失败
                    string msg = Language.StringByID(R.MyInternationalizationString.uEditorNoteInformationFail);
                    this.ShowErrorMsg(msg);
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// 删除胁迫的联系人方式
        /// </summary>
        /// <param name="areaCode"></param>
        /// <param name="phoneNum"></param>
        /// <returns></returns>
        public async Task<bool> DeleteCoercePhoneNumber(string areaCode, string phoneNum)
        {
            var Pra = new Safeguard.DelCoercePhoneNumberData();
            var Actonobj = new Safeguard.PushTargetActionObj();
            Actonobj.Type = 2;
            Pra.Actions.Add(Actonobj);
            Pra.LoginToken = this.GetLoginToken();
            var phoneInfo = new Safeguard.PushTargetInfo();
            Actonobj.PushTarget.Add(phoneInfo);
            //电话号码
            phoneInfo.PushNumber = areaCode + "-" + phoneNum;
            var result = await Safeguard.DelCoercePhoneNumberAsync(Pra);
            if (result == null || result.delCoercePhoneNumberResponseData == null || result.delCoercePhoneNumberResponseData.Result != 0)
            {
                //删除胁迫联系方式失败
                string msg = Language.StringByID(R.MyInternationalizationString.uDeleteCoercePhoneNumberFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 给联系号码添加备注的信息
        /// </summary>
        private class AddPushNumberNoteInfo
        {
            /// <summary>
            /// 固定253
            /// </summary>
            public int ActionType = 253;
            /// <summary>
            /// LoginToken
            /// </summary>
            public string LoginToken = string.Empty;
            /// <summary>
            /// 地区码-联系方式
            /// </summary>
            public string PushNumber = string.Empty;
            /// <summary>
            /// 联系人号码备注,最大63byte
            /// </summary>
            public string PushNumberNote = string.Empty;
        }
        #endregion
        #region ■ 执行目标状态的翻译文本_____________
        /// <summary>
        /// 获取执行目标的状态文本
        /// </summary>
        /// <param name="listTaskInfo">动作对象,可以为空</param>
        /// <returns></returns>
        public string GetAdjustTargetStatuText(List<Safeguard.TaskListInfo> listTaskInfo)
        {
            if (listTaskInfo == null || listTaskInfo.Count == 0)
            {
                //无动作
                return Language.StringByID(R.MyInternationalizationString.uNotAction);
            }
            //要考虑它的排列顺序(可以按需求变更编号)
            Dictionary<int, string> dicSort = new Dictionary<int, string>();
            //最大编号
            int MaxNo = 4;
            //开关的位置编号
            int ControlNo = 0;
            //百分比的位置编号
            int persentNo = 1;
            //空调温度的位置编号
            int temparetureNo = 2;
            //空调模式的位置编号
            int modelNo = 3;
            //空调风速的位置编号
            int windNo = 4;
            foreach (var info in listTaskInfo)
            {
                #region ■ 开关控制____
                //开关控制
                if (info.TaskType == 1)
                {
                    if (info.Data1 == 1)
                    {
                        //开
                        dicSort[ControlNo] = Language.StringByID(R.MyInternationalizationString.uSimpleOpen);
                    }
                    else
                    {
                        //关
                        dicSort[ControlNo] = Language.StringByID(R.MyInternationalizationString.uSimpleClose);
                    }
                }
                #endregion
                #region ■ 亮度调节____
                //亮度调节
                else if (info.TaskType == 3)
                {
                    if (info.Data1 == 0)
                    {
                        //关
                        dicSort[persentNo] = Language.StringByID(R.MyInternationalizationString.uSimpleClose);
                    }
                    else
                    {
                        dicSort[persentNo] = $"{(int)(info.Data1 * 1.0 / 254 * 100)}%";
                    }
                }
                #endregion
                #region ■ 窗帘设备____
                //窗帘设备(它的开关和开关控制是反过来的)
                else if (info.TaskType == 6)
                {
                    if (info.Data1 == 0)
                    {
                        //开
                        dicSort[ControlNo] = Language.StringByID(R.MyInternationalizationString.uSimpleOpen);
                    }
                    else if (info.Data1 == 1)
                    {
                        //关
                        dicSort[ControlNo] = Language.StringByID(R.MyInternationalizationString.uSimpleClose);
                    }
                    else if (info.Data1 == 5)
                    {
                        //窗帘百分比
                        dicSort[persentNo] = info.Data2 + "%";
                    }
                }
                #endregion
                #region ■ 空调设备____
                //空调设备
                else if (info.TaskType == 5)
                {
                    if (info.Data1 == 3)
                    {
                        if (info.Data2 == 0)
                        {
                            return Language.StringByID(R.MyInternationalizationString.uSimpleClose);
                        }
                        else if (info.Data2 == 1)
                        {
                            //自动
                            dicSort[modelNo] = Language.StringByID(R.MyInternationalizationString.Mode_Auto);
                        }
                        else if (info.Data2 == 3)
                        {
                            //制冷
                            dicSort[modelNo] = Language.StringByID(R.MyInternationalizationString.Mode_Cool);
                        }
                        else if (info.Data2 == 4)
                        {
                            //制热
                            dicSort[modelNo] = Language.StringByID(R.MyInternationalizationString.Mode_Heat);
                        }
                        else if (info.Data2 == 7)
                        {
                            //送风
                            dicSort[modelNo] = Language.StringByID(R.MyInternationalizationString.Mode_FanOnly);
                        }
                        else if (info.Data2 == 8)
                        {
                            //除湿
                            dicSort[modelNo] = Language.StringByID(R.MyInternationalizationString.Mode_Dry);
                        }
                    }
                    else if (info.Data1 == 4 || info.Data1 == 5|| info.Data1 == 7)
                    {
                        //温度
                        dicSort[temparetureNo] = $"{ info.Data2 / 100}℃";
                    }
                    else if (info.Data1 == 6)
                    {
                        if (info.Data2 == 1)
                        {
                            //低风
                            dicSort[windNo] = Language.StringByID(R.MyInternationalizationString.Fan_Low);
                        }
                        else if (info.Data2 == 2)
                        {
                            //中风
                            dicSort[windNo] = Language.StringByID(R.MyInternationalizationString.Fan_Middle);
                        }
                        else if (info.Data2 == 3)
                        {
                            //高风
                            dicSort[windNo] = Language.StringByID(R.MyInternationalizationString.Fan_Height);
                        }
                    }
                }
                #endregion
            }
            //如果开关和百分比一起存在的话,则不显示开关文字
            if (dicSort.ContainsKey(ControlNo) == true && dicSort.ContainsKey(persentNo) == true)
            {
                dicSort.Remove(ControlNo);
            }
            //拼接文本
            string txtvalue = string.Empty;
            for (int i = 0; i <= MaxNo; i++)
            {
                if (dicSort.ContainsKey(i) == true)
                {
                    txtvalue += dicSort[i] + " ";
                }
            }
            return txtvalue.Trim();
        }
        #endregion
        #region ■ 重置管理员密码_____________________
        /// <summary>
        /// 重置管理员密码
        /// </summary>
        /// <param name="password">新密码</param>
        /// <returns></returns>
        private async Task<bool> DoResetAdministratorPsw(string password)
        {
            var realWay = ZigBee.Device.ZbGateway.MainGateWay;
            if (realWay == null)
            {
                //错误:网关对象丢失
                //string msg = Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg);
                //this.ShowTipMsg(msg);
                return false;
            }
            //是否达成中断的时机
            bool canBreak = false;
            bool success = false;
            //超时时间
            int TimeOut = 0;
            string checkTopic = HdlGatewayLogic.Current.GetGatewayId(realWay) + "/Security/AdminSetNewPassword_Respon";
            Action<string, string> getResultAction = (topic, message) =>
            {
                try
                {
                    if (topic == checkTopic)
                    {
                        TimeOut = 0;
                        var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                        var result = JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString());
                        success = result == 0;
                        canBreak = true;
                    }
                }
                catch { }
            };
            realWay.Actions += getResultAction;
            try
            {
                var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 4033 } };
                var data = new Newtonsoft.Json.Linq.JObject { { "HomeId", Common.Config.Instance.HomeId }, { "Password", password } };
                jObject.Add("Data", data);
                realWay.Send("Security/AdminSetNewPassword", jObject.ToString());
            }
            catch
            {
                canBreak = true;
                //出现未知错误,请稍后再试
                //string msg = Language.StringByID(R.MyInternationalizationString.uUnKnowErrorAndResetAgain);
                //this.ShowTipMsg(msg);
            }
            while (canBreak == false && TimeOut < 20)
            {
                await Task.Delay(100);
                TimeOut++;
            }
            realWay.Actions -= getResultAction;
            getResultAction = null;
            if (TimeOut >= 20)
            {
                //重置管理员密码失败(网关回复超时)
                //string msg = Language.StringByID(R.MyInternationalizationString.uResetAdministratorPswFail);
                //msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "回复超时");
                //this.ShowTipMsg(msg);
                return false;
            }
            return success;
        }
        #endregion
        #region ■ 一般方法___________________________
        /// <summary>
        /// 获取所有防区的ID(默认是1~5)
        /// </summary>
        /// <returns></returns>
        private List<int> GetAllZoneId()
        {
            //防区id
            //1:24小时防区
            //2:24小时静音防区
            //3:出入防区
            //4:内部防区
            //5:周界防区
            List<int> list = new List<int>() { 1, 2, 3, 4, 5 };
            return list;
        }
        /// <summary>
        /// 获取防区的翻译名字
        /// </summary>
        /// <param name="ZoneID"></param>
        /// <returns></returns>
        public string GetGarrisonText(int ZoneID)
        {
            if (ZoneID == 1)
            {
                //24小时防区
                return Language.StringByID(R.MyInternationalizationString.u24HourSectors);
            }
            else if (ZoneID == 2)
            {
                //静音防区
                return Language.StringByID(R.MyInternationalizationString.uMuteSectors);
            }
            else if (ZoneID == 3)
            {
                //出入防区
                return Language.StringByID(R.MyInternationalizationString.uInAndOutSectors);
            }
            else if (ZoneID == 4)
            {
                //内部防区
                return Language.StringByID(R.MyInternationalizationString.uInteriorSectors);
            }
            else if (ZoneID == 5)
            {
                //周界防区
                return Language.StringByID(R.MyInternationalizationString.uPerimeterSectors);
            }
            return string.Empty;
        }
        /// <summary>
        /// 显示错误信息窗口
        /// </summary>
        /// <param name="msg"></param>
        private void ShowErrorMsg(string msg)
        {
            Application.RunOnMainThread(() =>
            {
                var contr = new ShowMsgControl(ShowMsgType.Error, msg);
                contr.Show();
            });
        }
        /// <summary>
        /// 显示正常信息窗口
        /// </summary>
        /// <param name="msg"></param>
        private void ShowNormalMsg(string msg)
        {
            Application.RunOnMainThread(() =>
            {
                var contr = new ShowMsgControl(ShowMsgType.Normal, msg);
                contr.Show();
            });
        }
        /// <summary>
        /// 显示Tip窗口
        /// </summary>
        /// <param name="msg"></param>
        private void ShowTipMsg(string msg)
        {
            Application.RunOnMainThread(() =>
            {
                var control = new ShowMsgControl(ShowMsgType.Tip, msg);
                control.Show();
            });
        }
        /// <summary>
        /// 获取设备的唯一主键
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        private string GetDeviceMainKeys(CommonDevice device)
        {
            return Common.LocalDevice.Current.GetDeviceMainKeys(device);
        }
        /// <summary>
        /// 获取登陆者的Token(好像管理员登陆的时候,需要变更Token,所以暂且定义一个函数出来)
        /// </summary>
        /// <returns></returns>
        public string GetLoginToken()
        {
            //获取控制主人账号的Token
            //return UserCenterLogic.GetConnectMainToken();
            return Config.Instance.Token;
        }
        #endregion
        #region ■ 结构体_____________________________
        /// <summary>
        /// 内部使用,安防防区的一些信息
        /// </summary>
        private class SafeguardZoneInfo
        {
            /// <summary>
            /// 防区id。
            /// </summary>
            public int ZoneId;
            /// <summary>
            /// 布防防区名称 ,最大32个字符
            /// </summary>
            public string ZoneName;
            /// <summary>
            /// 信息推送 0:推送  1:不推送 (只有防区ID:1,2,3才会有。4,5的都归为3,因为它是以防区模式ID(ActionType)为单位的)
            /// </summary>
            public int InformationPush = 1;
            /// <summary>
            /// 传感器设备的信息(keys:设备主键)
            /// </summary>
            public Dictionary<string, Safeguard.ZoneDeviceListData> dicSensor = new Dictionary<string, Safeguard.ZoneDeviceListData>();
            /// <summary>
            /// 该防区下全部设备文件路径(keys:设备主键,value:设备文件路径)
            /// </summary>
            public Dictionary<string, string> dicAllDevice = new Dictionary<string, string>();
            /// <summary>
            /// 该防区下面的报警设备(keys:设备主键),<只有防区ID:1,2,3才会有。4,5的都归为3,因为它是以防区模式ID(ActionType)为单位的>
            /// </summary>
            public Dictionary<string, Safeguard.CatActionResponseObj> dicAlarmDevice = new Dictionary<string, Safeguard.CatActionResponseObj>();
            /// <summary>
            /// 该防区下面的场景(keys:场景No),<只有防区ID:1,2,3才会有。4,5的都归为3,因为它是以防区模式ID(ActionType)为单位的>
            /// </summary>
            public Dictionary<int, string> dicScenes = new Dictionary<int, string>();
        }
        #endregion
    }
}
using Newtonsoft.Json;
using Shared.Common;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using ZigBee.Device;
namespace Shared.Phone.UserCenter
{
    /// <summary>
    /// <para>安防本地缓存(代码使用)</para>
    /// <para>防区ID(ZoneId):</para>
    /// <para>1:24小时防区  2:24小时静音防区  3:出入防区  4:内部防区  5:周界防区</para>
    /// <para>防区模式ID(ActionType -> 防区ID换算:ZoneId=3,4,5都当做3处理):</para>
    /// <para>1:24小时防区  2:静音防区  3:其他防区(出入防区、内部防区、周界防区)</para>
    /// <para>布防模式ID(GarrisonMode):</para>
    /// <para>1:在家布防 或者 布防(内部防区没有设置的时候)  2:离家布防</para>
    /// </summary>
    public class HdlSafeguardLogic
    {
        #region ■ 变量声明___________________________
        /// <summary>
        /// 本地安防数据
        /// </summary>
        private static HdlSafeguardLogic m_Current = null;
        /// <summary>
        /// 本地安防数据
        /// </summary>
        public static HdlSafeguardLogic Current
        {
            get
            {
                if (m_Current == null)
                {
                    m_Current = new HdlSafeguardLogic();
                }
                return m_Current;
            }
            set
            {
                m_Current = value;
            }
        }
        /// <summary>
        /// 当前的布防模式(注意,这个东西只给安防主界面初始化的时候使用!!)
        /// </summary>
        public GarrisonMode NowGarrisonMode = GarrisonMode.None;
        /// <summary>
        /// 用户密码的缓存
        /// </summary>
        private string UserPassword = null;
        /// <summary>
        /// 安防数据缓存
        /// </summary>
        private Dictionary<int, SafeguardZoneInfo> dicAllZoneInfo = new Dictionary<int, SafeguardZoneInfo>();
        #endregion
        #region ■ 刷新安防___________________________
        /// <summary>
        /// 从新从网关那里获取数据(失败时会弹出信息框)
        /// </summary>
        /// <returns></returns>
        public async Task<bool> ReFreshByGateway()
        {
            //先清空
            this.dicAllZoneInfo.Clear();
            var mainGateway = ZbGateway.MainGateWay;
            if (mainGateway == null)
            {
                //错误:网关对象丢失
                string msg = Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg);
                this.ShowTipMsg(msg);
                return false;
            }
            var mainWayId = mainGateway.GwId;
            //主题数固定5+3+1
            int topicCount = 9;
            //错误
            bool error = false;
            //防区设备信息
            var listDevice = new List<Safeguard.GetZoneDeviceListByIdResponData>();
            //报警目标
            var listAlarm = new List<Safeguard.CatZoneActionResponseData>();
            //安防模式
            var listMode = new List<Safeguard.GetModeUsingResponseData>();
            Action<string, string> action = (topic, message) =>
            {
                var gatewayID = topic.Split('/')[0];
                if (gatewayID != mainWayId)
                {
                    return;
                }
                //检测共通错误
                if (topic == gatewayID + "/" + "Error_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    var temp = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonDevice.ErrorResponData>(jobject["Data"].ToString());
                    if (temp != null)
                    {
                        string msg = HdlCheckLogic.Current.CheckCommonErrorCode(temp.Error);
                        if (msg != null)
                        {
                            this.ShowTipMsg(msg);
                        }
                    }
                    error = true;
                }
                //防区设备信息
                if (topic == gatewayID + "/Security/GetZoneDeviceList_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    var result = JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString());
                    if (result == 0)
                    {
                        var data = JsonConvert.DeserializeObject<Safeguard.GetZoneDeviceListByIdResponData>(jobject["Data"].ToString());
                        if (data != null)
                        {
                            //将防区传感器设备列表加入缓存
                            listDevice.Add(data);
                            topicCount--;
                            return;
                        }
                    }
                    error = true;
                }
                //防区报警目标
                if (topic == gatewayID + "/Security/GetZoneAction_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    var result = JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString());
                    if (result == 0)
                    {
                        var data = JsonConvert.DeserializeObject<Safeguard.CatZoneActionResponseData>(jobject["Data"].ToString());
                        if (data != null)
                        {
                            //将防区报警目标加入缓存
                            listAlarm.Add(data);
                            topicCount--;
                            return;
                        }
                    }
                    error = true;
                }
                //当前布防模式
                if (topic == gatewayID + "/Security/GetCurrentMode_Respon")
                {
                    var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                    var result = JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString());
                    if (result != 0)
                    {
                        //当前没有模仿模式
                        this.NowGarrisonMode = GarrisonMode.None;
                    }
                    else
                    {
                        var data = JsonConvert.DeserializeObject<Safeguard.GetModeUsingResponseData>(jobject["Data"].ToString());
                        if (data != null)
                        {
                            //设置当前模仿模式
                            this.NowGarrisonMode = (GarrisonMode)data.ModeId;
                        }
                    }
                    topicCount--;
                }
            };
            mainGateway.Actions += action;
            try
            {
                var jObject = new Newtonsoft.Json.Linq.JObject() { { "Cluster_ID", 0 }, { "Command", 4036 } };
                mainGateway.Send("Security/GetSecurityInfo", jObject.ToString());
            }
            catch { }
            var dateTime = DateTime.Now;
            while ((DateTime.Now - dateTime).TotalMilliseconds < 3000)
            {
                //if (error == true) { break; }
                if (topicCount <= 0)
                {
                    //9次主题全部接收完成
                    await Task.Delay(1000);
                    break;
                }
                await Task.Delay(50);
            }
            mainGateway.Actions -= action;
            if (topicCount > 0)
            {
                //获取防区信息失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetSafetyInfoFail);
                this.ShowTipMsg(msg);
                return false;
            }
            //将防区传感器设备列表加入缓存
            foreach (var data in listDevice)
            {
                this.SetZoneSensorDeviceToMemory(data);
            }
            //将防区报警目标加入缓存
            foreach (var data in listAlarm)
            {
                this.SetAlarmTargetDeviceToMemory(data);
            }
            return true;
        }
        /// <summary>
        /// 将防区设备(传感器)列表加入缓存
        /// </summary>
        /// <param name="allData">防区数据</param>
        private void SetZoneSensorDeviceToMemory(Safeguard.GetZoneDeviceListByIdResponData allData)
        {
            if (this.dicAllZoneInfo.ContainsKey(allData.ZoneId) == false)
            {
                this.dicAllZoneInfo[allData.ZoneId] = new SafeguardZoneInfo();
            }
            //设置基本信息
            SafeguardZoneInfo zoneInfo = this.dicAllZoneInfo[allData.ZoneId];
            zoneInfo.ZoneId = allData.ZoneId;
            zoneInfo.ZoneName = allData.ZoneName;
            //信息推送
            zoneInfo.InformationPush = allData.IsDisablePushMessage;
            //处理设备
            foreach (var data2 in allData.DeviceList)
            {
                string mainKey = LocalDevice.Current.GetDeviceMainKeys(data2.MacAddr, data2.Epoint);
                //传感器设备信息
                var Deviceinfo = new Safeguard.ZoneDeviceListData();
                Deviceinfo.IsBypass = data2.IsBypass;
                Deviceinfo.MomentStatus = data2.MomentStatus;
                Deviceinfo.TriggerZoneStatus = data2.TriggerZoneStatus;
                Deviceinfo.MacAddr = data2.MacAddr;
                Deviceinfo.Epoint = data2.Epoint;
                zoneInfo.dicSensor[mainKey] = Deviceinfo;
                //本地是否有这个设备
                CommonDevice device = LocalDevice.Current.GetDevice(mainKey);
                if (device != null)
                {
                    //全部设备
                    zoneInfo.dicAllDevice[mainKey] = device.FilePath;
                }
                else
                {
                    //全部设备(缺失的未知设备)
                    var tempDevice = new CommonDevice();
                    tempDevice.DeviceAddr = data2.MacAddr;
                    tempDevice.DeviceEpoint = data2.Epoint;
                    zoneInfo.dicAllDevice[mainKey] = tempDevice.FilePath;
                }
            }
        }
        /// <summary>
        /// 将报警目标列表加入缓存
        /// </summary>
        /// <param name="resData">
        /// <para>1:24小时防区触发动作</para>
        /// <para>2:24小时静音防区触发动作</para>
        /// <para>3:其他防区(出入防区、内部防区、周界防区)触发动作</para>
        /// </param>
        /// <param name="mode">是否显示错误</param>
        /// <returns></returns>
        private void SetAlarmTargetDeviceToMemory(Safeguard.CatZoneActionResponseData resData, ShowErrorMode mode = ShowErrorMode.NO)
        {
            int ActionType = resData.ActionType;
            if (this.dicAllZoneInfo.ContainsKey(ActionType) == false)
            {
                this.dicAllZoneInfo[ActionType] = new SafeguardZoneInfo();
                //设置基本信息
                this.dicAllZoneInfo[ActionType].ZoneId = ActionType;
            }
            SafeguardZoneInfo zoneInfo = this.dicAllZoneInfo[ActionType];
            zoneInfo.dicAlarmDevice.Clear();
            zoneInfo.dicScenes.Clear();
            foreach (var data in resData.Actions)
            {
                //设备
                if (data.Type == 0)
                {
                    //本地是否有这个设备
                    string mainKey = LocalDevice.Current.GetDeviceMainKeys(data.DeviceAddr, data.Epoint);
                    //报警信息
                    zoneInfo.dicAlarmDevice[mainKey] = data;
                    CommonDevice device = LocalDevice.Current.GetDevice(mainKey);
                    if (device != null)
                    {
                        //全部设备
                        zoneInfo.dicAllDevice[mainKey] = device.FilePath;
                    }
                    else
                    {
                        //全部设备(缺失的未知设备)
                        var tempDevice = new CommonDevice();
                        tempDevice.DeviceAddr = data.DeviceAddr;
                        tempDevice.DeviceEpoint = data.Epoint;
                        zoneInfo.dicAllDevice[mainKey] = tempDevice.FilePath;
                    }
                }
                //场景
                else if (data.Type == 1)
                {
                    //场景
                    zoneInfo.dicScenes[data.ScenesId] = data.ESName;
                }
            }
        }
        #endregion
        #region ■ 获取设备___________________________
        /// <summary>
        /// 获取指定防区的所有传感器设备的信息
        /// </summary>
        /// <param name="zoonId">防区ID(它似乎是唯一主键)</param>
        /// <returns></returns>
        public List<Safeguard.ZoneDeviceListData> GetSensorDevicesInfoByZoonID(int zoonId)
        {
            var list = new List<Safeguard.ZoneDeviceListData>();
            if (this.dicAllZoneInfo.ContainsKey(zoonId) == false)
            {
                return list;
            }
            SafeguardZoneInfo info = this.dicAllZoneInfo[zoonId];
            foreach (var data in info.dicSensor.Values)
            {
                list.Add(data);
            }
            return list;
        }
        /// <summary>
        /// 获取全部的传感器设备的信息(按防区分组)
        /// </summary>
        /// <returns></returns>
        public Dictionary<int, List<Safeguard.ZoneDeviceListData>> GetAllSensorDeviceInfo()
        {
            var dic = new Dictionary<int, List<Safeguard.ZoneDeviceListData>>();
            foreach (int ZoonId in this.dicAllZoneInfo.Keys)
            {
                List<Safeguard.ZoneDeviceListData> list = this.GetSensorDevicesInfoByZoonID(ZoonId);
                if (list.Count > 0)
                {
                    dic[ZoonId] = list;
                }
            }
            return dic;
        }
        /// <summary>
        /// 根据防区ID获取本地报警目标
        /// </summary>
        /// <param name="ZoneId">防区ID</param>
        /// <returns></returns>
        public List<Safeguard.CatActionResponseObj> GetLocalAlarmTargetInfoByZoneId(int ZoneId)
        {
            if (ZoneId > 3)
            {
                ZoneId = 3;
            }
            if (this.dicAllZoneInfo.ContainsKey(ZoneId) == false)
            {
                return new List<Safeguard.CatActionResponseObj>();
            }
            SafeguardZoneInfo zoneInfo = this.dicAllZoneInfo[ZoneId];
            //优先场景吧
            var list = new List<Safeguard.CatActionResponseObj>();
            foreach (int sceneId in zoneInfo.dicScenes.Keys)
            {
                var objData = new Safeguard.CatActionResponseObj();
                objData.Type = 1;
                objData.ScenesId = sceneId;
                objData.ESName = zoneInfo.dicScenes[sceneId];
                list.Add(objData);
            }
            foreach (var data in zoneInfo.dicAlarmDevice.Values)
            {
                list.Add(data);
            }
            return list;
        }
        /// <summary>
        /// 获取指定传感器所处的防区ID(不存在则返回-1)
        /// </summary>
        /// <param name="device">指定传感器设备</param>
        /// <returns></returns>
        public int GetZoneIdByIASZone(CommonDevice device)
        {
            string mainkey = this.GetDeviceMainKeys(device);
            foreach (SafeguardZoneInfo info in this.dicAllZoneInfo.Values)
            {
                if (info.dicSensor.ContainsKey(mainkey) == true)
                {
                    return info.ZoneId;
                }
            }
            return -1;
        }
        #endregion
        #region ■ 添加传感器_________________________
        /// <summary>
        /// 添加传感器设备到防区(失败时会弹出信息框)
        /// </summary>
        /// <param name="zoonId">防区ID(它似乎是唯一主键)</param>
        /// <param name="listdevice">设备列表</param>
        public async Task<bool> AddSensorDevice(int zoonId, List<CommonDevice> listdevice)
        {
            //现获取当前的布防模式
            var safetyMode = await this.GetSafetyMode();
            if (safetyMode != null)
            {
                //当前正处于布防模式,无法添加设备
                string msg = Language.StringByID(R.MyInternationalizationString.uCanNotAddDeviceInGarrisonMode);
                this.ShowErrorMsg(msg);
                return false;
            }
            //校验密码
            bool result = await this.ShowSafetyAdminValidatedDialog();
            if (result == false)
            {
                return false;
            }
            if (listdevice.Count == 0)
            {
                return true;
            }
            List<int> listMomentStatus = new List<int>();
            List<int> listTriggerStatus = new List<int>();
            foreach (var device in listdevice)
            {
                int MomentStatus = 1;
                int TriggerZoneStatus = 3;
                //获取安防传感器的瞬间状态设定值
                this.GetSafeguardSensorMomentStatus(device, ref MomentStatus, ref TriggerZoneStatus);
                listMomentStatus.Add(MomentStatus);
                listTriggerStatus.Add(TriggerZoneStatus);
            }
            //添加设备到网关
            List<string> listSuccess = await this.AddSensorDeviceToGateway(zoonId, listdevice, listMomentStatus, listTriggerStatus);
            if (listSuccess == null)
            {
                return false;
            }
            //修改缓存
            if (this.dicAllZoneInfo.ContainsKey(zoonId) == false)
            {
                this.dicAllZoneInfo[zoonId] = new SafeguardZoneInfo();
            }
            SafeguardZoneInfo info = this.dicAllZoneInfo[zoonId];
            for (int i = 0; i < listdevice.Count; i++)
            {
                CommonDevice device = listdevice[i];
                string mainkey = this.GetDeviceMainKeys(device);
                if (listSuccess.Contains(mainkey) == false)
                {
                    //没有添加成功
                    continue;
                }
                Safeguard.ZoneDeviceListData sensorInfo = null;
                if (info.dicSensor.ContainsKey(mainkey) == true)
                {
                    sensorInfo = info.dicSensor[mainkey];
                }
                else
                {
                    sensorInfo = new Safeguard.ZoneDeviceListData();
                    info.dicSensor[mainkey] = sensorInfo;
                    sensorInfo.Epoint = device.DeviceEpoint;
                    sensorInfo.MacAddr = device.DeviceAddr;
                    sensorInfo.IsBypass = 0;
                }
                info.dicAllDevice[mainkey] = device.FilePath;
                //设备信息
                sensorInfo.MomentStatus = listMomentStatus[0];
                sensorInfo.TriggerZoneStatus = listTriggerStatus[0];
            }
            return true;
        }
        /// <summary>
        /// 添加传感器设备到网关(失败时会弹出信息框)
        /// </summary>
        /// <param name="zoonId">防区ID(它似乎是唯一主键)</param>
        /// <param name="listdevice">设备列表</param>
        /// <param name="listMomentStatus">设备上报的状态是否为瞬间状态</param>
        /// <param name="listTriggerStatus">我也不知道这个是什么东西</param>
        /// <returns></returns>
        private async Task<List<string>> AddSensorDeviceToGateway(int zoonId, List<CommonDevice> listdevice, List<int> listMomentStatus, List<int> listTriggerStatus)
        {
            var addData = new Safeguard.AddDeviceToZoneData();
            addData.ZoneId = zoonId;
            addData.LoginToken = this.GetLoginToken();
            for (int i = 0; i < listdevice.Count; i++)
            {
                CommonDevice device = listdevice[i];
                //数据组装
                var deviceData = new Safeguard.DeviceListObj();
                deviceData.Epoint = device.DeviceEpoint;
                deviceData.MacAddr = device.DeviceAddr;
                deviceData.MomentStatus = listMomentStatus[i];
                deviceData.TriggerZoneStatus = listTriggerStatus[i];
                addData.DeviceList.Add(deviceData);
            }
            //没有数据
            if (addData.DeviceList.Count == 0)
            {
                return new List<string>();
            }
            //添加到网关
            var returnData = await Safeguard.AddDeviceToZoneAsync(addData);
            if (returnData == null || returnData.addDeviceToPartResponseData == null || returnData.addDeviceToPartResponseData.Result == 1)
            {
                //向防区添加设备失败
                string msg = Language.StringByID(R.MyInternationalizationString.uAddDeviceToZoneFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, returnData);
                this.ShowErrorMsg(msg);
                return null;
            }
            List<string> listSuccess = new List<string>();
            foreach (var data in returnData.addDeviceToPartResponseData.DeviceList)
            {
                //一批设备里面,成功添加的
                if (data.Status == 0)
                {
                    listSuccess.Add(LocalDevice.Current.GetDeviceMainKeys(data.MacAddr, data.Epoint));
                }
                else if (data.Status == 1)
                {
                    var device = Common.LocalDevice.Current.GetDevice(data.MacAddr, data.Epoint);
                    string msg = Common.LocalDevice.Current.GetDeviceEpointName(device) + "\r\n";
                    //目标设备不存在
                    msg += Language.StringByID(R.MyInternationalizationString.uTargetDeviceIsNotExsit);
                    this.ShowTipMsg(msg);
                }
                else if (data.Status == 2)
                {
                    var device = Common.LocalDevice.Current.GetDevice(data.MacAddr, data.Epoint);
                    string msg = Common.LocalDevice.Current.GetDeviceEpointName(device) + "\r\n";
                    //设备已加入其它防区
                    msg += Language.StringByID(R.MyInternationalizationString.uDeviceHadAddToTheOtherGarrison);
                    this.ShowTipMsg(msg);
                }
            }
            return listSuccess;
        }
        /// <summary>
        /// 获取安防传感器的瞬间状态设定值(添加传感器到安防时,需要调用此方法来初始化参数)
        /// </summary>
        /// <param name="device">设备对象</param>
        /// <param name="MomentStatus">设备上报的状态是否为瞬间状态</param>
        /// <param name="TriggerZoneStatus">我也不知道这个是什么东西</param>
        public void GetSafeguardSensorMomentStatus(CommonDevice device, ref int MomentStatus, ref int TriggerZoneStatus)
        {
            //运动传感器
            if (device.IasDeviceType == 13)
            {
                MomentStatus = 1;
                TriggerZoneStatus = 3;
            }
            //烟雾传感器
            else if (device.IasDeviceType == 40)
            {
                MomentStatus = 1;
                TriggerZoneStatus = 3;
            }
            //水侵传感器
            else if (device.IasDeviceType == 42)
            {
                MomentStatus = 1;
                TriggerZoneStatus = 3;
            }
            //燃气传感器
            else if (device.IasDeviceType == 43)
            {
                MomentStatus = 1;
                TriggerZoneStatus = 3;
            }
            //紧急按钮
            else if (device.IasDeviceType == 44)
            {
                MomentStatus = 1;
                TriggerZoneStatus = 3;
            }
            //钥匙扣
            else if (device.IasDeviceType == 277)
            {
                MomentStatus = 1;
                TriggerZoneStatus = 3;
            }
            //门窗传感器
            else if (device.IasDeviceType == 21 || device.IasDeviceType == 22)
            {
                MomentStatus = 0;
                TriggerZoneStatus = 3;
            }
            //如果是虚拟设备,则这个东西永恒为0
            if (device.DriveCode > 0)
            {
                MomentStatus = 0;
            }
        }
        #endregion
        #region ■ 删除设备___________________________
        /// <summary>
        /// 删除传感器设备
        /// </summary>
        /// <param name="zoonId">防区ID(它似乎是唯一主键)</param>
        /// <param name="listdevice">传感器设备对象</param>
        public async Task<bool> DeleteSensorDevice(int zoonId, List<CommonDevice> listdevice)
        {
            //现获取当前的布防模式
            var safetyMode = await this.GetSafetyMode();
            if (safetyMode != null)
            {
                //当前正处于布防模式,无法删除设备
                string msg = Language.StringByID(R.MyInternationalizationString.uCanNotDeleteDeviceInGarrisonMode);
                this.ShowErrorMsg(msg);
                return false;
            }
            //校验密码
            bool result = await this.ShowSafetyAdminValidatedDialog();
            if (result == false)
            {
                return false;
            }
            if (listdevice.Count == 0)
            {
                return true;
            }
            //从网关那里删除设备
            List<string> listKeys = await this.DeleteSensorDeviceFromGateway(zoonId, listdevice);
            if (listKeys == null)
            {
                return false;
            }
            //修改缓存
            if (this.dicAllZoneInfo.ContainsKey(zoonId) == false)
            {
                return true;
            }
            SafeguardZoneInfo info = this.dicAllZoneInfo[zoonId];
            foreach (CommonDevice device in listdevice)
            {
                string mainkey = this.GetDeviceMainKeys(device);
                if (info.dicSensor.ContainsKey(mainkey) == true
                    && listKeys.Contains(mainkey) == true)
                {
                    info.dicSensor.Remove(mainkey);
                    info.dicAllDevice.Remove(mainkey);
                }
            }
            return true;
        }
        /// <summary>
        /// 从网关那里删除传感器设备
        /// </summary>
        /// <param name="zoonId">防区ID(它似乎是唯一主键)</param>
        /// <param name="listdevice">设备对象</param>
        /// <returns></returns>
        private async Task<List<string>> DeleteSensorDeviceFromGateway(int zoonId, List<CommonDevice> listdevice)
        {
            var deteleData = new Safeguard.RemoveEqToZoneData();
            deteleData.ZoneId = zoonId;
            deteleData.LoginToken = this.GetLoginToken();
            foreach (CommonDevice device in listdevice)
            {
                //组装数据
                var removeData = new Safeguard.RemoveDeviceListObj();
                removeData.MacAddr = device.DeviceAddr;
                removeData.Epoint = device.DeviceEpoint;
                deteleData.RemoveDeviceList.Add(removeData);
            }
            //没有数据
            if (deteleData.RemoveDeviceList.Count == 0)
            {
                return new List<string>();
            }
            //从网关中移除
            var returnData = await Safeguard.RemoveDeviceToZoneAsync(deteleData);
            if (returnData == null || returnData.removeDeviceToZoneResponseData == null || returnData.removeDeviceToZoneResponseData.Result == 1)
            {
                //设备删除失败
                string msg = Language.StringByID(R.MyInternationalizationString.uDeviceDeleteFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, returnData);
                this.ShowErrorMsg(msg);
                return null;
            }
            List<string> listKeys = new List<string>();
            foreach (var data in returnData.removeDeviceToZoneResponseData.RemoveDeviceList)
            {
                if (data.Status == 0)
                {
                    listKeys.Add(LocalDevice.Current.GetDeviceMainKeys(data.MacAddr, data.Epoint));
                }
            }
            return listKeys;
        }
        #endregion
        #region ■ 存在检测___________________________
        /// <summary>
        /// 指定传感器设备是否存在于安防网关
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        public bool IsSensorDeviceExist(CommonDevice device)
        {
            string mainkey = this.GetDeviceMainKeys(device);
            foreach (SafeguardZoneInfo info in this.dicAllZoneInfo.Values)
            {
                if (info.dicSensor.ContainsKey(mainkey) == true)
                {
                    return true;
                }
            }
            return false;
        }
        /// <summary>
        /// 指定传感器设备是否存在于安防网关
        /// </summary>
        /// <param name="ZoneId">防区ID</param>
        /// <param name="device"></param>
        /// <returns></returns>
        public bool IsSensorDeviceExist(int ZoneId, CommonDevice device)
        {
            if (this.dicAllZoneInfo.ContainsKey(ZoneId) == false)
            {
                return false;
            }
            string mainkey = this.GetDeviceMainKeys(device);
            SafeguardZoneInfo info = this.dicAllZoneInfo[ZoneId];
            if (info.dicSensor.ContainsKey(mainkey) == true)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 指定报警设备是否存在于安防网关
        /// </summary>
        /// <param name="ZoneId">防区ID</param>
        /// <param name="device"></param>
        /// <returns></returns>
        public bool IsAlarmDeviceExist(int ZoneId, CommonDevice device)
        {
            if (ZoneId < 3)
            {
                if (this.dicAllZoneInfo.ContainsKey(ZoneId) == false)
                {
                    return false;
                }
                string mainkey = this.GetDeviceMainKeys(device);
                SafeguardZoneInfo info = this.dicAllZoneInfo[ZoneId];
                if (info.dicAlarmDevice.ContainsKey(mainkey) == true)
                {
                    return true;
                }
            }
            else
            {
                string mainkey = this.GetDeviceMainKeys(device);
                for (int i = 3; i <= 5; i++)
                {
                    if (this.dicAllZoneInfo.ContainsKey(i) == false)
                    {
                        continue;
                    }
                    SafeguardZoneInfo info = this.dicAllZoneInfo[i];
                    if (info.dicAlarmDevice.ContainsKey(mainkey) == true)
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        /// <summary>
        /// 指定布防是否存在于安防网关
        /// </summary>
        /// <param name="zoonId">防区ID(它似乎是唯一主键)</param>
        /// <returns></returns>
        public bool IsZoonExist(int zoonId)
        {
            return this.dicAllZoneInfo.ContainsKey(zoonId);
        }
        /// <summary>
        /// 是否设置有内部防区
        /// </summary>
        /// <returns></returns>
        public bool IsHadInternalDefenseArea()
        {
            foreach (SafeguardZoneInfo info in this.dicAllZoneInfo.Values)
            {
                //存在第四防区
                if (info.ZoneId == 4)
                {
                    //里面有没有设备
                    if (info.dicSensor.Count > 0)
                    {
                        return true;
                    }
                    //不再往下循环
                    return false;
                }
            }
            return false;
        }
        #endregion
        #region ■ 安防登陆___________________________
        /// <summary>
        /// 主用户登陆  0:密码错误  1:正常  -1:异常
        /// </summary>
        /// <param name="password"></param>
        /// <param name="showMode"></param>
        public async Task<int> AdminLogin(string password, ShowErrorMode showMode = ShowErrorMode.YES)
        {
            //尝试登陆
            var resultData = await ZigBee.Device.Safeguard.AdminLoginResponAsync(password, this.GetLoginToken());
            if (resultData == null)
            {
                return -1;
            }
            if (resultData != null && resultData.Result != 0)
            {
                if (showMode == ShowErrorMode.YES)
                {
                    //管理员密码错误
                    string msg = Language.StringByID(R.MyInternationalizationString.uAdministratorPasswordIsError);
                    this.ShowErrorMsg(msg);
                }
                return 0;
            }
            return 1;
        }
        /// <summary>
        /// 获取指定用户的密码,如果用户不存在,则返回null(错误不会弹出信息)
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public async Task<string> GetUserPassword(int userId)
        {
            //先获取密码
            var nowPw = await Safeguard.CatUserPasswordAsync(this.GetLoginToken());
            if (nowPw == null || nowPw.catUserPasswordResponseData == null)
            {
                return null;
            }
            foreach (var pw in nowPw.catUserPasswordResponseData.UserPasswordList)
            {
                if (pw.UserId == userId)
                {
                    return pw.Password;
                }
            }
            return null;
        }
        /// <summary>
        /// 获取全部用户的密码(错误会弹出信息)
        /// </summary>
        /// <param name="mode">是否显示错误</param>
        /// <returns></returns>
        public async Task<List<Safeguard.UserPasswordListObj>> GetAllUserPassword(ShowErrorMode mode = ShowErrorMode.YES)
        {
            //先获取密码
            var nowPw = await Safeguard.CatUserPasswordAsync(this.GetLoginToken());
            if (nowPw == null || nowPw.catUserPasswordResponseData == null)
            {
                //获取安防密码失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetSafetyPasswordFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, nowPw);
                if (mode == ShowErrorMode.YES)
                {
                    this.ShowErrorMsg(msg);
                }
                return null;
            }
            return nowPw.catUserPasswordResponseData.UserPasswordList;
        }
        /// <summary>
        /// 修改用户密码(不存在时,则新建)
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="password">密码</param>
        /// <param name="passWordTips">密码提示</param>
        /// <returns></returns>
        public async Task<bool> ChangedUserPassword(int userId, string password, string passWordTips)
        {
            //创建新用户
            var result = await Safeguard.SetUserPasswordAsync(userId, password, passWordTips, this.GetLoginToken());
            if (result == null || result.setUserPasswordResponseData == null)
            {
                if (userId != 5)
                {
                    //修改用户密码失败
                    string msg = Language.StringByID(R.MyInternationalizationString.uChangedUserPasswordFail);
                    //拼接上【网关回复超时】的Msg
                    msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                    this.ShowErrorMsg(msg);
                    return false;
                }
                else
                {
                    //修改胁迫密码失败
                    string msg = Language.StringByID(R.MyInternationalizationString.uChangedCoercePasswordFail);
                    this.ShowErrorMsg(msg);
                    return false;
                }
            }
            if (result.setUserPasswordResponseData.Result == 1)
            {
                //用户密码数已满(最大4个)
                string msg = Language.StringByID(R.MyInternationalizationString.uUserPasswordCountIsMax);
                this.ShowErrorMsg(msg);
                return false;
            }
            if (result.setUserPasswordResponseData.Result == 2)
            {
                //密码长度不正确
                string msg = Language.StringByID(R.MyInternationalizationString.uPasswordLengthIsError);
                this.ShowErrorMsg(msg);
                return false;
            }
            if (result.setUserPasswordResponseData.Result == 3)
            {
                //用户密码重复
                string msg = Language.StringByID(R.MyInternationalizationString.uUserPasswordIsRepeat);
                this.ShowErrorMsg(msg);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 显示校验管理员密码的窗口
        /// </summary>
        /// <returns></returns>
        public async Task<bool> ShowSafetyAdminValidatedDialog()
        {
            //式样变更,不再弹出输入管理员密码框,直接取默认密码admin
            //0:密码错误  1:正常 - 1:异常
            var result = await this.AdminLogin("admin", ShowErrorMode.NO);
            if (result != 1)
            {
                //获取执行权限失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetActionAuthorityFail);
                this.ShowTipMsg(msg);
                if (result == 0)
                {
                    //重置密码
                    await DoResetAdministratorPsw("admin");
                }
            }
            return result == 1;
        }
        /// <summary>
        /// 检测是否已经配置有用户密码(内部会弹出错误信息,-1:异常 0:没有配置 1:已经配置)
        /// </summary>
        /// <returns></returns>
        public async Task<int> CheckHadConfigureUserPsw()
        {
            var pswInfo = await this.GetAllUserPassword(ShowErrorMode.NO);
            if (pswInfo == null)
            {
                //出现未知错误,请稍后再试
                string msg = Language.StringByID(R.MyInternationalizationString.uUnKnowErrorAndResetAgain);
                this.ShowTipMsg(msg);
                return -1;
            }
            foreach (var data in pswInfo)
            {
                //4个用户密码
                if (data.UserId >= 1 && data.UserId <= 4)
                {
                    return 1;
                }
            }
            return 0;
        }
        /// <summary>
        /// 添加密码的备注
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <param name="password">网关说需要原来的密码,也不知道为什么</param>
        /// <param name="passWordTips">密码备注</param>
        /// <returns></returns>
        public async Task<bool> AddPassWordTips(int userId, string password, string passWordTips)
        {
            var result = await Safeguard.SetPassWordTipsAsync(userId, password, passWordTips, this.GetLoginToken());
            if (result == null || result.setUserPasswordResponseData == null)
            {
                //修改备注信息失败
                string msg = Language.StringByID(R.MyInternationalizationString.uEditorNoteInformationFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return false;
            }
            if (result.setUserPasswordResponseData.Result != 0)
            {
                //修改备注信息失败
                string msg = Language.StringByID(R.MyInternationalizationString.uEditorNoteInformationFail);
                this.ShowErrorMsg(msg);
                return false;
            }
            return true;
        }
        #endregion
        #region ■ 报警目标___________________________
        /// <summary>
        /// 添加报警目标到安防
        /// </summary>
        /// <param name="ZoneId">防区ID</param>
        /// <param name="listAction">添加的目标</param>
        /// <returns></returns>
        public async Task<bool> AddAlarmTagetToSafety(int ZoneId, List<Safeguard.AlarmActionObj> listAction)
        {
            //现获取当前的布防模式
            var safetyMode = await this.GetSafetyMode();
            if (safetyMode != null)
            {
                //当前正处于布防模式,无法添加设备
                string msg = Language.StringByID(R.MyInternationalizationString.uCanNotAddDeviceInGarrisonMode);
                this.ShowErrorMsg(msg);
                return false;
            }
            //验证身份
            bool login = await this.ShowSafetyAdminValidatedDialog();
            if (login == false)
            {
                return false;
            }
            if (ZoneId > 3)
            {
                ZoneId = 3;
            }
            var saveData = new Safeguard.AddZoneActionData();
            saveData.ActionType = ZoneId;
            saveData.Actions = listAction;
            saveData.LoginToken = this.GetLoginToken();
            //添加报警目标到安防
            var result = await Safeguard.AddZoneActionAsync(saveData);
            if (result == null || result.addZoneActionResponseData == null || result.addZoneActionResponseData.Result == 1)
            {
                //添加报警目标失败
                string msg = Language.StringByID(R.MyInternationalizationString.uAddAlarmTargetFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return false;
            }
            foreach (var data in result.addZoneActionResponseData.Actions)
            {
                if (data.Status == "1")
                {
                    if (data.Type == "0")
                    {
                        var device = Common.LocalDevice.Current.GetDevice(data.DeviceAddr, data.Epoint);
                        string msg = Common.LocalDevice.Current.GetDeviceEpointName(device) + "\r\n";
                        //目标设备不存在
                        msg += Language.StringByID(R.MyInternationalizationString.uTargetDeviceIsNotExsit);
                        this.ShowTipMsg(msg);
                    }
                    else if (data.Type == "1")
                    {
                        var scene = HdlSceneLogic.Current.GetSceneUIBySceneId(data.ScenesId);
                        if (scene != null)
                        {
                            string msg = scene.Name + "\r\n";
                            //目标场景不存在
                            msg += Language.StringByID(R.MyInternationalizationString.uTargetSceneIsNotExsit);
                            this.ShowTipMsg(msg);
                        }
                    }
                }
            }
            //将报警目标列表加入缓存(从新从网关那里获取新追加的设备)
            var resultData = await Safeguard.CatZoneActionAsync(ZoneId);
            if (resultData == null
                || resultData.catZoneActionResponseData == null
                || resultData.catZoneActionResponseData.Result == 1)
            {
                //获取报警目标列表失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetAlarmTargetListFail);
                this.ShowTipMsg(msg);
                return false;
            }
            this.SetAlarmTargetDeviceToMemory(resultData.catZoneActionResponseData, ShowErrorMode.YES);
            return true;
        }
        /// <summary>
        /// 删除报警目标
        /// </summary>
        /// <param name="ZoneId">防区ID</param>
        /// <param name="listActions">删除的目标</param>
        /// <returns></returns>
        public async Task<bool> DeleteAlarmTaget(int ZoneId, List<Safeguard.DelAlarmActionObj> listActions)
        {
            //现获取当前的布防模式
            var safetyMode = await this.GetSafetyMode();
            if (safetyMode != null)
            {
                //当前正处于布防模式,无法删除设备
                string msg = Language.StringByID(R.MyInternationalizationString.uCanNotDeleteDeviceInGarrisonMode);
                this.ShowErrorMsg(msg);
                return false;
            }
            //验证身份
            bool login = await this.ShowSafetyAdminValidatedDialog();
            if (login == false)
            {
                return false;
            }
            if (ZoneId > 3)
            {
                ZoneId = 3;
            }
            //参数
            var Pra = new Safeguard.DelZoneActionData();
            Pra.ActionType = ZoneId;
            Pra.Actions = listActions;
            Pra.LoginToken = this.GetLoginToken();
            //执行删除
            var result = await Safeguard.DelZoneActionAsync(Pra);
            if (result == null || result.delZoneActionResponseData == null || result.delZoneActionResponseData.Result == 1)
            {
                //删除报警目标失败
                string msg = Language.StringByID(R.MyInternationalizationString.uDeleteAlarmTargetFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return false;
            }
            //获取本地缓存
            if (this.dicAllZoneInfo.ContainsKey(ZoneId) == false)
            {
                return true;
            }
            SafeguardZoneInfo zoneInfo = this.dicAllZoneInfo[ZoneId];
            //修改缓存
            foreach (var device in result.delZoneActionResponseData.Actions)
            {
                //删除失败
                if (device.Status == "1")
                {
                    continue;
                }
                //设备
                if (device.Type == "0")
                {
                    //删除报警设备
                    string mainkeys = Common.LocalDevice.Current.GetDeviceMainKeys(device.DeviceAddr, device.Epoint);
                    if (zoneInfo.dicAlarmDevice.ContainsKey(mainkeys) == false)
                    {
                        continue;
                    }
                    zoneInfo.dicAlarmDevice.Remove(mainkeys);
                    zoneInfo.dicAllDevice.Remove(mainkeys);
                }
                //场景
                else if (device.Type == "1")
                {
                    //删除场景
                    if (zoneInfo.dicScenes.ContainsKey(device.ScenesId) == true)
                    {
                        zoneInfo.dicScenes.Remove(device.ScenesId);
                    }
                }
            }
            return true;
        }
        #endregion
        #region ■ 获取场景___________________________
        /// <summary>
        /// 根据防区ID获取本地的场景
        /// </summary>
        /// <param name="ZoneId">防区ID</param>
        /// <returns></returns>
        public Dictionary<int, string> GetLocalSceneByZoneID(int ZoneId)
        {
            if (ZoneId > 3)
            {
                ZoneId = 3;
            }
            if (this.dicAllZoneInfo.ContainsKey(ZoneId) == false)
            {
                return new Dictionary<int, string>();
            }
            var infoData = this.dicAllZoneInfo[ZoneId];
            return infoData.dicScenes;
        }
        #endregion
        #region ■ 旁路设置___________________________
        /// <summary>
        /// 旁路状态设置
        /// </summary>
        /// <param name="zoneId">防区ID</param>
        /// <param name="device">传感器设备</param>
        /// <param name="statu">旁路状态 -> 0:不旁路  1:旁路</param>
        /// <returns></returns>
        public async Task<bool> SetByPassStatuToSafety(int zoneId, CommonDevice device, int statu)
        {
            //验证
            bool flage = await this.ShowSafetyAdminValidatedDialog();
            if (flage == false)
            {
                return false;
            }
            //参数
            var Pra = new Safeguard.EqByPassData();
            Pra.ZoneId = zoneId;
            Pra.MacAddr = device.DeviceAddr;
            Pra.Epoint = device.DeviceEpoint;
            Pra.IsByPass = statu;
            Pra.LoginToken = this.GetLoginToken();
            var result = await Safeguard.EqByPassAllDataAsync(Pra);
            if (result == null || result.eqByPassResponseData != null && result.eqByPassResponseData.Result == 3)
            {
                //设置失败,系统当前处于撤防状态
                string msg2 = Language.StringByID(R.MyInternationalizationString.uByPassFailAndSystemInWithdrawGarrisonStatu);
                this.ShowErrorMsg(msg2);
                return false;
            }
            //其他错误
            if (result.eqByPassResponseData == null || result.eqByPassResponseData.Result != 0)
            {
                //旁路状态设置失败
                string msg = Language.StringByID(R.MyInternationalizationString.uSetByPassStatuFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return false;
            }
            return true;
        }
        #endregion
        #region ■ 布防撤防___________________________
        /// <summary>
        /// 设置安防的布防模式,成功时,内部不会提示信息(不要调用此方法来实现【撤防】)
        /// </summary>
        /// <param name="garrison">布防模式</param>
        /// <returns>网关现在实行的布防模式</returns>
        public async Task<GarrisonMode> SetSafetyGarrisonByModel(GarrisonMode garrison)
        {
            //检测其他防区里面有没有配置有传感器
            if (this.CheckHadInteriorSectorsSensor() == false)
            {
                //其他防区里没有配置传感器设备
                string msg = Language.StringByID(R.MyInternationalizationString.uNotSensorInOtherSectors);
                this.ShowErrorMsg(msg);
                return GarrisonMode.None;
            }
            if (this.UserPassword == null)
            {
                var data = HdlFileLogic.Current.ReadFileByteContent(DirNameResourse.SafeguardUserPassword);
                if (data != null)
                {
                    this.UserPassword = System.Text.Encoding.UTF8.GetString(data);
                }
            }
            if (string.IsNullOrEmpty(this.UserPassword) == true)
            {
                //输入密码
                string password = await this.ShowInputUserPasswordForm();
                if (string.IsNullOrEmpty(password) == true)
                {
                    return GarrisonMode.None;
                }
                var result = await this.SetSafetyGarrisonByModel(garrison, false);
                if (result != GarrisonMode.None && result != GarrisonMode.RemoveGarrison)
                {
                    //保存加密的密码到本地
                    HdlFileLogic.Current.SaveTextToFile(DirNameResourse.SafeguardUserPassword, this.UserPassword);
                }
                return result;
            }
            else
            {
                return await this.SetSafetyGarrisonByModel(garrison, true);
            }
        }
        /// <summary>
        /// 设置安防的布防模式,成功时,内部不会提示信息(不要调用此方法来实现【撤防】)
        /// </summary>
        /// <param name="garrison">布防模式</param>
        /// <param name="showPswForm">用户密码错误时,是否允许弹出输入用户密码的窗口</param>
        /// <returns>网关现在实行的布防模式</returns>
        private async Task<GarrisonMode> SetSafetyGarrisonByModel(GarrisonMode garrison, bool showPswForm)
        {
            //先把当前的模式给移除掉
            var flage = await this.RemoveSafetyGarrison(garrison, showPswForm);
            if (flage == -1)
            {
                return GarrisonMode.None;
            }
            //判断有没有其他逻辑去修改了布防模式
            //所以再次获取模式
            var safetyMode = await this.GetSafetyMode();
            if (safetyMode != null)
            {
                return GarrisonMode.None;
            }
            //参数
            var Pra = new Safeguard.EnableModeData();
            //模式ID
            Pra.ModeId = (int)garrison;
            //检查防区设备最近上报的安防信息状态进行布防
            Pra.CheckIASStatus = 1;
            //永久布防,直到撤防
            Pra.Setting = 1;
            //用户密码
            Pra.UserPassword = this.UserPassword;
            //执行布防
            var result = await Safeguard.EnableModeAsync(Pra);
            if (result == null || result.enableModeResponseData == null)
            {
                //布防设置失败
                string msg = Language.StringByID(R.MyInternationalizationString.uSetGarrisonFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return GarrisonMode.RemoveGarrison;
            }
            //错误检测
            if (result.enableModeResponseData.Result == 1)
            {
                //布防模式不存在
                string msg = Language.StringByID(R.MyInternationalizationString.uGarrisonModeIsNotEsixt);
                this.ShowErrorMsg(msg);
                return GarrisonMode.RemoveGarrison;
            }
            else if (result.enableModeResponseData.Result == 2)
            {
                //清空密码缓存
                this.UserPassword = null;
                if (showPswForm == false)
                {
                    //用户密码错误或未设置用户密码
                    string msg = Language.StringByID(R.MyInternationalizationString.uUserPasswordIsError);
                    this.ShowErrorMsg(msg);
                    return GarrisonMode.RemoveGarrison;
                }
                else
                {
                    //重新显示输入用户密码的窗口
                    string password = await this.ShowInputUserPasswordForm();
                    if (string.IsNullOrEmpty(password) == true)
                    {
                        return GarrisonMode.RemoveGarrison;
                    }
                    var result2 = await this.SetSafetyGarrisonByModel(garrison, false);
                    if (result2 != GarrisonMode.None && result2 != GarrisonMode.RemoveGarrison)
                    {
                        //保存加密密码到本地
                        HdlFileLogic.Current.SaveTextToFile(DirNameResourse.SafeguardUserPassword, this.UserPassword);
                    }
                    return result2;
                }
            }
            else if (result.enableModeResponseData.Result == 3)
            {
                //安防设备未就绪
                string msg = Language.StringByID(R.MyInternationalizationString.uSafetyDeviceDoNotReady);
                msg += "(" + result.enableModeResponseData.IASName + ")";
                this.ShowErrorMsg(msg);
                return GarrisonMode.RemoveGarrison;
            }
            else if (result.enableModeResponseData.Result == 4)
            {
                //其他布防模式正在启用中
                string msg = Language.StringByID(R.MyInternationalizationString.uOtherGarrisonIsActtion);
                this.ShowErrorMsg(msg);
                return (GarrisonMode)result.enableModeResponseData.ModeIdBeUsing;
            }
            else if (result.enableModeResponseData.Result == 5)
            {
                //模式属性不允许失能
                string msg = Language.StringByID(R.MyInternationalizationString.uGarrisonModeElementCanNotLostFunction);
                this.ShowErrorMsg(msg);
                return GarrisonMode.RemoveGarrison;
            }
            return garrison;
        }
        /// <summary>
        /// 移除当前正在运行的布防模式(成功时,内部不会提示信息)
        /// </summary>
        /// <param name="garrison">布防模式(这个变量只是为了变更提示错误信息,当不是撤防时,错误提示信息会改变)</param>
        /// <param name="showPswForm">用户密码错误时,是否允许弹出输入用户密码的窗口</param>
        /// <returns></returns>
        public async Task<int> RemoveSafetyGarrison(GarrisonMode garrison, bool showPswForm)
        {
            //现获取当前的布防模式
            var safetyMode = await this.GetSafetyMode();
            if (safetyMode == null)
            {
                //如果是撤防的话
                if (garrison == GarrisonMode.RemoveGarrison)
                {
                    //当前不存在布防
                    string msg = Language.StringByID(R.MyInternationalizationString.uNowDoNotHadGarrison);
                    this.ShowErrorMsg(msg);
                    return -1;
                }
                //并没有设置布防,也就不谈什么撤防了
                return 0;
            }
            //撤防的时候,无条件弹出输入密码框
            if (garrison == GarrisonMode.RemoveGarrison)
            {
                string psw = await this.ShowInputUserPasswordForm();
                if (string.IsNullOrEmpty(psw) == true)
                {
                    return -1;
                }
            }
            //撤防
            var result = await Safeguard.WithdrawModeAsync(this.UserPassword);
            if (result == null || result.withdrawModeResponseData == null)
            {
                //执行撤防操作的时候
                if (garrison == GarrisonMode.RemoveGarrison)
                {
                    //撤防失败
                    string msg = Language.StringByID(R.MyInternationalizationString.uRemoveGarrisonFail);
                    //拼接上【网关回复超时】的Msg
                    msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                    this.ShowErrorMsg(msg);
                }
                else
                {
                    //布防模式变更失败
                    string msg = Language.StringByID(R.MyInternationalizationString.uChangedGarrisonModeFail);
                    //拼接上【网关回复超时】的Msg
                    msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                    this.ShowErrorMsg(msg);
                }
                return -1;
            }
            if (result.withdrawModeResponseData.Result == 2)
            {
                //清空密码缓存
                this.UserPassword = null;
                if (showPswForm == false || garrison == GarrisonMode.RemoveGarrison)
                {
                    //用户密码错误或未设置用户密码
                    string msg = Language.StringByID(R.MyInternationalizationString.uUserPasswordIsError);
                    this.ShowErrorMsg(msg);
                    return -1;
                }
                else
                {
                    //重新显示输入用户密码的窗口
                    string password = await this.ShowInputUserPasswordForm();
                    if (string.IsNullOrEmpty(password) == true)
                    {
                        return -1;
                    }
                    var result2 = await this.RemoveSafetyGarrison(garrison, false);
                    if (result2 != -1)
                    {
                        //保存到加密密码本地
                        HdlFileLogic.Current.SaveTextToFile(DirNameResourse.SafeguardUserPassword, this.UserPassword);
                    }
                    return result2;
                }
            }
            else if (result.withdrawModeResponseData.Result == 3 && garrison == GarrisonMode.RemoveGarrison)
            {
                //当前模式不可撤防
                string msg = Language.StringByID(R.MyInternationalizationString.uNowGarrisonCanNotRemove);
                this.ShowErrorMsg(msg);
                return -1;
            }
            return 1;
        }
        /// <summary>
        /// 获取当前安防的模式(在家,离家等等),如果没有布防,则返回null
        /// </summary>
        public async Task<Safeguard.GetModeUsingResponseData> GetSafetyMode()
        {
            var result = await Safeguard.GetModeUsingAsync();
            if (result == null || result.getModeUsingResponseData == null)
            {
                return null;
            }
            if (result.getModeUsingResponseData.Result == 1)
            {
                return null;
            }
            return result.getModeUsingResponseData;
        }
        /// <summary>
        /// 显示输入用户密码的界面(返回null时代表出错或者取消)
        /// </summary>
        public async Task<string> ShowInputUserPasswordForm()
        {
            NumberPswInputDialogForm Dialogform = null;
            bool isShowingProgressBar = false;
            string ProgressBarText = string.Empty;
            string pasword = null;
            HdlThreadLogic.Current.RunMain(() =>
            {
                isShowingProgressBar = CommonPage.Loading.Visible;
                ProgressBarText = CommonPage.Loading.Text;
                if (isShowingProgressBar == true)
                {
                    //如果在弹出校验密码框的时候,显示着进度条的话,先暂时关闭进度条
                    CommonPage.Loading.Hide();
                }
                Dialogform = new NumberPswInputDialogForm();
                Dialogform.AddForm(Language.StringByID(R.MyInternationalizationString.uPleaseInputUserPassword), 4);
                //确认按钮
                Dialogform.FinishInputEvent += ((textValue) =>
                {
                    Dialogform.CloseForm();
                    //用户密码
                    pasword = textValue;
                    //加密密码
                    this.UserPassword = pasword;
                });
            });
            while (pasword == null)
            {
                if (Dialogform != null && Dialogform.Parent == null)
                {
                    break;
                }
                await Task.Delay(500);
            }
            //恢复进度条
            if (isShowingProgressBar == true)
            {
                Application.RunOnMainThread(() =>
                {
                    CommonPage.Loading.Start(ProgressBarText);
                });
            }
            return pasword;
        }
        /// <summary>
        /// 检测其他防区里面有没有配置有传感器(布防使用)
        /// </summary>
        /// <returns></returns>
        private bool CheckHadInteriorSectorsSensor()
        {
            for (int i = 3; i <= 5; i++)
            {
                if (dicAllZoneInfo.ContainsKey(i) == true
                    && dicAllZoneInfo[i].dicSensor.Count > 0)
                {
                    return true;
                }
            }
            return false;
        }
        #endregion
        #region ■ 信息推送___________________________
        /// <summary>
        /// 设置指定防区的信息推送状态
        /// </summary>
        /// <param name="zoneId">防区ID</param>
        /// <param name="statu">状态  0:推送  1:不推送</param>
        /// <returns></returns>
        public async Task<bool> SetGarrisonInformationPushStatu(int zoneId, int statu)
        {
            //校验密码
            bool flage = await this.ShowSafetyAdminValidatedDialog();
            if (flage == false)
            {
                return false;
            }
            //状态变更
            var result = await Safeguard.DisablePushMessageAsync(zoneId, statu);
            if (result == null || result.disablePushMessageResponseData == null || result.disablePushMessageResponseData.Result == 1)
            {
                //设置信息推送失败
                string msg = Language.StringByID(R.MyInternationalizationString.uSetInformationPushFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return false;
            }
            if (this.dicAllZoneInfo.ContainsKey(zoneId) == false)
            {
                return true;
            }
            SafeguardZoneInfo zoneInfo = this.dicAllZoneInfo[zoneId];
            zoneInfo.InformationPush = statu;
            return true;
        }
        /// <summary>
        /// 获取当前防区的信息推送状态
        /// </summary>
        /// <param name="zoneId">防区ID</param>
        /// <returns>0:推送  1:不推送</returns>
        public int GetGarrisonInformationPushStatu(int zoneId)
        {
            if (this.dicAllZoneInfo.ContainsKey(zoneId) == false)
            {
                return 1;
            }
            SafeguardZoneInfo zoneInfo = this.dicAllZoneInfo[zoneId];
            return zoneInfo.InformationPush;
        }
        #endregion
        #region ■ 延迟设置___________________________
        /// <summary>
        /// 获取防区的延迟时间(仅限出入防区),出错时返回null
        /// </summary>
        /// <returns></returns>
        public async Task<Safeguard.CatDelayTimeResponseData> GetGarrisonDelayTime()
        {
            //获取
            var result = await Safeguard.CatDelayTimeAsync();
            if (result == null || result.catDelayTimeResponseData == null)
            {
                //获取延时时间失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetDelayTimeFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return null;
            }
            return result.catDelayTimeResponseData;
        }
        /// <summary>
        /// 设置防区的进出延迟时间 (仅限出入防区),现接口不支持单个修改
        /// </summary>
        /// <param name="enterDelayTime">进入延时(秒)</param>
        /// <param name="goOutDelayTime">外出延时(秒)</param>
        /// <returns></returns>
        public async Task<bool> SetGarrisonDelayTime(int enterDelayTime, int goOutDelayTime)
        {
            //校验密码
            bool flage = await this.ShowSafetyAdminValidatedDialog();
            if (flage == false)
            {
                return false;
            }
            //更改时间
            var result = await Safeguard.SetDelayTimeAsync(enterDelayTime, goOutDelayTime, this.GetLoginToken());
            if (result == null || result.setDelayTimeResponseData == null)
            {
                //设置延时时间失败
                string msg = Language.StringByID(R.MyInternationalizationString.uSetDelayTimeFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return false;
            }
            return true;
        }
        #endregion
        #region ■ 胁迫设置___________________________
        /// <summary>
        /// 获取胁迫的电话联系方式(获取失败时会返回null)
        /// </summary>
        /// <returns></returns>
        public async Task<Safeguard.CheckCoercePhoneNumberResponseData> GetCoercePhoneNumber()
        {
            //获取
            var result = await Safeguard.CheckCoercePhoneNumberAsync();
            if (result == null || result.checkCoercePhoneNumberResponseData == null)
            {
                //获取胁迫联系方式信息失败
                string msg = Language.StringByID(R.MyInternationalizationString.uGetCoercePhoneNumberFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return null;
            }
            //没有数据
            if (result.checkCoercePhoneNumberResponseData.Result == 1)
            {
                return null;
            }
            return result.checkCoercePhoneNumberResponseData;
        }
        /// <summary>
        /// 设置胁迫的联系人方式
        /// </summary>
        /// <param name="listPhone">地区码-联系方式</param>
        /// <param name="listNote">联系人备注</param>
        /// <param name="addPhone">是否是新建联系人,false的时候,只改备注</param>
        /// <returns></returns>
        public async Task<bool> SetCoercePhoneNumber(List<string> listPhone, List<string> listNote, bool addPhone = true)
        {
            if (addPhone == true)
            {
                var Pra = new Safeguard.SetCoercePhoneNumberData();
                var Actonobj = new Safeguard.PushTargetActionObj();
                Actonobj.Type = 2;
                Pra.Actions.Add(Actonobj);
                Pra.LoginToken = this.GetLoginToken();
                for (int i = 0; i < listPhone.Count; i++)
                {
                    var phoneInfo = new Safeguard.PushTargetInfo();
                    Actonobj.PushTarget.Add(phoneInfo);
                    //电话号码
                    phoneInfo.PushNumber = listPhone[i];
                }
                var result = await Safeguard.SetCoercePhoneNumberAsync(Pra);
                if (result == null || result.setCoercePhoneNumberResponseData == null || result.setCoercePhoneNumberResponseData.Result != 0)
                {
                    //修改胁迫联系方式失败
                    string msg = Language.StringByID(R.MyInternationalizationString.uChangedCoercePhoneNumberFail);
                    //拼接上【网关回复超时】的Msg
                    msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                    this.ShowErrorMsg(msg);
                    return false;
                }
            }
            for (int i = 0; i < listNote.Count; i++)
            {
                var result = await Safeguard.SetCoercePhoneNumberNoteAsync(listPhone[i], listNote[i]);
                if (result == null)
                {
                    //修改备注信息失败
                    string msg = Language.StringByID(R.MyInternationalizationString.uEditorNoteInformationFail);
                    //拼接上【网关回复超时】的Msg
                    msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "回复超时");
                    this.ShowErrorMsg(msg);
                    return false;
                }
                if (result.Result == -2)
                {
                    //错误:网关对象丢失
                    string msg = Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg);
                    this.ShowErrorMsg(msg);
                    return false;
                }
                if (result.Result != 0)
                {
                    //修改备注信息失败
                    string msg = Language.StringByID(R.MyInternationalizationString.uEditorNoteInformationFail);
                    this.ShowErrorMsg(msg);
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// 删除胁迫的联系人方式
        /// </summary>
        /// <param name="areaCode"></param>
        /// <param name="phoneNum"></param>
        /// <returns></returns>
        public async Task<bool> DeleteCoercePhoneNumber(string areaCode, string phoneNum)
        {
            var Pra = new Safeguard.DelCoercePhoneNumberData();
            var Actonobj = new Safeguard.PushTargetActionObj();
            Actonobj.Type = 2;
            Pra.Actions.Add(Actonobj);
            Pra.LoginToken = this.GetLoginToken();
            var phoneInfo = new Safeguard.PushTargetInfo();
            Actonobj.PushTarget.Add(phoneInfo);
            //电话号码
            phoneInfo.PushNumber = areaCode + "-" + phoneNum;
            var result = await Safeguard.DelCoercePhoneNumberAsync(Pra);
            if (result == null || result.delCoercePhoneNumberResponseData == null || result.delCoercePhoneNumberResponseData.Result != 0)
            {
                //删除胁迫联系方式失败
                string msg = Language.StringByID(R.MyInternationalizationString.uDeleteCoercePhoneNumberFail);
                //拼接上【网关回复超时】的Msg
                msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, result);
                this.ShowErrorMsg(msg);
                return false;
            }
            return true;
        }
        /// <summary>
        /// 给联系号码添加备注的信息
        /// </summary>
        private class AddPushNumberNoteInfo
        {
            /// <summary>
            /// 固定253
            /// </summary>
            public int ActionType = 253;
            /// <summary>
            /// LoginToken
            /// </summary>
            public string LoginToken = string.Empty;
            /// <summary>
            /// 地区码-联系方式
            /// </summary>
            public string PushNumber = string.Empty;
            /// <summary>
            /// 联系人号码备注,最大63byte
            /// </summary>
            public string PushNumberNote = string.Empty;
        }
        #endregion
        #region ■ 执行目标状态的翻译文本_____________
        /// <summary>
        /// 获取执行目标的状态文本
        /// </summary>
        /// <param name="listTaskInfo">动作对象,可以为空</param>
        /// <returns></returns>
        public string GetAdjustTargetStatuText(List<Safeguard.TaskListInfo> listTaskInfo)
        {
            if (listTaskInfo == null || listTaskInfo.Count == 0)
            {
                //无动作
                return Language.StringByID(R.MyInternationalizationString.uNotAction);
            }
            //要考虑它的排列顺序(可以按需求变更编号)
            Dictionary<int, string> dicSort = new Dictionary<int, string>();
            //最大编号
            int MaxNo = listTaskInfo.Count > 4 ? listTaskInfo.Count : 4;
            //开关的位置编号
            int ControlNo = 0;
            //百分比的位置编号
            int persentNo = 1;
            //空调温度的位置编号
            int temparetureNo = 2;
            //空调模式的位置编号
            int modelNo = 3;
            //空调风速的位置编号
            int windNo = 4;
            //其他编号(不理会位置,以列表的顺序为准)
            int otherNo = 100;
            foreach (var info in listTaskInfo)
            {
                #region ■ 晾衣架______
                //★★★★临时处理,后期会删除
                if (info.Epoint != -1)
                {
                    //最高最低处
                    if (info.Epoint == 1)
                    {
                        dicSort[dicSort.Count + otherNo] = info.Data1 == 0 ? Language.StringByID(R.MyInternationalizationString.uTheHighestPoint) : Language.StringByID(R.MyInternationalizationString.uTheLowestPoint);
                    }
                    //风干
                    else if (info.Epoint == 3)
                    {
                        dicSort[dicSort.Count + otherNo] = info.Data1 == 1 ? Language.StringByID(R.MyInternationalizationString.uOpenAirdry) : Language.StringByID(R.MyInternationalizationString.uCloseAirdry);
                    }
                    //烘干
                    else if (info.Epoint == 4)
                    {
                        dicSort[dicSort.Count + otherNo] = info.Data1 == 1 ? Language.StringByID(R.MyInternationalizationString.uOpenDry) : Language.StringByID(R.MyInternationalizationString.uCloseDry);
                    }
                    //消毒
                    else if (info.Epoint == 5)
                    {
                        dicSort[dicSort.Count + otherNo] = info.Data1 == 1 ? Language.StringByID(R.MyInternationalizationString.uOpenDisinfect) : Language.StringByID(R.MyInternationalizationString.uCloseDisinfect);
                    }
                    //照明
                    else if (info.Epoint == 2)
                    {
                        dicSort[dicSort.Count + otherNo] = info.Data1 == 1 ? Language.StringByID(R.MyInternationalizationString.uOpenLighting) : Language.StringByID(R.MyInternationalizationString.uCloseLighting);
                    }
                    //特殊,不能往下走
                    continue;
                }
                #endregion
                #region ■ 开关控制____
                //开关控制
                if (info.TaskType == 1)
                {
                    if (info.Data1 == 1)
                    {
                        //开
                        dicSort[ControlNo] = Language.StringByID(R.MyInternationalizationString.uSimpleOpen);
                    }
                    else
                    {
                        //关
                        dicSort[ControlNo] = Language.StringByID(R.MyInternationalizationString.uSimpleClose);
                    }
                }
                #endregion
                #region ■ 亮度调节____
                //亮度调节
                else if (info.TaskType == 3)
                {
                    if (info.Data1 == 0)
                    {
                        //关
                        dicSort[persentNo] = Language.StringByID(R.MyInternationalizationString.uSimpleClose);
                    }
                    else
                    {
                        dicSort[persentNo] = HdlDeviceCommonLogic.Current.CalculateLightLevelPersent(info.Data1) + "%";
                    }
                }
                #endregion
                #region ■ 窗帘设备____
                //窗帘设备(它的开关和开关控制是反过来的)
                else if (info.TaskType == 6)
                {
                    if (info.Data1 == 0)
                    {
                        //开
                        dicSort[ControlNo] = Language.StringByID(R.MyInternationalizationString.uSimpleOpen);
                    }
                    else if (info.Data1 == 1)
                    {
                        //关
                        dicSort[ControlNo] = Language.StringByID(R.MyInternationalizationString.uSimpleClose);
                    }
                    else if (info.Data1 == 5)
                    {
                        //窗帘百分比
                        dicSort[persentNo] = info.Data2 + "%";
                    }
                }
                #endregion
                #region ■ 空调设备____
                //空调设备
                else if (info.TaskType == 5)
                {
                    if (info.Data1 == 3)
                    {
                        if (info.Data2 == 0)
                        {
                            return Language.StringByID(R.MyInternationalizationString.uSimpleClose);
                        }
                        else if (info.Data2 == 1)
                        {
                            //自动
                            dicSort[modelNo] = Language.StringByID(R.MyInternationalizationString.Mode_Auto);
                        }
                        else if (info.Data2 == 3)
                        {
                            //制冷
                            dicSort[modelNo] = Language.StringByID(R.MyInternationalizationString.Mode_Cool);
                        }
                        else if (info.Data2 == 4)
                        {
                            //制热
                            dicSort[modelNo] = Language.StringByID(R.MyInternationalizationString.Mode_Heat);
                        }
                        else if (info.Data2 == 7)
                        {
                            //送风
                            dicSort[modelNo] = Language.StringByID(R.MyInternationalizationString.Mode_FanOnly);
                        }
                        else if (info.Data2 == 8)
                        {
                            //除湿
                            dicSort[modelNo] = Language.StringByID(R.MyInternationalizationString.Mode_Dry);
                        }
                    }
                    else if (info.Data1 == 4 || info.Data1 == 5|| info.Data1 == 7)
                    {
                        //温度
                        dicSort[temparetureNo] = $"{ info.Data2 / 100}℃";
                    }
                    else if (info.Data1 == 6)
                    {
                        if (info.Data2 == 1)
                        {
                            //低风
                            dicSort[windNo] = Language.StringByID(R.MyInternationalizationString.Fan_Low);
                        }
                        else if (info.Data2 == 2)
                        {
                            //中风
                            dicSort[windNo] = Language.StringByID(R.MyInternationalizationString.Fan_Middle);
                        }
                        else if (info.Data2 == 3)
                        {
                            //高风
                            dicSort[windNo] = Language.StringByID(R.MyInternationalizationString.Fan_Height);
                        }
                    }
                }
                #endregion
            }
            //如果开关和百分比一起存在的话,则不显示开关文字
            if (dicSort.ContainsKey(ControlNo) == true && dicSort.ContainsKey(persentNo) == true)
            {
                dicSort.Remove(ControlNo);
            }
            //拼接文本
            string txtvalue = string.Empty;
            for (int i = 0; i <= MaxNo; i++)
            {
                if (dicSort.ContainsKey(i) == true)
                {
                    txtvalue += dicSort[i] + " ";
                }
            }
            //其他的
            MaxNo = otherNo + dicSort.Count;
            for (int i = otherNo; i < MaxNo; i++)
            {
                if (dicSort.ContainsKey(i) == true)
                {
                    txtvalue += dicSort[i] + " ";
                    continue;
                }
                break;
            }
            return txtvalue.Trim();
        }
        #endregion
        #region ■ 重置管理员密码_____________________
        /// <summary>
        /// 重置管理员密码
        /// </summary>
        /// <param name="password">新密码</param>
        /// <returns></returns>
        private async Task<bool> DoResetAdministratorPsw(string password)
        {
            var realWay = ZigBee.Device.ZbGateway.MainGateWay;
            if (realWay == null)
            {
                //错误:网关对象丢失
                //string msg = Language.StringByID(R.MyInternationalizationString.uErrorGatewayLostMsg);
                //this.ShowTipMsg(msg);
                return false;
            }
            //是否达成中断的时机
            bool canBreak = false;
            bool success = false;
            //超时时间
            int TimeOut = 0;
            string checkTopic = realWay.GwId + "/Security/AdminSetNewPassword_Respon";
            Action<string, string> getResultAction = (topic, message) =>
            {
                try
                {
                    if (topic == checkTopic)
                    {
                        TimeOut = 0;
                        var jobject = Newtonsoft.Json.Linq.JObject.Parse(message);
                        var result = JsonConvert.DeserializeObject<int>(jobject["Data"]["Result"].ToString());
                        success = result == 0;
                        canBreak = true;
                    }
                }
                catch { }
            };
            realWay.Actions += getResultAction;
            try
            {
                var jObject = new Newtonsoft.Json.Linq.JObject { { "Cluster_ID", 0 }, { "Command", 4033 } };
                var data = new Newtonsoft.Json.Linq.JObject { { "HomeId", Common.Config.Instance.HomeId }, { "Password", password } };
                jObject.Add("Data", data);
                realWay.Send("Security/AdminSetNewPassword", jObject.ToString());
            }
            catch
            {
                canBreak = true;
                //出现未知错误,请稍后再试
                //string msg = Language.StringByID(R.MyInternationalizationString.uUnKnowErrorAndResetAgain);
                //this.ShowTipMsg(msg);
            }
            while (canBreak == false && TimeOut < 20)
            {
                await Task.Delay(100);
                TimeOut++;
            }
            realWay.Actions -= getResultAction;
            getResultAction = null;
            if (TimeOut >= 20)
            {
                //重置管理员密码失败(网关回复超时)
                //string msg = Language.StringByID(R.MyInternationalizationString.uResetAdministratorPswFail);
                //msg = UserCenterLogic.CombineGatewayTimeOutMsg(msg, null, "回复超时");
                //this.ShowTipMsg(msg);
                return false;
            }
            return success;
        }
        #endregion
        #region ■ 一般方法___________________________
        /// <summary>
        /// 获取所有防区的ID(默认是1~5)
        /// </summary>
        /// <returns></returns>
        private List<int> GetAllZoneId()
        {
            //防区id
            //1:24小时防区
            //2:24小时静音防区
            //3:出入防区
            //4:内部防区
            //5:周界防区
            List<int> list = new List<int>() { 1, 2, 3, 4, 5 };
            return list;
        }
        /// <summary>
        /// 获取防区的翻译名字
        /// </summary>
        /// <param name="ZoneID"></param>
        /// <returns></returns>
        public string GetGarrisonText(int ZoneID)
        {
            if (ZoneID == 1)
            {
                //24小时防区
                return Language.StringByID(R.MyInternationalizationString.u24HourSectors);
            }
            else if (ZoneID == 2)
            {
                //静音防区
                return Language.StringByID(R.MyInternationalizationString.uMuteSectors);
            }
            else if (ZoneID == 3)
            {
                //出入防区
                return Language.StringByID(R.MyInternationalizationString.uInAndOutSectors);
            }
            else if (ZoneID == 4)
            {
                //内部防区
                return Language.StringByID(R.MyInternationalizationString.uInteriorSectors);
            }
            else if (ZoneID == 5)
            {
                //周界防区
                return Language.StringByID(R.MyInternationalizationString.uPerimeterSectors);
            }
            return string.Empty;
        }
        /// <summary>
        /// 显示错误信息窗口
        /// </summary>
        /// <param name="msg"></param>
        private void ShowErrorMsg(string msg)
        {
            Application.RunOnMainThread(() =>
            {
                var contr = new ShowMsgControl(ShowMsgType.Error, msg);
                contr.Show();
            });
        }
        /// <summary>
        /// 显示正常信息窗口
        /// </summary>
        /// <param name="msg"></param>
        private void ShowNormalMsg(string msg)
        {
            Application.RunOnMainThread(() =>
            {
                var contr = new ShowMsgControl(ShowMsgType.Normal, msg);
                contr.Show();
            });
        }
        /// <summary>
        /// 显示Tip窗口
        /// </summary>
        /// <param name="msg"></param>
        private void ShowTipMsg(string msg)
        {
            Application.RunOnMainThread(() =>
            {
                var control = new ShowMsgControl(ShowMsgType.Tip, msg);
                control.Show();
            });
        }
        /// <summary>
        /// 获取设备的唯一主键
        /// </summary>
        /// <param name="device"></param>
        /// <returns></returns>
        private string GetDeviceMainKeys(CommonDevice device)
        {
            return Common.LocalDevice.Current.GetDeviceMainKeys(device);
        }
        /// <summary>
        /// 获取登陆者的Token(好像管理员登陆的时候,需要变更Token,所以暂且定义一个函数出来)
        /// </summary>
        /// <returns></returns>
        public string GetLoginToken()
        {
            //获取控制主人账号的Token
            //return UserCenterLogic.GetConnectMainToken();
            return Config.Instance.Token;
        }
        #endregion
        #region ■ 结构体_____________________________
        /// <summary>
        /// 内部使用,安防防区的一些信息
        /// </summary>
        private class SafeguardZoneInfo
        {
            /// <summary>
            /// 防区id。
            /// </summary>
            public int ZoneId;
            /// <summary>
            /// 布防防区名称 ,最大32个字符
            /// </summary>
            public string ZoneName;
            /// <summary>
            /// 信息推送 0:推送  1:不推送
            /// </summary>
            public int InformationPush = 1;
            /// <summary>
            /// 传感器设备的信息(keys:设备主键)
            /// </summary>
            public Dictionary<string, Safeguard.ZoneDeviceListData> dicSensor = new Dictionary<string, Safeguard.ZoneDeviceListData>();
            /// <summary>
            /// 该防区下全部设备文件路径(keys:设备主键,value:设备文件路径)
            /// </summary>
            public Dictionary<string, string> dicAllDevice = new Dictionary<string, string>();
            /// <summary>
            /// 该防区下面的报警设备(keys:设备主键),<只有防区ID:1,2,3才会有。4,5的都归为3,因为它是以防区模式ID(ActionType)为单位的>
            /// </summary>
            public Dictionary<string, Safeguard.CatActionResponseObj> dicAlarmDevice = new Dictionary<string, Safeguard.CatActionResponseObj>();
            /// <summary>
            /// 该防区下面的场景(keys:场景No),<只有防区ID:1,2,3才会有。4,5的都归为3,因为它是以防区模式ID(ActionType)为单位的>
            /// </summary>
            public Dictionary<int, string> dicScenes = new Dictionary<int, string>();
        }
        #endregion
    }
}