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'

// 物料采集工序
@Component
export struct MaterialCollectView {
  @State scanCode: string = ''
  // 需要采集的工序物料
  @State itemArray: OperationItem[] = []
  // 总需求数
  @State needNum: number = 0
  // 实际数量（已采集数）
  @State realNum: number = 0
  // 扫码查到物料信息
  scanMaterial: ProcessMaterial = {}
  // 新增或者修改采集物料(1:新增 2:修改)（采集物料数量修改弹窗使用）
  addOrModifyCollect: number = 1
  // 扫码开工状态(0:未开工 1:已开工)
  @Link @Watch('queryByScanState') scanState: number
  // 当前流转卡号
  @Link seqNo: string
  // 选中工单
  @Link selectWorkOder: WorkOrderInfo
  // 选中工序id
  @Link selectOperationId: string
  // 扫码开工后的生产过程信息
  @Link process: ProcessInfo
  // 当前工位ID
  @Consume('currentStationId') currentStationId: string

  modifyMaterialNumDialogController: CustomDialogController = new CustomDialogController({
    builder: ModifyMaterialNumDialog({
      scanMaterial: this.scanMaterial,
      addOrModifyCollect: this.addOrModifyCollect,
      operationId: this.selectOperationId!,
      processId: this.process.id!,
      seqNo: this.seqNo,
      confirm: async ()=>{
        this.queryCollectHistory()
      },
    }),
    autoCancel: true, // 点击遮罩关闭
    customStyle: true,
    alignment: DialogAlignment.Center,
    maskColor: 'rgba(0,0,0,0.8)',  // 黑色遮罩
  })

  // 采集历史查询
  async queryCollectHistory() {
    this.itemArray = await ProcessRequest.post('/api/v1/process/itemRecord/list', {
      operationId: this.selectOperationId,
      workOrderCode: this.selectWorkOder.workOrderCode!,
      seqNo: this.seqNo,
      processId: this.process.id,
      pageNo: 1,
      pageSize: 999999} as RequestParamModel)
  }

  // 根据开工状态查询 需要采集的物料信息/物料采集历史
  async queryByScanState() {
    if (this.scanState === 1) {
      this.queryCollectHistory()
    } else {
      let res = await ProcessRequest.post('/api/v1/op/operationItem/page', {
        operationId: this.selectOperationId,
        pageNo: 1,
        pageSize: 999999} as RequestParamModel) as PageInfo
      this.itemArray = res.records as OperationItem[] || []
    }
    if (this.itemArray) {
      for (const element of this.itemArray) {
        this.needNum += element.needNum || 0
        this.realNum += element.realNum || 0
      }
    }
  }

  async aboutToAppear() {
    this.queryByScanState()
  }
  
  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)
            .onSubmit(async () => {
              if (this.scanState === 0) {
                promptAction.showToast({
                  message: '工序未开工，请先开工',
                  duration: 1500,
                  bottom: 100
                })
                return
              }
              let result: ProcessMaterial[] = await ProcessRequest.post('/api/v1/process/itemRecord/searchMaterial', {
              operationId: this.selectOperationId,
              processId: this.process.id!,
              seqNo: this.seqNo,
              scanCode: this.scanCode,
              workOrderCode: this.selectWorkOder.workOrderCode!} as RequestParamModel)
              if (result && result.length > 0) {
                if (result[0].num! <= 0) {
                  promptAction.showToast({
                    message: `${result[0].batchNo!}批次物料已用完`,
                    duration: 1500,
                    bottom: 100
                  })
                }
                this.scanMaterial = result[0]
                for (const element of result) {
                  element.operationId = this.selectOperationId
                  element.processId = this.process.id!
                  element.seqNo = this.seqNo
                  element.workOrderCode = this.selectWorkOder.workOrderCode!
                  element.trackBy = 'S'
                  element.itemSeq = this.scanCode
                }
                if ('BATCH' === result[0].codeType!) {
                  this.modifyMaterialNumDialogController.open()
                } else {
                  result[0].stationId = this.currentStationId
                  await ProcessRequest.post('/api/v1/process/itemRecord/add', result)
                }
                this.queryCollectHistory()
              }
            })
            .onChange((value: string) => {
              this.scanCode = value
            })
        }
        .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() {
            Row()
              .width(((this.realNum * 100)/ this.needNum).toFixed(2) + '%')
              .height('100%')
              .borderRadius($r('app.float.virtualSize_24'))
              .linearGradient({
                angle: 90,
                colors: [[$r('app.color.1050FF'), 0.0], [$r('app.color.73C3FF'), 1]]
              })
          }
          .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)
                  Text(item.itemCode!)
                    .fontSize($r('app.float.fontSize_12'))
                    .fontWeight(FontWeight.Lighter)
                    .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.codeTypeStr ? item.codeTypeStr : '')
                  .fontSize($r('app.float.fontSize_16'))
                  .fontWeight(FontWeight.Regular)
                  .fontColor($r('app.color.FFFFFF'))
                Row() {
                  Text((item.realNum ? item.realNum : 0) + '/')
                    .fontSize($r('app.float.fontSize_38'))
                    .fontWeight(FontWeight.Lighter)
                    .fontColor($r('app.color.FFFFFF'))
                  Text((item.needNum ? 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(()=>{
              if (this.scanState === 0) {
                promptAction.showToast({
                  message: '工序未开工，请先开工',
                  duration: 1500,
                  bottom: 100
                })
                return
              }
              this.scanMaterial = {
                materialCode: item.itemCode!,
                materialName: item.itemName!,
                spec: item.itemModel!,
                unitDictValue: item.unit!,
                totalNum: item.needNum!,
              }
              this.addOrModifyCollect = 2
              this.modifyMaterialNumDialogController.open()
            })
          })
        }
        .width('100%')
      }
      .scrollable(ScrollDirection.Vertical) // 垂直滚动
      .scrollBar(BarState.Auto)
      .width('93%')
      .height('84%')
      .align(Alignment.Top)
    }
    .width('100%')
    .height('100%')
  }

}