<template>
  <div class="label-studio-annotator">
    <div class="button-container">
      <el-button type="success" plain size="small"
                 :disabled="this.fileAnnotationStatus === '2' || this.annotations ===null" @click="agreement(1)"
      >
        通过
      </el-button>
      <el-button type="danger" plain size="small"
                 :disabled="this.fileAnnotationStatus === '2' || this.annotations ===null"
                 @click="showDisagreement()"
      >
        不通过
      </el-button>
    </div>
    <div id="label-studio" class="annotation-container"></div>

  </div>
</template>

<script>
import LabelStudio from 'label-studio'
import '@/assets/styles/labelStudio.scss'
import { agreement, manualAnnotate } from '../../../../api/dataCenter/annotationTask'

export default {
  name: 'LabelStudioAnnotator',
  props: {
    fileUrl: { type: String, required: true },
    taskId: { type: Number, required: true },
    config: { type: String, required: true },
    id: { type: Number, required: true },
    itemIndex: { type: Number, required: true },
    fileAnnotationStatus: { type: String, required: true },
    annotations: {
      type: Array,
      default: () => [] // 默认值为空数组
    }
  },
  computed: {
    index: {
      get() {
        return this.itemIndex
      },
      set(value) {
        this.$parent.updateItemIndex(value, this.annotationStatus) // 更新父组件的索引
      }
    }
  },
  data() {
    return {
      annotationStatus: '',
      labelStudio: null,
      annotationsList: [],
      disagreementReason: '' // 存储不同意的原因
    }
  },
  watch: {
    fileUrl: 'resetLabelStudio' // 当文件地址变化时，重置LabelStudio
  },
  mounted() {
    this.initLabelStudio() // 组件挂载完成后初始化LabelStudio
  },
  methods: {
    showDisagreement() {
      this.$prompt('请输入驳回原因', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'textarea', // 使用多行文本框
        inputPlaceholder: '请输入描述',
        inputPattern: /^.{0,200}$/, // 限制最多200字符
        inputErrorMessage: '描述不能超过200字符',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            // 验证输入框内容是否为空（必填）
            if (!instance.inputValue) {
              this.$message({
                type: 'error',
                message: '不通过原因不能为空'
              })
              return // 阻止关闭弹框
            }
          }
          done()
        }
      })
        .then(({ value }) => {
          this.sendDisagreement(value)
        })
        .catch(() => {
        })
    },
    // 发送不同意原因到后台
    sendDisagreement(value) {
      agreement({
        taskId: Number(this.taskId),
        fileId: Number(this.id),
        auditFailedReason: value
      }).then(response => {
        this.$modal.msgSuccess('已提交不通过原因')
        this.annotationStatus = '3'
        this.index++ // 更新索引
      }).catch(error => {
        console.log(error)
      })
    },
    // 处理返回的标注数据
    getAnnotations() {
      return [{
        result: this.annotations.map(annotation => ({
          type: 'rectanglelabels',
          from_name: 'label',
          to_name: 'image',
          value: {
            rectanglelabels: [annotation.label],
            x: annotation.x,
            y: annotation.y,
            width: annotation.width,
            height: annotation.height
          }
        }))
      }]
    },
    //不同意
    disagreement() {

    },
    //同意的接口调用后台
    agreement() {
      agreement({
        taskId: Number(this.taskId),
        fileId: Number(this.id)
      }).then(response => {
        this.annotationStatus = '2'
        this.$modal.msgSuccess('已同意标注')
        this.index++ // 更新索引
      }).catch(error => {
        console.log(error)
      })
    },
    // 初始化 LabelStudio
    initLabelStudio() {
      this.cleanupLabelStudio() // 清理之前的实例

      const task = {
        id: this.id,
        data: { image: this.fileUrl }
      }
      if (this.annotations) {
        task.annotations = this.getAnnotations()
      }

      this.$nextTick(() => {
        const labelStudioElement = document.getElementById('label-studio')
        if (!labelStudioElement) {
          console.error('Label Studio element not found')
          return
        }

        this.labelStudio = new LabelStudio('label-studio', {
          config: this.config,
          interfaces: [],
          user: { pk: 1, firstName: '标注者', lastName: '用户' },
          task,
          onLabelStudioLoad: (LS) => {
            if (!LS.annotationStore.selectedAnnotation) {
              const annotation = LS.annotationStore.addAnnotation({ userGenerate: true })
              LS.annotationStore.selectAnnotation(annotation.id)
            }
          }
        })
      })
    },
    // 重置 LabelStudio
    resetLabelStudio() {
      this.cleanupLabelStudio()
      this.initLabelStudio() // 重新初始化
    },
    // 清理 LabelStudio 实例
    cleanupLabelStudio() {
      if (this.labelStudio && this.labelStudio.destroy) {
        this.labelStudio.destroy()
      }
      const labelStudioElement = document.getElementById('label-studio')
      if (labelStudioElement) {
        labelStudioElement.innerHTML = '' // 清空容器
      }
      this.labelStudio = null // 置空实例
    }
  }
}
</script>

<style>
.button-container {
  margin: 10px;
}

.label-studio-annotator {
  width: 100%;
  height: 96%;
}

.annotation-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;

  > div {
    width: 100%;
    height: 100%;
    padding: 5px;
  }
}
</style>
