import ProcessRequest from '../../common/util/request/ProcessRequest'
import ProcessCheck from '../../viewmodel/process/ProcessCheck'
import ProcessInfo from '../../viewmodel/process/ProcessInfo'
import RequestParamModel from '../../viewmodel/RequestParamModel'
import promptAction from '@ohos.promptAction'
import PageInfo from '../../viewmodel/PageInfo'
import { AddUnqualifiedRecordDialog } from '../AddUnqualifiedRecordDialog'
import DictValue from '../../viewmodel/DictValue'
import ProcessEscalationFault from '../../viewmodel/process/ProcessEscalationFault'

@Component
export struct SelfInspectView {
  // 点检列表
  @State checkArray: ProcessCheck[] = []
  @State selectCheck: number = -1
  // 不良类型记录列表
  @State defectRecords: ProcessEscalationFault[] = []
  // 不良类型（数据字典）
  @State defectTypes: DictValue[] = []
  // 扫码开工状态(0:未开工 1:已开工)
  @Link @Watch('queryByScanState') scanState: number
  // 当前流转卡号
  @Link seqNo: string
  // 选中工序id
  @Link selectOperationId: string
  // 扫码开工后的生产过程信息
  @Link process: ProcessInfo
  // 是否是修改不良类型记录
  editDefectRecord: boolean = false
  // 修改时选中的不良类型记录
  selectDefectRecord: ProcessEscalationFault = {}

  defectTypeDictCode: string = 'defect_mana'

  // 根据开工状态查询 工序点检项/工序点检历史操作
  async queryByScanState() {
    if (this.scanState === 1) {
      this.checkArray = await ProcessRequest.post('/api/v1/process/check/list', {
        operationId: this.selectOperationId,
        processId: this.process.id!,
        seqNo: this.seqNo
      } as RequestParamModel)
    } else {
      let result = await ProcessRequest.post('/api/v1/op/operationCheck/page', {
        operationId: this.selectOperationId,
        pageNo: 1,
        pageSize: 999999
      } as RequestParamModel) as PageInfo;
      this.checkArray = result.records as ProcessCheck[] || []
    }
  }

  async aboutToAppear() {
    this.queryByScanState()
    this.defectTypes = await ProcessRequest.get(`/api/v1/sys/dictData/queryByType/${this.defectTypeDictCode}`)
    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
            }
          }
        }
      }
    }
  }

  build() {
    Row() {
      // 点检
      Column() {
        Row() {
          Text('点检列表')
            .fontSize($r('app.float.fontSize_24'))
            .fontWeight(FontWeight.Medium)
            .fontColor($r('app.color.FFFFFF'))
        }
        .height('10.2%')
        .width('100%')

        List({space: 6}) {
          ForEach(this.checkArray, (item: ProcessCheck, index: number) => {
            ListItem() {
              Column() {
                Row() {
                  Text(item.checkName ? item.checkName : '')
                    .fontSize($r('app.float.fontSize_24'))
                    .fontWeight(FontWeight.Medium)
                    .fontColor($r('app.color.FFFFFF'))
                  Row() {
                    Text('检查确认')
                      .fontSize($r('app.float.fontSize_16'))
                      .fontWeight(FontWeight.Regular)
                      .fontColor($r('app.color.FFFFFF'))
                    Toggle({ type: ToggleType.Switch, isOn: item.result === '1' ? true : false })
                      .selectedColor($r('app.color.30D158'))
                      .switchPointColor($r('app.color.FFFFFF'))
                      .onChange(async (isOn: boolean) => {
                        this.selectCheck = index
                        if (this.scanState === 0) {
                          promptAction.showToast({
                            message: '工序未开工，请先开工',
                            duration: 1500,
                            bottom: 100
                          })
                          return
                        }
                        await ProcessRequest.post('/api/v1/process/check/update', {
                          id: item.id,
                          result: isOn ? '1': '2'
                        } as RequestParamModel)
                      })
                  }
                  .height('100%')
                }
                .width('95.3%')
                .justifyContent(FlexAlign.SpaceBetween)
                .height($r('app.float.virtualSize_88'))
                Column() {
                  Text('点检内容：' + item.content ? item.content : '')
                    .fontSize($r('app.float.fontSize_16'))
                    .fontWeight(FontWeight.Lighter)
                    .fontColor($r('app.color.FFFFFF'))
                  Text('标准值：' + item.standard ? item.standard : '')
                    .fontSize($r('app.float.fontSize_16'))
                    .fontWeight(FontWeight.Lighter)
                    .fontColor($r('app.color.FFFFFF'))
                  Text('上限值：' + (item.upper ? item.upper : ' '))
                    .fontSize($r('app.float.fontSize_16'))
                    .fontWeight(FontWeight.Lighter)
                    .fontColor($r('app.color.FFFFFF'))
                  Text('下限值：' + (item.lower ? item.lower : ' '))
                    .fontSize($r('app.float.fontSize_16'))
                    .fontWeight(FontWeight.Lighter)
                    .fontColor($r('app.color.FFFFFF'))
                }
                .width('95.3%')
                .alignItems(HorizontalAlign.Start)
              }
              .borderRadius($r('app.float.virtualSize_16'))
              .backgroundColor(this.selectCheck === index ? $r('app.color.2030D158') : $r('app.color.10FFFFFF'))
              .width('100%')
              .onClick(()=>{
                this.selectCheck = index
              })
            }
          })
        }
        .width('100%')
        .height('87.6%')
        .alignListItem(ListItemAlign.Center)
      }
      .height('100%')
      .width('59%')
      Divider()
        .vertical(true)
        .strokeWidth(1)
        .color($r('app.color.15FFFFFF'))
        .height('100%')
        .padding({top: '5.3%', bottom: '2.2%'})
      // 不良类型记录
      Column() {
        Row() {
          Text('不良类型记录')
            .fontSize($r('app.float.fontSize_24'))
            .fontWeight(FontWeight.Medium)
            .fontColor($r('app.color.FFFFFF'))
        }
        .height('10.2%')
        .width('100%')
        // 添加不良类型
        Row({space: 4}) {
          Image($r("app.media.general_create"))
            .width($r('app.float.virtualSize_24'))
            .height($r('app.float.virtualSize_24'))
            .fillColor($r('app.color.0A84FF'))
          Text('添加')
            .fontColor($r('app.color.0A84FF'))
            .fontSize($r('app.float.fontSize_24'))
            .fontWeight(FontWeight.Medium)
        }
        .width('28.2%')
        .height('7.1%')
        .justifyContent(FlexAlign.Center)
        .backgroundColor($r('app.color.20FFFFFF'))
        .borderRadius($r('app.float.fontSize_16'))
        .onClick(()=>{
          if(this.scanState === 0) {
            promptAction.showToast({
              message: '工序未开工，请先开工',
              duration: 1500,
              bottom: 100
            })
            return
          }
          this.addUnqualifiedRecordController.open()
        })
        // 不良类型记录列表
        List({space: 6}) {
          ForEach(this.defectRecords, (item: ProcessEscalationFault, index: number) => {
            ListItem() {
              Column() {
                Text(item.reasonList ? item.reasonList[0].bugTypeLabel! + '（' + item.reasonList[0].bugName! + '）' : '')
                  .fontColor($r('app.color.FFFFFF'))
                  .fontSize($r('app.float.fontSize_16'))
                  .fontWeight(FontWeight.Bold)
                  .height($r('app.float.virtualSize_48'))
                Text('备注：' + (item.remark ? item.remark : ''))
                  .fontColor($r('app.color.FFFFFF'))
                  .fontSize($r('app.float.fontSize_16'))
                  .fontWeight(FontWeight.Lighter)
                  .padding({bottom: 10})
              }
              .width('92%')
              .alignItems(HorizontalAlign.Start)
            }
            .backgroundColor($r('app.color.20FFFFFF'))
            .borderRadius($r('app.float.fontSize_16'))
            .width('100%')
            .onClick(()=>{
              this.selectDefectRecord = item
              this.editDefectRecord = true
              this.addUnqualifiedRecordController.open()
            })
          })
        }
        .width('100%')
        .height('77.9%')
        .alignListItem(ListItemAlign.Center)
        .margin({top: 10})
      }
      .height('100%')
      .width('35.4%')
      .alignItems(HorizontalAlign.Start)
    }
    .width('100%')
    .height('100%')
    .justifyContent(FlexAlign.SpaceEvenly)
    .alignItems(VerticalAlign.Top)
  }

  // 添加不良类型记录弹窗
  addUnqualifiedRecordController: CustomDialogController = new CustomDialogController({
    builder: AddUnqualifiedRecordDialog({
      isEdit: this.editDefectRecord,
      defectTypes: this.defectTypes,
      defectRecord: this.selectDefectRecord,
      seqNo: this.seqNo,
      selectOperationId: this.selectOperationId,
      process: this.process,
      defectRecords: this.defectRecords,
    }),
    autoCancel: true, // 点击遮罩关闭
    customStyle: true,
    alignment:DialogAlignment.Center,
    maskColor: 'rgba(0,0,0,0.8)',  // 黑色遮罩
  })
}