import ProcessRequest from '../common/util/request/ProcessRequest'
import RequestParamModel from '../viewmodel/RequestParamModel'
import WorkOrderInfo from '../viewmodel/WorkOrderInfo'
import { WorkOrderPage } from '../viewmodel/WorkOrderPage'

@CustomDialog
export struct SelectWorkOrderDialog {
  private scrollerMaterial: Scroller = new Scroller()
  //工单列表
  @State workOrderList: WorkOrderInfo[] = []
  //选择的工单索引
  @State selectedOrderIndex: number = -1
  //扫描的工单号
  @State scanOrderValue:string = ''
  @Link selectWorkOder: WorkOrderInfo
  // 当前工位ID
  @Consume('currentStationId') currentStationId: string
  controller: CustomDialogController
  onConfirm: () => void = () => {
  }

  //加载所有工单
  loadWorkOrders = async () => {
    let queryRes = await ProcessRequest.post('/api/v1/plan/workOrder/taskPage2', {
      queryCode:this.scanOrderValue,
      queryComplete: 0,
      stationId:this.currentStationId
    } as RequestParamModel) as WorkOrderPage;
    this.workOrderList = queryRes?.records??[]
  };

  private onSelectOrder(index: number) {
    this.selectedOrderIndex = index
  }

  aboutToAppear(): void {
    this.loadWorkOrders();
  }

  build() {
    Column() {
      Column() {
        Text("选择工单")
          .fontColor($r('app.color.FFFFFF'))
          .fontSize($r('app.float.fontSize_30'))
      }.height('8%')
      .width('100%')
      .justifyContent(FlexAlign.Center)

      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'))
          .margin({ left: '2%'})
        // 扫码输入框
        TextInput({text:this.scanOrderValue, 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(async () => {
            let queryRes = await ProcessRequest.post('/api/v1/plan/workOrder/taskPage2', {
              queryCode:this.scanOrderValue
            } as RequestParamModel) as WorkOrderPage;
            this.workOrderList = queryRes?.records??[]
          })
          .onChange((value: string) => {
            this.scanOrderValue = value;
            this.loadWorkOrders()
          })
      }
      .height('6%')
      .width('30%')
      .borderRadius($r('app.float.virtualSize_16'))
      .backgroundColor($r('app.color.000000'))
      .margin({ left: '2%' ,top:'2%'})

      Divider()
        .vertical(false)
        .strokeWidth(1)
        .color($r('app.color.15FFFFFF'))
        .margin({ top: '2%' ,bottom:'2%',left:'2%',right:'2%'})

      Column() {
        Grid(this.scrollerMaterial) {
          ForEach(this.workOrderList, (order: WorkOrderInfo, index) => {
            GridItem() {
              Row(){
                Column() {
                  // 订单标题（带订单号）
                  Text(`${order.orderName}`)
                    .fontSize($r('app.float.fontSize_30'))
                    .fontColor($r('app.color.FFFFFF'))
                    .width('100%')
                    .textAlign(TextAlign.Start)
                    .margin({ bottom: '2%',left:'2%' })
                  Column({ space: 3 }) {
                    Text(`产品编号: ${order.materialCode}`)
                      .fontColor($r('app.color.FFFFFF'))
                      .fontSize($r('app.float.fontSize_16'))
                      .fontWeight(FontWeight.Lighter)
                      .textAlign(TextAlign.Start)
                    Text(`订单编号: ${order.orderCode} `)
                      .fontColor($r('app.color.FFFFFF'))
                      .fontSize($r('app.float.fontSize_16'))
                      .fontWeight(FontWeight.Lighter)
                      .textAlign(TextAlign.Start)
                    Text(`工单编号: ${order.workOrderCode}`)
                      .fontColor($r('app.color.FFFFFF'))
                      .fontSize($r('app.float.fontSize_16'))
                      .fontWeight(FontWeight.Lighter)
                      .textAlign(TextAlign.Start)
                    Text(`完成/计划: ${order.completeNum}/${order.planNum}`)
                      .fontColor($r('app.color.FFFFFF'))
                      .fontSize($r('app.float.fontSize_16'))
                      .fontWeight(FontWeight.Lighter)
                      .textAlign(TextAlign.Start)
                  }
                  .width('100%')
                  .margin({left:'2%'})
                  .justifyContent(FlexAlign.Start)
                  .alignItems(HorizontalAlign.Start)
                }
                .alignItems(HorizontalAlign.Start)
                .width('70%')
                .padding(8)
                Stack(){
                  if (order.workOrderState ==="6") {
                    Image($r("app.media.process_complete_test"))
                      .width($r('app.float.virtualSize_112'))
                      .height($r('app.float.virtualSize_80'))
                      .position({ x: '30%', y: '0%' })
                      .fillColor($r('app.color.FFFFFF'))
                      .zIndex(0)
                  }
                  Image($r('app.media.order_name_copy'))
                    .width($r('app.float.virtualSize_56'))
                    .height($r('app.float.virtualSize_56'))
                    .fillColor($r('app.color.FFFFFF'))
                    .zIndex(1)
                    .onClick(()=>{
                      this.scanOrderValue = this.workOrderList[index]?.workOrderCode ?? '';
                    })
                }
                .width('30%')
                .height('100%')
              }
            }
            .height('27%')
            .backgroundColor(index === this.selectedOrderIndex ? $r('app.color.2030D158') : $r('app.color.20FFFFFF'))
            .borderRadius($r('app.float.virtualSize_24'))
            .border({
              width: 2,
              color: index === this.selectedOrderIndex ? $r('app.color.2030D158') : $r('app.color.20FFFFFF')
            })
            .onClick(() => {
              this.onSelectOrder(index)
            })

          })
        }
        .columnsTemplate('1fr 1fr 1fr')
        .columnsGap(10)
        .rowsGap(10)
        .width('100%')
        .height('97%')
        .padding(10)
      }
      .height('68%')
      .margin({left:'1%',right:'1%'})

      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(() => {
            if(this.selectedOrderIndex==-1) return
            console.log('hhtest', 'yixuanz ----------' + JSON.stringify(this.selectWorkOder))
            console.log('hhtest', 'yixuanz ----------' + JSON.stringify(this.workOrderList[this.selectedOrderIndex]))
            // 重新选中的工单就是之前的工单，则不做任何操作
            if (this.selectWorkOder && this.selectWorkOder.workOrderCode && this.workOrderList[this.selectedOrderIndex].workOrderCode! === this.selectWorkOder.workOrderCode!) {
              this.controller.close();
              return
            }
            this.selectWorkOder = this.workOrderList[this.selectedOrderIndex]
            this.onConfirm();
            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'))
  }
}
