// 数量修改
import ProcessRequest from '../common/util/request/ProcessRequest'
import OperationItem from '../viewmodel/OperationItem'
import ProcessMaterial from '../viewmodel/process/ProcessMaterial'
import RequestParamModel from '../viewmodel/RequestParamModel'
import promptAction from '@ohos.promptAction'

@CustomDialog
export struct ModifyMaterialNumDialog {
  @State materialName :string = ''
  @State materialModel :string = ''
  @State unit :string = ''
  // 总需求数
  @State needNum: number = 0
  workOrderCode :string = ''
  operationId :string = ''
  processId :string = ''
  seqNo :string = ''
  // 新增时扫码搜索到的物料
  scanMaterial: ProcessMaterial = {}
  // 新增或者修改采集物料(1:新增 2:修改)
  addOrModifyCollect: number = 1
  @State collectMaterials: ProcessMaterial[] = []
  @State collectNumArray: number[] = []
  // 当前工位ID
  @Consume('currentStationId') currentStationId: string
  // 批次高度
  batchHeight: number = 93.6

  controller: CustomDialogController
  confirm: () => void = () => {}

  async aboutToAppear() {
    if (!this.scanMaterial) {
      return
    }
    this.materialName = this.scanMaterial.materialName!
    this.materialModel = this.scanMaterial.spec!
    this.unit = this.scanMaterial.unitDictValue!
    // 总需求数
    this.needNum = this.scanMaterial.totalNum!
    // 修改物料采集，则先查询采集历史
    if (this.addOrModifyCollect === 2) {
      let result: OperationItem[] = await ProcessRequest.post('/api/v1/process/itemRecord/itemInfo/list',{
        itemCode: this.scanMaterial.materialCode!,
        opId: this.operationId,
        processId: this.processId
      } as RequestParamModel)
      if (result) {
        for (let i = result.length - 1; i >= 0 ;i--) {
          let material: ProcessMaterial = JSON.parse(JSON.stringify(result[i]))
          material.materialName = result[i].itemName
          material.materialCode = result[i].itemCode
          material.spec = result[i].itemModel
          material.workOrderCode = this.workOrderCode
          this.collectMaterials.push(material)
          this.collectNumArray.push(material.num ? material.num : 0)
        }
      }
    } else {
      if (this.scanMaterial) {
        this.collectMaterials.push(this.scanMaterial)
        let num: number = 0
        // 如果需求数量小于扫码数量，则默认采集需求数量
        if (this.scanMaterial.needNum! < this.scanMaterial.num!) {
          num = this.needNum
        } else {
          num = this.scanMaterial.num!
        }
        this.collectNumArray.push(num)
      }
    }

    // for (const element of this.collectMaterials) {
    //   this.collectNumArray.push(element.num ? element.num : 0)
    // }
  }

  build() {
    Column() {
      // 标题
      Column(){
        Text('数量')
          .fontColor($r('app.color.FFFFFF'))
          .fontSize($r('app.float.fontSize_30'))
      }
      .height($r('app.float.virtualSize_100'))
      .justifyContent(FlexAlign.Center)
      Column(){
        Text(`物料名称：${this.materialName}`)
          .fontColor($r('app.color.FFFFFF'))
          .fontSize($r('app.float.fontSize_16'))
          .fontWeight(FontWeight.Lighter)
        Text(`型号：${this.materialModel}`)
          .fontColor($r('app.color.FFFFFF'))
          .fontSize($r('app.float.fontSize_16'))
          .fontWeight(FontWeight.Lighter)
        Text(`需求数量：：${this.scanMaterial?.totalNum!}`)
          .fontColor($r('app.color.FFFFFF'))
          .fontSize($r('app.float.fontSize_16'))
          .fontWeight(FontWeight.Lighter)
      }
      .height($r('app.float.virtualSize_56'))
      .width('70.4%')
      .justifyContent(FlexAlign.Start)
      .alignItems(HorizontalAlign.Start)

      Scroll() {
        Flex({ wrap: FlexWrap.Wrap, direction: FlexDirection.Row, justifyContent: FlexAlign.Start, alignItems: ItemAlign.Start}) {
          ForEach(this.collectMaterials, (item: ProcessMaterial, index: number) => {
            Column({space: 5}) {
              Row() {
                Text('批次号：')
                  .fontColor($r('app.color.FFFFFF'))
                  .fontSize($r('app.float.fontSize_16'))
                  .fontWeight(FontWeight.Lighter)
                Text(item?.batchNo!)
                  .fontColor($r('app.color.FFFFFF'))
                  .fontSize($r('app.float.fontSize_16'))
                  .fontWeight(FontWeight.Bold)
              }
              Row() {
                Text(`数量（${this.unit}）`)
                  .fontColor($r('app.color.FFFFFF'))
                  .fontSize($r('app.float.fontSize_16'))
                  .fontWeight(FontWeight.Regular)
                Blank()
                if (this.addOrModifyCollect === 1) {
                  Text('还需采集：')
                    .fontColor($r('app.color.FFFFFF'))
                    .fontSize($r('app.float.fontSize_16'))
                    .fontWeight(FontWeight.Lighter)
                  Text(`${this.scanMaterial?.needNum!}`)
                    .fontColor($r('app.color.FFFFFF'))
                    .fontSize($r('app.float.fontSize_16'))
                    .fontWeight(FontWeight.Regular)
                }
              }
              .width('100%')

              Row(){
                Row() {
                  Button({ type: ButtonType.Normal }) {
                    Image($r('app.media.process_material_subtraction'))
                      .width('50%')
                      .height('50%')
                      .objectFit(ImageFit.Contain)
                      .fillColor($r('app.color.FFFFFF'))
                  }
                  .width('100%')
                  .height('100%')
                  .backgroundColor($r('app.color.20FFFFFF'))
                  .borderRadius($r('app.float.virtualSize_16'))
                  .opacity(((this.addOrModifyCollect === 1 && this.collectNumArray[index] <= 1) || (this.addOrModifyCollect === 2 && this.collectNumArray[index] <= 0)) ? 0.3 : 1)
                  .onClick(() => {
                    if (this.addOrModifyCollect === 1) {
                      if (this.collectNumArray[index] > 1) {
                        this.collectNumArray[index]--
                      } else {
                        this.collectNumArray[index] = 0
                      }
                    } else {
                      if (this.collectNumArray[index] > 0) {
                        this.collectNumArray[index]--
                      } else {
                        this.collectNumArray[index] = 0
                      }
                    }
                  })
                }.width('22%')
                Row(){
                  TextInput({text: (this.collectNumArray.length > index ? this.collectNumArray[index].toString() : '0')})
                    .fontSize($r('app.float.fontSize_38'))
                    .fontWeight(FontWeight.Lighter)
                    .fontColor($r('app.color.FFFFFF'))
                    .textAlign(TextAlign.Center)
                    .type(InputType.Number)
                    .onChange((value: string) => {
                      this.collectNumArray[index] = parseInt(value)
                      if (this.addOrModifyCollect === 1) {
                        if (this.collectNumArray[index] > this.scanMaterial?.needNum!) {
                          this.collectNumArray[index] = this.scanMaterial?.needNum!
                        } else if (this.collectNumArray[index] < 1) {
                          this.collectNumArray[index] = 1
                        }
                      } else {
                        if (this.collectNumArray[index] > this.needNum) {
                          this.collectNumArray[index] = this.needNum
                        } else if (this.collectNumArray[index] < 0) {
                          this.collectNumArray[index] = 0
                        }
                      }
                    })
                }
                .width('56%')
                .justifyContent(FlexAlign.Center)
                Row() {
                  Button({ type: ButtonType.Normal }) {
                    Image($r('app.media.process_material_add'))
                      .width('50%')
                      .height('50%')
                      .objectFit(ImageFit.Contain)
                      .fillColor($r('app.color.FFFFFF'))
                      .borderRadius($r('app.float.virtualSize_16'))
                  }
                  .width('100%')
                  .height('100%')
                  .backgroundColor($r('app.color.20FFFFFF'))
                  .borderRadius($r('app.float.virtualSize_16'))
                  .opacity(((this.addOrModifyCollect === 1 && this.collectNumArray[index] >= this.scanMaterial?.needNum!) || (this.addOrModifyCollect === 2 && this.collectNumArray[index] >= this.needNum)) ? 0.3 : 1)
                  .onClick(() => {
                    if (this.addOrModifyCollect === 1) {
                      if (this.collectNumArray[index] < this.scanMaterial?.needNum!) {
                        this.collectNumArray[index]++
                      } else {
                        this.collectNumArray[index] = this.scanMaterial?.needNum!
                      }
                    } else {
                      if (this.collectNumArray[index] < this.needNum!) {
                        this.collectNumArray[index]++
                      } else {
                        this.collectNumArray[index] = this.needNum!
                      }
                    }
                  })
                }.width('22%')
              }
              .height($r('app.float.virtualSize_80'))
              .width('100%')
              .backgroundColor($r('app.color.10FFFFFF'))
              .borderRadius($r('app.float.virtualSize_16'))
              if (index < this.collectMaterials.length - 1) {
                Row() {
                  Divider()
                    .vertical(false)
                    .color($r('app.color.15FFFFFF'))
                }
                .justifyContent(FlexAlign.Center)
                .width('100%')
              }
            }
            .height(this.batchHeight)
            .alignItems(HorizontalAlign.Start)
          })
        }
        .width('100%')
      }
      .scrollable(ScrollDirection.Vertical) // 垂直滚动
      .scrollBar(BarState.Auto)
      .width('70.4%')
      .height(this.collectMaterials.length * this.batchHeight)
      .align(Alignment.Top)
      .constraintSize({ maxHeight: '70%' })

      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(async () => {
            if (this.addOrModifyCollect === 1) {
              if (this.collectNumArray[0] > this.scanMaterial?.needNum!) {
                promptAction.showToast({
                  message: `采集数量超过需求数量，请检查...`,
                  duration: 1500,
                  bottom: 100
                })
                return
              }
              // 调接口新增采集
              this.scanMaterial.stationId = this.currentStationId
              this.scanMaterial.num = this.collectNumArray[0]
              this.scanMaterial.seqNo = this.seqNo
              let params: ProcessMaterial[] = []
              params.push(this.scanMaterial)
              await ProcessRequest.post('/api/v1/process/itemRecord/add', params)
            } else {
              let total: number = 0
              for (const element of this.collectNumArray) {
                total += element;
              }
              if (total > this.needNum) {
                promptAction.showToast({
                  message: `采集数量超过需求数量，请检查...`,
                  duration: 1500,
                  bottom: 100
                })
                return
              }
             // 调批量修改的接口
              let stillNeed: number = this.needNum
              for (let i = 0; i < this.collectMaterials.length; i++) {
                this.collectMaterials[i].num = this.collectNumArray[i]
                stillNeed -= this.collectNumArray[i]
                this.collectMaterials[i].needNum = stillNeed
              }
              await ProcessRequest.post('/api/v1/process/itemRecord/batchUpdate', this.collectMaterials)
            }
            this.confirm();
            this.controller.close();
          })
        }
      }
      .width('100%')
      .height($r('app.float.virtualSize_56'))
    }
    .width('30%')
    .backgroundColor($r('app.color.2A2A2A'))
    .justifyContent(FlexAlign.End)
    .borderRadius($r('app.float.virtualSize_16'))
  }
}