//切换产品
import CommonConstants from '../common/constants/CommonConstants'
import ProcessRequest from '../common/util/request/ProcessRequest'
import OperationComponent from '../viewmodel/process/OperationComponent'
import ProcessInfo from '../viewmodel/process/ProcessInfo'
import TaskSeqVO from '../viewmodel/process/TaskSeqInfo'
import RequestParamModel from '../viewmodel/RequestParamModel'
import WorkOrderInfo from '../viewmodel/WorkOrderInfo'

@CustomDialog
export struct SwitchingProductDialog{
  private scrollerList: Scroller = new Scroller()
  //查询报工
  @State queryTaskSeq: TaskSeqVO[] = []
  //选中的工单
  @State selectWorkOder: WorkOrderInfo = {}
  //当前工序号
  @Prop currentOperationId:string = ''
  //当前工位
  @Prop currentStationId:string = ''
  //当前工序已报工数量
  @State reportedNum:number = 0
  //计划报工数量
  @State planReportNum:number = 0
  //选择的按钮索引(默认加载全部)
  @State selectedButtonIndex: number = 0
  //工步
  @Link opComponents: OperationComponent[]
  //扫描的流水号/序列/铭牌号
  @Link scanSeqValue: string
  // 扫码开工后的生产过程信息
  @Link process: ProcessInfo
  // 扫码开工状态(0:未开工 1:已开工)
  @Link scanState: number

  controller: CustomDialogController
  onQueryTask = async (currentStateList: Array<number>): Promise<number> => {
    let res = await ProcessRequest.post('/api/v1/plan/seq/list', {
      stationId:this.currentStationId,
      workOrderCode:this.selectWorkOder.workOrderCode,
      operationId:this.currentOperationId,
      stateList:currentStateList
    } as RequestParamModel) as TaskSeqVO[];
    this.queryTaskSeq = res
    return res.length
  }

  onSwitchProduct=async ()=> {
    if (!this.selectWorkOder.workOrderCode || !this.currentStationId) {
      return
    }
    this.opComponents = await ProcessRequest.get('/api/v1/op/compent/get/' + this.currentOperationId)
    if (this.opComponents) {
      for (const element of this.opComponents) {
        if (CommonConstants.OPERATION_COMPONENT_TYPE.has(element.compentType??'')) {
          element.compentType = CommonConstants.OPERATION_COMPONENT_TYPE.get(element.compentType??'')
        }
      }
    }
  }

  handleAllClick():void {
    this.onQueryTask([])
  }

  handleReportedClick():void{
    this.onQueryTask([2])
  }

  handleUnreportedClick():void{
    this.onQueryTask([-1,0,1])
  }

  async aboutToAppear() {
    this.reportedNum = await this.onQueryTask([2]);
    this.planReportNum = await this.onQueryTask([]);
  }

  @Builder
  buildButton(index: number, text: string,onClick: () => void) {
    Row(){
      if(this.selectedButtonIndex === index)
      {
        Image($r('app.media.process_radio_check'))
          .width($r('app.float.virtualSize_24'))
          .height($r('app.float.virtualSize_24'))
          .fillColor($r('app.color.0A84FF'))
      }else{
        Image($r('app.media.process_radio_no_check'))
          .width($r('app.float.virtualSize_24'))
          .height($r('app.float.virtualSize_24'))
          .fillColor($r('app.color.FFFFFF'))
      }
      Row(){}.width('10%')
      Text(text)
        .fontSize($r('app.float.fontSize_16'))
        .fontColor($r('app.color.FFFFFF'))
    }
    .justifyContent(FlexAlign.Center)
    .width('31%')
    .height('100%')
    .backgroundColor(this.selectedButtonIndex === index ? $r('app.color.200A84FF') : $r('app.color.20FFFFFF')) // 选中蓝/未选中灰
    .borderRadius($r('app.float.virtualSize_16'))
    .margin({ right:'3%'})
    .onClick(() => {
      this.selectedButtonIndex = index
      onClick();
    })
  }

  build() {
    Column() {
      Column() {
        Text("切换产品")
          .fontColor($r('app.color.FFFFFF'))
          .fontSize($r('app.float.fontSize_30'))
      }
      .height('8%')
      .width('100%')
      .justifyContent(FlexAlign.Center)

     Row(){
       Column(){
         Row(){
           Column({space:3}){
             Text(this.selectWorkOder.materialName)
               .fontSize($r('app.float.fontSize_24'))
               .fontColor($r('app.color.FFFFFF'))
             Text(this.selectWorkOder.materialCode)
               .fontSize($r('app.float.fontSize_12'))
               .fontColor($r('app.color.FFFFFF'))
               .fontWeight(FontWeight.Lighter)
             Row(){
               Text("工单 ")
                 .fontSize($r('app.float.fontSize_16'))
                 .fontColor($r('app.color.FFFFFF'))
                 .fontWeight(FontWeight.Lighter)
               Text(this.selectWorkOder.workOrderCode)
                 .fontSize($r('app.float.fontSize_16'))
                 .fontColor($r('app.color.FFFFFF'))
             }
           }
           .height('100%')
           .width('70%')
           .justifyContent(FlexAlign.End)
           .alignItems(HorizontalAlign.Start)
           Column(){
             Row(){
               Text(`${this.reportedNum}/`)
                 .fontSize($r('app.float.fontSize_38'))
                 .fontColor($r('app.color.FFFFFF'))
               Text(`${this.planReportNum}`)
                 .fontSize($r('app.float.fontSize_38'))
                 .fontColor($r('app.color.60FFFFFF'))
             }
             Text('当前工序已报工/计划')
               .fontSize($r('app.float.fontSize_12'))
               .fontColor($r('app.color.FFFFFF'))
               .fontWeight(FontWeight.Lighter)

           }
           .height('100%')
           .width('30%')
           .justifyContent(FlexAlign.End)
           .alignItems(HorizontalAlign.End)
         }
         .height('10%')
         .width('100%')
         Row(){
           Row() {
             this.buildButton(0, '全部', () => this.handleAllClick())
             this.buildButton(1, '已报工', () => this.handleReportedClick())
             this.buildButton(2, '未报工', () => this.handleUnreportedClick())
           }.width('100%')
           .height('55%')
         }
         .height('10%')
         .width('80%')
         .margin({right:'20%'})
         .justifyContent(FlexAlign.Start)
         Column(){
           List({space: 8, scroller:this.scrollerList}) {
             ForEach(this.queryTaskSeq, (item:TaskSeqVO) => {
               ListItem() {
                 taskSeqItem({
                   item:item,
                   scanSeqValue:this.scanSeqValue,
                   selectedButtonIndex:this.selectedButtonIndex
                 })
                   .onClick(()=>{
                     this.scanSeqValue = item.seqNo!
                   })
               }
             })
           }
           .width('100%')
           .height('100%')
         }
         .height('80%')
         .width('100%')

       }
       .height('100%')
       .width('46%')
       Divider()
         .vertical(true)
         .strokeWidth(1)
         .color($r('app.color.15FFFFFF'))
         .margin({ bottom: '2%'})
       Column(){
         Text("扫描流水/序列/铭牌号")
           .fontSize($r('app.float.fontSize_16'))
           .fontColor($r('app.color.FFFFFF'))
           .margin({left:'22%'})
         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'))
             .objectFit(ImageFit.Contain)
             .margin({left:'2%'})
           // 扫码输入框
           TextInput({text:this.scanSeqValue, 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(() => {

             })
             .onChange((value: string) => {
               this.scanSeqValue = value;
             })
         }
         .height('6%')
         .width('60%')
         .borderRadius($r('app.float.virtualSize_16'))
         .backgroundColor($r('app.color.000000'))
         .margin({top:'2%',bottom:'5%',left:'20%'})
       }
       .justifyContent(FlexAlign.Center)
       .alignItems(HorizontalAlign.Start)
       .width('46%')
       .height('100%')
     }
      .justifyContent(FlexAlign.SpaceEvenly)
      .width('100%')
      .height('81%')
      .margin({ top: '2%'})

      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(() => {
            this.scanState = 0
            this.process = {}
            this.onSwitchProduct();
            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'))
  }
}

@Component
export struct taskSeqItem{
  @Prop item: TaskSeqVO
  @Link scanSeqValue:string
  @State scaleValue : number = 1
  @Link selectedButtonIndex:number
  build() {
    Row() {
      Text('S/N ')
        .fontSize($r('app.float.fontSize_16'))
        .fontColor($r('app.color.FFFFFF'))
        .fontWeight(FontWeight.Lighter)
        .margin({ left:'2%'})
      Text(this.item.seqNo)
        .fontSize($r('app.float.fontSize_16'))
        .fontColor($r('app.color.FFFFFF'))
        .textAlign(TextAlign.Start)
      Blank()
      if(this.selectedButtonIndex != 2) {
        Text(this.item.state! === '2' ? `报工时间：${this.item.updated}` : '')
          .fontSize($r('app.float.fontSize_16'))
          .fontColor($r('app.color.60FFFFFF'))
          .fontWeight(FontWeight.Lighter)
          .margin({ right:'2%'})
      }
    }.width('100%')
    .justifyContent(FlexAlign.Start)
    .backgroundColor($r('app.color.20FFFFFF'))
    .padding(10)
    .borderRadius($r('app.float.virtualSize_16'))
    .scale({ x: this.scaleValue, y: this.scaleValue })
    .animation({
      duration: 200,
      curve: Curve.Linear  // 弹性曲线更生动
    })
    .onClick(() => {
      this.scaleValue = 0.9;  // 点击时缩小
      setTimeout(() => {
        this.scanSeqValue = this.item?.seqNo??''
        this.scaleValue = 1;
      }, 200);
    })
  }
}

