<template>
  <div>
    <el-dialog title="创建标注任务" :visible.sync="isOpen" width="700px" append-to-body @close="cancel"
               :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="taskName">
          <el-input v-model="form.taskName" maxlength="20" placeholder="请输入任务名称"/>
        </el-form-item>
        <el-form-item label="描述" prop="taskDesc">
          <el-input
            type="textarea"
            placeholder="请输入描述"
            v-model="form.taskDesc"
            maxlength="200"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <el-form-item label="时间" prop="data">
          <el-date-picker
            style="width: 100%;"
            v-model="form.data"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="标注类型" prop="annotateType">
          <el-select v-model="form.annotateType" placeholder="请选择标注类型" clearable style="width: 100%">
            <el-option v-for="dict in dict.type.ai_annotate_type" :key="dict.value" :label="dict.label"
                       :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="标签" prop="label">
          <treeselect v-model="form.label" :disable-branch-nodes="true" :multiple="true" :options="labelsListOptions"
                      :normalizer="normalizer" placeholder="请选择标签"
          />
        </el-form-item>
        <el-form-item label="是否启用标注团队" prop="isStartTeam" label-width="130px">
          <el-switch
            v-model="form.startTeam"
          >
          </el-switch>
        </el-form-item>
        <div v-show="form.startTeam">
          <el-form-item label="选择标注人员" prop="isStartTeam" label-width="100px">
            <el-button type="primary" @click="selectOpen=true">选择标注人员</el-button>
          </el-form-item>
          <el-form-item label="分配数量" prop="isStartTeam" label-width="100px">
            <el-table
              size="mini"
              :data="tableData"
            >
              <el-table-column
                label="姓名"
                prop="name"
                align="center"
                max-width="180"
              >
              </el-table-column>
              <el-table-column
                prop="type"
                label="角色"
                align="center"
                max-width="180"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row.type === '0' ? '审核人员' : '标注人员' }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="num"
                align="center"
                label="数量"
                max-width="50"
              >
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.num"
                    :min="1"
                    :max="scope.row.type === '0' ? getReviewerMax(scope.row) : getLabelingMax(scope.row)"
                    style="width: 150px"
                  ></el-input-number>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </template>
    </el-dialog>
    <select-personnel-dialog dataset-id="" :open="selectOpen" @dialog-cancel="handleCancel" @update-data="updateData"/>
  </div>

</template>

<script>

import selectPersonnelDialog from '../child/selectPersonnelDialog.vue'
import { add } from '@/api/dataCenter/annotationTask'
import { listDataSetLabels } from '@/api/dataCenter/labels'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { parseTime } from '../../../../utils/bonus'

export default {
  dicts: ['ai_annotate_type'],
  components: { selectPersonnelDialog, Treeselect },
  props: {
    open: {
      type: Boolean,
      default: false,
      required: true
    },
    datasetNum: {
      type: Number,
      default: 0,
      required: true
    },
    datasetId: {
      type: Number,
      default: 0,
      required: true
    }
  },
  computed: {
    isOpen: {
      get() {
        return this.open
      },
      set(value) {
        this.$emit('update:open', value)
      }
    }
  },
  watch: {
    isOpen(newVal, oldVal) {
      if (newVal) {
        this.getTreeselect()
      }

    }
  },
  data() {
    return {
      tableData: [],
      // 样本标签管理树选项
      labelsListOptions: [],
      labels: [],
      selectOpen: false,
      form: {}, // 初始化为空
      rules: {
        taskName: [
          { required: true, message: '任务名称不能为空', trigger: 'blur' }
        ],
        annotateType: [
          { required: true, message: '标注类型不能为空', trigger: 'blur' }
        ],
        label: [
          { required: true, message: '请选择标签', trigger: 'blur' }
        ],
        data: [
          { required: true, message: '请选择时间', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.labelName,
        label: node.labelName,
        children: node.children
      }
    },
    /** 查询样本标签管理下拉树结构 */
    getTreeselect() {
      listDataSetLabels({}).then(response => {
        console.log(response)
        this.labelsListOptions = []
        const menu = { labelId: 0, labelName: '主类目', children: [] }
        menu.children = this.handleTree(response.data, 'labelId')
        this.labelsListOptions.push(menu)
      })
    },
    getReviewerMax(row) {
      // 假设总数是 this.datasetNum，其他值可以从 tableData 动态计算
      const totalAssigned = this.tableData
        .filter(item => item.type === '0' && item.id !== row.id)
        .reduce((sum, item) => sum + item.num, 0)
      return this.datasetNum - totalAssigned
    },
    getLabelingMax(row) {
      const totalAssigned = this.tableData
        .filter(item => item.type === '1' && item.id !== row.id)
        .reduce((sum, item) => sum + item.num, 0)
      return this.datasetNum - totalAssigned
    },
    // 数据提交
    submitForm() {
      if (this.tableData.length === 0 && this.form.isStartTeam) {
        this.$modal.msgWarning('请选择人员')
        return
      }
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.startTime = parseTime(this.form.data[0])
          this.form.endTime = parseTime(this.form.data[1])
          this.form.isStartTeam =  this.form.startTeam?'1':'0';
          this.form.labels = this.form.label.join(",")
          if (this.form.isStartTeam) {
            let annotators = []
            let reviewers = []
            this.tableData.forEach((item) => {
              if (item.type === '0') {
                reviewers.push(item)
              }
              if (item.type === '1') {
                annotators.push(item)
              }
            })
            this.form.annotators = annotators
            this.form.reviewers = reviewers
          }
          this.form.datasetId = this.datasetId
          add(this.form).then(response => {
            this.$modal.msgSuccess('发布成功')
            this.cancel()
          })
        }
      })
    },
    updateData(data) {
      this.tableData = []
      let num = Math.max(data.selectReviewer.length, data.selectLabeling.length)
      let minNum = Math.floor(this.datasetNum / num) // 基础分配
      if (minNum < 1) {
        this.$modal.msgWarning('每人最少分配1张')
        return
      }
      // 处理 Reviewer 的分配
      let reviewerRemainder = this.datasetNum % data.selectReviewer.length // 余数
      let reviewerNum = Math.floor(this.datasetNum / data.selectReviewer.length) // 基础分配
      data.selectReviewer.forEach(item => {
        item.num = reviewerNum // 默认基础分配
        if (reviewerRemainder > 0) {
          item.num += 1 // 如果有余数，额外分配 1
          reviewerRemainder-- // 减少余数
        }
        this.tableData.push(item)
      })

      // 处理 Labeling 的分配
      let labelingRemainder = this.datasetNum % data.selectLabeling.length // 余数
      let labelingNum = Math.floor(this.datasetNum / data.selectLabeling.length) // 基础分配

      data.selectLabeling.forEach(item => {
        item.num = labelingNum // 默认基础分配
        if (labelingRemainder > 0) {
          item.num += 1 // 如果有余数，额外分配 1
          labelingRemainder-- // 减少余数
        }
        this.tableData.push(item)
      })

    },
    // 取消按钮
    cancel() {
      this.isOpen = false
      this.reset()
      this.$emit('dialog-cancel') // 通知父组件
    },
    // 表单重置
    reset() {
      this.tableData = []
      this.form = {} // 清空表单
      this.$refs.form.resetFields() // 调用 Element UI 的重置方法
    },
    // 处理取消事件
    handleCancel() {
      this.selectOpen = false
    }
  }
}
</script>

<style scoped lang="scss">
/* 样式按需定义 */
/* 提升优先级 */
.vue-treeselect--has-value .vue-treeselect__input {
  line-height: inherit !important;
  vertical-align: baseline !important;
}
</style>
