// 工位的设备列表
import router from '@ohos.router'
import EquipmentRequest from '../utils/EquipmentRequest'


export class HardwareModel {
  name?: string
  text?: string
  type?: Resource
  open?: Resource
  colse?: Resource
  select?: boolean
  temp?: number
  manufacturer?: string //: "厂家",
  brand?: string //"品牌或型号，比如JBC",
  deviceName?: string //"设备自定义名称或资产编号",
  deviceType?: string // "类别，比如电络铁",
  deviceNo?: string // "设备编号，唯一号",
  devicePic?: string // "图片",
  state?: number //"状态：0正常，-1：离线，1故障",
  workshop?: string //"产线",
  station?: string //"工站/工位",
  devicePosition?: string // "空间位置，目前暂时不用",
  data?: HardwareModel[]
  enable?: boolean | string //是否启用了设备
  imageSource?: ResourceStr
  length?: string
  height?: string
  value?: string //硬件设备的一个数据
}

interface ImageDictModel {
  sansedeng: ResourceStr
  saomaqiang: ResourceStr
  diannengbiao: ResourceStr
  multimeter: ResourceStr
  dukaqi: ResourceStr
  chengkongdianyuan: ResourceStr
  shukongdian: ResourceStr
  diandongluosidao: ResourceStr
  zhaomingdeng: ResourceStr
}


@Entry
@Component
struct StationDevicesPage {
  //注释掉的是假数据，实际更具请求硬件获取
  @State private items: Array<HardwareModel> = [
  //   {
  //   name: '三色灯',
  //   text: '装配工位001',
  //   type: $r('app.media.sansedeng'),
  //   open: $r('app.media.open'),
  //   colse: $r('app.media.colse'),
  //   select: true,
  //   temp: 1,
  //   deviceName: "三色灯"
  // }
  ]
  imageDict: ImageDictModel = {
    sansedeng: $r("app.media.sansedeng"),
    saomaqiang: $r('app.media.saomaqiang'),
    diannengbiao: $r('app.media.diannengbiao'),
    multimeter: $r('app.media.multimeter'),
    dukaqi: $r('app.media.dukaqi'),
    chengkongdianyuan: $r('app.media.chengkongdianyuan'),
    shukongdian: $r('app.media.shukongdian'),
    diandongluosidao: $r('app.media.diandongluosidao'),
    zhaomingdeng: $r('app.media.zhaomingdeng')
  }
  scroller: Scroller = new Scroller()
  getDeviceList = async () => {
    console.log("==========")
    let res: HardwareModel = await EquipmentRequest.get('/api/v1/device/list') as HardwareModel

    let deviceValues: HardwareModel = await EquipmentRequest.get('/api/v1/station/data') as HardwareModel

    let ybkc: HardwareModel = new HardwareModel()
    let gaoduchi: HardwareModel = new HardwareModel()
    deviceValues?.data?.forEach((item) => {
      if (item.deviceNo == "1106-50100") {
        ybkc.value = item.length
      }
      if (item.deviceNo == "1150-300C00") {
        gaoduchi.value = item.height
      }
    })

    console.log("==========", JSON.stringify(res), JSON.stringify(deviceValues))
    let array: HardwareModel[] | undefined = res?.data?.filter((device) => {
      device.imageSource = Reflect.get(this.imageDict, device.devicePic!)
      return device.enable! === true || device.enable! === "true"
    })
    array?.forEach((item) => {
      if (item.deviceNo == "1106-50100") {
        item.value = ybkc.value
      }
      if (item.deviceNo == "1150-300C00") {
        item.value = gaoduchi.value
      }
    })
    this.items = array ?? []
  }
  // 点击选择了设备之后
  @State currentDevice: HardwareModel = {}
  openDeviceOperationDialog = (d: HardwareModel) => {
    this.currentDevice = d
    if (d.deviceName == "三色灯") {
      this.lightDController.open()
    }
    else if (d.deviceNo == "EC2A-IM24R00") {
      this.theOtherController.open()
    }
  }
  // 三色灯dialoag
  lightDController = new CustomDialogController({
    builder: ThreeColorsLight({
      device: this.currentDevice
    }),
    alignment: DialogAlignment.Center,
    customStyle: true,
  })
  // 另一个灯的
  theOtherController = new CustomDialogController({
    builder: TheOtherLight({
      device: this.currentDevice
    }),
    alignment: DialogAlignment.Center,
    customStyle: true,
  })

  aboutToAppear(): void {
    this.getDeviceList()
  }

  build() {

    Column() {
      Row() {
        Image($r('app.media.back_white'))
          .height(px2vp(48))
          .width(px2vp(48))
          .onClick(async () => {
            router.back()
          })

        Text("刷新")
          .fontColor('#FFFFFF')
          .fontWeight(FontWeight.Medium)
          .fontSize(24)
          .margin({ left: 20 })
          .onClick(() => {
            this.getDeviceList()
          })

      }
      .width('100%')
      .height('8%')
      .alignItems(VerticalAlign.Center)
      .justifyContent(FlexAlign.Start)

      Column() {

        //  Scroll(this.scroller){
        Grid(this.scroller) {
          ForEach(this.items, (item: HardwareModel, index) => {
            GridItem() {

              Row() {
                Column() {
                  Text(item.deviceName)
                    .fontColor('#FFFFFF')
                    .fontWeight(FontWeight.Medium)
                    .fontSize(24)
                  Text(item.deviceNo)
                    .fontColor('#FFFFFF')
                    .opacity(0.6)
                    .fontWeight(FontWeight.Regular)
                    .fontSize(20)
                  Text(item.value)
                    .fontColor('#ffffff')
                    .opacity(0.8)
                    .fontWeight(FontWeight.Regular)
                    .fontSize(18)
                  Row() {
                    Image(item.imageSource)
                      .width(px2vp(120))
                      .height(px2vp(120))

                  }.height('50%')
                  .width('100%')
                  .padding({ left: 10 })
                }
                .width('100%')
                .padding(10)
                .borderRadius(10)
                .alignItems(HorizontalAlign.Start)
                .height('100%')
              }
              .width('100%')
              .height('30%')
              .padding({ left: 10 })
              .borderRadius(10)
              .backgroundColor('#66ffffff')
              .onClick(() => {
                this.openDeviceOperationDialog(item)
              })
            }
          })
        }
        .columnsTemplate('1fr 1fr 1fr 1fr 1fr 1fr')
        .columnsGap(10)
        .rowsGap(10)
        .width('100%')
        .height('100%')
        .editMode(true) //设置Grid是否进入编辑模式，进入编辑模式可以拖拽Grid组件内部GridItem
        .supportAnimation(true) //设置Grid是否开启拖拽补位动画
        .height('80%')
        .width('100%')
        .padding({ top: 10 })

      }
    }
    .backgroundImage($r('app.media.zhihuigc'))
    .backgroundImageSize({ width: '100%', height: '100%' })
    .width('100%')
    .height('100%')
    .padding(20)

  }
}


@Extend(Button)
function DeviceBtnS(color: ResourceColor) {
  .fontColor(Color.White).width(70).height(30).backgroundColor(color)

}


// 三色灯
interface SSDModel {
  uiType: "Text" | "Button",
  textValue: string,
  key: string
  value: string
  btnColor: ResourceColor
}

interface SSDParamsData {
  lighting?: string
  buzzer?: string
  flash?: string
  outputs?: string
}

interface SSDParams {
  deviceNo: string
  data: SSDParamsData
}

@CustomDialog
struct ThreeColorsLight {
  controller: CustomDialogController
  @Prop device: HardwareModel
  @State operations: SSDModel[][] = [
    [{
      uiType: 'Text',
      textValue: "亮灯",
      key: "lighting",
      value: "todo",
      btnColor: $r("app.color.red_100")
    },
      {
        uiType: 'Button',
        textValue: "红灯",
        key: "lighting",
        value: "red",
        btnColor: $r("app.color.red_100")
      },
      {
        uiType: 'Button',
        textValue: "黄灯",
        key: "lighting",
        value: "yellow",
        btnColor: $r("app.color.yellow_1")
      },
      {
        uiType: 'Button',
        textValue: "绿灯",
        key: "lighting",
        value: "green",
        btnColor: $r("app.color.green_100")
      },
      {
        uiType: 'Button',
        textValue: "关闭",
        key: "lighting",
        value: "off",
        btnColor: $r("app.color.gray_6666")
      },
    ],
    [{
      uiType: 'Text',
      textValue: "蜂鸣",
      key: "buzzer",
      value: "todo",
      btnColor: $r("app.color.red_100")
    },
      {
        uiType: 'Button',
        textValue: "大声",
        key: "buzzer",
        value: "loud",
        btnColor: $r("app.color.red_100")
      },
      {
        uiType: 'Button',
        textValue: "小声",
        key: "buzzer",
        value: "low",
        btnColor: $r("app.color.green_100")
      },
      {
        uiType: 'Button',
        textValue: "关闭",
        key: "buzzer",
        value: "off",
        btnColor: $r("app.color.gray_6666")
      },
    ],


    [{
      uiType: 'Text',
      textValue: "闪光",
      key: "flash",
      value: "todo",
      btnColor: $r("app.color.red_100")
    },
      {
        uiType: 'Button',
        textValue: "闪光快",
        key: "flash",
        value: "fast",
        btnColor: $r("app.color.red_100")
      },
      {
        uiType: 'Button',
        textValue: "闪光中",
        key: "flash",
        value: "middle",
        btnColor: $r("app.color.yellow_1")
      },
      {
        uiType: 'Button',
        textValue: "闪光慢",
        key: "flash",
        value: "slow",
        btnColor: $r("app.color.green_100")
      },
      {
        uiType: 'Button',
        textValue: "关闭",
        key: "flash",
        value: "off",
        btnColor: $r("app.color.gray_6666")
      },
    ],
  ]
  toOperation = (m: SSDModel) => {
    console.log("toOperation", JSON.stringify(m))
    let data: SSDParamsData = {
      lighting: '',
      buzzer: '',
      flash: ''
    }

    Reflect.set(data, m.key, m.value)


    console.log("toOperation", JSON.stringify(data))

    EquipmentRequest.post("/api/v1/device/setup", {
      deviceNo: this.device.deviceNo ?? "",
      data: data
    } as SSDParams)

  }

  build() {
    Column() {

      ForEach(this.operations, (ops: SSDModel[], index) => {
        ListItem() {
          Row({ space: 10 }) {
            ForEach(ops, (op: SSDModel) => {
              if (op.uiType === "Text") {
                Text(op.textValue)
              }
              else {
                Button({ type: ButtonType.Capsule }) {
                  Text(op.textValue)
                }.DeviceBtnS(op.btnColor)
                .onClick(() => {
                  this.toOperation(op)
                })
              }
            })

          }
        }
      })


    }
    .justifyContent(FlexAlign.SpaceEvenly)
    .alignItems(HorizontalAlign.Start)
    .padding({ left: 15 })
    .width(400)
    .height(240)
    .backgroundColor(Color.White)
    .borderRadius(10)

  }
}

@CustomDialog
struct TheOtherLight {
  controller: CustomDialogController
  @Prop device: HardwareModel
  @State operations: SSDModel[][] = [
    [
      {
        uiType: 'Button',
        textValue: "红灯",
        key: "outputs",
        value: "4",
        btnColor: $r("app.color.red_100")
      },
      {
        uiType: 'Button',
        textValue: "黄灯",
        key: "outputs",
        value: "7",
        btnColor: $r("app.color.yellow_1")
      },
      {
        uiType: 'Button',
        textValue: "绿灯",
        key: "outputs",
        value: "1",
        btnColor: $r("app.color.green_100")
      },
      {
        uiType: 'Button',
        textValue: "关闭",
        key: "outputs",
        value: "0",
        btnColor: $r("app.color.gray_6666")
      },
    ],
  ]
  toOperation = (m: SSDModel) => {

    let data: SSDParamsData = {
      outputs: '',
    }

    Reflect.set(data, m.key, m.value)

    EquipmentRequest.post("/api/v1/device/setup", {
      deviceNo: this.device.deviceNo ?? "",
      data: data
    } as SSDParams)

  }

  build() {
    Column() {

      ForEach(this.operations, (ops: SSDModel[], index) => {
        ListItem() {
          Row({ space: 10 }) {
            ForEach(ops, (op: SSDModel) => {
              if (op.uiType === "Text") {
                Text(op.textValue)
              }
              else {
                Button({ type: ButtonType.Capsule }) {
                  Text(op.textValue)
                }.DeviceBtnS(op.btnColor)
                .onClick(() => {
                  this.toOperation(op)
                })
              }
            })

          }
        }
      })


    }
    .justifyContent(FlexAlign.SpaceEvenly)
    .alignItems(HorizontalAlign.Start)
    .padding({ left: 15 })
    .width(400)
    .height(140)
    .backgroundColor(Color.White)
    .borderRadius(10)

  }
}


