<template>
  <ConfirmDialog
    :open="open"
    :badge="modeMeta.badge"
    :title="modeMeta.title"
    :description="modeMeta.description"
    cancel-text="取消"
    :confirm-text="modeMeta.confirmText"
    busy-text="提交中..."
    :confirm-disabled="confirmDisabled"
    :busy="busy"
    @close="closeDialog"
    @confirm="submitAction"
  >
    <div class="assignment-form">
      <p v-if="permissionReason" class="assignment-error" role="alert">
        {{ permissionReason }}
      </p>

      <template v-if="requiresCandidate">
        <label class="candidate-search">
          <span>候选审批人</span>
          <div>
            <input
              v-model="candidateKeyword"
              type="search"
              placeholder="输入姓名、工号或邮箱"
              :disabled="busy"
              @keydown.enter.prevent="loadCandidates"
            />
            <button type="button" :disabled="candidateLoading || busy" @click="loadCandidates">
              <i :class="candidateLoading ? 'mdi mdi-loading mdi-spin' : 'mdi mdi-magnify'"></i>
              查询
            </button>
          </div>
        </label>

        <div class="candidate-list" role="radiogroup" aria-label="审批候选人">
          <p v-if="candidateLoading">正在加载候选人...</p>
          <p v-else-if="candidateError" class="assignment-error">{{ candidateError }}</p>
          <p v-else-if="!candidates.length">暂无符合条件的候选人。</p>
          <label
            v-for="candidate in candidates"
            v-else
            :key="candidate.employeeId"
            :class="{ disabled: !candidate.qualified }"
          >
            <input
              v-model="targetEmployeeId"
              type="radio"
              :value="candidate.employeeId"
              :disabled="!candidate.qualified || busy"
            />
            <span>
              <strong>{{ candidate.name || candidate.employeeNo }}</strong>
              <small>{{ candidate.employeeNo }} · {{ candidate.email }}</small>
              <em v-if="!candidate.qualified">{{ candidate.reason || '不符合当前动作资格' }}</em>
            </span>
          </label>
        </div>
      </template>

      <label v-if="mode === 'delegate'" class="assignment-field">
        <span>委托失效时间（可选）</span>
        <input v-model="expiresAt" type="datetime-local" :disabled="busy" />
        <small>到期后的恢复行为由服务端审批任务策略决定。</small>
      </label>

      <label class="assignment-field">
        <span>{{ modeMeta.reasonLabel }} <em>必填</em></span>
        <textarea
          v-model="reason"
          maxlength="500"
          :disabled="busy"
          :placeholder="modeMeta.reasonPlaceholder"
        ></textarea>
        <small>{{ reason.length }}/500</small>
      </label>

      <p v-if="submitError" class="assignment-error" role="alert">{{ submitError }}</p>
    </div>
  </ConfirmDialog>
</template>

<script setup>
import { computed, ref, watch } from 'vue'

import {
  delegateApprovalTask,
  fetchApprovalTaskCandidates,
  revokeApprovalTaskDelegation,
  transferApprovalTask
} from '../../services/approvalTasks.js'
import { resolveApprovalTaskRetryKey } from '../../views/scripts/approvalTaskRetry.js'
import ConfirmDialog from '../shared/ConfirmDialog.vue'

const MODE_METADATA = {
  delegate: {
    badge: '临时委托',
    title: '委托当前审批任务',
    description: '委托只改变当前任务的实际处理人，原任务责任人与到期策略以服务端记录为准。',
    confirmText: '确认委托',
    reasonLabel: '委托原因',
    reasonPlaceholder: '说明委托原因和需要候选人关注的事项。'
  },
  transfer: {
    badge: '审批转交',
    title: '转交当前审批任务',
    description: '转交会永久改变当前任务处理人，请确认候选人具备服务端返回的处理资格。',
    confirmText: '确认转交',
    reasonLabel: '转交原因',
    reasonPlaceholder: '说明转交原因和后续责任边界。'
  },
  delegation_revoke: {
    badge: '撤销委托',
    title: '撤销当前任务委托',
    description: '服务端会按最新任务版本复核是否仍可撤销，并记录完整审计事件。',
    confirmText: '确认撤销',
    reasonLabel: '撤销原因',
    reasonPlaceholder: '说明撤销委托的原因。'
  }
}

const props = defineProps({
  open: { type: Boolean, default: false },
  task: { type: Object, default: () => ({}) },
  mode: {
    type: String,
    default: 'delegate',
    validator: (value) => ['delegate', 'transfer', 'delegation_revoke'].includes(value)
  },
  serviceOverrides: { type: Object, default: () => ({}) }
})

const emit = defineEmits(['close', 'completed'])
const candidateKeyword = ref('')
const candidates = ref([])
const candidateLoading = ref(false)
const candidateError = ref('')
const targetEmployeeId = ref('')
const expiresAt = ref('')
const reason = ref('')
const busy = ref(false)
const submitError = ref('')
const requestId = ref('')
const requestFingerprint = ref('')
let candidateRequestSequence = 0

const normalizedTask = computed(() => props.task?.task || props.task || {})
const taskId = computed(() => String(normalizedTask.value.id || '').trim())
const availableActions = computed(() => new Set(
  Array.isArray(normalizedTask.value.availableActions)
    ? normalizedTask.value.availableActions
    : Array.isArray(normalizedTask.value.available_actions)
      ? normalizedTask.value.available_actions
      : []
))
const modeMeta = computed(() => MODE_METADATA[props.mode] || MODE_METADATA.delegate)
const requiresCandidate = computed(() => ['delegate', 'transfer'].includes(props.mode))
const canAct = computed(() =>
  Boolean(taskId.value)
  && Number(normalizedTask.value.version) >= 1
  && availableActions.value.has(props.mode)
)
const permissionReason = computed(() => {
  if (canAct.value) return ''
  return String(
    normalizedTask.value.readOnlyReason
    ?? normalizedTask.value.read_only_reason
    ?? '服务端未授权当前审批动作。'
  ).trim()
})
const selectedCandidate = computed(() =>
  candidates.value.find((candidate) => candidate.employeeId === targetEmployeeId.value) || null
)
const confirmDisabled = computed(() =>
  !canAct.value
  || reason.value.trim().length < 2
  || (requiresCandidate.value && !selectedCandidate.value?.qualified)
)

watch(
  [() => props.open, taskId, () => props.mode],
  ([open]) => {
    if (!open) return
    resetForm()
    if (requiresCandidate.value && canAct.value) {
      void loadCandidates()
    }
  }
)

function resetForm() {
  candidateRequestSequence += 1
  candidateKeyword.value = ''
  candidates.value = []
  candidateError.value = ''
  targetEmployeeId.value = ''
  expiresAt.value = ''
  reason.value = ''
  submitError.value = ''
  requestId.value = ''
  requestFingerprint.value = ''
}

async function loadCandidates() {
  if (!taskId.value || !requiresCandidate.value || !canAct.value) return
  const sequence = ++candidateRequestSequence
  candidateLoading.value = true
  candidateError.value = ''
  try {
    const service = props.serviceOverrides.fetchApprovalTaskCandidates
      || fetchApprovalTaskCandidates
    const result = await service(taskId.value, {
      action: props.mode,
      keyword: candidateKeyword.value,
      limit: 50
    })
    if (sequence !== candidateRequestSequence) return
    candidates.value = Array.isArray(result?.items) ? result.items : []
    if (!candidates.value.some((candidate) => candidate.employeeId === targetEmployeeId.value)) {
      targetEmployeeId.value = ''
    }
  } catch (error) {
    if (sequence === candidateRequestSequence) {
      candidates.value = []
      candidateError.value = error?.message || '审批候选人加载失败。'
    }
  } finally {
    if (sequence === candidateRequestSequence) {
      candidateLoading.value = false
    }
  }
}

function resolveExpiresAt() {
  if (!expiresAt.value) return ''
  const date = new Date(expiresAt.value)
  if (Number.isNaN(date.getTime())) {
    throw new Error('委托失效时间格式无效。')
  }
  return date.toISOString()
}

async function submitAction() {
  if (confirmDisabled.value || busy.value) return
  const serviceMap = {
    delegate: props.serviceOverrides.delegateApprovalTask || delegateApprovalTask,
    transfer: props.serviceOverrides.transferApprovalTask || transferApprovalTask,
    delegation_revoke: props.serviceOverrides.revokeApprovalTaskDelegation
      || revokeApprovalTaskDelegation
  }
  busy.value = true
  submitError.value = ''
  try {
    const payload = {
      expectedTaskVersion: Number(normalizedTask.value.version),
      reason: reason.value.trim()
    }
    if (requiresCandidate.value) {
      payload.targetEmployeeId = targetEmployeeId.value
    }
    if (props.mode === 'delegate' && expiresAt.value) {
      payload.expiresAt = resolveExpiresAt()
    }
    const retryKey = resolveApprovalTaskRetryKey({
      action: props.mode,
      scopeId: taskId.value || 'task',
      payload,
      previousFingerprint: requestFingerprint.value,
      previousRequestId: requestId.value
    })
    requestId.value = retryKey.requestId
    requestFingerprint.value = retryKey.fingerprint
    payload.requestId = retryKey.requestId
    const mutation = await serviceMap[props.mode](taskId.value, payload)
    emit('completed', { mode: props.mode, mutation })
    emit('close')
  } catch (error) {
    submitError.value = error?.message || '审批任务分配操作失败。'
  } finally {
    busy.value = false
  }
}

function closeDialog() {
  if (!busy.value) emit('close')
}
</script>

<style scoped>
.assignment-form,
.assignment-field,
.candidate-search,
.candidate-list {
  display: grid;
  gap: 8px;
}

.candidate-search > span,
.assignment-field > span {
  color: #334155;
  font-size: 12px;
  font-weight: 850;
}

.candidate-search > div {
  display: flex;
  gap: 8px;
}

.candidate-search input,
.assignment-field input,
.assignment-field textarea {
  width: 100%;
  min-height: 38px;
  padding: 8px 10px;
  border: 1px solid #dbe5ef;
  border-radius: 6px;
  outline: none;
}

.candidate-search button {
  flex: 0 0 auto;
  padding: 0 13px;
  border: 1px solid var(--theme-primary);
  border-radius: 6px;
  background: #fff;
  color: var(--theme-primary-active);
  font-weight: 800;
}

.candidate-list {
  max-height: 210px;
  overflow-y: auto;
}

.candidate-list > p {
  margin: 0;
  padding: 12px;
  border-radius: 6px;
  background: #f8fafc;
  color: #64748b;
  font-size: 12px;
}

.candidate-list label {
  display: flex;
  align-items: flex-start;
  gap: 9px;
  padding: 9px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
}

.candidate-list label.disabled {
  background: #f8fafc;
  opacity: 0.7;
}

.candidate-list label span,
.candidate-list label strong,
.candidate-list label small,
.candidate-list label em {
  display: block;
}

.candidate-list label strong {
  color: #0f172a;
  font-size: 13px;
}

.candidate-list label small {
  margin-top: 2px;
  color: #64748b;
}

.candidate-list label em {
  margin-top: 3px;
  color: #b45309;
  font-size: 11px;
  font-style: normal;
}

.assignment-field textarea {
  min-height: 82px;
  resize: vertical;
}

.assignment-field small {
  color: #64748b;
  font-size: 11px;
}

.assignment-field em {
  color: #b91c1c;
  font-style: normal;
}

.assignment-error {
  margin: 0;
  padding: 9px 10px;
  border: 1px solid #fecaca;
  border-radius: 6px;
  background: #fef2f2;
  color: #b91c1c;
  font-size: 12px;
}
</style>
