import router from '@ohos.router';
import CommonConstants from '../Common/constants/CommonConstants';
import ElectricScrewdriverPresetModel from '../model/ElectricScrewdriverPresetModel';
import ElectricSolderingIronPresetModel from '../model/ElectricSolderingIronPresetModel';
import AntiWristStrap from '../viewmodel/device/AntiWristStrap';
import ElectricScrewdriver from '../viewmodel/device/ElectricScrewdriver';
import ElectricScrewdriverPreset from '../viewmodel/device/ElectricScrewdriverPreset';
import ElectricSolderingIron from '../viewmodel/device/ElectricSolderingIron';
import ElectricSolderingIronPreset from '../viewmodel/device/ElectricSolderingIronPreset';
import ThreeColourLight from '../viewmodel/device/ThreeColourLight';
import WeldFumeExtractor from '../viewmodel/device/WeldFumeExtractor';
import { AddSubtractComp } from '../common/component/AddSubtractComp'
import MqttDataItem from '../viewmodel/mqtt/MqttDataItem';
import MqttCmdData from '../viewmodel/mqtt/MqttCmdData';
import MqttManager from '../common/util/mqtt';


// 声明接受参数的类型
interface Params {
  deviceType?: number,
  // 在线状态（1:在线 0:离线）
  onlineStatus?: number,
  // 三色灯
  threeColourLight?: ThreeColourLight,
  // 电烙铁
  solderingIron?: ElectricSolderingIron,
  // 电烙铁
  screwdriver?: ElectricScrewdriver,
}

const params = router.getParams() as Params; // 获取传递过来的参数对象

@Component
@Entry
struct DeviceControllerPage {

  /*
  * 业务参数
  * */
  @State deviceShows: DeviceShow[] = [
    {deviceName: '三色灯', deviceImage: $r('app.media.device_three_color_light')},
    {deviceName: '电烙铁', deviceImage: $r('app.media.device_electric_soldering_iron')},
    {deviceName: '电动螺丝刀', deviceImage: $r('app.media.device_electric_screwdriver')},
  ]
  // 0:三色灯 1:电烙铁 2:电动螺丝刀
  @State deviceType: number = 2
  // @State deviceType: number = 0
  @State onlineStatus: number = 0
  //三色灯
  @StorageProp('ThreeColourLight') threeColourLight: ThreeColourLight = {}
  //焊烟排烟机/空气净化器
  @StorageProp('WeldFumeExtractor') weldFumeExtractor: WeldFumeExtractor = { ExhaustFan: 0}
  // 电烙铁
  @StorageProp('ElectricSolderingIron')  solderingIron: ElectricSolderingIron = { SolderingCurrTemp: 0}
  // 电动螺丝刀
  @StorageProp('ElectricScrewdriver') screwdriver: ElectricScrewdriver = { TorqueHoldTime:0 }
  // 防静电手环
  @StorageProp('AntiWristStrap') wristStrap: AntiWristStrap = { RingWearNormal: 0, RingWearStandby: 0, RingWearFault: 0, OnlineStatus: 0}

  // 电烙铁预设列表
  @State ironPresets: ElectricSolderingIronPreset[] = []
  // 电动螺丝刀预设列表
  @State screwdriverPresets: ElectricScrewdriverPreset[] = []

  // 预设温度
  @State presetTemp: number = CommonConstants.ironTempMin

  // 选择预设
  @State selectPreset: number = -1
  // 操作预设（删除或者修改预设名称）
  @State operatePreset: number = -1

  // 修改预设名称弹窗控制器
  updatePresetNameController: CustomDialogController = new CustomDialogController({
    builder: updatePresetNameDialog({
      ironPresets: this.ironPresets,
      selectPreset: this.selectPreset,
      cancel: ()=> {},
      confirm: async ()=> {
        if (this.deviceType === 1) {
          ElectricSolderingIronPresetModel.updatePreset(this.ironPresets[this.selectPreset]);
          this.ironPresets = []
          this.ironPresets = await ElectricSolderingIronPresetModel.getPresetList();
        } else if (this.deviceType === 2) {
          ElectricScrewdriverPresetModel.updatePreset(this.screwdriverPresets[this.selectPreset]);
          this.screwdriverPresets = []
          this.screwdriverPresets = await ElectricScrewdriverPresetModel.getPresetList();
        }
      },
    }),
    autoCancel: true,
    alignment: DialogAlignment.Center,
    // gridCount: 3,
    customStyle: true,
  })

  async aboutToAppear() {
    this.deviceType = ((params && params.deviceType != null) ? params.deviceType : 1000)
    this.onlineStatus = ((params && params.onlineStatus != null) ? params.onlineStatus : 0)

    if (this.deviceType === 1) {
      this.ironPresets = await ElectricSolderingIronPresetModel.getPresetList();
      this.presetTemp = this.solderingIron?.SolderingCurrTemp!;
    } else if (this.deviceType === 2) {
      this.screwdriverPresets = await ElectricScrewdriverPresetModel.getPresetList();
    }
  }

  // async aboutToDisappear() {
  //   await this.disconnect();
  //   await this.destroy()
  // }

  build() {
    Column() {
      // 顶部操作栏
      Row() {
        Row().width('2.5%')
        Image($r('app.media.general_return'))
          .width($r('app.float.virtualSize_48'))
          .height($r('app.float.virtualSize_48'))
          .fillColor($r('app.color.FFFFFF'))
          .onClick(()=>{
            router.back({
              url: 'pages/ProcessIndex',
              params: {
                auxiliaryOperationFlag: true
              }
            })
          })
        Row().width('0.6%')
        Text(this.deviceShows[this.deviceType]?.deviceName!)
          .fontSize($r('app.float.fontSize_30'))
          .fontColor($r('app.color.FFFFFF'))
          .fontWeight(FontWeight.Medium)

        Blank()

        if (this.deviceType != 0) {
          // 三色灯没有这些按钮
          Row() {
            Text('返回')
              .fontColor($r('app.color.0A84FF'))
              .fontSize($r('app.float.fontSize_24'))
              .fontWeight(FontWeight.Medium)
          }
          .width('5.6%')
          .height('48%')
          .justifyContent(FlexAlign.Center)
          .backgroundColor($r('app.color.20FFFFFF'))
          .borderRadius($r('app.float.virtualSize_16'))
          .onClick(()=>{
            router.back({
              url: 'pages/ProcessIndex',
              params: {
                auxiliaryOperationFlag: true
              }
            })
          })
          Row().width('1%')

          Row() {
            Text('保存预设')
              .fontColor($r('app.color.0A84FF'))
              .fontSize($r('app.float.fontSize_24'))
              .fontWeight(FontWeight.Medium)
          }
          .width('8.1%')
          .height('48%')
          .justifyContent(FlexAlign.Center)
          .backgroundColor($r('app.color.20FFFFFF'))
          .borderRadius($r('app.float.virtualSize_16'))
          .onClick(async ()=>{
            switch (this.deviceType) {
              case 1:
              // 下发命令
                this.issueControlCommand('SolderingSetTemp', this.presetTemp);
              // 小于0，说明是新增预设
                if (this.selectPreset < 0) {
                  console.log('hhtest', '-----------新增预设');
                  if (!this.ironPresets || this.ironPresets.length <= 0) {
                    let preset: ElectricSolderingIronPreset = {
                      setName: '自定义1',
                      setValue: this.presetTemp,
                      unitString: '℃'
                    }
                    let id: number | undefined = await ElectricSolderingIronPresetModel.addPreset(preset)
                    this.ironPresets = await ElectricSolderingIronPresetModel.getPresetList()
                    return
                  }
                  let setName = '自定义'
                  let index = 1
                  for (const element of this.ironPresets) {
                    if (element.setName?.startsWith(setName)) {
                      let temp = element.setName?.slice(3, -1);
                      let tempIndex = parseInt(temp);
                      if (!isNaN(tempIndex)) {
                        if (tempIndex > index) {
                          index = tempIndex
                        }
                      }
                    }
                  }
                  let preset: ElectricSolderingIronPreset = {
                    setName: setName + (++index),
                    setValue: this.presetTemp,
                    unitString: '℃'
                  }
                  ElectricSolderingIronPresetModel.addPreset(preset)
                } else {
                  // 下发命令
                  this.issueControlCommand('SolderingSetTemp', this.presetTemp);
                  // 修改预设
                  let preset: ElectricSolderingIronPreset = this.ironPresets[this.selectPreset]
                  preset.setValue = this.presetTemp
                  let resultNum: number | undefined = await ElectricSolderingIronPresetModel.updatePreset(preset)
                }
                this.ironPresets = await ElectricSolderingIronPresetModel.getPresetList()
                break
              case 2:
              // 下发命令
                this.issueControlCommand('TightenTorqueTarget', this.screwdriver.TightenTorqueTarget);
                this.issueControlCommand('TighteRotationDirection', this.screwdriver.TighteRotationDirection);
                this.issueControlCommand('TorqueHoldTime', this.screwdriver.TorqueHoldTime);
                this.issueControlCommand('TorqueUpperLimit', this.screwdriver.TorqueUpperLimit);
                this.issueControlCommand('TorqueLowerLimit', this.screwdriver.TorqueLowerLimit);
                this.issueControlCommand('EnableFloatSlipDetection', this.screwdriver.EnableFloatSlipDetection);
                this.issueControlCommand('FloatDetectionTurns', this.screwdriver.FloatDetectionTurns);
                this.issueControlCommand('SlipDetectionTurns', this.screwdriver.SlipDetectionTurns);
                if (this.selectPreset < 0) {
                  if (!this.ironPresets || this.ironPresets.length <= 0) {
                    let preset: ElectricScrewdriverPreset = {
                      setName: '自定义1',
                      TighteRotationDirection: this.screwdriver.TighteRotationDirection,
                      TorqueHoldTime: this.screwdriver.TorqueHoldTime,
                      TightenTorqueTarget: this.screwdriver.TightenTorqueTarget,
                      TorqueUpperLimit: this.screwdriver.TorqueUpperLimit,
                      TorqueLowerLimit: this.screwdriver.TorqueLowerLimit,
                      EnableFloatSlipDetection: this.screwdriver.EnableFloatSlipDetection,
                      FloatDetectionTurns: this.screwdriver.FloatDetectionTurns,
                      SlipDetectionTurns: this.screwdriver.SlipDetectionTurns,
                      TightenTorqueMax: this.screwdriver.TightenTorqueMax,
                      TightenResult: this.screwdriver.TightenResult,
                    }
                    let id: number | undefined = await ElectricScrewdriverPresetModel.addPreset(preset)
                    this.ironPresets = await ElectricScrewdriverPresetModel.getPresetList()
                    return
                  }
                  let setName = '自定义'
                  let index = 1
                  for (const element of this.ironPresets) {
                    if (element.setName?.startsWith(setName)) {
                      let temp = element.setName?.slice(3, -1);
                      let tempIndex = parseInt(temp);
                      if (!isNaN(tempIndex)) {
                        if (tempIndex > index) {
                          index = tempIndex
                        }
                      }
                    }
                  }
                  let preset: ElectricScrewdriverPreset = {
                    setName: '自定义1',
                    TighteRotationDirection: this.screwdriver.TighteRotationDirection,
                    TorqueHoldTime: this.screwdriver.TorqueHoldTime,
                    TightenTorqueTarget: this.screwdriver.TightenTorqueTarget,
                    TorqueUpperLimit: this.screwdriver.TorqueUpperLimit,
                    TorqueLowerLimit: this.screwdriver.TorqueLowerLimit,
                    EnableFloatSlipDetection: this.screwdriver.EnableFloatSlipDetection,
                    FloatDetectionTurns: this.screwdriver.FloatDetectionTurns,
                    SlipDetectionTurns: this.screwdriver.SlipDetectionTurns,
                    TightenTorqueMax: this.screwdriver.TightenTorqueMax,
                    TightenResult: this.screwdriver.TightenResult,
                  }
                  ElectricScrewdriverPresetModel.addPreset(preset)
                } else {
                  // 修改预设
                  let preset: ElectricScrewdriverPreset = {
                    id: this.screwdriverPresets[this.selectPreset].id,
                    setName: this.screwdriverPresets[this.selectPreset].setName,
                    TighteRotationDirection: this.screwdriver.TighteRotationDirection,
                    TorqueHoldTime: this.screwdriver.TorqueHoldTime,
                    TightenTorqueTarget: this.screwdriver.TightenTorqueTarget,
                    TorqueUpperLimit: this.screwdriver.TorqueUpperLimit,
                    TorqueLowerLimit: this.screwdriver.TorqueLowerLimit,
                    EnableFloatSlipDetection: this.screwdriver.EnableFloatSlipDetection,
                    FloatDetectionTurns: this.screwdriver.FloatDetectionTurns,
                    SlipDetectionTurns: this.screwdriver.SlipDetectionTurns,
                    TightenTorqueMax: this.screwdriver.TightenTorqueMax,
                    TightenResult: this.screwdriver.TightenResult,
                  }
                  let resultNum: number | undefined = await ElectricScrewdriverPresetModel.updatePreset(preset)
                }
                this.ironPresets = await ElectricScrewdriverPresetModel.getPresetList()
                break
            }
          })

          Row().width('1%')
          Row() {
            Text('完成')
              .fontColor($r('app.color.FFFFFF'))
              .fontSize($r('app.float.fontSize_24'))
              .fontWeight(FontWeight.Medium)
          }
          .width('5.6%')
          .height('48%')
          .justifyContent(FlexAlign.Center)
          .backgroundColor($r('app.color.30D158'))
          .borderRadius($r('app.float.virtualSize_16'))
          .onClick(async ()=>{
            switch (this.deviceType) {
              case 1:
                if (this.selectPreset < 0) {
                  this.issueControlCommand('SolderingSetTemp', this.presetTemp);
                } else {
                  // 下发命令
                  this.issueControlCommand('SolderingSetTemp', this.presetTemp);
                  // 修改预设
                  let preset: ElectricSolderingIronPreset = this.ironPresets[this.selectPreset]
                  preset.setValue = this.presetTemp
                  let resultNum: number | undefined = await ElectricSolderingIronPresetModel.updatePreset(preset)
                }
                break
              case 2:
                if (this.selectPreset < 0) {
                  // 下发命令
                  this.issueControlCommand('TightenTorqueTarget', this.screwdriver.TightenTorqueTarget);
                  this.issueControlCommand('TighteRotationDirection', this.screwdriver.TighteRotationDirection);
                  this.issueControlCommand('TorqueHoldTime', this.screwdriver.TorqueHoldTime);
                  this.issueControlCommand('TorqueUpperLimit', this.screwdriver.TorqueUpperLimit);
                  this.issueControlCommand('TorqueLowerLimit', this.screwdriver.TorqueLowerLimit);
                  this.issueControlCommand('EnableFloatSlipDetection', this.screwdriver.EnableFloatSlipDetection);
                  this.issueControlCommand('FloatDetectionTurns', this.screwdriver.FloatDetectionTurns);
                  this.issueControlCommand('SlipDetectionTurns', this.screwdriver.SlipDetectionTurns);
                } else {
                  // 下发命令
                  this.issueControlCommand('TightenTorqueTarget', this.screwdriver.TightenTorqueTarget);
                  this.issueControlCommand('TighteRotationDirection', this.screwdriver.TighteRotationDirection);
                  this.issueControlCommand('TorqueHoldTime', this.screwdriver.TorqueHoldTime);
                  this.issueControlCommand('TorqueUpperLimit', this.screwdriver.TorqueUpperLimit);
                  this.issueControlCommand('TorqueLowerLimit', this.screwdriver.TorqueLowerLimit);
                  this.issueControlCommand('EnableFloatSlipDetection', this.screwdriver.EnableFloatSlipDetection);
                  this.issueControlCommand('FloatDetectionTurns', this.screwdriver.FloatDetectionTurns);
                  this.issueControlCommand('SlipDetectionTurns', this.screwdriver.SlipDetectionTurns);
                  // 修改预设
                  let preset: ElectricScrewdriverPreset = {
                    id: this.screwdriverPresets[this.selectPreset].id,
                    setName: this.screwdriverPresets[this.selectPreset].setName,
                    TighteRotationDirection: this.screwdriver.TighteRotationDirection,
                    TorqueHoldTime: this.screwdriver.TorqueHoldTime,
                    TightenTorqueTarget: this.screwdriver.TightenTorqueTarget,
                    TorqueUpperLimit: this.screwdriver.TorqueUpperLimit,
                    TorqueLowerLimit: this.screwdriver.TorqueLowerLimit,
                    EnableFloatSlipDetection: this.screwdriver.EnableFloatSlipDetection,
                    FloatDetectionTurns: this.screwdriver.FloatDetectionTurns,
                    SlipDetectionTurns: this.screwdriver.SlipDetectionTurns,
                    TightenTorqueMax: this.screwdriver.TightenTorqueMax,
                    TightenResult: this.screwdriver.TightenResult,
                  }
                  let resultNum: number | undefined = await ElectricScrewdriverPresetModel.updatePreset(preset)
                }
                break
            }
            router.back({
              url: 'pages/ProcessIndex',
              params: {
                auxiliaryOperationFlag: true
              }
            })
          })
        }
        Row().width('2.5%')
      }
      .width('100%')
      .height('10.7%')

      Row() {
        // 左侧设备图片与信息
        Column() {
          Row().height('8%')
          Image(this.deviceShows[this.deviceType]?.deviceImage!)
            .height($r('app.float.virtualSize_300'))
            .width($r('app.float.virtualSize_300'))
          //设备编号
          Row().height('4.25%')
          Row({space: 2}) {
            Circle()
              .width($r('app.float.virtualSize_5'))
              .height($r('app.float.virtualSize_5'))
              .fill($r('app.color.40FFFFFF'))
            Row() {
              Text('编号：')
                .fontSize($r('app.float.fontSize_16'))
                .fontColor($r('app.color.FFFFFF'))
                .fontWeight(FontWeight.Regular)
              Text('DF441AS114F5555')
                .fontSize($r('app.float.fontSize_16'))
                .fontColor($r('app.color.FFFFFF'))
                .fontWeight(FontWeight.Regular)
            }
            .height('100%')
          }
          .width('80%')
          .height('3%')
          //设备状态
          Row({space: 2}) {
            Circle()
              .width($r('app.float.virtualSize_5'))
              .height($r('app.float.virtualSize_5'))
              .fill($r('app.color.40FFFFFF'))
            Row() {
              Text('状态：')
                .fontSize($r('app.float.fontSize_16'))
                .fontColor($r('app.color.FFFFFF'))
                .fontWeight(FontWeight.Regular)
              Text(this.onlineStatus === 1 ? '在线' : '离线')
                .fontSize($r('app.float.fontSize_16'))
                .fontColor(this.onlineStatus === 1 ? $r('app.color.30D158') : $r('app.color.30FFFFFF'))
                .fontWeight(FontWeight.Regular)
            }
          }
          .width('80%')
          .height('3%')
          //设备计量有效期
          Row({space: 2}) {
            Circle()
              .width($r('app.float.virtualSize_5'))
              .height($r('app.float.virtualSize_5'))
              .fill($r('app.color.40FFFFFF'))
            Row() {
              Text('计量有效期：')
                .fontSize($r('app.float.fontSize_16'))
                .fontColor($r('app.color.FFFFFF'))
                .fontWeight(FontWeight.Regular)
              Text('2024/11/11~2025/11/11')
                .fontSize($r('app.float.fontSize_16'))
                .fontColor($r('app.color.FFFFFF'))
                .fontWeight(FontWeight.Regular)
            }
          }
          .width('80%')
          .height('3%')

          // 设备相关信息
          Column() {
            Row({space: 2}) {
              Circle()
                .width($r('app.float.virtualSize_5'))
                .height($r('app.float.virtualSize_5'))
                .fill($r('app.color.40FFFFFF'))
              Row() {
                Text('电压：')
                  .fontSize($r('app.float.fontSize_16'))
                  .fontColor($r('app.color.FFFFFF'))
                  .fontWeight(FontWeight.Regular)
                Text('24V DC；')
                  .fontSize($r('app.float.fontSize_16'))
                  .fontColor($r('app.color.FFFFFF'))
                  .fontWeight(FontWeight.Regular)
              }
              .alignItems(VerticalAlign.Bottom)
            }
            .width('80%')
            .height('2.5%')

            Row({space: 2}) {
              Row().width($r('app.float.virtualSize_5'))
              Row() {
                Text('电流：')
                  .fontSize($r('app.float.fontSize_16'))
                  .fontColor($r('app.color.FFFFFF'))
                  .fontWeight(FontWeight.Regular)
                Text('Max. 0.25A；')
                  .fontSize($r('app.float.fontSize_16'))
                  .fontColor($r('app.color.FFFFFF'))
                  .fontWeight(FontWeight.Regular)
              }
            }
            .width('80%')
            .height('2%')

            Row({space: 2}) {
              Row().width($r('app.float.virtualSize_5'))
              Row() {
                Text('功率：')
                  .fontSize($r('app.float.fontSize_16'))
                  .fontColor($r('app.color.FFFFFF'))
                  .fontWeight(FontWeight.Regular)
                Text('6.6W')
                  .fontSize($r('app.float.fontSize_16'))
                  .fontColor($r('app.color.FFFFFF'))
                  .fontWeight(FontWeight.Regular)
              }
            }
            .width('80%')
            .height('2%')
          }
        }
        .width('25%')
        .height('100%')

        Divider().vertical(true)
          .height('80%')
          .color($r('app.color.FFFFFF'))
          .opacity(0.15)

        //不同设备类型展示不同页面
        if (this.deviceType === 0) {
          //三色灯
          Column({space: 15}) {
            // 红灯
            Row() {
              Column() {
                Circle()
                  .width($r('app.float.virtualSize_40'))
                  .height($r('app.float.virtualSize_40'))
                  .fill($r('app.color.FF453A'))
                  .opacity(this.threeColourLight?.LedRed! === 1 ? 1 : 0.2)
                  .strokeWidth(this.threeColourLight?.LedRed! ? 20 : 0)
                  .stroke($r('app.color.FF453A'))
                  .strokeOpacity(this.threeColourLight?.LedRed! ? 0.3 : 1)

                Row().height('10%')
                Text('红灯')
                  .fontSize($r('app.float.fontSize_24'))
                  .fontColor(this.threeColourLight?.LedRed! === 1 ? $r('app.color.99000000') : $r('app.color.60FFFFFF'))
                  .fontWeight(FontWeight.Regular)
              }
            }
            .width('90%')
            .height('25%')
            .justifyContent(FlexAlign.Center)
            .borderRadius($r('app.float.virtualSize_16'))
            .backgroundColor(this.threeColourLight?.LedRed! === 1 ? $r('app.color.E5E5E5') : $r('app.color.10FFFFFF'))
            .onClick(()=>{
              this.issueControlCommand('LedRed', this.threeColourLight?.LedRed! === 1 ? 0 : 1)
              this.threeColourLight = {
                LedRed: this.threeColourLight?.LedRed! === 1 ? 0 : 1,
                LedOrange: this.threeColourLight?.LedOrange!,
                LedGreen: this.threeColourLight?.LedGreen!,
                Buzzer: this.threeColourLight?.Buzzer!,
                OpenStatus: this.threeColourLight?.OpenStatus!,
                OnlineStatus: this.threeColourLight?.OnlineStatus!
              }
            })

            // 黄灯
            Row() {
              Column() {
                Circle()
                  .width($r('app.float.virtualSize_40'))
                  .height($r('app.float.virtualSize_40'))
                  .fill($r('app.color.FFD60A'))
                  .opacity(this.threeColourLight?.LedOrange! === 1 ? 1 : 0.2)
                  .strokeWidth(this.threeColourLight?.LedOrange! ? 20 : 0)
                  .stroke($r('app.color.FFD60A'))
                  .strokeOpacity(this.threeColourLight?.LedOrange! ? 0.3 : 1)
                Row().height('10%')
                Text('黄灯')
                  .fontSize($r('app.float.fontSize_24'))
                  .fontColor(this.threeColourLight?.LedOrange! === 1 ? $r('app.color.99000000') : $r('app.color.60FFFFFF'))
                  .fontWeight(FontWeight.Regular)
              }
            }
            .width('90%')
            .height('25%')
            .justifyContent(FlexAlign.Center)
            .borderRadius($r('app.float.virtualSize_16'))
            .backgroundColor(this.threeColourLight?.LedOrange! === 1 ? $r('app.color.E5E5E5') : $r('app.color.10FFFFFF'))
            .onClick(()=>{
              this.issueControlCommand('LedOrange', this.threeColourLight?.LedOrange! === 1 ? 0 : 1)
              this.threeColourLight = {
                LedRed: this.threeColourLight?.LedRed!,
                LedOrange: this.threeColourLight?.LedOrange! === 1 ? 0 : 1,
                LedGreen: this.threeColourLight?.LedGreen!,
                Buzzer: this.threeColourLight?.Buzzer!,
                OpenStatus: this.threeColourLight?.OpenStatus!,
                OnlineStatus: this.threeColourLight?.OnlineStatus!
              }
            })

            // 绿灯
            Row() {
              Column() {
                Circle()
                  .width($r('app.float.virtualSize_40'))
                  .height($r('app.float.virtualSize_40'))
                  .fill($r('app.color.30D158'))
                  .opacity(this.threeColourLight?.LedGreen! === 1 ? 1 : 0.2)
                  .strokeWidth(this.threeColourLight?.LedGreen! ? 20 : 0)
                  .stroke($r('app.color.30D158'))
                  .strokeOpacity(this.threeColourLight?.LedGreen! ? 0.3 : 1)

                Row().height('10%')
                Text('绿灯')
                  .fontSize($r('app.float.fontSize_24'))
                  .fontColor(this.threeColourLight?.LedGreen! === 1 ? $r('app.color.99000000') : $r('app.color.60FFFFFF'))
                  .fontWeight(FontWeight.Regular)
              }
            }
            .width('90%')
            .height('25%')
            .justifyContent(FlexAlign.Center)
            .borderRadius($r('app.float.virtualSize_16'))
            .backgroundColor(this.threeColourLight?.LedGreen! === 1 ? $r('app.color.E5E5E5') : $r('app.color.10FFFFFF'))
            .onClick(()=>{
              this.issueControlCommand('LedGreen', this.threeColourLight?.LedGreen! === 1 ? 0 : 1)
              this.threeColourLight = {
                LedRed: this.threeColourLight?.LedRed!,
                LedOrange: this.threeColourLight?.LedOrange!,
                LedGreen: this.threeColourLight?.LedGreen! === 1 ? 0 : 1,
                Buzzer: this.threeColourLight?.Buzzer!,
                OpenStatus: this.threeColourLight?.OpenStatus!,
                OnlineStatus: this.threeColourLight?.OnlineStatus!
              }
            })
          }
          .width('50%')
          .height('100%')
          .justifyContent(FlexAlign.Center)

          Divider().vertical(true)
            .height('80%')
            .color($r('app.color.FFFFFF'))
            .opacity(0.15)

          Column() {
            Image(this.threeColourLight?.Buzzer! === 1 ? $r('app.media.device_buzzer_open') : $r('app.media.device_buzzer_off'))
              .width($r('app.float.virtualSize_380'))
              .height($r('app.float.virtualSize_380'))
              .borderRadius($r('app.float.virtualSize_16'))
              .onClick(()=>{
                this.issueControlCommand('Buzzer', this.threeColourLight?.Buzzer! === 1 ? 0 : 1)
                this.threeColourLight = {
                  LedRed: this.threeColourLight?.LedRed!,
                  LedOrange: this.threeColourLight?.LedOrange!,
                  LedGreen: this.threeColourLight?.LedGreen!,
                  Buzzer: this.threeColourLight?.Buzzer! === 1 ? 0 : 1,
                  OpenStatus: this.threeColourLight?.OpenStatus!,
                  OnlineStatus: this.threeColourLight?.OnlineStatus!
                }
              })
          }
          .width('25%')
          .height('100%')
          .justifyContent(FlexAlign.Center)
          .alignItems(HorizontalAlign.Center)
        } else if (this.deviceType === 1) {
          //电烙铁
          // 电烙铁预设
          Column() {
            Row() {
              Text('参数预设')
                .fontColor($r('app.color.FFFFFF'))
                .fontSize($r('app.float.fontSize_30'))
                .fontWeight(FontWeight.Medium)
                .opacity(0.9)
            }
            .height('12%')
            .justifyContent(FlexAlign.Center)

            List({space: 10}) {
              ForEach(this.ironPresets, (item: ElectricSolderingIronPreset, index: number) => {
                ListItem() {
                  Column({space: 1}) {
                    Text(item.setValue! + item.unitString!)
                      .fontColor($r('app.color.FFFFFF'))
                      .fontSize($r('app.float.fontSize_24'))
                      .fontWeight(FontWeight.Medium)
                    Text(item.setName)
                      .fontColor($r('app.color.FFFFFF'))
                      .fontSize($r('app.float.fontSize_16'))
                      .fontWeight(FontWeight.Lighter)
                  }
                  .width('80%')
                  .height('10%')
                  .justifyContent(FlexAlign.Center)
                  .borderRadius($r('app.float.virtualSize_16'))
                  .backgroundColor((this.operatePreset === index ? $r('app.color.20FFD60A') : (this.selectPreset === index ? $r('app.color.2064BB5C') : $r('app.color.20FFFFFF'))))
                  .borderWidth((this.operatePreset === index ? 1 : (this.selectPreset === index ? 1 : 0)))
                  .borderColor((this.operatePreset === index ? $r('app.color.FFD60A') : (this.selectPreset === index ? $r('app.color.64BB5C') : $r('app.color.FFFFFF'))))
                  .onClick(()=>{
                    if (this.selectPreset === index || this.operatePreset === index) {
                      this.selectPreset = -1
                      this.operatePreset = -1
                    } else {
                      this.selectPreset = index
                      this.operatePreset = -1
                      this.presetTemp = this.ironPresets[index]?.setValue!
                    }
                  })
                  .gesture(
                    LongPressGesture({ duration: 1000 })
                      // 长按动作一结束触发
                      .onActionEnd(() => {
                        this.operatePreset = index
                        this.selectPreset = index
                      })
                  )
                  .bindPopup(this.operatePreset === index, {
                    builder: this.popupBuilder,
                    placement: Placement.Bottom,
                    popupColor: $r('app.color.60000000'),
                    enableArrow: true,
                    autoCancel: true,
                    showInSubWindow: false,
                  })
                }
                .width('100%')
              })
            }
            .scrollBar(BarState.On)
            .alignListItem(ListItemAlign.Start)
          }
          .width('25%')
          .height('100%')
          Divider().vertical(true)
            .height('80%')
            .color($r('app.color.FFFFFF'))
            .opacity(0.15)
          //电烙铁温度设置
          Column() {
            Row() {
              Text('参数设置')
                .fontColor($r('app.color.FFFFFF'))
                .fontSize($r('app.float.fontSize_30'))
                .fontWeight(FontWeight.Medium)
                .opacity(0.9)
            }
            .height('12%')
            .width('90%')
            .justifyContent(FlexAlign.Start)

            Row() {
              Text(this.presetTemp + '℃')
                .fontSize($r('app.float.fontSize_70'))
                .fontColor($r('app.color.FFFFFF'))
                .fontWeight(FontWeight.Lighter)
            }
            .height('18.5%')

            Row() {
              Slider({ style: SliderStyle.OutSet, value: this.presetTemp, min: CommonConstants.ironTempMin, max: CommonConstants.ironTempMax, step: 1})
                // .blockStyle({ type: SliderBlockType.IMAGE, image: $r('app.media.device_controller_temp'), })
                .blockSize({width: $r('app.float.virtualSize_48'), height: $r('app.float.virtualSize_48')})
                .selectedColor($r('app.color.0A84FF'))
                .borderRadius($r('app.float.virtualSize_29'))
                .onChange((value: number) => {
                  this.presetTemp = value
                })
            }
            .width('90%')
            .height('12.5%')
            .backgroundColor($r('app.color.10FFFFFF'))
            .borderRadius($r('app.float.virtualSize_105'))
          }
          .width('50%')
          .height('100%')
        } else if (this.deviceType === 2) {
          //电动螺丝刀
          // 电动螺丝刀预设
          Column() {
            Row() {
              Text('参数预设')
                .fontColor($r('app.color.FFFFFF'))
                .fontSize($r('app.float.fontSize_30'))
                .fontWeight(FontWeight.Medium)
                .opacity(0.9)
            }
            .height('12%')
            .justifyContent(FlexAlign.Center)

            List({space: 10}) {
              ForEach(this.screwdriverPresets, (item: ElectricScrewdriverPreset, index: number) => {
                ListItem() {
                  Column({space: 1}) {
                    Row() {
                      Text(item.TighteRotationDirection! === 1 ? '顺时针' : '逆时针')
                        .fontColor($r('app.color.FFFFFF'))
                        .fontSize($r('app.float.fontSize_24'))
                        .fontWeight(FontWeight.Medium)
                      Blank()
                      Text(item.TightenTorqueTarget! + '')
                        .fontColor($r('app.color.FFFFFF'))
                        .fontSize($r('app.float.fontSize_16'))
                        .fontWeight(FontWeight.Regular)
                      Text('Kgf.cm')
                        .fontColor($r('app.color.60FFFFFF'))
                        .fontSize($r('app.float.fontSize_16'))
                        .fontWeight(FontWeight.Regular)
                    }
                    .width('100%')

                    Row() {
                      Text(item.setName)
                        .fontColor($r('app.color.FFFFFF'))
                        .fontSize($r('app.float.fontSize_16'))
                        .fontWeight(FontWeight.Lighter)
                      Blank()
                      Text(item.TorqueHoldTime! + '')
                        .fontColor($r('app.color.FFFFFF'))
                        .fontSize($r('app.float.fontSize_16'))
                        .fontWeight(FontWeight.Regular)
                      Text('ms')
                        .fontColor($r('app.color.60FFFFFF'))
                        .fontSize($r('app.float.fontSize_16'))
                        .fontWeight(FontWeight.Regular)
                    }
                    .width('100%')
                  }
                  .width('80%')
                  .height('10%')
                  .justifyContent(FlexAlign.Center)
                  .borderRadius($r('app.float.virtualSize_16'))
                  .backgroundColor((this.operatePreset === index ? $r('app.color.20FFD60A') : (this.selectPreset === index ? $r('app.color.2064BB5C') : $r('app.color.20FFFFFF'))))
                  .borderWidth((this.operatePreset === index ? 1 : (this.selectPreset === index ? 1 : 0)))
                  .borderColor((this.operatePreset === index ? $r('app.color.FFD60A') : (this.selectPreset === index ? $r('app.color.64BB5C') : $r('app.color.FFFFFF'))))
                  .onClick(()=>{
                    if (this.selectPreset === index || this.operatePreset === index) {
                      this.selectPreset = -1
                      this.operatePreset = -1
                    } else {
                      this.selectPreset = index
                      this.operatePreset = -1
                      this.screwdriver = this.screwdriverPresets[this.selectPreset]
                    }
                  })
                  .gesture(
                    LongPressGesture({ duration: 1000 })
                      // 长按动作一结束触发
                      .onActionEnd(() => {
                        this.operatePreset = index
                        this.selectPreset = index
                      })
                  )
                  .bindPopup(this.operatePreset === index, {
                    builder: this.popupBuilder,
                    placement: Placement.Bottom,
                    popupColor: $r('app.color.60000000'),
                    enableArrow: true,
                    autoCancel: true,
                    showInSubWindow: false,
                  })
                }
                .width('100%')
              })
            }
            .scrollBar(BarState.On)
            .alignListItem(ListItemAlign.Start)
          }
          .width('25%')
          .height('100%')
          Divider().vertical(true)
            .height('80%')
            .color($r('app.color.FFFFFF'))
            .opacity(0.15)
          // 电动螺丝刀参数设置
          Column() {
            Row() {
              Text('参数设置')
                .fontColor($r('app.color.FFFFFF'))
                .fontSize($r('app.float.fontSize_30'))
                .fontWeight(FontWeight.Medium)
                .opacity(0.9)
            }
            .height('12%')
            .width('90%')
            .justifyContent(FlexAlign.Start)

            Column() {
              Row() {
                Row() {
                  Row().width('2%')
                  Text('旋转方向')
                    .fontColor($r('app.color.FFFFFF'))
                    .fontSize($r('app.float.fontSize_16'))
                    .fontWeight(FontWeight.Regular)
                }
                .width('50%')
                .justifyContent(FlexAlign.Start)

                Row() {
                  Row().width('2%')
                  Text('保持时间(ms)')
                    .fontColor($r('app.color.FFFFFF'))
                    .fontSize($r('app.float.fontSize_16'))
                    .fontWeight(FontWeight.Regular)
                }
                .width('50%')
                .justifyContent(FlexAlign.Start)
              }
              .width('100%')

              Row() {
                Select([{value: '顺时针'}, {value: '逆时针'}])
                  .selected(this.screwdriver.TighteRotationDirection! ? this.screwdriver.TighteRotationDirection - 1 : 0)
                  .value(this.screwdriver.TighteRotationDirection! === 2 ? '逆时针' : '顺时针')
                  .font({ size: $r('app.float.fontSize_24'), weight: FontWeight.Medium})
                  .fontColor($r('app.color.FFFFFF'))
                  .borderRadius($r('app.float.virtualSize_16'))
                  .width('44%')
                  .height('100%')
                  .backgroundColor($r('app.color.20FFFFFF'))
                  .selectedOptionFontColor($r('app.color.30D158'))
                  .selectedOptionFont({size: $r('app.float.fontSize_24'), weight: FontWeight.Bold})
                  .optionFontColor($r('app.color.000000'))
                  .optionFont({size: $r('app.float.fontSize_24'), weight: FontWeight.Medium})
                  .menuAlign(MenuAlignType.START)
                  .onSelect((index: number) => {
                    this.screwdriver.TighteRotationDirection = index + 1
                  })

                Row().width('6%')

                AddSubtractComp({
                  inputNum: this.screwdriver.TorqueHoldTime,
                  obj: this.screwdriver,
                  editPropertyName: 'TorqueHoldTime',
                  lowerLimit: 0,
                })
                  .width('44%')
                  .height('100%')
              }
              .width('100%')
              .height('70%')
            }
            .height('12%')
            .width('90%')
            // 力矩和扭力偏差上限
            Column() {
              Row() {
                Row() {
                  Row().width('2%')
                  Text('目标扭力(Kgf.cm)')
                    .fontColor($r('app.color.FFFFFF'))
                    .fontSize($r('app.float.fontSize_16'))
                    .fontWeight(FontWeight.Regular)
                }
                .width('50%')
                .justifyContent(FlexAlign.Start)

                Row() {
                  Row().width('2%')
                  Text('扭力偏差上限(Kgf.cm)')
                    .fontColor($r('app.color.FFFFFF'))
                    .fontSize($r('app.float.fontSize_16'))
                    .fontWeight(FontWeight.Regular)
                }
                .width('50%')
                .justifyContent(FlexAlign.Start)
              }
              .width('100%')

              Row() {
                AddSubtractComp({
                  inputNum: this.screwdriver.TightenTorqueTarget,
                  obj: this.screwdriver,
                  editPropertyName: 'TightenTorqueTarget',
                  lowerLimit: 0,
                })
                  .width('44%')
                  .height('100%')

                Row().width('6%')

                AddSubtractComp({
                  inputNum: this.screwdriver.TorqueUpperLimit,
                  obj: this.screwdriver,
                  editPropertyName: 'TorqueUpperLimit',
                  lowerLimit: 0,
                })
                  .width('44%')
                  .height('100%')
              }
              .width('100%')
              .height('70%')
            }
            .height('12%')
            .width('90%')

            // 扭力偏差下限和开启浮高滑牙检测
            Column() {
              Row() {
                Row() {
                  Row().width('2%')
                  Text('扭力偏差上限(Kgf.cm)')
                    .fontColor($r('app.color.FFFFFF'))
                    .fontSize($r('app.float.fontSize_16'))
                    .fontWeight(FontWeight.Regular)
                }
                .width('50%')
                .justifyContent(FlexAlign.Start)

                Row() {
                  Row().width('2%')
                  Text('开启浮高滑牙检测')
                    .fontColor($r('app.color.FFFFFF'))
                    .fontSize($r('app.float.fontSize_16'))
                    .fontWeight(FontWeight.Regular)
                }
                .width('50%')
                .justifyContent(FlexAlign.Start)
              }
              .width('100%')

              Row() {
                AddSubtractComp({
                  inputNum: this.screwdriver.TorqueLowerLimit,
                  obj: this.screwdriver,
                  editPropertyName: 'TorqueLowerLimit',
                  lowerLimit: 0,
                })
                  .width('44%')
                  .height('100%')

                Row().width('6%')

                Row() {
                  Toggle({ type: ToggleType.Switch, isOn: false })
                    .height('100%')
                    .width('30%')
                    .selectedColor($r('app.color.30D158'))
                    .switchPointColor("#CAC8C4")
                    .onChange((isOn: boolean) => {
                      if (isOn) {
                        this.screwdriver.EnableFloatSlipDetection = 1
                      } else {
                        this.screwdriver.EnableFloatSlipDetection = 0
                      }
                    })
                }
                .width('44%')
                .height('100%')
                .justifyContent(FlexAlign.Start)
              }
              .width('100%')
              .height('70%')
            }
            .height('12%')
            .width('90%')

            // 浮高界定圈数和滑牙界定圈数
            Column() {
              Row() {
                Row() {
                  Row().width('2%')
                  Text('浮高界定圈数(r)')
                    .fontColor($r('app.color.FFFFFF'))
                    .fontSize($r('app.float.fontSize_16'))
                    .fontWeight(FontWeight.Regular)
                }
                .width('50%')
                .justifyContent(FlexAlign.Start)

                Row() {
                  Row().width('2%')
                  Text('滑牙界定圈数(r)')
                    .fontColor($r('app.color.FFFFFF'))
                    .fontSize($r('app.float.fontSize_16'))
                    .fontWeight(FontWeight.Regular)
                }
                .width('50%')
                .justifyContent(FlexAlign.Start)
              }
              .width('100%')

              Row() {
                AddSubtractComp({
                  inputNum: this.screwdriver.FloatDetectionTurns,
                  obj: this.screwdriver,
                  editPropertyName: 'FloatDetectionTurns',
                  lowerLimit: 0,
                })
                  .width('44%')
                  .height('100%')

                Row().width('6%')

                AddSubtractComp({
                  inputNum: this.screwdriver.SlipDetectionTurns,
                  obj: this.screwdriver,
                  editPropertyName: 'SlipDetectionTurns',
                  lowerLimit: 0,
                })
                  .width('44%')
                  .height('100%')
              }
              .width('100%')
              .height('70%')
            }
            .height('12%')
            .width('90%')
          }
          .width('50%')
          .height('100%')
          .justifyContent(FlexAlign.SpaceEvenly)
        }
      }
      .width('100%')
      .height('89.3%')
    }
    .width('100%')
    .height('100%')
    .backgroundColor($r('app.color.000000'))
    .onClick(()=>{
      this.selectPreset = -1
      this.operatePreset = -1
    })
  }

  // popup构造器定义弹框内容
  @Builder popupBuilder() {
    Column() {
      Row() {
        Text('重命名')
          .fontColor($r('app.color.0A84FF'))
          .fontSize($r('app.float.fontSize_24'))
          .fontWeight(FontWeight.Medium)
      }
      .width('100%')
      .height('50%')
      .justifyContent(FlexAlign.Center)
      .onClick(()=> {
        // 修改预设名称
        this.operatePreset = -1
        this.updatePresetNameController.open()
      })
      Divider().color($r('app.color.FFFFFF'))
        .width('100%')
        .opacity(0.15)
      Row() {
        Text('删除')
          .fontColor($r('app.color.FF453A'))
          .fontSize($r('app.float.fontSize_24'))
          .fontWeight(FontWeight.Medium)
      }
      .width('100%')
      .height('50%')
      .justifyContent(FlexAlign.Center)
      .onClick(async ()=>{
        // 删除预设
        switch (this.deviceType) {
          case 1:
            let preset: ElectricSolderingIronPreset = this.ironPresets[this.operatePreset]
            await ElectricSolderingIronPresetModel.deletePresetById(preset.id!)
            this.operatePreset = -1
            this.selectPreset = -1
            this.ironPresets = await ElectricSolderingIronPresetModel.getPresetList()
            break
          case 2:
            let screwdriverPreset: ElectricScrewdriverPreset = this.screwdriverPresets[this.operatePreset]
            let resultNum: number | undefined = await ElectricScrewdriverPresetModel.deletePresetById(screwdriverPreset.id!)
            this.operatePreset = -1
            this.selectPreset = -1
            this.ironPresets = await ElectricSolderingIronPresetModel.getPresetList()
            break
        }

      })
    }
    .width(px2vp(292))
    .height(px2vp(160))
  }

  private issueControlCommand(tag: string, value: number) {
    let item: MqttDataItem = {
      tag: tag,
      value: value
    };
    let mqttData: MqttCmdData = {
      w: [item]
    };
    MqttManager.publish(CommonConstants.mqttSubscribePublish, JSON.stringify(mqttData))
  }
}

// 修改预设名称弹窗
@CustomDialog
struct updatePresetNameDialog {

  // 若尝试在CustomDialog中传入多个其他的Controller，以实现在CustomDialog中打开另一个或另一些CustomDialog，那么此处需要将指向自己的controller放在最后
  controller?: CustomDialogController
  cancel?: () => void = () => {
  }
  confirm: () => void = () => {
  }
  @State presetName: string = ''
  @State info: string = ''
  @Link ironPresets: ElectricSolderingIronPreset[]
  selectPreset: number = 0

  aboutToAppear() {
    if (this.ironPresets && this.ironPresets[this.selectPreset]) {
      this.presetName = this.ironPresets[this.selectPreset]?.setName!
      this.info = this.ironPresets[this.selectPreset]?.setName! + '℃'
    }
  }

  build() {
    Column(){
      Text('保存预设')
        .textAlign(TextAlign.Center)
        .width('100%')
        .height('30%')
        .fontWeight(FontWeight.Medium)
        .fontSize($r('app.float.fontSize_12'))
        .fontColor($r('app.color.FFFFFF'))

      Row() {
        Text(this.info)
          .fontSize($r('app.float.fontSize_16'))
          .fontWeight(FontWeight.Regular)
          .fontColor($r('app.color.FFFFFF'))
          .maxLines(3)
      }
      .height('18.5%')
      .width('77.5%')
      .alignItems(VerticalAlign.Top)
      .justifyContent(FlexAlign.Start)

      TextInput({placeholder: '自定义1', text: this.presetName })
        .placeholderColor($r('app.color.30FFFFFF'))
        .placeholderFont({ size: $r('app.float.fontSize_16'), weight: FontWeight.Medium})
        .fontColor($r('app.color.FFFFFF'))
        .width('77.5%')
        .height('18%')
        .borderRadius($r('app.float.virtualSize_16'))
        .backgroundColor($r('app.color.000000'))
        .onChange((value: string) => {
          this.presetName = value
        })
      Row().height('13%')

      Divider().color($r('app.color.FFFFFF'))
        .width('100%')
        .opacity(0.15)

      Row(){
        Row() {
          Text('取消')
            .fontColor($r('app.color.60FFFFFF'))
            .fontSize($r('app.float.fontSize_16'))
            .fontWeight(FontWeight.Medium)
            .onClick(()=>{
              if (this.controller != undefined) {
                this.controller.close()
              }
            })
        }
        .width('50%')
        .height('100%')
        .justifyContent(FlexAlign.Center)
        Divider().vertical(true).color($r('app.color.FFFFFF'))
          .height('100%')
          .opacity(0.15)
        Row() {
          Text('确认')
            .fontColor($r('app.color.007AFF'))
            .fontSize($r('app.float.fontSize_16'))
            .fontWeight(FontWeight.Medium)
            .onClick(()=>{
              if (this.ironPresets && this.ironPresets[this.selectPreset]) {
                this.ironPresets[this.selectPreset].setName = this.presetName
              }
              this.confirm();
              if (this.controller != undefined) {
                this.controller.close()
              }
            })
        }
        .width('50%')
        .height('100%')
        .justifyContent(FlexAlign.Center)
      }
      .width('100%')
      .height('17.5%')
      .justifyContent(FlexAlign.Center)
    }
    .width('25%')
    .height('30%')
    .backgroundColor($r('app.color.2A2A2A'))
    .borderRadius($r('app.float.virtualSize_16'))
  }
}

class DeviceShow {
  deviceName?: string
  deviceImage?: Resource
}