//添加不良类型记录或者编辑不良类型
import ProcessRequest from '../common/util/request/ProcessRequest';
import { BindTaskSeqVO } from '../viewmodel/BindTaskSeqVO';
import TaskSeqVO from '../viewmodel/process/TaskSeqInfo';
import RequestParamModel from '../viewmodel/RequestParamModel';
import { Font } from '@ohos.arkui.UIContext';
import DictValue from '../viewmodel/DictValue';
import ProcessEscalationFault from '../viewmodel/process/ProcessEscalationFault';
import ProcessBaseBug from '../viewmodel/process/ProcessBaseBug';
import ProcessInfo from '../viewmodel/process/ProcessInfo';

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

  //是否是编辑状态（需要传入的参数）
  @Prop isEdit: boolean = false
  //选择不良类型索引（需要传入的参数）
  @Prop selectDefectType: number = -1
  //选择缺陷类型索引（需要传入的参数）
  @Prop selectedDefectBug: number= -1
  // 不良类型（数据字典）
  @Prop defectTypes: DictValue[] = []
  // 不良类型对应的缺陷
  defectBugs: ProcessBaseBug[] = []
  // 不良类型对应的缺陷map（key为不良类型字典值，value为对应的缺陷）
  defectBugMap: Map<string, ProcessBaseBug[]> = new Map<string, ProcessBaseBug[]>()
  //不良类型
  @State defectTypeOptions: Array<SelectOption> = []
  //缺陷类型
  @State defectBugOptions: Array<SelectOption> = []
  // 如果是修改需要从自检页面传过来
  @State defectRecord: ProcessEscalationFault = {}
  // 不良类型记录列表
  @Link defectRecords: ProcessEscalationFault[]
  // 备注
  @State defectRemark: string = ''

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

  // 刷新不良类型对应的缺陷
  async refreshDefectBugs() {
    let defectTypeValue: string = this.defectTypes[this.selectDefectType]?.dictValue!
    this.defectBugOptions = []
    if (this.defectBugMap.has(defectTypeValue)) {
      this.defectBugs = this.defectBugMap.get(defectTypeValue)!
    } else {
      this.defectBugs = await ProcessRequest.post('/api/v1/op/baseBug/list', {
        bugType: defectTypeValue
      } as RequestParamModel)
      this.defectBugMap.set(defectTypeValue, this.defectBugs)
    }
    // 遍历封装缺陷下拉选择框
    for (let i = 0; i < this.defectBugs.length; i++) {
      this.defectBugOptions.push({value: this.defectBugs[i].bugName!})
    }
    this.selectedDefectBug = 0;
  }
  // 刷新不良类型记录列表
  async refreshDefectRecords() {
    this.defectRecords = []
    this.defectRecords = await ProcessRequest.post('/api/v1/process/escalationFault/list', {
      seqNo: this.seqNo
    } as RequestParamModel)
    if (this.defectRecords && this.defectTypes) {
      for (const element of this.defectRecords) {
        if (element.reasonList) {
          for (const dict of this.defectTypes) {
            if (element.reasonList[0].bugType === dict.dictValue) {
              element.reasonList[0].bugTypeLabel = dict.dictLabel
              break
            }
          }
        }
      }
    }
  }

  async aboutToAppear() {
    for (let i = 0; i < this.defectTypes.length; i++) {
      this.defectTypeOptions.push({value: this.defectTypes[i].dictLabel!})
    }
    // 新增时，默认选中第一个不良类型及其第一种缺陷
    if (!this.isEdit && this.defectTypes) {
      this.defectRecord = {}
      this.selectDefectType = 0
      this.defectBugs = await ProcessRequest.post('/api/v1/op/baseBug/list', {
        bugType: this.defectTypes[0].dictValue!
      } as RequestParamModel)
      this.defectBugMap.set(this.defectTypes[0].dictValue!, this.defectBugs)
      for (let i = 0; i < this.defectBugs.length; i++) {
        this.defectBugOptions.push({value: this.defectBugs[i].bugName!})
      }
      this.selectedDefectBug = 0;
    } else if (this.isEdit && this.defectRecord && this.defectRecord.reasonList) {
      this.defectRemark = this.defectRecord.remark ? this.defectRecord.remark : ''
      // 修改时，不良类型、缺陷名称直接选中
      let defectTypeValue: string = this.defectRecord.reasonList[0].bugType!
      // 不良类型选中
      for (let i = 0; i < this.defectTypes.length; i++) {
        if (defectTypeValue === this.defectTypes[i].dictValue!) {
          this.selectDefectType = i;
          break
        }
      }
      // 查询不良类型下所有的缺陷
      let defectBugCode: string = this.defectRecord.reasonList[0].bugCode!
      this.defectBugs = await ProcessRequest.post('/api/v1/op/baseBug/list', {
        bugType: defectTypeValue
      } as RequestParamModel)
      this.defectBugMap.set(defectTypeValue, this.defectBugs)
      // 缺陷名称选中
      for (let i = 0; i < this.defectBugs.length; i++) {
        this.defectBugOptions.push({value: this.defectBugs[i].bugName!})
        if (defectBugCode === this.defectBugs[i].bugCode) {
          this.selectedDefectBug = i;
          break
        }
      }
    }
  }

  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 () => {
              await ProcessRequest.post('/api/v1/process/escalationFault/del', {
                id: this.defectRecord.id!
              } as RequestParamModel)
              // 重新刷新不良类型记录列表
              this.refreshDefectRecords()
              if (this.controller) {
                this.controller.close()
              }
            })
            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 () => {
              this.defectRecord.remark = this.defectRemark
              if (this.defectRecord.reasonList) {
                this.defectRecord.reasonList[0].bugType = this.defectBugs[this.selectedDefectBug].bugType!
                this.defectRecord.reasonList[0].bugCode = this.defectBugs[this.selectedDefectBug].bugCode!
                this.defectRecord.reasonList[0].bugName = this.defectBugs[this.selectedDefectBug].bugName!
                this.defectRecord.reasonList = [...this.defectRecord.reasonList]
              }
              await ProcessRequest.post('/api/v1/process/escalationFault/updateRemarkAndDefect', this.defectRecord)
              // 重新刷新不良类型记录列表
              this.refreshDefectRecords()
              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.processId = this.process.id!
              this.defectRecord.seqNoList = [this.seqNo]
              this.defectRecord.reasonList = [this.defectBugs[this.selectedDefectBug]]
              this.defectRecord.processesList = [this.selectOperationId]
              this.defectRecord.personResponsible = this.currentUserName
              this.defectRecord.remark = this.defectRemark
              this.defectRecord.stationId = this.currentStationId
              await ProcessRequest.post('/api/v1/process/escalationFault/add', this.defectRecord)
              // 重新刷新不良类型记录列表
              this.refreshDefectRecords()
              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'))
  }
}