import {LoginStatus} from '../viewmodel/process/EnumerationType'
import MqttManager from '../common/util/mqtt';
import CardReader from '../viewmodel/device/CardReader'
import { MqttClientOptions, MqttConnectOptions } from '@ohos/mqtt';
import CommonConstants from '../common/constants/CommonConstants';
import router from '@ohos.router';
@Entry
@Component
struct ProcessIndex {
  //0代表初始，1代表登陆成功，2代表正在登陆，3代表登陆失败
  @State LoginStatus: LoginStatus = LoginStatus.INITIAL
  @StorageProp('CardReader') cardReader: CardReader = {}
  @State isConnected: boolean = false
  private timerId: number = 0
  // 根据状态获取提示文字
  getStatusText(): string {
    switch (this.LoginStatus) {
      case LoginStatus.INITIAL:
        return "请使用工作卡贴近读卡器"
      case LoginStatus.SUCCESS:
        return "验证成功"
      case LoginStatus.LOGGING_IN:
        return "正在验证中..."
      case LoginStatus.FAILED:
        return "验证失败，请重试"
      default:
        return "请使用工作卡贴近读卡器"
    }
  }

  connectMQTT = async ()=> {
    console.info("sssssss12")

    const clientOptions: MqttClientOptions = {
      url: 'mqtt://192.168.1.3:1883',   // 替换实际IP
      clientId: `process_client_${Date.now()}`,
      persistenceType: 1,              // 使用英文逗号       // 建议开启自动重连
    };
    // MQTT连接配置
    const connectOptions: MqttConnectOptions = {
      cleanSession: true,
      connectTimeout: 30,
      keepAliveInterval: 60,
      userName: 'optional_username',
      password: 'optional_password'
    };
    try {
      if (this.isConnected) {
        return;
      }
      console.info("sssssss123")
      MqttManager.init(clientOptions);
      this.isConnected = await MqttManager.connect(connectOptions);
      if (this.isConnected ) {
        console.info('hhtest', 'MQTT connected successfully');
        await MqttManager.subscribe(CommonConstants.mqttSubscribeTopic1);
     //   await MqttManager.subscribe(CommonConstants.mqttSubscribeTopic3);
        if (CommonConstants.mqttSubscribeTopic1 != CommonConstants.mqttSubscribeTopic2) {
          await MqttManager.subscribe(CommonConstants.mqttSubscribeTopic2);
        }
      } else {
        console.error('hhtest', 'MQTT connection failed');
      }
    } catch (err) {
      console.error('hhtest', `MQTT error: ${JSON.stringify(err)}`);
    }
  }
  private delay(ms: number): Promise<void> {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }

  timerIds(): void {
    console.info("sssssss121")
    this.timerId = setInterval(async (): Promise<void> => {  // 添加 async
      const rfidCard = (this.cardReader.RfidCardNum1 || '') + (this.cardReader.RfidCardNum2 || '');
      if (rfidCard === '') {
        this.LoginStatus = LoginStatus.INITIAL;
        return;
      }
      this.LoginStatus = LoginStatus.LOGGING_IN;

      // 使用 await
      await this.delay(1500);

      if (rfidCard === '3b530bb') {
        this.LoginStatus = LoginStatus.SUCCESS;
        // 等待1秒显示成功状态
        await this.delay(1000);
        this.navigateToTarget();
      } else {
        this.LoginStatus = LoginStatus.FAILED;
        // 等待1秒显示失败状态
        await this.delay(1000);
        this.LoginStatus = LoginStatus.INITIAL;
      }
    }, 3000);
  }

  private navigateToTarget(): void {
    clearInterval(this.timerId);
    this.timerId = 0;


    router.pushUrl({
      url: 'pages/ProcessIndex'
    }).then(() => {
      console.log('跳转成功');
    }).catch((error: Error) => {
      console.error('跳转失败:', error);
    });
  }

  onPageShow(): void {
    this.LoginStatus = LoginStatus.INITIAL
    this.timerIds()
  }
aboutToAppear(): void {
  this.connectMQTT()
}
  getStatusImage(): Resource {
    switch (this.LoginStatus) {
      case LoginStatus.INITIAL:
        return $r("app.media.id_card_white")
      case LoginStatus.SUCCESS:
        return $r("app.media.id_card_green")
      case LoginStatus.FAILED:
        return $r("app.media.id_card_red") // 需要你有对应的红色图片
      case LoginStatus.LOGGING_IN:
        return $r("app.media.id_card_yellow") // 需要你有对应的黄色图片
      default:
        return $r("app.media.id_card_green")
    }
  }
  // 根据登录状态获取边框颜色
  getBorderColor(): string {
    switch (this.LoginStatus) {
      case LoginStatus.INITIAL:
        return '#FFFFFF' // 白色 - 初始状态
      case LoginStatus.SUCCESS:
        return '#7ed321' // 绿色 - 登录成功
      case LoginStatus.LOGGING_IN:
        return '#f8e71c' // 黄色 - 正在登录
      case LoginStatus.FAILED:
        return '#f81c1c' // 红色 - 登录失败
      default:
        return '#FFFFFF' // 默认白色
    }
  }
  build() {
    Column(){
      Column(){
        Text("操作人员身份验证")
          .fontSize($r('app.float.fontSize_60'))
          .fontColor($r('app.color.FFFFFF'))
          .fontWeight(FontWeight.Bolder)
        Text("请完成身份验证继续")
          .fontSize($r('app.float.fontSize_24'))
          .fontColor($r('app.color.FFFFFF'))
          .margin({ top:'1%'})
          .fontWeight(FontWeight.Lighter)
      }.height('30%')
      .justifyContent(FlexAlign.Center)
      Column(){
        Image(this.getStatusImage())
          .width($r('app.float.virtualSize_156'))
          .height($r('app.float.virtualSize_156'))
        Text(this.getStatusText())
          .fontSize($r('app.float.fontSize_30'))
          .fontColor($r('app.color.FFFFFF'))
          .fontWeight(FontWeight.Regular)
          .margin({ top:'1%'})
      }.height('40%')
      .width('30%')
      .borderWidth('4px')
      .justifyContent(FlexAlign.Center)
      .borderRadius($r('app.float.fontSize_16'))
      //green == #7ed321,yellow ==#f8e71c ,red=#f81c1c
      .borderColor(this.getBorderColor())
      Column(){
        Row(){
          Image($r('app.media.tips'))
            .width($r('app.float.virtualSize_32'))
            .height($r('app.float.virtualSize_32'))
          Text("操作指引")
            .fontSize($r('app.float.fontSize_30'))
            .fontColor($r('app.color.FFFFFF'))
            .fontWeight(FontWeight.Bold)
            .margin({ top:'1%',left:'2%'})
        }
        .alignItems(VerticalAlign.Center)
        .height('20%')
        Row(){
          Image($r("app.media.check_one"))
            .width($r('app.float.virtualSize_24'))
            .height($r('app.float.virtualSize_24'))
          Text("将你的员工卡贴近读卡器感应区")
            .fontSize($r('app.float.fontSize_24'))
            .fontColor($r('app.color.FFFFFF'))
            .fontWeight(FontWeight.Lighter)
            .margin({ top:'1%',left:'2%'})
        }
        .alignItems(VerticalAlign.Center)
        Row(){
          Image($r("app.media.check_one"))
            .width($r('app.float.virtualSize_24'))
            .height($r('app.float.virtualSize_24'))
          Text("验证成功后进入产品扫码界面")
            .fontSize($r('app.float.fontSize_24'))
            .fontColor($r('app.color.FFFFFF'))
            .fontWeight(FontWeight.Lighter)
            .margin({ top:'1%',left:'2%'})
        }
        .alignItems(VerticalAlign.Center)
      }.height('35%')
      .width('30%')
      .margin({top:'5%'})
      .alignItems(HorizontalAlign.Start)
    }
    .backgroundColor($r('app.color.000000'))
    .width('100%')
    .height('100%')
  }
}


