//零星叫料
import ProcessRequest from '../common/util/request/ProcessRequest'
import MaterialInfo from '../viewmodel/MaterialInfo'
import PageInfo from '../viewmodel/PageInfo'
import RequestParamModel from '../viewmodel/RequestParamModel'

@CustomDialog
export struct LittleMaterialRequestDialog {
  private scrollerMaterial: Scroller = new Scroller()
  //物料配件列表
  @State materialTypesList: MaterialInfo[] = [];
  //监控选中的索引
  @State @Watch('onSelectedIndexesChange') selectedIndexes: number[] = [];
  //选中物料
  @State selectMaterials:MaterialInfo[]=[]
  //查询物料名字
  @State queryMaterialName: string = ''
  //物料map(名称,数量)
  @State materialNumMap: Record<string, number> = {};

  //实时更新选中物料
  onSelectedIndexesChange() {
    this.selectMaterials = this.selectedIndexes.map(index => this.materialTypesList[index]);
  }
  controller: CustomDialogController
  onConfirm: () => void = () => {}

  //加载物料配件类型
  loadMaterialTypes = async () => {
    let res = await ProcessRequest.post('/api/v1/base/material/page',
      {
        materialName: this.queryMaterialName
      }  as RequestParamModel) as PageInfo;
    this.materialTypesList = res.records as MaterialInfo[] || []
    //初始所有物料数量为0
    this.materialTypesList.forEach(item => {
      this.materialNumMap[item.materialName??''] = 0;
    });
  };


  private onDeleteMaterial(item: MaterialInfo) {
    // 找到物料在已选列表中的索引
    const selectedIndex = this.selectMaterials.findIndex(m => m.materialName === item.materialName);
    if (selectedIndex !== -1) {
      // 从已选列表中移除
      this.selectMaterials.splice(selectedIndex, 1);
      this.selectMaterials = [...this.selectMaterials]; // 触发状态更新
      // 找到物料在总列表中的索引
      const materialIndex = this.materialTypesList.findIndex(m => m.materialName === item.materialName);
      if (materialIndex !== -1) {
        // 从选中索引中移除
        this.selectedIndexes = this.selectedIndexes.filter(i => i !== materialIndex);
      }
    }
  }

  private onSelectMaterial(index: number) {
    if (this.selectedIndexes.includes(index)) {
      this.selectedIndexes = this.selectedIndexes.filter(i => i !== index);
    } else {
      this.selectedIndexes = [index, ...this.selectedIndexes];
    }
  }
  aboutToAppear(): void {
    this.loadMaterialTypes()
  }

  sendMaterialRequest=async()=>{
    let res = await ProcessRequest.post('/api/v1/process/vehicleOperation/sporadicCallItem',
      {
        // materialName: this.queryMaterialName
      }  as RequestParamModel) as PageInfo;
  }

  build() {
    Column() {
      Column() {
        Text("零星叫料")
          .fontColor($r('app.color.FFFFFF'))
          .fontSize($r('app.float.fontSize_30'))
      }
      .height('8%')
      .width('100%')
      .justifyContent(FlexAlign.Center)

      Row(){
        Column() {
          Text("查询物料")
            .fontColor($r('app.color.FFFFFF'))
            .fontSize($r('app.float.fontSize_24'))
          Row() {
            TextInput({ text: this.queryMaterialName, 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)
              .width('84%')
              .onChange((value: string) => {
                this.queryMaterialName = value
                this.loadMaterialTypes()
              })
            Row() {
              Image($r('app.media.process_search'))
                .width($r('app.float.virtualSize_48'))
                .height($r('app.float.virtualSize_48'))
                .fillColor($r('app.color.0A84FF'))
                .onClick(() => {
                  this.loadMaterialTypes()
                })
            }
            .width('16%')
            .height('100%')
            .justifyContent(FlexAlign.Center)
            .borderRadius($r('app.float.virtualSize_16'))
            .backgroundColor($r('app.color.20FFFFFF'))
          }
          .height('8%')
          .width('60%')
          .margin({bottom:'2%',top:'2%'})
          .borderRadius($r('app.float.virtualSize_16'))
          .backgroundColor($r('app.color.000000'))
          List({ scroller: this.scrollerMaterial }) {
            ForEach(this.materialTypesList, (item: MaterialInfo, index) => {
              ListItem() {
                Row() {
                  Column({space:5}){
                    Text(`${item.materialName}`)
                      .fontSize($r('app.float.fontSize_16'))
                      .fontColor($r('app.color.FFFFFF'))
                    Text(`${item.spec}`)
                      .fontSize($r('app.float.fontSize_12'))
                      .fontColor($r('app.color.FFFFFF'))
                      .fontWeight(FontWeight.Lighter)
                  }
                  .width('90%')
                  .height('100%')
                  .justifyContent(FlexAlign.Center)
                  .alignItems(HorizontalAlign.Start)
                  Column(){
                    Text(`${item.unitDictValue}`)
                      .fontSize($r('app.float.fontSize_16'))
                      .fontColor($r('app.color.FFFFFF'))
                      .fontWeight(FontWeight.Lighter)
                  }
                  .width('10%')
                  .height('100%')
                  .justifyContent(FlexAlign.Center)

                }
                .height('90%')
                .width('95%')
                .margin({ left: '2%' })
                .justifyContent(FlexAlign.Center)
              }
              .height('10%')
              .width('100%')
              .margin({ bottom: 8})
              .borderRadius($r('app.float.virtualSize_16'))
              .backgroundColor(
                this.selectedIndexes.includes(index) ?
                $r('app.color.2030D158') :
                $r('app.color.20FFFFFF')
              )
              .border({
                width: this.selectedIndexes.includes(index) ? 2 : 0,
                color: this.selectedIndexes.includes(index) ?
                $r('app.color.2030D158') :
                $r('app.color.20FFFFFF')
              })
              .onClick(() => {
                this.onSelectMaterial(index)
              })
            })
          }
          .width('100%')
          .height('82%')
        }
        .width('50%')
        .alignItems(HorizontalAlign.Start)
        .justifyContent(FlexAlign.Start)
        .margin({left:'2%'})
        .height('100%')
        Image($r('app.media.arrow_right'))
          .width($r('app.float.virtualSize_48'))
          .height($r('app.float.virtualSize_48'))
          .fillColor($r('app.color.FFFFFF'))
          .margin({left:'2%',right:'2%'})
        Column() {
          Row(){
           Text("已选物料")
            .fontColor($r('app.color.FFFFFF'))
            .fontSize($r('app.float.fontSize_24'))
          }
          .width('100%')
          .height('6%')
          .justifyContent(FlexAlign.Start)
          List({ scroller: this.scrollerMaterial }) {
            ForEach(this.selectMaterials, (item: MaterialInfo) => {
              ListItem() {
                Column(){
                  Row(){
                    Column({space:5}){
                      Text(`${item.materialName}`)
                        .fontSize($r('app.float.fontSize_24'))
                        .fontColor($r('app.color.FFFFFF'))
                      Text(`${item.spec}`)
                        .fontSize($r('app.float.fontSize_16'))
                        .fontColor($r('app.color.FFFFFF'))
                        .fontWeight(FontWeight.Lighter)
                    }
                    .width('86%')
                    .alignItems(HorizontalAlign.Start)
                    Column(){
                      Image($r('app.media.process_delete_seq'))
                        .width($r('app.float.virtualSize_48'))
                        .height($r('app.float.virtualSize_48'))
                        .fillColor($r('app.color.FF453A'))
                        .onClick(()=>{
                          this.onDeleteMaterial(item)
                        })
                    }
                    .width('14%')
                    .alignItems(HorizontalAlign.End)
                  }
                  .height('38%')
                  Text(`数量(${item.unitDictValue})`)
                    .fontSize($r('app.float.fontSize_16'))
                    .fontColor($r('app.color.FFFFFF'))
                    .margin({bottom:'1%'})
                    .width('100%')
                    .textAlign(TextAlign.Start)
                  Column(){
                    AddAndSubButton({
                      materialNum:this.materialNumMap[item.materialName??''],
                      onChange: (num: number) => {
                        this.materialNumMap[item.materialName??''] = num
                      }
                    })
                  }
                  .height('52%')
                  .width('100%')
                  .margin({bottom:'2%'})
                }
                .height('100%')
                .width('100%')
                .alignItems(HorizontalAlign.Start)
              }
              .height('30%')
              .width('100%')
              .margin({ bottom: 8})
            })
          }
          .width('95%')
          .height('92%')
          .divider({
            strokeWidth:1,
            color:$r('app.color.15FFFFFF')
          })
        }
        .width('40%')
        .alignItems(HorizontalAlign.Start)
        .justifyContent(FlexAlign.Start)
        .height('100%')

      }
      .height('84%')
      .width('100%')

      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.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
struct AddAndSubButton {
  @State addClick: number = 1
  @State subClick: number = 1
  @Prop materialNum: number
  onChange: (num: number) => void = () => {}
  handleValueChange(delta: number) {
    const newNum = this.materialNum + delta
    if (newNum >= 0) {
      this.onChange(newNum)
    }
  }

  build() {
    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'))
        .scale({ x: this.addClick, y: this.addClick })
        .animation({
          duration: 200,
          curve: Curve.Linear
        })
        .onClick(() => {
          this.addClick = 0.9;
          setTimeout(() => {
            this.addClick = 1;
            if(this.materialNum>0)
            {
              this.handleValueChange(-1)
            }
          }, 200);
        })
      }.width('22%')

      Row() {
        Text(String(this.materialNum))
          .fontColor($r('app.color.FFFFFF'))
          .fontSize($r('app.float.fontSize_38'))
      }
      .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'))
        .scale({ x: this.subClick, y: this.subClick })
        .animation({
          duration: 200,
          curve: Curve.Linear
        })
        .onClick(() => {
          this.subClick = 0.9;
          setTimeout(() => {
            this.subClick = 1;
            this.handleValueChange(1)
          }, 200);
        })
      }.width('22%')
    }.width('100%')
    .height('100%')
    .backgroundColor($r('app.color.10FFFFFF'))
    .borderRadius($r('app.float.virtualSize_16'))
  }
}