import ProcessRequest from '../common/util/request/ProcessRequest'
import RequestParamModel from '../viewmodel/RequestParamModel'
import WorkOrderInfo from '../viewmodel/WorkOrderInfo'
import { WorkOrderPage } from '../viewmodel/WorkOrderPage'
import {ProcessCurrentView} from '../viewmodel/process/EnumerationType'
import OperationInfo from '../viewmodel/process/OperationInfo';
@Component
export struct SelectWorkOrderView {
  @Link processCurrentView:ProcessCurrentView
  private scrollerMaterial: Scroller = new Scroller()
  @Link previousView:ProcessCurrentView
  //工单列表
  @State workOrderList: WorkOrderInfo[] = []
  //选择的工单索引
  @State selectedOrderIndex: number = -1
  //扫描的工单号
  @State scanOrderValue:string = ''
  @Link selectWorkOder: WorkOrderInfo

  // 当前工位ID
 // @Consume('currentStationId') currentStationId: string

  //加载所有工单
  loadWorkOrders = async () => {
    // let queryRes = await ProcessRequest.post('/api/v1/plan/workOrder/taskPage2', {
    //   queryCode:this.scanOrderValue,
    //   queryComplete: 0,
    //   stationId:this.currentStationId,
    //   pageNo: 1,
    //   pageSize: 99999,
    // } as RequestParamModel) as WorkOrderPage;
    // this.workOrderList = queryRes?.records??[]
    if (this.scanOrderValue) {
      // let queryRes = await ProcessRequest.post('/api/v1/plan/workOrder/taskPage2', {
      //   queryCode:this.scanOrderValue,
      //   queryComplete: 0,
      //   stationId:this.currentStationId,
      //   pageNo: 1,
      //   pageSize: 99999,
      // } as RequestParamModel) as WorkOrderPage;
      // this.workOrderList = queryRes?.records??[]
    } else {
      // 没有扫描值时，显示示例数据
      this.loadDemoData();
    }
  };

  loadDemoData = () => {
    const demoData: WorkOrderInfo[] = [
      {
       materialName: "智能手机外壳",
      materialCode: "PH-CASE-001",
      orderCode: "ORD-2024-1001",
      workOrderCode: "WO-2024-0801",
      workOrderState: "1",
      completeNum: "150",
      planNum: "500",
      ops: [
        {
          operationId: "OP001",
          operationName: "外壳预处理",
          isEnd: true,
          operationCode: "OP-PRE-001",
          stationId:'123',
        } as OperationInfo,
        {
          operationId: "OP002",
          operationName: "表面打磨",
          isEnd: true,
          operationCode: "OP-POLISH-002",
          stationId:'3c3c3d3d',
        } as OperationInfo,
        {
          operationId: "OP003",
          operationName: "喷涂处理",
          isEnd: false,
          operationCode: "OP-SPRAY-003",
          stationId:'123',
        } as OperationInfo,
        {
          operationId: "OP004",
          operationName: "质量检验",
          isEnd: false,
          operationCode: "OP-QC-004",
          stationId:'3c3c3d3d',
        } as OperationInfo
      ]
    } as WorkOrderInfo,
      {
        materialName: "笔记本电脑电池",
        materialCode: "NB-BATT-002",
        orderCode: "ORD-2024-1002",
        workOrderCode: "WO-2024-0802",
        workOrderState: "3",
        completeNum: "150",
        planNum: "500"
      } as WorkOrderInfo,
      {
        materialName: "智能手表屏幕",
        materialCode: "WT-SCR-003",
        orderCode: "ORD-2024-1003",
        workOrderCode: "WO-2024-0803",
        workOrderState: "6",
        completeNum: "150",
        planNum: "500"
      } as WorkOrderInfo,
      {
        materialName: "无线耳机芯片",
        materialCode: "BUD-CHIP-004",
        orderCode: "ORD-2024-1004",
        workOrderCode: "WO-2024-0804",
        workOrderState: "2",
        completeNum: "150",
        planNum: "500"
      } as WorkOrderInfo,
      {
        materialName: "平板电脑主板",
        materialCode: "TAB-MB-005",
        orderCode: "ORD-2024-1005",
        workOrderCode: "WO-2024-0805",
        workOrderState: "4",
        completeNum: "150",
        planNum: "500"
      } as WorkOrderInfo,
      {
        materialName: "摄像头模组",
        materialCode: "CAM-MOD-006",
        orderCode: "ORD-2024-1006",
        workOrderCode: "WO-2024-0806",
        workOrderState: "1",
        completeNum: "150",
        planNum: "500"
      } as WorkOrderInfo
    ];
    this.workOrderList = demoData;
  };

  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)
      .alignItems(HorizontalAlign.Start)
      .margin({ left: '2%'})

      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,
              pageNo: 1,
              pageSize: 99999,
            } 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({space: 1}) {
                  // 订单标题（带订单号）
                  Text(`${order.materialName}`)
                    .fontSize($r('app.float.fontSize_24'))
                    .fontColor($r('app.color.FFFFFF'))
                    .width('100%')
                    .textAlign(TextAlign.Start)
                    .margin({left:'2%' })
                  Column() {
                    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.6%')
            .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.processCurrentView = this.previousView)

          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
            this.selectWorkOder = this.workOrderList[this.selectedOrderIndex]
            this.processCurrentView = ProcessCurrentView.WORK_STEP_VIEW
          //   if(this.selectedOrderIndex==-1) return
          //   // 重新选中的工单就是之前的工单，则不做任何操作
          //   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('100%')
      .width('100%')
      .justifyContent(FlexAlign.End)
      .alignItems(HorizontalAlign.Start)
      .borderColor($r('app.color.000000'))
      .borderWidth(1)
      .borderRadius($r('app.float.virtualSize_16'))
  }
}
