<script setup lang="ts">
import { useRoute } from 'vue-router'
import SetTarget from './set-target.vue'
import hud from '@/utils/hud'
import type { SetTargetData } from '../..'
import { shareStore } from '@/stores/share'

defineOptions({ name: 'TargetItem' })

type ObjType = {
  objectId: any
}

const { taskSinglePerson } = storeToRefs(shareStore())

const route = useRoute()
const { schoolId } = route.query

// 显示设置对象
const showSetTarget = ref(false)

// 对象的文字
const targetText = ref('')

// 对象的类型
const objTypeCode = ref('')

// 选中的对象数组
const objTypeList = ref([] as ObjType[])

// 设置对象
function toSetTarget() {
  showSetTarget.value = true
}

// 设置对象数据
function setTargetData(data: SetTargetData, text: any) {
  targetText.value = text
  // 对象
  if (data.students?.length) {
    // 选择了个人
    objTypeCode.value = 'person'
    objTypeList.value = data.students.map(item => ({ objectId: item.id }))
    // 设置单人id
    if (data.students.length === 1) {
      taskSinglePerson.value.userId = data.students[0].id
    } else {
      taskSinglePerson.value.userId = ''
    }
  } else if (data.classes?.length) {
    objTypeCode.value = 'class'
    objTypeList.value = data.classes.map(item => ({ objectId: item.id }))
    // 清空单人id
    taskSinglePerson.value.userId = ''
  } else {
    objTypeCode.value = ''
    objTypeList.value = []
    // 清空单人id
    taskSinglePerson.value.userId = ''
  }
}

defineExpose({
  submit() {
    if (!objTypeCode.value || !objTypeList.value.length) {
      hud.error('请选择任务对象')
      return
    }
    return {
      objTypeCode: toRaw(objTypeCode.value),
      objTypeList: toRaw(objTypeList.value),
    }
  },
})
</script>

<template>
  <!-- 任务对象 -->
  <div class="mj-data-row">
    <div class="mj-data-item target required">
      <span class="mj-data-item-title">任务对象</span>
      <span v-if="targetText" class="value" @click="toSetTarget" v-html="targetText" />
      <mj-button class="button" type="warn" @click="toSetTarget">设置</mj-button>
    </div>
  </div>
  <set-target v-model="showSetTarget" :school-id="schoolId" @ok="setTargetData" />
</template>

<style lang="scss" scoped>
@use '../index.scss' as *;

.target {
  .value {
    margin-right: 2rem;
  }

  .button {
    width: 150px;
  }
}
</style>
