/*
 * 入库台料口操作
 * */
import MqttManager from '../common/util/mqtt';
import {MQTTPublishData} from '../common/util/mqtt';
import promptAction from '@ohos.promptAction';
import { ConfirmDialog } from './ConfirmDialog';
import { ConfirmDialogParams } from '../viewmodel/ConfirmDialogParam';
import ProcessRequest from '../common/util/request/ProcessRequest';
import RequestParamModel from '../viewmodel/RequestParamModel';
import MaterialInfo from '../viewmodel/MaterialInfo';

@CustomDialog
export struct InAndOutBoundDialog {
  @State materialNum: number=0
  @State scanMaterialList: MaterialInfo[] = []
  controller: CustomDialogController
  onConfirm: () => void = () => {}

  build() {
    Column() {
      InBoundView({
        materialNum:this.materialNum,
        boxMaterials:this.scanMaterialList
      }).height('93%')
      Column() {
        Divider()
          .vertical(false)
          .strokeWidth(1)
          .color($r('app.color.15FFFFFF'))
        Row() {
          Text('关闭')
            .fontColor($r('app.color.60FFFFFF'))
            .fontSize($r('app.float.fontSize_30'))
        }
        .justifyContent(FlexAlign.Center)
        .alignItems(VerticalAlign.Center)
        .width('100%')
        .height('100%')
        .onClick(() => this.controller.close())
      }
      .width('100%')
      .height('7%')
    }
    .height('80%')
    .width('30%')
    .backgroundColor($r('app.color.2A2A2A'))
    .justifyContent(FlexAlign.End)
    .borderRadius(16)
  }
}


@Component
export struct InBoundView {
  //右下角抽屉日志
  @Prop messages: string[] = []
  //物料数量
  @Link materialNum:number
  //伸出按钮缩放
  @State putOutButtonClick :number = 1
  //缩回按钮缩放
  @State putInButtonClick :number = 1
  //入库按钮缩放
  @State InboundButtonClick :number = 1
  //入库料箱物料表
  @Link private boxMaterials: Array<MaterialInfo>
  //弹窗提示内容
  @State reminds:string = ''
  //全局变量 料箱重量
  @StorageLink('materialBoxWeight') materialBoxWeight: number =0;
  //全局变量 抽屉状态
  @StorageLink('drawerPositionStatus') drawerPositionStatus: number=1 ;
  //全局变量 抽屉内料箱ID
  @StorageLink('materialBoxInRfid') materialBoxInRfid: string = '';

  commonDialogController: CustomDialogController | null = null;
  private showConfirmDialog(params: ConfirmDialogParams) {
    if (this.commonDialogController) {
      this.commonDialogController.close()
    }

    this.commonDialogController = new CustomDialogController({
      builder: ConfirmDialog({
        title: params.title || '提示',
        message: params.message,
        onConfirm: params.onConfirm
      }),
      cancel: () => console.log('用户取消操作'),
      customStyle: true,
      autoCancel:false,
      maskColor: 'rgba(0,0,0,0.6)'
    });

    this.commonDialogController.open();
  }
  //入库命令
  Warehousing = async () => {
    let res: MaterialInfo[] = await ProcessRequest.post("/api/v1/wmsOrder/inBox", {
       houseNo:'1',
      stanCode:'GW0001',
      vehicleCode:this.materialBoxInRfid,
      detailsList: this.boxMaterials
    } as RequestParamModel)
    console.log('testTag', 'aaaaaaaa1' + JSON.stringify(res));
    this.boxMaterials = []
    this.materialNum = 0 ;
    promptAction.showToast({
      message: '请求成功，业务处理中。。。',
      duration: 2000,
      bottom: 150
    });

  }

  //抽屉推出
  pushOut =()=>{
    const drawerCommand: MQTTPublishData = {
      w: [
        {
          tag: "Station1Set",
          value: 0
        }
      ]
    };
    MqttManager.publish('station100/cmd/devices', drawerCommand, 1, true);
  }

  //抽屉伸入
  pushIn =()=>{
    const drawerCommand: MQTTPublishData = {
      w: [
        {
          tag: "Station1Set",
          value: 1
        }
      ]
    };
    MqttManager.publish('station100/cmd/devices', drawerCommand, 1, true);
  }

  build() {
    Column() {
      Text('出入库料口操作')
        .fontColor($r('app.color.FFFFFF'))
        .fontSize($r('app.float.fontSize_38'))
        .margin({ top: '3%' })
      Column() {
        Stack() {
          Image(
            this.drawerPositionStatus === 1
              ? (this.materialBoxWeight >0 ? $r('app.media.drawer_in_box') : $r('app.media.drawer_in_no_box'))
              : (this.materialBoxWeight >0 ? $r('app.media.drawer_out_box') : $r('app.media.drawer_out_no_box'))
          )// 替换为您的电梯图片资源
            .width('100%')
            .height('100%')
            .borderRadius($r('app.float.virtualSize_16'))
            .objectFit(ImageFit.Fill)
          // 文字信息层（左下角）
          Column() {
            Row() {
              Image($r('app.media.material_weight'))
                .width('5%')
                .height('30%')
                .fillColor($r('app.color.30D158'))
              Text(String(this.materialBoxWeight)+"kg")
                .margin({ left: 10 })
                .fontSize($r('app.float.fontSize_38'))
                .fontColor($r('app.color.30D158')) // 绿色文字
            }

            Row() {
              Image($r('app.media.material_rfid'))
                .width('5%')
                .height('30%')
                .fillColor($r('app.color.30D158'))

              Text(this.materialBoxInRfid)
                .margin({ left: 10 })
                .fontSize($r('app.float.fontSize_38'))
                .fontColor($r('app.color.30D158')) // 绿色文字
            }
          }.height('19%').alignItems(HorizontalAlign.Start).justifyContent(FlexAlign.SpaceEvenly)
          .position({ x: '3%', y: '78%' })

          // 右上角物料信息
          Row() {
            Text(`物料:${this.materialNum}`)
              .fontSize(18)
              .fontColor($r('app.color.0A84FF'))// 使用图片中的蓝色
              .fontWeight(FontWeight.Medium)
          }
          .justifyContent(FlexAlign.Center)
          .backdropBlur(5) // 关键：背景模糊效果（模拟图片中的隐约线条）
          .backgroundColor($r('app.color.40000000')) // 10%透明白底
          .borderRadius($r('app.float.virtualSize_16')) // 圆角大小根据图片调整
          .width('20%') // 自适应文字宽度
          .height('10%') // 固定高度
          .position({ x: '78%', y: '2%' })

          // 右侧纵向时间信息
          Column({ space: 5 }) {
            ForEach(this.messages, (item: string) => {
              Text(item)// .fontColor($r('app.color.0A84FF'))
                // .fontSize($r('app.float.fontSize_16'))
                .fontSize($r('app.float.fontSize_12'))
                .fontColor($r('app.color.0A84FF')) // 图片中的蓝色
            })
          }
          .position({ x: '68%', y: '80%' })
          .alignItems(HorizontalAlign.End)
        }
        .width('95%')
        .height('100%')
      }
      .height('67%')
      .width('100%')
      .margin({ top: '3%' })

      //.justifyContent(FlexAlign.SpaceAround)
      Row() {
        Button({ type: ButtonType.Normal }) {
          Text("伸出")
            .fontSize($r('app.float.fontSize_30'))
            .fontColor($r('app.color.0A84FF'))
        }
        .width('48%')
        .height('100%')
        .backgroundColor($r('app.color.20FFFFFF'))
        .borderRadius($r('app.float.virtualSize_16'))
        .scale({ x: this.putOutButtonClick, y: this.putOutButtonClick })
        .animation({
          duration: 200,
          curve: Curve.Linear
        })
        .onClick(() => {
          this.putOutButtonClick = 0.9; // 点击时缩小
          setTimeout(() => {
            this.putOutButtonClick = 1; // 0.2秒后恢复
            this.showConfirmDialog({
              title: '抽屉伸出',
              message: `确定要抽屉伸出吗？`,
              onConfirm: ()=> {
                this.pushOut();
              }
            });
          }, 200);
        })

        Button({ type: ButtonType.Normal }) {
          Text("缩回")
            .fontSize($r('app.float.fontSize_30'))
            .fontColor($r('app.color.0A84FF'))
        }
        .width('48%')
        .margin({left:'4%'})
        .height('100%')
        .backgroundColor($r('app.color.20FFFFFF'))
        .borderRadius($r('app.float.virtualSize_16'))
        .scale({ x: this.putInButtonClick, y: this.putInButtonClick })
        .animation({
          duration: 200,
          curve: Curve.Linear
        })
        .onClick(() => {
          this.putInButtonClick = 0.9; // 点击时缩小
          setTimeout(() => {
            this.putInButtonClick = 1; // 0.2秒后恢复
            this.showConfirmDialog({
              title: '抽屉缩回',
              message: `确定要抽屉缩回吗？`,
              onConfirm: () => {
                this.pushIn();
              }
            })
          }, 200);
        })
      }
      .width('95%')
      .height('6%')
      .margin({ top: '2%' })
      .justifyContent(FlexAlign.Start)
      .alignItems(VerticalAlign.Top)

      Button({ type: ButtonType.Normal }) {
        Text("入库")
          .fontSize($r('app.float.fontSize_30'))
          .fontColor($r('app.color.0A84FF'))
      }
      .margin({ top: '9%' })
      .width('95%')
      .height('6%')
      .backgroundColor($r('app.color.20FFFFFF'))
      .borderRadius($r('app.float.virtualSize_16'))
      .scale({ x: this.InboundButtonClick, y: this.InboundButtonClick })
      .animation({
        duration: 200,
        curve: Curve.Linear
      })
      .onClick(() => {
        this.InboundButtonClick = 0.9; // 点击时缩小
        setTimeout(() => {
          this.InboundButtonClick = 1; // 0.2秒后恢复
        }, 200);
        if(this.drawerPositionStatus == 0)
        {
          promptAction.showToast({
            message: '抽屉未缩回',
            duration: 2000
          });
          return
        }

        if(this.materialBoxWeight == 0)
        {
          promptAction.showToast({
            message: '未放入料箱',
            duration: 2000
          });
          return
        }

        this.showConfirmDialog({
          title: '入库确认',
          message: `确定要${this.materialBoxInRfid}料箱入库吗？`,
          onConfirm: () => {
            this.Warehousing();
          }
        })
      })
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.Start)
  }
}





