//添加或者编辑不良类型记录
import ProcessRequest from '../common/util/request/ProcessRequest';
import RequestParamModel from '../viewmodel/RequestParamModel';
import DictValue from '../viewmodel/DictValue';
import ProcessBaseBug from '../viewmodel/process/ProcessBaseBug';
import ProcessInfo from '../viewmodel/process/ProcessInfo';
import ProcessDefectRecord from '../viewmodel/process/ProcessDefectRecord';

@CustomDialog
export struct DefectRecordDialog {
  controller: CustomDialogController
  onConfirm: ()=> void = () => {}
  scroller: Scroller = new Scroller()

  //是否是编辑状态（需要传入的参数）
  @Prop isEdit: boolean = false
  //选择不良类型索引（需要传入的参数）
  @State selectDefectType: number = -1
  @Prop defectIndex:number
  //选择缺陷类型索引（需要传入的参数）
  @State selectedDefectBug: number= -1
  // 不良类型对应的缺陷
 // defectBugs: ProcessBaseBug[] = []
  // 不良类型对应的缺陷map（key为不良类型字典值，value为对应的缺陷）
  defectBugMap: Map<string, ProcessBaseBug[]> = new Map<string, ProcessBaseBug[]>()
  //不良类型
  @State defectTypeOptions: Array<SelectOption> = [
    { value: '外观缺陷', icon: '' },
    { value: '尺寸不良', icon: '' },
    { value: '功能异常', icon: '' },
    { value: '材料问题', icon: '' },
    { value: '装配问题', icon: '' },
    { value: '包装问题', icon: '' }
  ]
  //缺陷类型
  @State defectBugOptions: Array<SelectOption> = []

  defectRecord: ProcessDefectRecord = {}
  // 不良类型记录列表
  @Link defectRecords: ProcessDefectRecord[]
  // 备注
  @State defectRemark: string = ''

  //@Consume('currentUserName') currentUserName: string
  //@Consume('currentStationId') currentStationId: string
  seqNo: string = ''
  selectOperationId: string = ''
  process: ProcessInfo = {}

  // 刷新不良类型对应的缺陷
  private initDefectBugMap() {
    this.defectBugMap.set('外观缺陷', [
      { bugType: '外观缺陷', bugCode: 'A001-01', bugName: '划痕' },
      { bugType: '外观缺陷', bugCode: 'A001-02', bugName: '污渍' },
      { bugType: '外观缺陷', bugCode: 'A001-03', bugName: '色差' }
    ])

    this.defectBugMap.set('尺寸不良', [
      { bugType: '尺寸不良', bugCode: 'A002-01', bugName: '尺寸偏大' },
      { bugType: '尺寸不良', bugCode: 'A002-02', bugName: '尺寸偏小' }
    ])

    this.defectBugMap.set('功能异常', [
      { bugType: '功能异常', bugCode: 'A003-01', bugName: '功能失效' },
      { bugType: '功能异常', bugCode: 'A003-02', bugName: '性能不达标' }
    ])

    this.defectBugMap.set('材料问题', [
      { bugType: '材料问题', bugCode: 'A004-01', bugName: '材料裂纹' },
      { bugType: '材料问题', bugCode: 'A004-02', bugName: '材料变形' }
    ])

    this.defectBugMap.set('装配问题', [
      { bugType: '装配问题', bugCode: 'A005-01', bugName: '装配错位' },
      { bugType: '装配问题', bugCode: 'A005-02', bugName: '螺丝松动' }
    ])

    this.defectBugMap.set('包装问题', [
      { bugType: '包装问题', bugCode: 'A006-01', bugName: '包装破损' },
      { bugType: '包装问题', bugCode: 'A006-02', bugName: '标签错误' }
    ])
  }


    refreshDefectBugs() {
      // 清空当前缺陷类型选项
      this.defectBugOptions = []
      this.selectedDefectBug = -1
      // 检查是否有选中的不良类型
      if (this.selectDefectType === -1) {
        return
      }
      // 获取选中的不良类型值
      const selectedDefectType = this.defectTypeOptions[this.selectDefectType].value as string
      // 从映射中获取对应的缺陷列表
      const defectBugs = this.defectBugMap.get(selectedDefectType)

      if (defectBugs && defectBugs.length > 0) {
        // 将缺陷列表转换为SelectOption格式
        this.defectBugOptions = defectBugs.map((bug: ProcessBaseBug): SelectOption => {
          const option: SelectOption = {
            value: bug.bugName || '',
            icon: ''
          }
          return option
        })
        // 如果是编辑状态且有初始值，尝试匹配对应的缺陷
        if (this.isEdit && this.defectRecord.bugName) {
          const index = defectBugs.findIndex(bug => bug.bugName === this.defectRecord.bugName)
          if (index !== -1) {
            this.selectedDefectBug = index
          }
        }
      }
  }

  // 添加不良记录到列表
  private addDefectRecordToArray(record: ProcessDefectRecord) {
    // 添加新记录到数组
    this.defectRecords.push(record)
    // 触发数组更新（如果需要）
    this.defectRecords = [...this.defectRecords]
  }
  private isEditLoad(){
      if (this.isEdit && this.defectRecord) {
        this.defectRemark = this.defectRecord.remark || ''
        if (this.defectRecord.defectType) {
          const defectTypeIndex = this.defectTypeOptions.findIndex(
            option => option.value === this.defectRecord.defectType
          )
          if (defectTypeIndex !== -1) {
            this.selectDefectType = defectTypeIndex
          }
        }
        // 刷新缺陷类型选项并设置选中的缺陷类型
        this.refreshDefectBugs()
      }
  }


  private deleteDefectRecord() {
    if (!this.isEdit) {
      console.error('删除失败：不是编辑状态')
      return
    }
    // 从数组中删除记录 - 使用索引查找
    if (this.defectIndex >= 0 && this.defectIndex < this.defectRecords.length) {
      this.defectRecords.splice(this.defectIndex, 1)
      // 触发数组更新
      this.defectRecords = [...this.defectRecords]
      console.info('成功删除不良记录')
    } else {
      console.error('未找到要删除的记录，索引无效：' + this.defectIndex)
    }
  }


  aboutToAppear(): void {
    this.initDefectBugMap()
    this.isEditLoad()
  }
  build() {
    Column(){
      Column() {
        Text(this.isEdit ? '不良类型记录' : '添加不良类型记录')
          .fontColor($r('app.color.FFFFFF'))
          .fontSize($r('app.float.fontSize_30'))
      }
      .height('12%')
      .width('100%')
      .justifyContent(FlexAlign.Center)
      Column(){
        Text('不良类型')
          .fontSize($r('app.float.fontSize_16'))
          .fontColor($r('app.color.FFFFFF'))
        Select(this.defectTypeOptions)
          .height('16%')
          .width('100%')
          .borderRadius($r('app.float.virtualSize_16'))
          .selected(this.selectDefectType === -1 ? 0 : this.selectDefectType)
          .value(this.selectDefectType === -1 ? '请选择' : String(this.defectTypeOptions[this.selectDefectType].value))
          .backgroundColor($r('app.color.20FFFFFF'))
          .selectedOptionBgColor($r('app.color.20FFFFFF'))
          .fontColor(this.selectDefectType === -1 ? $r('app.color.30FFFFFF'):$r('app.color.FFFFFF'))
          .font({size:$r('app.float.fontSize_24')})
          .selectedOptionFont({
            size:$r('app.float.fontSize_24')
          })
          .onSelect((index: number) => {
            if (this.selectDefectType === index) {
              return
            }
            this.selectDefectType = index
            this.refreshDefectBugs()
          })
          .margin({top:'3%',bottom:'3%'})
        Text('缺陷名称')
          .fontSize($r('app.float.fontSize_16'))
          .fontColor($r('app.color.FFFFFF'))
        Select(this.defectBugOptions)
          .height('16%')
          .width('100%')
          .borderRadius($r('app.float.virtualSize_16'))
          .selected(this.selectedDefectBug === -1 ? 0 : this.selectedDefectBug)
          .value(this.selectedDefectBug === -1 ? '请选择' : String(this.defectBugOptions[this.selectedDefectBug]?.value ? this.defectBugOptions[this.selectedDefectBug]?.value : ''))
          .backgroundColor($r('app.color.20FFFFFF'))
          .selectedOptionBgColor($r('app.color.20FFFFFF'))
          .fontColor(this.selectedDefectBug === -1 ? $r('app.color.30FFFFFF'):$r('app.color.FFFFFF'))
          .font({size:$r('app.float.fontSize_24')})
          .selectedOptionFont({
            size:$r('app.float.fontSize_24')
          })
          .onSelect((index: number) => {
            this.selectedDefectBug = index
          })
          .margin({top:'3%',bottom:'3%'})
        Text('备注')
          .fontSize($r('app.float.fontSize_16'))
          .fontColor($r('app.color.FFFFFF'))
        TextArea({placeholder:'请录入不良详情', text: this.defectRemark})
          .backgroundColor($r('app.color.000000'))
          .height('40%')
          .width('100%')
          .fontColor($r('app.color.FFFFFF'))
          .placeholderColor($r('app.color.30FFFFFF'))
          .placeholderFont({size:$r('app.float.fontSize_16')})
          .fontSize($r('app.float.fontSize_16'))
          .textAlign(TextAlign.Start)
          .maxLength(200)
          .margin({top:'3%',bottom:'3%'})
          .borderRadius($r('app.float.virtualSize_16'))
          .onChange((value: string) => {
            this.defectRemark = value
          })
      }
      .width('70%')
      .height('80%')
      .margin({left:'15%',right:'15%'})
      .alignItems(HorizontalAlign.Start)
      if(this.isEdit){
        Column() {
          Divider()
            .vertical(false)
            .strokeWidth(1)
            .color($r('app.color.15FFFFFF'))
          Row() {
            Row() {
              Text('删除')
                .fontColor($r('app.color.FF453A'))
                .fontSize($r('app.float.fontSize_30'))
            }
            .justifyContent(FlexAlign.Center)
            .width('33.3%')
            .onClick(async () => {
              AlertDialog.show(
                {
                  title: '确认删除',
                  message: '确定要删除这条不良记录吗？',
                  primaryButton: {
                    value: '取消',
                    action: () => {
                      console.info('取消删除')
                    }
                  },
                  secondaryButton: {
                    value: '确定',
                    action: () => {
                      // 执行删除操作
                      this.deleteDefectRecord()
                      // 关闭对话框
                      if (this.controller) {
                        this.controller.close()
                      }
                      // 可以添加删除成功提示
                      // prompt.showToast({ message: '删除成功', duration: 2000 })
                    }
                  },
                  cancel: () => {
                    console.info('取消删除操作')
                  }
                }
              )
            })
            Divider()
              .vertical(true)
              .strokeWidth(1)
              .color($r('app.color.15FFFFFF'))
            Row() {
              Text('取消')
                .fontColor($r('app.color.60FFFFFF'))
                .fontSize($r('app.float.fontSize_30'))
            }
            .justifyContent(FlexAlign.Center)
            .width('33.3%')
            .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('33.3%')
            .onClick(async () => {
              const selectedDefectType = this.defectTypeOptions[this.selectDefectType].value as string
              const defectBugs = this.defectBugMap.get(selectedDefectType)

              if (!defectBugs || this.selectedDefectBug >= defectBugs.length) {
                return
              }

              const selectedDefectBug = defectBugs[this.selectedDefectBug]

              // 直接修改原对象（如果需要深拷贝，可以先复制）
              const recordToUpdate = this.defectRecords[this.defectIndex]
              recordToUpdate.remark = this.defectRemark
              recordToUpdate.defectType = selectedDefectBug.bugType!
              recordToUpdate.bugName = selectedDefectBug.bugName!

              // 使用splice触发更新（或者重新赋值数组）
              this.defectRecords.splice(this.defectIndex, 1, recordToUpdate)
              this.defectRecords = [...this.defectRecords] // 重新赋值触发更新

              if (this.controller) {
                this.controller.close()
              }
            })
          }
        }
        .width('100%')
        .height('8%')
      }else{
        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 () => {
              this.defectRecord.remark = this.defectRemark
              const selectedDefectType = this.defectTypeOptions[this.selectDefectType].value as string
              const defectBugs = this.defectBugMap.get(selectedDefectType)
              if (!defectBugs ) {
                return
              }
              const selectedDefectBug = defectBugs[this.selectedDefectBug]
              this.defectRecord.defectType = selectedDefectBug.bugType!
              this.defectRecord.bugName = selectedDefectBug.bugName!
              this.addDefectRecordToArray(this.defectRecord)
              if (this.controller) {
                this.controller.close()
              }
            })
          }
        }
        .width('100%')
        .height('8%')
      }
    }
    .height('71%')
    .width('30%')
    .backgroundColor($r('app.color.2A2A2A'))
    .justifyContent(FlexAlign.End)
    .alignItems(HorizontalAlign.Start)
    .borderColor($r('app.color.000000'))
    .borderWidth(1)
    .borderRadius($r('app.float.virtualSize_16'))
  }
}