<template>
  <div class="reviewer-setting">
    <el-form :model="formData" label-width="100px" v-loading="loading">
      <!-- 当前采购代表 -->
      <el-form-item label="当前代表" v-if="currentRepresentor.teacherName">
        <el-tag type="success">{{ currentRepresentor.teacherName }} ({{ currentRepresentor.teacherNo }})</el-tag>
        <el-tag v-if="currentRepresentor.representorType" type="info" style="margin-left: 8px;">{{ getRepresentorTypeLabel(currentRepresentor.representorType) }}</el-tag>
      </el-form-item>

      <!-- 选择方式 -->
      <el-form-item label="选择方式">
        <el-radio-group v-model="formData.selectMode" @change="handleSelectModeChange">
          <el-radio label="DESIGNATED">指定人员</el-radio>
          <el-radio label="RANDOM">随机抽取</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 指定人员模式 -->
      <el-form-item v-if="formData.selectMode === 'DESIGNATED'" label="选择人员" required>
        <org-selector
          v-model:orgList="selectedUserList"
          type="user"
          :multiple="false"
          @update:orgList="handleUserChange" />
      </el-form-item>

      <!-- 随机抽取模式 -->
      <template v-if="formData.selectMode === 'RANDOM'">
        <el-form-item label="选择候选人" required>
          <org-selector
            v-model:orgList="candidateUserList"
            type="user"
            :multiple="true"
            @update:orgList="handleCandidateChange" />
        </el-form-item>

        <!-- 候选人列表 -->
        <el-form-item label="候选人列表" v-if="candidates.length > 0">
          <el-table :data="candidates" stripe size="small" max-height="200">
            <el-table-column type="index" label="序号" width="60" align="center" />
            <el-table-column prop="teacherNo" label="工号" width="120" />
            <el-table-column prop="teacherName" label="姓名" />
          </el-table>
        </el-form-item>

        <!-- 随机抽取结果 -->
        <el-form-item label="抽取结果">
          <div class="random-roller">
            <span v-if="rollingName" class="rolling">{{ rollingName }}</span>
            <span v-else-if="selectedCandidate.teacherName" class="selected">
              已抽取：{{ selectedCandidate.teacherName }} ({{ selectedCandidate.teacherNo }})
            </span>
            <span v-else class="placeholder">点击下方按钮进行随机抽取</span>
          </div>
        </el-form-item>

        <!-- 随机抽取按钮 -->
        <el-form-item v-if="candidates.length > 1">
          <el-button type="primary" :loading="rolling" @click="handleRandomSelect">
            {{ rolling ? '抽取中...' : '随机抽取' }}
          </el-button>
        </el-form-item>
      </template>

      <!-- 人员类型选择 -->
      <el-form-item label="人员类型">
        <el-select v-model="formData.representorType" placeholder="请选择人员类型" clearable style="width: 200px;">
          <el-option
            v-for="item in representorTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>

      <!-- 保存按钮 -->
      <el-form-item>
        <el-button type="primary" :loading="saving" :disabled="!canSave" @click="handleSave">
          保存设置
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts" name="ReviewerSetting">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useMessage } from '/@/hooks/message'
import { useDict } from '/@/hooks/dict'
import { getReviewerSetting, setReviewerSetting, randomSelectReviewer } from '/@/api/purchase/docProcess'
import orgSelector from '/@/components/OrgSelector/index.vue'

const props = defineProps<{
  applyId: string | number
}>()

const emit = defineEmits<{
  (e: 'saved'): void
}>()

// 常量
const SELECT_MODE = {
  DESIGNATED: 'DESIGNATED',
  RANDOM: 'RANDOM',
} as const

// 字典数据
const { PURCHASE_REPRESENTOR_TYPE: representorTypeDict } = useDict('PURCHASE_REPRESENTOR_TYPE')

// 人员类型选项
const representorTypeOptions = computed(() => {
  return (representorTypeDict.value || []).map((item: any) => ({
    value: item.value,
    label: item.label
  }))
})

// 表单数据
const formData = ref({
  selectMode: 'DESIGNATED' as 'DESIGNATED' | 'RANDOM',
  teacherNo: '',
  teacherName: '',
  candidates: [] as Array<{ teacherNo: string; teacherName: string }>,
  representorType: ''
})

// 当前采购代表（已有设置）
const currentRepresentor = ref({
  teacherNo: '',
  teacherName: '',
  representorType: ''
})

// 用户选择相关
const selectedUserList = ref<any[]>([])
const candidateUserList = ref<any[]>([])

// 候选人列表
const candidates = ref<Array<{ teacherNo: string; teacherName: string }>>([])

// 随机抽取相关
const rolling = ref(false)
const rollingName = ref('')
const selectedCandidate = ref<{ teacherNo: string; teacherName: string }>({ teacherNo: '', teacherName: '' })
let rollInterval: ReturnType<typeof setInterval> | null = null

// 加载状态
const loading = ref(false)
const saving = ref(false)

// 是否可以保存
const canSave = computed(() => {
  if (formData.value.selectMode === SELECT_MODE.DESIGNATED) {
    return formData.value.teacherNo && formData.value.teacherName
  } else {
    return formData.value.teacherNo && formData.value.teacherName && candidates.value.length > 0
  }
})

// 处理选择方式变化
const handleSelectModeChange = () => {
  formData.value.teacherNo = ''
  formData.value.teacherName = ''
  formData.value.candidates = []
  selectedUserList.value = []
  candidateUserList.value = []
  candidates.value = []
  selectedCandidate.value = { teacherNo: '', teacherName: '' }
  rollingName.value = ''
}

// 获取人员类型标签
const getRepresentorTypeLabel = (value: string): string => {
  const option = representorTypeOptions.value.find((item: any) => item.value === value)
  return option ? option.label : value
}

// 处理指定人员变化
const handleUserChange = (list: any[]) => {
  if (list && list.length > 0) {
    const user = list[0]
    formData.value.teacherNo = user.username || user.userName || ''
    formData.value.teacherName = user.name || user.realName || ''
  } else {
    formData.value.teacherNo = ''
    formData.value.teacherName = ''
  }
}

// 处理候选人变化
const handleCandidateChange = (list: any[]) => {
  candidates.value = (list || []).map(user => ({
    teacherNo: user.username || user.userName || '',
    teacherName: user.name || user.realName || ''
  }))
  // 重置已选结果
  if (candidates.value.length > 0) {
    selectedCandidate.value = { ...candidates.value[0] }
    formData.value.teacherNo = selectedCandidate.value.teacherNo
    formData.value.teacherName = selectedCandidate.value.teacherName
  } else {
    selectedCandidate.value = { teacherNo: '', teacherName: '' }
    formData.value.teacherNo = ''
    formData.value.teacherName = ''
  }
}

// 随机抽取动画
const startRollingAnimation = (finalCandidate: { teacherNo: string; teacherName: string }) => {
  if (candidates.value.length === 0) return

  if (rollInterval) {
    clearInterval(rollInterval)
    rollInterval = null
  }

  rollingName.value = ''
  rolling.value = true

  let currentIndex = 0
  const totalDuration = 2000
  const intervalTime = 80

  rollInterval = setInterval(() => {
    rollingName.value = candidates.value[currentIndex].teacherName
    currentIndex = (currentIndex + 1) % candidates.value.length
  }, intervalTime)

  setTimeout(() => {
    if (rollInterval) {
      clearInterval(rollInterval)
      rollInterval = null
    }
    rolling.value = false
    rollingName.value = ''
    selectedCandidate.value = finalCandidate
    formData.value.teacherNo = finalCandidate.teacherNo
    formData.value.teacherName = finalCandidate.teacherName
  }, totalDuration)
}

// 执行随机抽取
const handleRandomSelect = async () => {
  if (candidates.value.length < 2) {
    useMessage().warning('请至少选择2位候选人')
    return
  }

  rolling.value = true
  try {
    const res = await randomSelectReviewer({
      applyId: props.applyId,
      selectMode: SELECT_MODE.RANDOM,
      candidates: candidates.value
    })
    const result = res?.data || res
    if (result?.teacherNo) {
      startRollingAnimation({
        teacherNo: result.teacherNo,
        teacherName: result.teacherName || ''
      })
    }
  } catch (e: any) {
    rolling.value = false
    useMessage().error(e?.msg || '随机抽取失败')
  }
}

// 保存设置
const handleSave = async () => {
  if (!canSave.value) {
    useMessage().warning('请完善设置信息')
    return
  }

  saving.value = true
  try {
    const params: any = {
      applyId: props.applyId,
      selectMode: formData.value.selectMode,
      teacherNo: formData.value.teacherNo,
      teacherName: formData.value.teacherName,
      representorType: formData.value.representorType
    }

    if (formData.value.selectMode === SELECT_MODE.RANDOM) {
      params.candidates = candidates.value
    }

    await setReviewerSetting(params)
    useMessage().success('保存成功')
    emit('saved')
    await loadData()
  } catch (e: any) {
    useMessage().error(e?.msg || '保存失败')
  } finally {
    saving.value = false
  }
}

// 加载数据
const loadData = async () => {
  if (!props.applyId) return

  loading.value = true
  try {
    const res = await getReviewerSetting(props.applyId)
    const data = res?.data || res
    if (data) {
      currentRepresentor.value = {
        teacherNo: data.teacherNo || '',
        teacherName: data.teacherName || '',
        representorType: data.representorType || ''
      }
      formData.value.selectMode = data.selectMode || SELECT_MODE.DESIGNATED
      formData.value.teacherNo = data.teacherNo || ''
      formData.value.teacherName = data.teacherName || ''
      formData.value.representorType = data.representorType || ''

      if (data.candidateList && data.candidateList.length > 0) {
        candidates.value = data.candidateList
        formData.value.candidates = data.candidateList
        // 回显候选人
        candidateUserList.value = data.candidateList.map((c: any) => ({
          username: c.teacherNo,
          userName: c.teacherNo,
          name: c.teacherName,
          realName: c.teacherName
        }))
      }

      if (data.teacherNo && data.selectMode === SELECT_MODE.DESIGNATED) {
        selectedUserList.value = [{
          username: data.teacherNo,
          userName: data.teacherNo,
          name: data.teacherName,
          realName: data.teacherName
        }]
      }

      if (data.selectMode === SELECT_MODE.RANDOM && data.teacherNo) {
        selectedCandidate.value = {
          teacherNo: data.teacherNo,
          teacherName: data.teacherName || ''
        }
      }
    }
  } catch (_) {
    // 忽略错误
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadData()
})

onUnmounted(() => {
  if (rollInterval) {
    clearInterval(rollInterval)
    rollInterval = null
  }
})
</script>

<style scoped lang="scss">
.reviewer-setting {
  padding: 16px;
}

.random-roller {
  padding: 12px 16px;
  background: var(--el-fill-color-light);
  border-radius: 4px;
  min-height: 40px;
  display: flex;
  align-items: center;

  .rolling {
    font-size: 16px;
    font-weight: 500;
    color: var(--el-color-primary);
    animation: blink 0.1s infinite;
  }

  .selected {
    font-size: 16px;
    font-weight: 600;
    color: var(--el-color-success);
  }

  .placeholder {
    color: var(--el-text-color-placeholder);
  }
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.7; }
}
</style>