//设备点检
import ProcessRequest from '../common/util/request/ProcessRequest'
import DeviceInfo from '../viewmodel/DeviceInfo'
import RequestParamModel from '../viewmodel/RequestParamModel'
import TimeUtil from "../common/util/TimeUtil"
import PageInfo from '../viewmodel/PageInfo'

//todo 需要后端接口
@CustomDialog
export struct EquipmentInspectionDialog {
  private scrollerDevice: Scroller = new Scroller()
  //查找设备编码
  @State queryDeviceNo:string = ''
  //当前日期
  @State currentDate: string = ''
  //设备列表
  @State devicesList: DeviceInfo[] = [
  ];
  //选中设备索引
  @State selectDeviceIndex:number=-1
  controller: CustomDialogController
  onConfirm: () => void = () => {}

  onQueryDeviceCode = async ()=> {
    let res = await ProcessRequest.post('/api/v1/device/page', {
      deviceNo: this.queryDeviceNo
    } as RequestParamModel) as PageInfo;
    this.devicesList = res.records as DeviceInfo[] || []
  }

  //当前日期
  updateCurrentDate() {
    const now = new Date()
    const year = now.getFullYear()
    const month = (now.getMonth() + 1).toString().padStart(2, '0')
    const day = now.getDate().toString().padStart(2, '0')
    this.currentDate = `${year}/${month}/${day}`
  }

  //对比当前日期和有效期
  private compareDates(currentDate: string, targetDate: string): number {
    if (!targetDate) return -1; // 无效日期视为已过期
    const normalizeDate = (dateStr: string) => {
      let result = dateStr.split('/').join('-');
      result = result.split('年').join('-')
        .split('月').join('-')
        .split('日').join('-');
      return result;
    };
    try {
      const current = new Date(normalizeDate(currentDate));
      const target = new Date(normalizeDate(targetDate));
      if (isNaN(current.getTime()) || isNaN(target.getTime())) {
        return -1;
      }
      return target.getTime() - current.getTime();
    } catch (e) {
      return -1; // 日期解析异常视为已过期
    }
  }

  aboutToAppear(): void {
    this.updateCurrentDate();
    this.onQueryDeviceCode();
  }
  build() {
    Column() {
      Column() {
        Text("设备点检")
          .fontColor($r('app.color.FFFFFF'))
          .fontSize($r('app.float.fontSize_30'))
      }
      .height('8%')
      .width('100%')
      .justifyContent(FlexAlign.Center)

      Column() {
        Text("扫描设备 ")
            .fontColor($r('app.color.FFFFFF'))
            .fontSize($r('app.float.fontSize_24'))
        Row(){
          Row() {
            // 左侧二维码图标
            Image($r('app.media.material_qr_code'))
              .width($r('app.float.virtualSize_32'))
              .height($r('app.float.virtualSize_32'))
              .fillColor($r('app.color.FFFFFF'))
              .objectFit(ImageFit.Contain)
              .margin({left:'2%'})
            // 扫码输入框
            TextInput({text:this.queryDeviceNo, placeholder: '请扫描设备编码' })
              .type(InputType.Normal)
              .placeholderFont({ size: $r('app.float.fontSize_16') })
              .placeholderColor($r('app.color.30FFFFFF'))
              .fontSize($r('app.float.fontSize_16'))
              .fontColor($r('app.color.FFFFFF'))
              .enableKeyboardOnFocus(false)
              .onSubmit(() => {
                this.onQueryDeviceCode()
              })
              .onChange((value: string) => {
                this.queryDeviceNo = value;
                //this.onQueryDeviceCode()
              })
          }
          .height('100%')
          .width('65%')
          .borderRadius($r('app.float.virtualSize_16'))
          .backgroundColor($r('app.color.000000'))
          Text(this.currentDate)
            .fontColor($r('app.color.FFFFFF'))
            .fontSize($r('app.float.fontSize_16'))
            .margin({left:'3%'})
        }
        .height('8%')
        .width('50%')
        .margin({bottom:'1%',top:'1%'})
        List({scroller: this.scrollerDevice }) {
            ForEach(this.devicesList, (item: DeviceInfo, index) => {
              ListItem() {
                Row() {
                  Column(){
                    Text(`${item.deviceName}`)
                      .fontSize($r('app.float.fontSize_24'))
                      .fontColor($r('app.color.FFFFFF'))
                    Text(`型号：${item.deviceType}`)
                      .fontSize($r('app.float.fontSize_16'))
                      .fontColor($r('app.color.FFFFFF'))
                      .fontWeight(FontWeight.Lighter)
                      .margin({top:'2%',bottom:'1%'})
                    Text(`设备编码：${item.deviceNo}`)
                      .fontSize($r('app.float.fontSize_16'))
                      .fontColor($r('app.color.FFFFFF'))
                      .fontWeight(FontWeight.Lighter)
                  }
                  .width('30%')
                  .height('100%')
                  .justifyContent(FlexAlign.Center)
                  .alignItems(HorizontalAlign.Start)
                  .margin({right:'16%'})
                  Column({space:5}){
                    Text(`计量有效期：`)
                      .fontSize($r('app.float.fontSize_16'))
                      .fontColor($r('app.color.FFFFFF'))
                      .fontWeight(FontWeight.Lighter)
                    Row(){
                      Image(this.compareDates(this.currentDate, item.meteringDate) > 0
                      ?$r('app.media.device_normal') :$r('app.media.device_expire')
                      )
                        .width($r('app.float.virtualSize_24'))
                        .height($r('app.float.virtualSize_24'))
                        .margin({left:'2%'})
                      Text(`${item.meteringDate}`)
                        .fontSize($r('app.float.fontSize_16'))
                        .fontColor(
                          this.compareDates(this.currentDate, item.meteringDate) > 0
                            ? $r('app.color.30D158')  // 有效期未过（绿色）
                            : $r('app.color.FF453A')  // 已过期（红色）
                        )
                        .margin({left:'2%'})
                    }
                    .width('65%')
                    .borderRadius($r('app.float.virtualSize_16'))
                    .backgroundColor($r('app.color.000000'))
                    .height('25%')
                    .alignItems(VerticalAlign.Center)
                  }
                  .width('22%')
                  .height('100%')
                  .justifyContent(FlexAlign.Center)
                  .alignItems(HorizontalAlign.Start)
                  Column({space:5}){
                    Text(`维保有效期：`)
                      .fontSize($r('app.float.fontSize_16'))
                      .fontColor($r('app.color.FFFFFF'))
                      .fontWeight(FontWeight.Lighter)
                    Row(){
                      Image(this.compareDates(this.currentDate, item.updated) > 0
                        ?$r('app.media.device_normal') :$r('app.media.device_expire')
                      )
                        .width($r('app.float.virtualSize_24'))
                        .height($r('app.float.virtualSize_24'))
                        .margin({left:'2%'})
                      Text(`${item.updated}`)
                        .fontSize($r('app.float.fontSize_16'))
                        .fontColor(
                          this.compareDates(this.currentDate, item.updated) > 0
                            ? $r('app.color.30D158')
                            : $r('app.color.FF453A')
                        )
                        .margin({left:'2%'})
                    }
                    .width('65%')
                    .borderRadius($r('app.float.virtualSize_16'))
                    .backgroundColor($r('app.color.000000'))
                    .height('25%')
                    .alignItems(VerticalAlign.Center)
                  }
                  .width('22%')
                  .height('100%')
                  .justifyContent(FlexAlign.Center)
                  .alignItems(HorizontalAlign.Start)
                  Column(){
                   Image($r('app.media.process_delete_seq'))
                     .width($r('app.float.virtualSize_48'))
                     .height($r('app.float.virtualSize_48'))
                     .fillColor($r('app.color.FF453A'))
                     .onClick(()=>{
                       this.devicesList.splice(index, 1);
                     })
                  }
                  .width('10%')
                  .height('100%')
                  .justifyContent(FlexAlign.Center)

                }
                .height('90%')
                .width('95%')
                .justifyContent(FlexAlign.Start)
              }
              .height('18%')
              .width('100%')
              .margin({ bottom: 8})
              .borderRadius($r('app.float.virtualSize_16'))
              .backgroundColor($r('app.color.10FFFFFF'))
            })
          }.height('82%')
        }
        .width('96%')
        .height('84%')
        .alignItems(HorizontalAlign.Start)
        .justifyContent(FlexAlign.Start)
        .margin({left:'2%',right:'2%'})

      Column() {
        Divider()
          .vertical(false)
          .strokeWidth(1)
          .color($r('app.color.15FFFFFF'))
        Row() {
          Row() {
            Text('取消')
              .fontColor($r('app.color.60FFFFFF'))
              .fontSize($r('app.float.fontSize_30'))
          }
          .justifyContent(FlexAlign.Center)
          .width('50%')
          .onClick(() => this.controller.close())

          Divider()
            .vertical(true)
            .strokeWidth(1)
            .color($r('app.color.15FFFFFF'))
          Row() {
            Text('确定')
              .fontColor($r('app.color.007AFF'))
              .fontSize($r('app.float.fontSize_30'))
          }
          .justifyContent(FlexAlign.Center)
          .width('50%')
          .onClick(() => {
            this.controller.close();
          })
        }
      }
      .width('100%')
      .height('8%')
    }
    .height('71%')
    .width('62%')
    .backgroundColor($r('app.color.2A2A2A'))
    .justifyContent(FlexAlign.End)
    .alignItems(HorizontalAlign.Start)
    .borderColor($r('app.color.000000'))
    .borderWidth(1)
    .borderRadius($r('app.float.virtualSize_16'))
  }
}
