import ProcessRequest from '../../common/util/request/ProcessRequest'
import OperationItem from '../../viewmodel/OperationItem'
import ProcessInfo from '../../viewmodel/process/ProcessInfo'
import ProcessMaterial from '../../viewmodel/process/ProcessMaterial'
import RequestParamModel from '../../viewmodel/RequestParamModel'
import WorkOrderInfo from '../../viewmodel/WorkOrderInfo'
import promptAction from '@ohos.promptAction'
import { ModifyMaterialNumDialog } from '../ModifyMaterialNumDialog'
import PageInfo from '../../viewmodel/PageInfo'
import OperationComponent from '../../viewmodel/process/OperationComponent'

// 补充缺失的UI相关导入（根据实际项目调整）


// 物料采集工序
@Component
export struct MaterialCollectView {
  @State scanCode: string = ''
  @Link opComponents: OperationComponent[]
  @Link index:number
  // 需要采集的工序物料
  @Link itemArray: OperationItem[]
  // 总需求数
  @State needNum: number = 0
  // 实际数量（已采集数）
  @State realNum: number = 0
  // 扫码查到物料信息（修复：规范类型断言）
  scanMaterial: ProcessMaterial = {} as ProcessMaterial
  // 新增或者修改采集物料(1:新增 2:修改)
  addOrModifyCollect: number = 1
  // 扫码开工状态(0:未开工 1:已开工)（注释完整）
  // @Link @Watch('queryByScanState') scanState: number = 0
  // 当前流转卡号（补充未完成的变量声明）
  currentFlowCardNo: string = ''

  controller: TextInputController = new TextInputController()


  aboutToAppear() {
    // 页面显示时统计总量
    this.calculateTotalNumbers()
    setTimeout(() => {
      focusControl.requestFocus('CATCH_FOCUS')
    }, 500)
    //console.info("sssss"+this.index+"sss"+this.componentStates[this.index])
  }


  private delay(ms: number): Promise<void> {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }

  // 统计realNum总量和needNum总量（修复：用空值合并更安全）
  async calculateTotalNumbers() {
    let totalRealNum = 0
    let totalNeedNum = 0

    this.itemArray.forEach((item: OperationItem) => {
      totalRealNum += item.realNum ?? 0
      totalNeedNum += item.needNum ?? 0
    })

    this.realNum = totalRealNum
    this.needNum = totalNeedNum
    if(this.realNum === this.needNum)
    {
      if(!this.opComponents[this.index].isComplete)
      {
        this.opComponents[this.index].isComplete=true
        this.index++
      }
      //await this.delay(1500)
      promptAction.showToast({
        message: `所有物料已采集完成`,
        duration: 2000
      })

    }
  }

  async handleScanInput() {
    await this.delay(200)
    // 查找对应的物料
    const foundItemIndex = this.itemArray.findIndex((item: OperationItem) =>
    item.itemCode === this.scanCode.trim()
    )

    if (foundItemIndex !== -1) {
      // 创建新的数组副本（触发UI更新）
      const newItemArray = [...this.itemArray]
      const foundItem = newItemArray[foundItemIndex]

      // 检查是否已达到需求数量
      if (foundItem.realNum! >= foundItem.needNum!) {
        promptAction.showToast({
          message: `物料 ${foundItem.itemName} 已采集完成，无需再次采集`,
          duration: 2000
        })
        this.scanCode = ''
        return
      }

      // 采集数量+1（确保非空）
      foundItem.realNum = (foundItem.realNum ?? 0) + 1

      // 更新数组引用触发UI更新
      this.itemArray = newItemArray

      // 重新统计总量
      this.calculateTotalNumbers()

      promptAction.showToast({
        message: `物料 ${foundItem.itemName} 采集成功`,
        duration: 1000
      })
    } else {
      promptAction.showToast({
        message: '未找到对应的物料信息',
        duration: 2000
      })
    }

    // 清空扫码输入框
    this.scanCode = ''
    focusControl.requestFocus('CATCH_FOCUS')
  }

  build() {
    Column() {
      // 扫码框和已采集统计
      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'))
            .margin({ left: '2%'})
          // 扫码输入框（修复：语法格式）
          TextInput({ text: this.scanCode, placeholder: '请扫描物料编码' })
            .type(InputType.Normal)
            .placeholderFont({ size: $r('app.float.fontSize_16') })
            .placeholderColor($r('app.color.30FFFFFF'))
            .fontSize($r('app.float.fontSize_30'))
            .fontColor($r('app.color.FFFFFF'))
            .enableKeyboardOnFocus(false)
            .key('CATCH_FOCUS')
            .onChange((value: string) => {
              this.scanCode = value
              // 扫码完成（换行符触发）
              // if (value.length > 0 && value.includes('\n')) {
              //   setTimeout(() => {
              //     this.handleScanInput()
              //   }, 500)
              // }
            })
            .onSubmit(() => {
              // 回车键提交
              this.handleScanInput()
            })
        }
        .height('52.8%')
        .width('28.4%')
        .borderRadius($r('app.float.virtualSize_16'))
        .backgroundColor($r('app.color.000000'))

        // 采集进度统计
        Column() {
          Text(`${this.realNum}/${this.needNum}`)
            .fontColor($r('app.color.FFFFFF'))
            .fontSize($r('app.float.fontSize_16'))
            .fontWeight(FontWeight.Regular)
          Row() {
            Progress({ value: this.realNum, total: this.needNum, type: ProgressType.Linear })
          }
          .height('30%')
          .width('100%')
          .backgroundColor($r('app.color.10FFFFFF'))
          .borderRadius($r('app.float.virtualSize_24'))
        }
        .width('13.1%')
        .height('31.3%')
        .alignItems(HorizontalAlign.End)
        .justifyContent(FlexAlign.SpaceBetween)
      }
      .height('13.5%')
      .width('93%')
      .justifyContent(FlexAlign.SpaceBetween)

      // 需要采集物料展示（修复：字符串拼接语法）
      Scroll() {
        Flex({
          wrap: FlexWrap.Wrap,
          direction: FlexDirection.Row,
          justifyContent: FlexAlign.Start,
          alignItems: ItemAlign.Start
        }) {
          ForEach(this.itemArray, (item: OperationItem, index: number) => {
            Column() {
              Row() {
                Column() {
                  Text(item.itemName!)
                    .fontSize($r('app.float.fontSize_24'))
                    .fontWeight(FontWeight.Medium)
                    .fontColor($r('app.color.FFFFFF'))
                    .maxLines(1)
                }
                .width('45.5%')
                .height('100%')
                .justifyContent(FlexAlign.Center)
                .alignItems(HorizontalAlign.Start)

                // 完成状态图标
                Row() {
                  if (item.realNum! >= item.needNum!) {
                    Image($r('app.media.process_complete_test'))
                      .height('100%')
                      .width('45.5%')
                      .objectFit(ImageFit.Fill)
                  }
                }
                .width('50%')
                .height('100%')
                .alignItems(VerticalAlign.Top)
                .justifyContent(FlexAlign.End)
              }
              .height('45.8%')
              .width('100%')
              .justifyContent(FlexAlign.End)

              // 物料编码和采集数量
              Row() {
                Text(item.itemCode!) // 修复：空值合并替代三元表达式
                  .fontSize($r('app.float.fontSize_16'))
                  .fontWeight(FontWeight.Regular)
                  .fontColor($r('app.color.FFFFFF'))

                Row() {
                  // 修复：模板字符串避免赋值表达式错误
                  Text(`${item.realNum ?? 0}/`)
                    .fontSize($r('app.float.fontSize_38'))
                    .fontWeight(FontWeight.Lighter)
                    .fontColor($r('app.color.FFFFFF'))
                  Text(`${item.needNum ?? 0}${item.unit ?? ''}`)
                    .fontSize($r('app.float.fontSize_38'))
                    .fontWeight(FontWeight.Lighter)
                    .fontColor($r('app.color.FFFFFF'))
                    .opacity(0.6)
                }
              }
              .height('42.2%')
              .width('91%')
              .justifyContent(FlexAlign.SpaceBetween)
              .alignItems(VerticalAlign.Bottom)
            }
            .width('32.8%')
            .height('25.2%')
            .borderRadius($r('app.float.virtualSize_16'))
            .backgroundColor($r('app.color.20FFFFFF'))// 替换为实际颜色值（可选）
            .margin({
              top: index > 2 ? '1%' : '0%',
              left: (index % 3) === 0 ? '0%' : '0.8%'
            })
            .onClick(() => {
              // 可补充物料点击逻辑（如修改数量）
            })
          })
        }
        .width('100%')
      }
      .scrollable(ScrollDirection.Vertical)
      .scrollBar(BarState.Auto)
      .width('93%')
      .height('84%')
      .align(Alignment.Top)
    }
    .width('100%')
    .height('100%')
    //.backgroundColor($r('app.color.101010')) // 补充页面背景（可选）
  }
}