using Shared.SimpleControl.Phone;
using System;
using System.Collections.Generic;
using System.Collections;

namespace Shared.SimpleControl.Pad
{
    public class SystemPanel
    {
        /// <summary>
        /// 按键配置的目标列表
        /// </summary>
        List<byte []> targetList = new List<byte []> ();
        /// <summary>
        /// 支持绑定到面板按键
        /// </summary>
        List<string> supportDeviceFileList;//本地设备信息
        int currentSelectedEquipmentType = 0;//下来列表选择要显示的设备,0表示所有,1表示灯光,2表示窗帘,3表示逻辑模块

        /// <summary>
        /// 当前选择的按键
        /// </summary>
        Button btn;

        public SystemPanel ()
        {
            //找出当前支持绑定到面板按键
            supportDeviceFileList = IO.FileUtils.ReadFiles ().FindAll ((obj) => {
                string [] str = obj.Split ('_');
                return obj.StartsWith ("Equipment_")
                          && str.Length == 5
                          && (str [1] == DeviceType.LightSwitch.ToString ()
                              || str [1] == DeviceType.LightDimming.ToString ()
                              || str [1] == DeviceType.CurtainModel.ToString ()
                              || str [1] == DeviceType.CurtainRoller.ToString ()
                              || str [1] == DeviceType.CurtainTrietex.ToString ()
                              || str [1] == DeviceType.LogicModule.ToString ()
                             );
            });
        }

        /// <summary>
        /// Shows the equipments.
        /// </summary>
        void showEquipments (FrameLayout inVerticalscrolView, bool onlyShowSelected = false)
        {
            inVerticalscrolView.RemoveAll ();
            int btnLimmingNum = 0;
            btn = null;
            List<string> willBeShowDeviceFilePath = new List<string> ();

            if (onlyShowSelected) {
                foreach (var bytes in targetList) {
                    foreach (var deviceFilePath in supportDeviceFileList) {
                        if (deviceFilePath.EndsWith (bytes [3] + "_" + bytes [4] + "_" + bytes [5]) || deviceFilePath.EndsWith (bytes [3] + "_" + bytes [4] + "_0" + bytes [5])) {
                            willBeShowDeviceFilePath.Add (deviceFilePath);
                            break;
                        }
                    }
                }
            } else {
                if (currentSelectedEquipmentType == 0) {//判断是否为当前要显示的类型
                    willBeShowDeviceFilePath = supportDeviceFileList;
                } else if (currentSelectedEquipmentType == 1) {
                    willBeShowDeviceFilePath = supportDeviceFileList.FindAll ((obj) => { return obj.Split ('_') [1] == DeviceType.LightDimming.ToString () || obj.Split ('_') [1] == DeviceType.LightSwitch.ToString (); });
                } else if (currentSelectedEquipmentType == 2) {
                    willBeShowDeviceFilePath = supportDeviceFileList.FindAll ((obj) => { return obj.Split ('_') [1] == DeviceType.CurtainRoller.ToString () || obj.Split ('_') [1] == DeviceType.CurtainTrietex.ToString () || obj.Split ('_') [1] == DeviceType.CurtainModel.ToString (); });
                } else if (currentSelectedEquipmentType == 3) {
                    willBeShowDeviceFilePath = supportDeviceFileList.FindAll ((obj) => { return obj.Split ('_') [1] == DeviceType.LogicModule.ToString (); });
                }
                //foreach (var deviceFilePath in supportDeviceFileList) {
                //    string [] str = deviceFilePath.Split ('_');
                //    if (currentSelectedEquipmentType == 0) {//判断是否为当前要显示的类型
                //        willBeShowDeviceFilePath = supportDeviceFileList;
                //        break;
                //    } else if (currentSelectedEquipmentType == 1) {
                //        if (str [1] == DeviceType.LightDimming.ToString () || str [1] == DeviceType.LightSwitch.ToString ())
                //            willBeShowDeviceFilePath.Add (deviceFilePath);
                //    } else if (currentSelectedEquipmentType == 2) {
                //        if (str [1] == DeviceType.CurtainModel.ToString () || str [1] == DeviceType.CurtainRoller.ToString () || str [1] == DeviceType.CurtainTrietex.ToString ())
                //            willBeShowDeviceFilePath.Add (deviceFilePath);
                //    } else if (currentSelectedEquipmentType == 3) {
                //        if (str [1] == DeviceType.LogicModule.ToString ()) {
                //            willBeShowDeviceFilePath.Add (deviceFilePath);
                //        }
                //    }
                //}
            }
            foreach (string deviceFilePath in willBeShowDeviceFilePath)//显示在本地找到的所有设备
            {
                Common common = Newtonsoft.Json.JsonConvert.DeserializeObject<Common> (System.Text.Encoding.UTF8.GetString (IO.FileUtils.ReadFile (deviceFilePath)));

                if (common == null) {
                    continue;
                }
                var btnDevice = new Button () {
                    Width = Application.GetRealWidth (250),
                    Height = Application.GetRealHeight (80),
                    TextAlignment = TextAlignment.Center,
                    Radius = (uint)Application.GetMinRealAverage (6),
                    BackgroundColor = 0xFB757575,
                    Text = common.Name,
                    //是否是配置目标
                    Tag = false,
                };
                string [] str = deviceFilePath.Split ('_');//str的格式为,前缀_设备类型_子网号_设备号_回路号
                                                           //当保存在本地的设备信息回路号小于10的时候,前面会加了个0,在这里去掉
                                                           //如果包括了当前设备,就显示为选中状态
                if (null != targetList.Find ((bytes) => {
                    if (common.Type == DeviceType.CurtainRoller || common.Type == DeviceType.CurtainTrietex) {
                        return bytes [3] + "_" + bytes [4] == str [2] + "_" + str [3];
                    } else {
                        return bytes [3] + "_" + bytes [4] + "_" + bytes [5] == str [2] + "_" + str [3] + "_" + str [4].TrimStart ('0');
                    }
                })) {
                    btnDevice.BackgroundColor = SkinStyle.Current.MainColor;
                    btnDevice.Tag = true;
                }
                btnDevice.AddTag ("DeviceFilePath", deviceFilePath);

                btnDevice.Y = (int)btnLimmingNum / 2 * Application.GetRealHeight (80 + 10) + Application.GetRealHeight (13);
                if (btnLimmingNum % 2 == 0) {
                    btnDevice.X = Application.GetRealWidth (13);
                } else {
                    btnDevice.X = btnDevice.Width + Application.GetRealWidth (13 + 14);
                }
                btnLimmingNum++;

                btnDevice.MouseUpEventHandler += (sender, e) => {
                    //如果之前的按键点击了,也不是配置过的目标
                    if (btn != null) {
                        if ((bool)btn.Tag) {
                            btn.BackgroundColor = SkinStyle.Current.MainColor;
                        } else {
                            btn.BackgroundColor = 0xFB757575;
                        }
                    }
                    btn = btnDevice;
                    btn.BackgroundColor = SkinStyle.Current.SelectedColor;
                };
                inVerticalscrolView.AddChidren (btnDevice);
            }
            inVerticalscrolView.Height = (btnLimmingNum / 2 + 1) * Application.GetRealHeight (80 + 13);
        }

        /// <summary>
        /// 显示面板回路的具体配置信息
        /// 这里传进来的PanelDeviceButtonKey的参数只有基本的大类、小类、子网号、设备号、回路号、模式的基本信息,
        /// 后面的其他信息为面板回路的配置信息
        /// 如果该面板回路为单一开关,则该条信息只有一条
        /// 如果为组合,则为多条,前面的基本信息是相同的
        /// </summary>
        public void SystemWirelessPanelButtonKeyShow (DryContact deviceLoop, Common panelDevice)
        {
            currentSelectedEquipmentType = 0;
            btn = null;

            SystemMiddle.ThirdScrolView.RemoveAll ();

            #region  top

            EditText textButton = new EditText () {
                X = Application.GetRealWidth (30),
                Height = Application.GetRealHeight (50),
                Width = Application.GetRealWidth (400),
                Text = deviceLoop.Name,
                TextAlignment = TextAlignment.CenterLeft,
                Gravity = Gravity.CenterVertical,
                SelectedBackgroundColor = 0xFF000000,
                TextSize = 15,
                Enable = false
            };
            SystemMiddle.ThirdScrolView.TitleView.AddChidren (textButton);

            Button btnPositon = new Button () {
                Height = Application.GetRealHeight (90),
                Width = Application.GetRealWidth (90),
                UnSelectedImagePath = "Panel/Position.png",
                Gravity = Gravity.CenterVertical,
                X = textButton.Right + Application.GetRealWidth (20)
            };
            if (deviceLoop.Type != DeviceType.DryContact)
                SystemMiddle.ThirdScrolView.TitleView.AddChidren (btnPositon);
            btnPositon.MouseUpEventHandler += (sender, e) => {
                var positionByte = Control.ControlBytesSendHasReturn (Command.ReadInstructionPanelKey, deviceLoop.SubnetID, deviceLoop.DeviceID, new byte [] { 17, deviceLoop.LoopID });

                System.Threading.Tasks.Task.Run (() => {
                    for (int i = 0; i < 6; i++) {
                        positionByte [2] = positionByte [2] == 1 ? (byte)0 : (byte)1;
                        Control.ControlBytesSend (Command.InstructionPanelKey, deviceLoop.SubnetID, deviceLoop.DeviceID, positionByte, SendCount.Zero);
                        System.Threading.Thread.Sleep (500);
                    }
                });
            };

            Button editor = new Button () {
                Height = Application.GetRealHeight (90),
                Width = Application.GetRealWidth (70),
                UnSelectedImagePath = "Item/Editor.png",
                SelectedImagePath = "Item/EditorSelected.png",
                Gravity = Gravity.CenterVertical,
                X = Application.GetRealWidth (550)
            };
            SystemMiddle.ThirdScrolView.TitleView.AddChidren (editor);
            editor.MouseUpEventHandler += (sender, e) => {
                if (editor.IsSelected) {
                    MainPage.Loading.Start ();
                    editor.IsSelected = textButton.IsSelected = textButton.Enable = false;
                    byte [] remakeBytes = CommonPage.MyEncodingGB2312.GetBytes (textButton.Text.Trim ());
                    textButton.IsSelected = editor.IsSelected = textButton.Enable = false;
                    System.Threading.Tasks.Task.Run (() => {
                        byte [] updateBytes = Control.ControlBytesSendHasReturn (Command.ReadDeviceLoopInfo, deviceLoop.SubnetID, deviceLoop.DeviceID, new byte [] {
                             deviceLoop.BigClass,deviceLoop.MinClass,deviceLoop.LoopID
                        });
                        if (updateBytes == null) {
                            Application.RunOnMainThread (() => {
                                new Alert (Language.StringByID (R.MyInternationalizationString.Tip), Language.StringByID (R.MyInternationalizationString.TipEquipmentNotOnline), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                                MainPage.Loading.Hide ();
                            });
                            return;
                        }
                        byte [] uBytes = new byte [20];
                        Array.Copy (remakeBytes, 0, uBytes, 0, remakeBytes.Length < 20 ? remakeBytes.Length : 20);
                        Array.Copy (uBytes, 0, updateBytes, 3, 20 < uBytes.Length ? 20 : uBytes.Length);
                        var reBytes = Control.ControlBytesSendHasReturn (Command.SetDeviceLoopInfo, deviceLoop.SubnetID, deviceLoop.DeviceID, updateBytes);
                        if (reBytes != null) {
                            Application.RunOnMainThread (() => {
                                deviceLoop.Name = textButton.Text.Trim ();
                                IO.FileUtils.SaveEquipmentMessage (deviceLoop, deviceLoop.LoopID.ToString ());
                                MainPage.Loading.Hide ();
                            });
                        } else {
                            Application.RunOnMainThread (() => {
                                new Alert (Language.StringByID (R.MyInternationalizationString.Tip), Language.StringByID (R.MyInternationalizationString.TipEquipmentNotOnline), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                                MainPage.Loading.Hide ();
                            });
                        }
                    });
                } else {
                    textButton.Enable = textButton.IsSelected = editor.IsSelected = true;
                }
            };
            #endregion

            FrameLayout frameLayoutBody = new FrameLayout () {
                Height = Application.GetRealHeight (746),
                Width = LayoutParams.MatchParent,
            };
            SystemMiddle.ThirdScrolView.AddChidren (frameLayoutBody);

            System.Threading.Tasks.Task.Run (() => {
                Application.RunOnMainThread (() => {
                    MainPage.Loading.Start ();
                });
                try {
                    targetList.Clear ();
                    CommonPage.DeviceList.Clear ();

                    //int loopCount = 1;
                    bool hasNotInLocalDevice = false;
                    byte [] enableBytes = Control.ControlBytesSendHasReturn (Command.ReadButtonKeyEnable,
                        deviceLoop.SubnetID, deviceLoop.DeviceID,
                        new byte [] { deviceLoop.LoopID });
                    if (enableBytes == null) {
                        enableBytes = new byte [panelDevice.LoopCount];
                        for (int lc = 0; lc < panelDevice.LoopCount; lc++) {
                            enableBytes [lc] = 1;
                        }
                    }
                    for (int i = 2; i < enableBytes.Length; i++) {
                        if (enableBytes [i] > 0) {
                            var enableString = Convert.ToString (enableBytes [i], 2);
                            for (int j = 0; j < enableString.Length; j++) {
                                char ch = enableString [enableString.Length - j - 1];
                                if (ch == '1') {
                                    int targetID = ((i - 2) * 8) + j + 1;
                                    byte [] usefullBytes = Control.ControlBytesSendHasReturn (Command.ReadWirelessPanelButtonKey,
                                                                                                deviceLoop.SubnetID, deviceLoop.DeviceID,
                                                                                              new byte [] { deviceLoop.LoopID, (byte)targetID });
                                    if (usefullBytes == null) {
                                        Application.RunOnMainThread (() => {
                                            MainPage.Loading.Hide ();
                                            var alert = new Alert (Language.StringByID (R.MyInternationalizationString.Tip),
                                                        Language.StringByID (R.MyInternationalizationString.TipEquipmentNotOnline),
                                                        Language.StringByID (R.MyInternationalizationString.Close), Language.StringByID (R.MyInternationalizationString.ReFresh));
                                            alert.Show ();
                                            alert.ResultEventHandler += (sender_alert, e_alert) => {
                                                if (e_alert) {
                                                    this.SystemWirelessPanelButtonKeyShow (deviceLoop, panelDevice);
                                                } else {
                                                    new SystemEquipmentBase ().EquipmentBaseViewShow (panelDevice);
                                                }
                                            };
                                        });
                                        return;
                                    }
                                    byte [] data = targetList.Find ((obj) => {
                                        return obj [3] + "_" + obj [4] + "_" + obj [5] == usefullBytes [3] + "_" + usefullBytes [4] + "_" + usefullBytes [5];
                                    });
                                    if (data == null) {
                                        if (usefullBytes [1] != (byte)(targetList.Count + 1)) {
                                            //将间隔了无效数据行的数据移动到有效数据行末尾
                                            var typeb = usefullBytes [2];
                                            usefullBytes [2] = 0;
                                            Control.ControlBytesSendHasReturn (Command.WriteWirelessPanelButtonKey, deviceLoop.SubnetID, deviceLoop.DeviceID, usefullBytes);
                                            usefullBytes [1] = (byte)(targetList.Count + 1);
                                            usefullBytes [2] = typeb;
                                            Control.ControlBytesSendHasReturn (Command.WriteWirelessPanelButtonKey, deviceLoop.SubnetID, deviceLoop.DeviceID, usefullBytes);
                                        }
                                        targetList.Add (usefullBytes);
                                    } else {
                                        usefullBytes [2] = 0;
                                        Control.ControlBytesSendHasReturn (Command.WriteWirelessPanelButtonKey, deviceLoop.SubnetID, deviceLoop.DeviceID, usefullBytes);
                                    }
                                }
                            }
                        }
                    }

                    Application.RunOnMainThread (() => {
                        MainPage.Loading.Hide ();
                        FrameLayout frameLayout1 = new FrameLayout () {
                            Height = Application.GetRealHeight (748),
                        };
                        frameLayoutBody.AddChidren (frameLayout1);

                        int cellNumber = 0;
                        int cellY = Application.GetRealHeight (70);
                        int btnWidth = Application.GetRealWidth (173);
                        int btnHeight = Application.GetRealHeight (43);
                        int btnX = Application.GetRealWidth (50);

                        //---Min
                        var btnGoalSunbetID = new Button () {
                            Width = btnWidth,
                            Height = btnHeight,
                            X = btnX,
                            Y = cellY * cellNumber++ + 10,
                            TextID = R.MyInternationalizationString.Mode,
                            TextAlignment = TextAlignment.CenterLeft,
                        };
                        frameLayout1.AddChidren (btnGoalSunbetID);

                        string [] modeText = new string [8];///写在language里面,和写出相应的空调的参数对应值
                        modeText [0] = Language.StringByID (R.MyInternationalizationString.InvalidMode);
                        modeText [1] = Language.StringByID (R.MyInternationalizationString.SingleSwitch);
                        modeText [2] = Language.StringByID (R.MyInternationalizationString.SingleOpen);
                        modeText [3] = Language.StringByID (R.MyInternationalizationString.SingleClose);
                        modeText [4] = Language.StringByID (R.MyInternationalizationString.CombinedOpen);
                        modeText [5] = Language.StringByID (R.MyInternationalizationString.CombinedClose);
                        modeText [6] = Language.StringByID (R.MyInternationalizationString.Move);
                        modeText [7] = Language.StringByID (R.MyInternationalizationString.CombinedSwitch);

                        if (deviceLoop.Type == DeviceType.DryContact) {
                            modeText [0] = Language.StringByID (R.MyInternationalizationString.MechanicalSwitch);
                            modeText [3] = Language.StringByID (R.MyInternationalizationString.SingleSwitch);
                            modeText [1] = Language.StringByID (R.MyInternationalizationString.SingleOpen);
                            modeText [2] = Language.StringByID (R.MyInternationalizationString.SingleClose);
                            modeText [4] = Language.StringByID (R.MyInternationalizationString.CombinedOpen);
                            modeText [5] = Language.StringByID (R.MyInternationalizationString.CombinedClose);
                            modeText [6] = Language.StringByID (R.MyInternationalizationString.CombinedSwitch);
                            modeText [7] = Language.StringByID (R.MyInternationalizationString.MultiFunction);
                        }

                        /// [keyMode]
                        ///00000=无效模式
                        ///00001=单一开/关
                        ///00002=单一开
                        ///00003=单一关
                        ///00004=组合开
                        ///00005=组合关
                        ///00006=点动
                        ///00007=组合开/关
                        ///00008=键分开 - 点动
                        ///00009=键分开 - 组合
                        ///00010=双击/单一开关
                        ///00011=双击/组合开关
                        ///00013=闹钟
                        ///00014=机械开关
                        ///00015=键分开 - 单一
                        ///00016=短按/长点动
                        ///00017=短按/长按
                        ///00018=键分开 - 短按/长点动
                        ///00019=键分开 - 短/长按
                        ///00020=超链接
                        ///00021=单一循环
                        ///按键模式
                        var spinnerMode = new Spinner () {
                            X = btnGoalSunbetID.X + btnGoalSunbetID.Width,
                            Y = btnGoalSunbetID.Y,
                            Width = Application.GetRealWidth (540) - btnGoalSunbetID.Width,
                            Height = Application.GetRealHeight (65),
                        };

                        spinnerMode.AdapterStr = modeText;
                        spinnerMode.SelectedItemChanged += (sender, e) => {
                            byte [] loopData = Control.ControlBytesSendHasReturn (Command.ReadDeviceLoopInfo, deviceLoop.SubnetID, deviceLoop.DeviceID,
                                                                                  new byte [] { deviceLoop.BigClass, deviceLoop.MinClass, deviceLoop.LoopID });
                            if (loopData != null) {
                                loopData [23] = Convert.ToByte (e);
                                deviceLoop.Mode = Convert.ToByte (e);
                                Control.ControlBytesSend (Command.SetDeviceLoopInfo, deviceLoop.SubnetID, deviceLoop.DeviceID, loopData);
                                IO.FileUtils.SaveEquipmentMessage (deviceLoop, deviceLoop.LoopID.ToString ());
                            } else {
                                new Alert (Language.StringByID (R.MyInternationalizationString.Tip),
                                            Language.StringByID (R.MyInternationalizationString.TipEquipmentNotOnline),
                                           Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                            }
                        };
                        frameLayout1.AddChidren (spinnerMode);

                        spinnerMode.CurrentRow = deviceLoop.Mode;

                        var btnOutput = new Button () {
                            Width = btnWidth,
                            Height = btnHeight,
                            X = btnX,
                            Y = cellY * cellNumber++ + 10,
                            TextID = R.MyInternationalizationString.DeviceTyep,
                            TextAlignment = TextAlignment.CenterLeft,
                        };
                        frameLayoutBody.AddChidren (btnOutput);

                        string [] typeText = new string []{
                                Language.StringByID(R.MyInternationalizationString.All),
                                Language.StringByID(R.MyInternationalizationString.Lights),
                                Language.StringByID(R.MyInternationalizationString.Curtain),
                            Language.StringByID(R.MyInternationalizationString.LogicModule),
                               // Language.StringByID(R.MyInternationalizationString.AC ),
                               // Language.StringByID(R.MyInternationalizationString.TerrestrialHeat),
                        };
                        FrameLayout inVerticalscrolView;
                        var spinnerType = new Spinner () {
                            X = btnOutput.X + btnOutput.Width,
                            Y = btnOutput.Y,
                            Width = Application.GetRealWidth (540) - btnOutput.Width,
                            Height = Application.GetRealHeight (65),
                        };
                        spinnerType.AdapterStr = typeText;
                        frameLayout1.AddChidren (spinnerType);

                        //显示出所有设备
                        var verticalScrolView = new VerticalScrolViewLayout () {
                            Height = Application.GetRealHeight (480),
                            Width = Application.GetRealWidth (540),
                            BackgroundColor = 0xFF333333,
                            X = btnX,
                            Y = cellY * cellNumber + 10,
                        };
                        frameLayout1.AddChidren (verticalScrolView);
                        inVerticalscrolView = new FrameLayout ();
                        verticalScrolView.AddChidren (inVerticalscrolView);
                        //加载所有的设备
                        showEquipments (inVerticalscrolView);

                        spinnerType.SelectedItemChanged += (sender, e) => {
                            currentSelectedEquipmentType = e;
                            showEquipments (inVerticalscrolView, false);
                        };

                        var btnShowEquipments = new Button () {
                            Width = btnWidth + Application.GetRealWidth (40),
                            Height = Application.GetRealHeight (50),
                            X = btnX,
                            Y = verticalScrolView.Bottom + Application.GetRealHeight (30),
                            TextID = R.MyInternationalizationString.AlreadyConfigured,
                            BackgroundColor = 0xFF333333,
                            SelectedBackgroundColor = SkinStyle.Current.SelectedColor,
                            BorderWidth = 1,
                            Radius = 5,
                            BorderColor = SkinStyle.Current.Transparent,
                            TextAlignment = TextAlignment.Center,
                        };

                        frameLayout1.AddChidren (btnShowEquipments);

                        var btnEquipmnetSetting = new Button () {
                            Width = btnWidth - Application.GetRealWidth (20),
                            Height = Application.GetRealHeight (50),
                            X = btnX + btnShowEquipments.Width + Application.GetRealWidth (10),
                            Y = btnShowEquipments.Y,
                            BackgroundColor = 0xFF333333,
                            SelectedBackgroundColor = SkinStyle.Current.SelectedColor,
                            BorderWidth = 1,
                            Radius = 5,
                            BorderColor = SkinStyle.Current.Transparent,
                            TextID = R.MyInternationalizationString.Setting,
                            TextAlignment = TextAlignment.Center,
                        };
                        frameLayoutBody.AddChidren (btnEquipmnetSetting);
                        btnEquipmnetSetting.MouseUpEventHandler += (sender, e) => {
                            if (btn == null) {
                                new Alert (Language.StringByID (R.MyInternationalizationString.Tip), Language.StringByID (R.MyInternationalizationString.TipSelectDevicSet), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                            } else {
                                Common common = Newtonsoft.Json.JsonConvert.DeserializeObject<Common> (System.Text.Encoding.UTF8.GetString (IO.FileUtils.ReadFile (btn.GetTagByKey ("DeviceFilePath").ToString ())));
                                if (common == null) {
                                    return;
                                }
                                byte [] sendBytes = new byte [9];

                                byte [] data = null;
                                if (common.Type == DeviceType.CurtainRoller || common.Type == DeviceType.CurtainTrietex) {
                                    data = targetList.Find ((obj) => {
                                        return obj [3] + "_" + obj [4] == common.SubnetID + "_" + common.DeviceID;
                                    });
                                } else {
                                    data = targetList.Find ((obj) => {
                                        return obj [3] + "_" + obj [4] + "_" + obj [5] == common.SubnetID + "_" + common.DeviceID + "_" + common.LoopID;
                                    });
                                }
                                if (data == null) {
                                    if (deviceLoop.Mode <= 3) {
                                        targetList.Clear ();
                                        sendBytes [1] = 1;
                                    } else if (deviceLoop.Mode == 6) {
                                        targetList.Clear ();
                                        sendBytes [1] = 1;
                                    } else {
                                        sendBytes [1] = (byte)(targetList.Count + 1);
                                    }
                                    sendBytes [0] = deviceLoop.LoopID;
                                    sendBytes [3] = common.SubnetID;
                                    sendBytes [4] = common.DeviceID;
                                    sendBytes [5] = common.LoopID;
                                } else {
                                    sendBytes = data;
                                }
                                string deviceType = common.Type.ToString ();

                                #region setingDialog
                                Dialog dialog = new Dialog () {
                                    BackgroundColor = SkinStyle.Current.MainColor,
                                    Width = Application.GetRealWidth (480),
                                    Height = Application.GetRealHeight (560),
                                };
                                Button btnEquipmentTitle = new Button () {
                                    X = Application.GetRealWidth (35),
                                    Y = Application.GetRealHeight (15),
                                    Width = Application.GetRealWidth (250),
                                    Height = Application.GetRealHeight (50),
                                    TextAlignment = TextAlignment.CenterLeft,
                                    TextID = R.MyInternationalizationString.Device
                                };
                                dialog.AddChidren (btnEquipmentTitle);
                                Button btnLine1 = new Button () {
                                    Width = LayoutParams.MatchParent,
                                    Height = 1,
                                    BackgroundColor = SkinStyle.Current.MainColor,
                                    Y = dialog.Height - Application.GetRealHeight (87),
                                };
                                dialog.AddChidren (btnLine1);
                                Button btnBack = new Button () {
                                    UnSelectedImagePath = "Item/PositioningDialogBack.png",
                                    Width = Application.GetRealWidth (123),
                                    Height = Application.GetRealHeight (87),
                                    Y = btnLine1.Bottom,
                                };
                                dialog.AddChidren (btnBack);
                                btnBack.MouseUpEventHandler += (senderB, eB) => {
                                    dialog.Close ();
                                };
                                Button btnLine2 = new Button () {
                                    Width = 1,
                                    Height = Application.GetRealHeight (87),
                                    BackgroundColor = SkinStyle.Current.MainColor,
                                    X = btnBack.Right,
                                    Y = btnLine1.Bottom
                                };
                                dialog.AddChidren (btnLine2);
                                Button btnSave = new Button () {
                                    Width = dialog.Width - Application.GetRealWidth (124),
                                    Height = Application.GetRealHeight (85),
                                    X = btnBack.Width + Application.GetRealWidth (2),
                                    Y = btnBack.Y,
                                    TextID = R.MyInternationalizationString.SAVE,
                                    UnSelectedImagePath = "Item/DialogSave2.png",
                                    SelectedImagePath = "Item/DialogSave2.png",
                                };
                                dialog.AddChidren (btnSave);
                                btnEquipmentTitle.Text = common.Name;
                                if (deviceType == DeviceType.LightDimming.ToString () || deviceType == DeviceType.LightSwitch.ToString ()) {
                                    if (deviceType == DeviceType.LightSwitch.ToString () || deviceType == DeviceType.LightSwitchSocket.ToString ()) {
                                        //btnEquipmentTitle.TextID = R.MyInternationalizationString.SwitchLights;
                                        var lblChangeName = new Button () {
                                            X = Application.GetRealWidth (20),
                                            Y = btnEquipmentTitle.Bottom + Application.GetRealHeight (20),
                                            Width = Application.GetRealWidth (200),
                                            Height = Application.GetRealHeight (60),
                                            TextID = R.MyInternationalizationString.DelayTime,
                                            TextAlignment = TextAlignment.CenterLeft,
                                        };
                                        dialog.AddChidren (lblChangeName);
                                        var etDelayTime = new EditText () {
                                            X = lblChangeName.Right + Application.GetRealWidth (10),
                                            Y = btnEquipmentTitle.Bottom + Application.GetRealHeight (20),
                                            Width = lblChangeName.Width,
                                            Height = lblChangeName.Height,
                                            TextAlignment = TextAlignment.CenterLeft,
                                            Text = " " + (sendBytes [7] * 256 + sendBytes [8]).ToString (),
                                            BackgroundColor = 0xFF000000,
                                            SelectedBackgroundColor = 0xFF000000,
                                        };
                                        dialog.AddChidren (etDelayTime);
                                        var btnTest = new Button () {
                                            X = btnEquipmentTitle.X,
                                            Y = etDelayTime.Bottom + Application.GetRealHeight (30),
                                            Width = Application.GetRealWidth (200),
                                            Height = Application.GetRealHeight (60),
                                            BackgroundColor = 0xFF333333,
                                            SelectedBackgroundColor = SkinStyle.Current.SelectedColor,
                                            BorderWidth = 1,
                                            Radius = 5,
                                            BorderColor = SkinStyle.Current.Transparent,
                                            TextID = R.MyInternationalizationString.ON,
                                        };
                                        dialog.AddChidren (btnTest);

                                        if (sendBytes [6] == 100) {
                                            btnTest.IsSelected = true;
                                        } else {
                                            btnTest.IsSelected = false;
                                        }
                                        btnTest.MouseUpEventHandler += (sender3, e3) => {
                                            btnTest.IsSelected = !btnTest.IsSelected;
                                            if (btnTest.IsSelected) {
                                                sendBytes [6] = 100;
                                                btnTest.TextID = R.MyInternationalizationString.ON;
                                            } else {
                                                sendBytes [6] = 0;
                                                btnTest.TextID = R.MyInternationalizationString.OFF;
                                            }
                                            Control.ControlBytesSend (Command.SetSingleLight, sendBytes [3], sendBytes [4], new byte [] { sendBytes [5], sendBytes [6], sendBytes [7], sendBytes [8] });
                                        };

                                        btnSave.MouseUpEventHandler += (sender2, e2) => {
                                            sendBytes [2] = 0x59;
                                            int dtime;
                                            if (int.TryParse (etDelayTime.Text.Trim ().ToString (), out dtime)) {
                                                if (dtime > 3600 || dtime < 0) {
                                                    new Alert (Language.StringByID (R.MyInternationalizationString.Tip), Language.StringByID (R.MyInternationalizationString.PleaseEnterTheNumberTwo), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                                                    return;
                                                }
                                            } else {
                                                new Alert (Language.StringByID (R.MyInternationalizationString.Tip), Language.StringByID (R.MyInternationalizationString.PleaseEnterTheNumberTwo), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                                                return;
                                            }
                                            sendBytes [7] = (byte)(Convert.ToInt32 (etDelayTime.Text.Trim ()) / 256);
                                            sendBytes [8] = (byte)(Convert.ToInt32 (etDelayTime.Text.Trim ()) % 256);
                                            if (hasNotInLocalDevice) {
                                                foreach (var bytesend in targetList) {
                                                    Control.ControlBytesSend (Command.WriteWirelessPanelButtonKey, deviceLoop.SubnetID, deviceLoop.DeviceID, bytesend);
                                                }
                                            }
                                            if (!targetList.Contains (sendBytes)) {
                                                targetList.Add (sendBytes);
                                            }
                                            Control.ControlBytesSend (Command.WriteWirelessPanelButtonKey, deviceLoop.SubnetID, deviceLoop.DeviceID, sendBytes);
                                            dialog.Close ();
                                            showEquipments (inVerticalscrolView);
                                        };

                                    } else if (deviceType == DeviceType.LightDimming.ToString ()) {
                                        //btnEquipmentTitle.TextID = R.MyInternationalizationString.DimmingLights;
                                        var lblChangeName = new Button () {
                                            X = Application.GetRealWidth (10),
                                            Y = btnEquipmentTitle.Bottom + Application.GetRealHeight (20),
                                            Width = Application.GetRealWidth (200),
                                            Height = Application.GetRealHeight (60),
                                            TextID = R.MyInternationalizationString.DelayTime,
                                            TextAlignment = TextAlignment.CenterLeft,
                                        };
                                        dialog.AddChidren (lblChangeName);
                                        var etDelayTime = new EditText () {
                                            X = lblChangeName.Right + Application.GetRealWidth (10),
                                            Y = btnEquipmentTitle.Bottom + Application.GetRealHeight (20),
                                            Width = lblChangeName.Width,
                                            Height = lblChangeName.Height,
                                            TextAlignment = TextAlignment.CenterLeft,
                                            Text = " " + (sendBytes [7] * 256 + sendBytes [8]).ToString (),
                                            BackgroundColor = 0xFF000000,
                                            SelectedBackgroundColor = 0xFF000000,
                                        };
                                        dialog.AddChidren (etDelayTime);


                                        #region 进度条
                                        bool unEnableDimmingLight = true;
                                        if (UserConfig.Instance.UnEnableDimmingLight.Contains (sendBytes [3] + "_" + sendBytes [4] + "_" + sendBytes [5])) {
                                            unEnableDimmingLight = false;
                                        }
                                        var btnMinBrightness = new Button () {
                                            Width = Application.GetRealWidth (50),
                                            Height = Application.GetRealHeight (80),
                                            X = Application.GetRealWidth (10),
                                            Y = lblChangeName.Bottom + Application.GetRealHeight (30),
                                            Text = "0%",
                                            TextColor = 0xFF333333,
                                            TextAlignment = TextAlignment.Center,
                                        };
                                        if (unEnableDimmingLight)
                                            dialog.AddChidren (btnMinBrightness);

                                        var f = new FrameLayout () {
                                            Width = Application.GetRealWidth (540 - 210),
                                            Height = Application.GetRealHeight (80),
                                            X = btnMinBrightness.Right,
                                            Y = btnMinBrightness.Y,
                                        };
                                        if (unEnableDimmingLight)
                                            dialog.AddChidren (f);

                                        HorizontalSeekBar horizontalSeekBar = new HorizontalSeekBar () {
                                            Gravity = Gravity.CenterVertical,
                                            Progress = sendBytes [6],
                                            ThumbColor = 0xFFFFFFFF,
                                        };
                                        f.AddChidren (horizontalSeekBar);

                                        var btnMaxBrightness = new Button () {
                                            Width = Application.GetRealWidth (100),
                                            Height = Application.GetRealHeight (80),
                                            X = f.Right,
                                            Y = btnMinBrightness.Y,
                                            Text = sendBytes [7] * 256 + sendBytes [8] + "%",
                                            TextColor = 0xFF333333,
                                        };
                                        if (unEnableDimmingLight)
                                            dialog.AddChidren (btnMaxBrightness);
                                        horizontalSeekBar.ProgressChanged += (s, ee) => {
                                            sendBytes [6] = (byte)ee;
                                            btnMaxBrightness.Text = sendBytes [6].ToString () + "%";
                                            Control.ControlBytesSend (Command.SetSingleLight, sendBytes [3],
                                                                      sendBytes [4], new byte [] { sendBytes [5], sendBytes [6], 0, 0 });
                                        };
                                        #endregion

                                        var btnTest = new Button () {
                                            X = btnEquipmentTitle.X,
                                            Y = f.Bottom + Application.GetRealHeight (30),
                                            Width = Application.GetRealWidth (200),
                                            Height = Application.GetRealHeight (60),
                                            BackgroundColor = 0xFF333333,
                                            SelectedBackgroundColor = SkinStyle.Current.SelectedColor,
                                            BorderWidth = 1,
                                            Radius = 5,
                                            BorderColor = SkinStyle.Current.Transparent,
                                            TextID = R.MyInternationalizationString.ON,
                                            Gravity = Gravity.CenterHorizontal,
                                        };
                                        dialog.AddChidren (btnTest);
                                        btnTest.MouseUpEventHandler += (sender3, e3) => {
                                            btnTest.IsSelected = !btnTest.IsSelected;
                                            if (btnTest.IsSelected) {
                                                sendBytes [6] = 100;
                                                btnTest.TextID = R.MyInternationalizationString.ON;
                                                horizontalSeekBar.Progress = 100;
                                                btnMaxBrightness.Text = "100%";
                                            } else {
                                                sendBytes [6] = 0;
                                                btnTest.TextID = R.MyInternationalizationString.OFF;
                                                horizontalSeekBar.Progress = 0;
                                                btnMaxBrightness.Text = "0%";
                                            }
                                            Control.ControlBytesSend (Command.SetSingleLight, sendBytes [3],
                                                                      sendBytes [4], new byte [] { sendBytes [5], sendBytes [6], 0, 0 });
                                        };

                                        if (sendBytes [6] == 0) {
                                            btnTest.IsSelected = false;
                                        } else {
                                            btnTest.IsSelected = true;
                                        }


                                        btnSave.MouseUpEventHandler += (sender2, e2) => {
                                            sendBytes [2] = 0x59;
                                            int dtime;
                                            if (int.TryParse (etDelayTime.Text.Trim ().ToString (), out dtime)) {
                                                if (dtime > 3600 || dtime < 0) {
                                                    new Alert (Language.StringByID (R.MyInternationalizationString.Tip), Language.StringByID (R.MyInternationalizationString.PleaseEnterTheNumberTwo), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                                                    return;
                                                }
                                            } else {
                                                new Alert (Language.StringByID (R.MyInternationalizationString.Tip), Language.StringByID (R.MyInternationalizationString.PleaseEnterTheNumberTwo), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                                                return;
                                            }
                                            sendBytes [7] = (byte)(Convert.ToInt32 (etDelayTime.Text.Trim ()) / 256);
                                            sendBytes [8] = (byte)(Convert.ToInt32 (etDelayTime.Text.Trim ()) % 256);

                                            if (hasNotInLocalDevice) {
                                                foreach (var bytesend in targetList) {
                                                    Control.ControlBytesSend (Command.WriteWirelessPanelButtonKey, deviceLoop.SubnetID, deviceLoop.DeviceID, bytesend);
                                                }
                                            }
                                            if (!targetList.Contains (sendBytes)) {
                                                targetList.Add (sendBytes);
                                            }
                                            Control.ControlBytesSend (Command.WriteWirelessPanelButtonKey, deviceLoop.SubnetID, deviceLoop.DeviceID, sendBytes);
                                            dialog.Close ();
                                            showEquipments (inVerticalscrolView);
                                        };
                                    }
                                } else if (deviceType == DeviceType.CurtainModel.ToString () || deviceType == DeviceType.CurtainTrietex.ToString () || deviceType == DeviceType.CurtainRoller.ToString ()) {
                                    if (deviceType == DeviceType.CurtainModel.ToString ()) {
                                        //btnEquipmentTitle.TextID = R.MyInternationalizationString.CurtainModel;
                                        var btnOpenCurtain = new Button () {
                                            Width = Application.GetRealWidth (124),
                                            Height = Application.GetRealHeight (125),
                                            UnSelectedImagePath = "Curtain/CurtainOpen.png",
                                            SelectedImagePath = "Curtain/CurtainOpenSelected.png",
                                            X = btnEquipmentTitle.X,
                                            Y = Application.GetRealHeight (255),
                                        };
                                        dialog.AddChidren (btnOpenCurtain);
                                        var btnOpenLbl = new Button () {
                                            Width = Application.GetRealWidth (124),
                                            Height = Application.GetRealHeight (30),
                                            X = btnOpenCurtain.X,
                                            Y = btnOpenCurtain.Bottom + Application.GetRealHeight (5),
                                            TextID = R.MyInternationalizationString.Open,
                                            TextColor = SkinStyle.Current.TextColor1,
                                        };
                                        dialog.AddChidren (btnOpenLbl);

                                        var btnStopCurtain = new Button () {
                                            Width = Application.GetRealWidth (124),
                                            Height = Application.GetRealHeight (125),
                                            X = Application.GetRealWidth ((480 - 124) / 2),
                                            Y = btnOpenCurtain.Y,
                                            SelectedImagePath = "Curtain/CurtainTimeOutSelected.png",
                                            UnSelectedImagePath = "Curtain/CurtainTimeOut.png",
                                        };
                                        dialog.AddChidren (btnStopCurtain);
                                        var btnStopLbl = new Button () {
                                            Width = Application.GetRealWidth (124),
                                            Height = Application.GetRealHeight (30),
                                            X = btnStopCurtain.X,
                                            Y = btnOpenLbl.Y,
                                            TextID = R.MyInternationalizationString.Stop,
                                            TextColor = SkinStyle.Current.TextColor1,
                                        };
                                        dialog.AddChidren (btnStopLbl);

                                        var btnCloseCurtain = new Button () {
                                            Width = Application.GetRealWidth (124),
                                            Height = Application.GetRealHeight (125),
                                            X = Application.GetRealWidth (480 - 124 - 35),
                                            Y = btnOpenCurtain.Y,
                                            UnSelectedImagePath = "Curtain/CurtainClose.png",
                                            SelectedImagePath = "Curtain/CurtainCloseSelected.png",
                                        };
                                        if (sendBytes [6] == 2) {
                                            btnCloseCurtain.IsSelected = true;
                                            btnStopCurtain.IsSelected = false;
                                            btnOpenCurtain.IsSelected = false;
                                        } else if (sendBytes [6] == 0) {
                                            btnCloseCurtain.IsSelected = false;
                                            btnStopCurtain.IsSelected = true;
                                            btnOpenCurtain.IsSelected = false;
                                        } else if (sendBytes [6] == 1) {
                                            btnCloseCurtain.IsSelected = false;
                                            btnStopCurtain.IsSelected = false;
                                            btnOpenCurtain.IsSelected = true;
                                        }
                                        btnCloseCurtain.MouseUpEventHandler += (sender3, e3) => {
                                            btnCloseCurtain.IsSelected = true;
                                            btnOpenCurtain.IsSelected = false;
                                            btnStopCurtain.IsSelected = false;
                                            sendBytes [6] = 2;
                                        };
                                        btnOpenCurtain.MouseUpEventHandler += (sender3, e3) => {
                                            btnCloseCurtain.IsSelected = false;
                                            btnOpenCurtain.IsSelected = true;
                                            btnStopCurtain.IsSelected = false;
                                            sendBytes [6] = 1;
                                        };
                                        btnStopCurtain.MouseUpEventHandler += (sender3, e3) => {
                                            btnCloseCurtain.IsSelected = false;
                                            btnOpenCurtain.IsSelected = false;
                                            btnStopCurtain.IsSelected = true;
                                            sendBytes [6] = 0;
                                        };
                                        dialog.AddChidren (btnCloseCurtain);
                                        btnStopCurtain.IsSelected = true;
                                        var btnCloseLbl = new Button () {
                                            Width = Application.GetRealWidth (94),
                                            Height = Application.GetRealHeight (30),
                                            X = btnCloseCurtain.X,
                                            Y = btnOpenLbl.Y,
                                            TextID = R.MyInternationalizationString.Close,
                                            TextColor = SkinStyle.Current.TextColor1,
                                        };
                                        dialog.AddChidren (btnCloseLbl);
                                        btnSave.MouseUpEventHandler += (sender2, e2) => {
                                            if (hasNotInLocalDevice) {
                                                foreach (var bytesend in targetList) {
                                                    Control.ControlBytesSend (Command.WriteWirelessPanelButtonKey, deviceLoop.SubnetID, deviceLoop.DeviceID, bytesend);
                                                }
                                            }
                                            if (!targetList.Contains (sendBytes)) {
                                                targetList.Add (sendBytes);
                                            }
                                            sendBytes [2] = 0x5C;
                                            Control.ControlBytesSend (Command.WriteWirelessPanelButtonKey, deviceLoop.SubnetID, deviceLoop.DeviceID, sendBytes);
                                            dialog.Close ();
                                            showEquipments (inVerticalscrolView);
                                        };
                                    } else if (deviceType == DeviceType.CurtainTrietex.ToString () || deviceType == DeviceType.CurtainRoller.ToString ()) {
                                        //btnEquipmentTitle.TextID = R.MyInternationalizationString.Curtain;

                                        var horizontalScrolViewMain = new HorizontalScrolViewLayout () {
                                            Height = Application.GetRealHeight (78),
                                            Y = Application.GetRealHeight (75),
                                        };
                                        dialog.AddChidren (horizontalScrolViewMain);

                                        var middleLayout = new FrameLayout {
                                            Height = Application.GetRealHeight (292),
                                            Y = horizontalScrolViewMain.Bottom,
                                        };
                                        dialog.AddChidren (middleLayout);

                                        var curtainState = new Button {
                                            Width = Application.GetRealWidth (240),
                                            Height = LayoutParams.MatchParent,
                                            UnSelectedImagePath = "Item/Menu.png",
                                            SelectedImagePath = "Item/MenuSelected.png",
                                            TextID = R.MyInternationalizationString.CurtainState,
                                            TextAlignment = TextAlignment.Center,
                                            IsSelected = true,
                                        };
                                        horizontalScrolViewMain.AddChidren (curtainState);

                                        var curtainProgress = new Button {
                                            Width = Application.GetRealWidth (240),
                                            Height = LayoutParams.MatchParent,
                                            UnSelectedImagePath = "Item/Menu.png",
                                            SelectedImagePath = "Item/MenuSelected.png",
                                            TextID = R.MyInternationalizationString.CurtainProgress,
                                            TextAlignment = TextAlignment.Center,
                                        };
                                        horizontalScrolViewMain.AddChidren (curtainProgress);

                                        EventHandler<MouseEventArgs> handler = (sender1, e1) => {
                                            middleLayout.RemoveAll ();
                                            curtainState.IsSelected = true;
                                            curtainProgress.IsSelected = false;

                                            #region curtain status
                                            var btnOpenCurtain = new Button () {
                                                Width = Application.GetRealWidth (124),
                                                Height = Application.GetRealHeight (125),
                                                UnSelectedImagePath = "Curtain/CurtainOpen.png",
                                                SelectedImagePath = "Curtain/CurtainOpenSelected.png",
                                                X = btnEquipmentTitle.X,
                                                Y = Application.GetRealHeight (85),
                                            };
                                            middleLayout.AddChidren (btnOpenCurtain);
                                            if (sendBytes [5] == 1) {
                                                if (sendBytes [6] == 1) {
                                                    btnOpenCurtain.IsSelected = true;
                                                }
                                            }

                                            var btnOpenLbl = new Button () {
                                                Width = Application.GetRealWidth (124),
                                                Height = Application.GetRealHeight (30),
                                                X = btnOpenCurtain.X,
                                                Y = btnOpenCurtain.Bottom + Application.GetRealHeight (5),
                                                TextID = R.MyInternationalizationString.Open,
                                                TextColor = SkinStyle.Current.TextColor1,
                                            };
                                            middleLayout.AddChidren (btnOpenLbl);

                                            var btnStopCurtain = new Button () {
                                                Width = Application.GetRealWidth (124),
                                                Height = Application.GetRealHeight (125),
                                                X = Application.GetRealWidth ((480 - 124) / 2),
                                                Y = btnOpenCurtain.Y,
                                                UnSelectedImagePath = "Curtain/CurtainTimeOut.png",
                                                SelectedImagePath = "Curtain/CurtainTimeOutSelected.png",
                                            };
                                            middleLayout.AddChidren (btnStopCurtain);
                                            if (sendBytes [5] == 1) {
                                                if (sendBytes [6] == 0) {
                                                    btnStopCurtain.IsSelected = true;
                                                }
                                            }

                                            var btnStopLbl = new Button () {
                                                Width = Application.GetRealWidth (124),
                                                Height = Application.GetRealHeight (30),
                                                X = btnStopCurtain.X,
                                                Y = btnOpenLbl.Y,
                                                TextID = R.MyInternationalizationString.Stop,
                                                TextColor = SkinStyle.Current.TextColor1,
                                            };
                                            middleLayout.AddChidren (btnStopLbl);

                                            var btnCloseCurtain = new Button () {
                                                Width = Application.GetRealWidth (124),
                                                Height = Application.GetRealHeight (125),
                                                X = Application.GetRealWidth (480 - 124 - 35),
                                                Y = btnOpenCurtain.Y,
                                                UnSelectedImagePath = "Curtain/CurtainClose.png",
                                                SelectedImagePath = "Curtain/CurtainCloseSelected.png",
                                            };
                                            middleLayout.AddChidren (btnCloseCurtain);
                                            if (sendBytes [5] == 1) {
                                                if (sendBytes [6] == 2) {
                                                    btnCloseCurtain.IsSelected = true;
                                                }
                                            }

                                            var btnCloseLbl = new Button () {
                                                Width = Application.GetRealWidth (94),
                                                Height = Application.GetRealHeight (30),
                                                X = btnCloseCurtain.X,
                                                Y = btnOpenLbl.Y,
                                                TextID = R.MyInternationalizationString.Close,
                                                TextColor = SkinStyle.Current.TextColor1,
                                            };
                                            middleLayout.AddChidren (btnCloseLbl);

                                            btnCloseCurtain.MouseUpEventHandler += (sender3, e3) => {
                                                btnCloseCurtain.IsSelected = true;
                                                btnOpenCurtain.IsSelected = false;
                                                btnStopCurtain.IsSelected = false;
                                                sendBytes [5] = 1;
                                                sendBytes [6] = 2;
                                                UpdataStatus (sendBytes);
                                            };
                                            btnOpenCurtain.MouseUpEventHandler += (sender3, e3) => {
                                                btnCloseCurtain.IsSelected = false;
                                                btnOpenCurtain.IsSelected = true;
                                                btnStopCurtain.IsSelected = false;
                                                sendBytes [5] = 1;
                                                sendBytes [6] = 1;
                                                UpdataStatus (sendBytes);
                                            };
                                            btnStopCurtain.MouseUpEventHandler += (sender3, e3) => {
                                                btnCloseCurtain.IsSelected = false;
                                                btnOpenCurtain.IsSelected = false;
                                                btnStopCurtain.IsSelected = true;
                                                sendBytes [5] = 1;
                                                sendBytes [6] = 0;
                                                UpdataStatus (sendBytes);
                                            };
                                            #endregion
                                        };

                                        curtainState.MouseUpEventHandler += handler;

                                        EventHandler<MouseEventArgs> progressHandler = (sender1, e1) => {
                                            middleLayout.RemoveAll ();
                                            curtainProgress.IsSelected = true;
                                            curtainState.IsSelected = false;

                                            #region 进度条
                                            var btnLine = new Button () {
                                                Width = Application.GetRealWidth (640),
                                                Height = 1,
                                                BackgroundColor = 0xFF000000,
                                            };
                                            middleLayout.AddChidren (btnLine);

                                            var curtainbtnCurrentStatus = new Button () {
                                                Width = Application.GetRealWidth (400),
                                                Height = Application.GetRealHeight (50),
                                                X = Application.GetRealWidth (20),
                                                Y = Application.GetRealHeight (80),
                                                TextAlignment = TextAlignment.CenterLeft,
                                                Text = Language.StringByID (R.MyInternationalizationString.CurrentStatusProgress) + ":" + sendBytes [6].ToString () + "%",
                                            };
                                            middleLayout.AddChidren (curtainbtnCurrentStatus);

                                            var btnMinBrightness = new Button () {
                                                Width = Application.GetRealWidth (50),
                                                Height = Application.GetRealHeight (40),
                                                X = Application.GetRealWidth (2),
                                                Y = curtainbtnCurrentStatus.Bottom + Application.GetRealHeight (30),
                                                Text = "0%",
                                                TextColor = 0xFF333333,
                                                TextAlignment = TextAlignment.Center,
                                            };
                                            middleLayout.AddChidren (btnMinBrightness);

                                            var f = new FrameLayout () {
                                                Width = Application.GetRealWidth (540 - 192),
                                                Height = Application.GetRealHeight (80),
                                                X = btnMinBrightness.Right,
                                                Y = btnMinBrightness.Y,
                                            };
                                            middleLayout.AddChidren (f);

                                            var curtainhorizontalSeekBar = new HorizontalSeekBar () {
                                                Width = Application.GetRealWidth (540 - 193),
                                                Height = LayoutParams.MatchParent,
                                                Gravity = Gravity.CenterVertical,
                                                Progress = sendBytes [6],
                                                ThumbColor = 0xFFFFFFFF,
                                            };
                                            f.AddChidren (curtainhorizontalSeekBar);

                                            if (sendBytes [5] == 1) {
                                                if (sendBytes [6] == 1) {
                                                    sendBytes [6] = 100;
                                                    curtainbtnCurrentStatus.Text = Language.StringByID (R.MyInternationalizationString.CurrentStatusProgress) + ":" + 100 + "%";
                                                    curtainhorizontalSeekBar.Progress = 100;
                                                } else if (sendBytes [6] == 2) {
                                                    sendBytes [6] = 0;
                                                    curtainhorizontalSeekBar.Progress = 0;
                                                    curtainbtnCurrentStatus.Text = Language.StringByID (R.MyInternationalizationString.CurrentStatusProgress) + ":" + 0 + "%";

                                                } else {
                                                    curtainhorizontalSeekBar.Progress = sendBytes [6];
                                                    curtainbtnCurrentStatus.Text = Language.StringByID (R.MyInternationalizationString.CurrentStatusProgress) + ":" + sendBytes [6].ToString () + "%";
                                                }
                                            }

                                            var btnMaxBrightness = new Button () {
                                                Width = Application.GetRealWidth (100),
                                                Height = Application.GetRealHeight (40),
                                                X = f.Right,
                                                Y = btnMinBrightness.Y,
                                                Text = "100%",
                                                TextColor = 0xFF333333,
                                            };
                                            middleLayout.AddChidren (btnMaxBrightness);

                                            curtainhorizontalSeekBar.ProgressChanged += (s, ee) => {
                                                sendBytes [5] = 17;
                                                sendBytes [6] = (byte)ee;
                                                curtainhorizontalSeekBar.Progress = sendBytes [6];
                                                curtainbtnCurrentStatus.Text = Language.StringByID (R.MyInternationalizationString.CurrentStatusProgress) + ":" + sendBytes [6].ToString () + "%";
                                            };
                                            #endregion
                                        };
                                        curtainProgress.MouseUpEventHandler += progressHandler;

                                        if (sendBytes [5] == 1) {
                                            handler (curtainState, null);
                                        } else {
                                            progressHandler (curtainProgress, null);
                                        }

                                        btnSave.MouseUpEventHandler += (sender2, e2) => {
                                            if (hasNotInLocalDevice) {
                                                foreach (var bytesend in targetList) {
                                                    Control.ControlBytesSend (Command.WriteWirelessPanelButtonKey, deviceLoop.SubnetID, deviceLoop.DeviceID, bytesend);
                                                }
                                            }
                                            if (!targetList.Contains (sendBytes)) {
                                                targetList.Add (sendBytes);
                                            }
                                            sendBytes [2] = 0x5C;
                                            Control.ControlBytesSend (Command.WriteWirelessPanelButtonKey, deviceLoop.SubnetID, deviceLoop.DeviceID, sendBytes);
                                            dialog.Close ();
                                            showEquipments (inVerticalscrolView);
                                        };
                                    }
                                } else if (deviceType == DeviceType.LogicModule.ToString ()) {
                                    Button btnTest = new Button () {
                                        Width = Application.GetRealWidth (170),
                                        Height = Application.GetRealHeight (70),
                                        TextID = R.MyInternationalizationString.Test,
                                        Gravity = Gravity.Center,
                                        SelectedBackgroundColor = SkinStyle.Current.SelectedColor,
                                        BackgroundColor = 0xFF333333,
                                    };
                                    dialog.AddChidren (btnTest);
                                    btnTest.MouseUpEventHandler += (sender2, e2) => {
                                        btnTest.IsSelected = false;
                                    };
                                    LogicModule device = Newtonsoft.Json.JsonConvert.DeserializeObject<LogicModule> (System.Text.Encoding.UTF8.GetString (IO.FileUtils.ReadFile (btn.GetTagByKey ("DeviceFilePath").ToString ())));
                                    btnTest.MouseDownEventHandler += (sender2, e2) => {
                                        btnTest.IsSelected = true;

                                        Control.ControlBytesSendHasReturn (Command.SetScene, device.SubnetID, device.DeviceID, new byte [] {
                                            device.AreaID,device.AreaSceneID});
                                    };
                                    btnSave.MouseUpEventHandler += (sender2, e2) => {
                                        if (hasNotInLocalDevice) {
                                            foreach (var bytesend in targetList) {
                                                Control.ControlBytesSend (Command.WriteWirelessPanelButtonKey, deviceLoop.SubnetID, deviceLoop.DeviceID, bytesend);
                                            }
                                        }
                                        if (!targetList.Contains (sendBytes)) {
                                            targetList.Add (sendBytes);
                                        }
                                        sendBytes [2] = 0x55;
                                        sendBytes [6] = device.AreaSceneID;
                                        Control.ControlBytesSend (Command.WriteWirelessPanelButtonKey, deviceLoop.SubnetID, deviceLoop.DeviceID, sendBytes);
                                        dialog.Close ();

                                        showEquipments (inVerticalscrolView);
                                    };
                                }
                                dialog.Show ();
                                #endregion
                            }
                        };

                        var btnDel = new Button () {
                            Width = btnWidth - Application.GetRealWidth (20),
                            Height = Application.GetRealHeight (50),
                            X = btnEquipmnetSetting.X + btnEquipmnetSetting.Width + Application.GetRealWidth (10),
                            Y = btnShowEquipments.Y,
                            BackgroundColor = 0xFF333333,
                            SelectedBackgroundColor = SkinStyle.Current.SelectedColor,
                            BorderWidth = 1,
                            Radius = 5,
                            BorderColor = SkinStyle.Current.Transparent,
                            TextID = R.MyInternationalizationString.Delete,
                            TextAlignment = TextAlignment.Center,
                        };

                        btnShowEquipments.MouseUpEventHandler += (sender, e) => {
                            btnShowEquipments.IsSelected = !btnShowEquipments.IsSelected;
                            if (btnShowEquipments.IsSelected) {
                                showEquipments (inVerticalscrolView, true);
                            } else {
                                //加载设备按钮
                                showEquipments (inVerticalscrolView);
                            }
                        };
                        frameLayoutBody.AddChidren (btnDel);

                        btnDel.MouseUpEventHandler += (sender, e) => {
                            if (btn == null) {
                                return;
                            }
                            Common common = Newtonsoft.Json.JsonConvert.DeserializeObject<Common> (System.Text.Encoding.UTF8.GetString (IO.FileUtils.ReadFile (btn.GetTagByKey ("DeviceFilePath").ToString ())));
                            if (common == null) {
                                return;
                            }
                            if (btnShowEquipments.IsSelected) {
                                btn.RemoveFromParent ();
                            } else {
                                btn.BackgroundColor = 0xFB757575;
                                btn.Tag = false;
                            }
                            btn = null;

                            System.Threading.Tasks.Task.Run (() => {
                                var data = targetList.Find ((obj) => {
                                    return obj [3] + "_" + obj [4] + "_" + obj [5] == common.SubnetID + "_" + common.DeviceID + "_" + common.LoopID;
                                });
                                if (data == null) {
                                    return;
                                }
                                data [2] = 0;
                                targetList.Remove (data);
                                //Control.ControlBytesSendHasReturn (Command.WriteWirelessPanelButtonKey, panelButtonKey.SubnetID, panelButtonKey.DeviceID, data);
                                targetList.Add (data);
                                for (int i = 0; i < targetList.Count; i++) {
                                    var bytes = targetList [i];
                                    bytes [1] = (byte)(i + 1);
                                    Control.ControlBytesSendHasReturn (Command.WriteWirelessPanelButtonKey, deviceLoop.SubnetID, deviceLoop.DeviceID, bytes);
                                }
                                targetList.Remove (data);
                            });
                        };
                    });
                } catch { } finally {
                    Application.RunOnMainThread (() => {
                        MainPage.Loading.Hide ();
                    });
                }
            });

            //SystemMiddle.InitFrameLayoutBottomButton (R.MyInternationalizationString.ReFresh, (sender, e) => {
            //    SystemWirelessPanelButtonKeyShow (deviceLoop, panelDevice);
            //});
        }

        void UpdataStatus (byte [] sendBytes)
        {
            ///
            Common common = Newtonsoft.Json.JsonConvert.DeserializeObject<Common> (System.Text.Encoding.UTF8.GetString (IO.FileUtils.ReadFile (btn.GetTagByKey ("DeviceFilePath").ToString ())));
            if (common == null) {
                return;
            }
            sendBytes [3] = common.SubnetID;
            sendBytes [4] = common.DeviceID;
            sendBytes [5] = common.LoopID;
            /// /////////
            if (Control.ControlBytesSendHasReturn (Command.UpdataCurtainModelStutas, sendBytes [3], sendBytes [4],
            new byte [] { sendBytes [5], 1 }) == null) {
                Application.RunOnMainThread (() => {
                    new Alert (Language.StringByID (R.MyInternationalizationString.Tip), Language.StringByID (R.MyInternationalizationString.TipEquipmentNotOnline), Language.StringByID (R.MyInternationalizationString.Close)).Show ();
                });
            } else {

            }
        }
    }
}