import { computed, ref } from 'vue'

import { fetchEmployees } from '../../services/employees.js'
import { createAgentAssetReview } from '../../services/agentAssets.js'
import {
  buildReviewNote
} from './auditViewRuntimeModel.js'
import {
  normalizeText,
  resolveReviewMeta
} from './auditViewModel.js'

export function useAuditRuleReviewFlow({
  selectedSkill,
  selectedSkillIsRule,
  selectedSkillUsesJsonRisk,
  canEditSelected,
  canManageSelected,
  isDisplayingWorkingVersion,
  canOpenRiskRuleReviewSubmit,
  riskRuleTestPassed,
  detailBusy,
  actionState,
  refreshCurrentAssets,
  loadSelectedAssetDetail,
  resolveActor,
  toast
}) {
  const reviewSubmitOpen = ref(false)
  const reviewSubmitVersion = ref('')
  const reviewSubmitReviewer = ref('')
  const reviewSubmitReviewerLoading = ref(false)
  const reviewSubmitReviewerOptions = ref([])

  const canSubmitReview = computed(
    () =>
      !selectedSkillUsesJsonRisk.value &&
      canEditSelected.value &&
      selectedSkillIsRule.value &&
      isDisplayingWorkingVersion.value
  )
  const hasReviewSubmitReviewers = computed(() => reviewSubmitReviewerOptions.value.length > 0)
  const canReviewSelected = computed(
    () => canManageSelected.value && selectedSkillIsRule.value && isDisplayingWorkingVersion.value
  )

  async function reviewSelectedRule(reviewStatus) {
    if (!selectedSkill.value || !selectedSkillIsRule.value || detailBusy.value) {
      return
    }
    if (reviewStatus === 'pending' && !canSubmitReview.value) {
      return
    }
    if (reviewStatus !== 'pending' && !canReviewSelected.value) {
      return
    }

    actionState.value = `review-${reviewStatus}`
    try {
      await createAgentAssetReview(
        selectedSkill.value.id,
        {
          version: selectedSkill.value.workingVersion,
          reviewer: resolveActor(),
          review_status: reviewStatus,
          review_note: buildReviewNote(reviewStatus)
        },
        { actor: resolveActor() }
      )
      await refreshCurrentAssets()
      await loadSelectedAssetDetail(selectedSkill.value.id, { silent: true })
      toast(`当前规则版本已标记为${resolveReviewMeta(reviewStatus).label}。`)
    } catch (error) {
      toast(error?.message || '规则审核提交失败，请稍后重试。')
    } finally {
      actionState.value = ''
    }
  }

  async function loadReviewSubmitReviewers() {
    reviewSubmitReviewerLoading.value = true
    try {
      const employees = await fetchEmployees()
      reviewSubmitReviewerOptions.value = (Array.isArray(employees) ? employees : [])
        .filter(
          (item) =>
            item.status === '在职' &&
            Array.isArray(item.roleCodes) &&
            item.roleCodes.includes('manager')
        )
        .map((item) => ({
          value: item.name,
          label: `${item.name} · ${item.position || '高级管理员'}`
        }))
    } catch (error) {
      reviewSubmitReviewerOptions.value = []
      toast(error?.message || '审核人列表加载失败，请稍后重试。')
    } finally {
      reviewSubmitReviewerLoading.value = false
    }
  }

  async function openSubmitReviewDialog() {
    if (
      selectedSkillUsesJsonRisk.value &&
      !canOpenRiskRuleReviewSubmit.value
    ) {
      return
    }
    if (!selectedSkill.value || !canSubmitReview.value || detailBusy.value) {
      return
    }

    reviewSubmitVersion.value = selectedSkill.value.workingVersion || selectedSkill.value.displayVersion || ''
    reviewSubmitReviewer.value = selectedSkill.value.reviewer || ''
    reviewSubmitOpen.value = true
    await loadReviewSubmitReviewers()
    if (!reviewSubmitReviewerOptions.value.some((item) => item.value === reviewSubmitReviewer.value)) {
      reviewSubmitReviewer.value = reviewSubmitReviewerOptions.value[0]?.value || ''
    }
  }

  function closeSubmitReviewDialog() {
    if (detailBusy.value) {
      return
    }
    reviewSubmitOpen.value = false
  }

  async function submitSelectedRuleForReview() {
    if (!selectedSkill.value || !canSubmitReview.value || detailBusy.value) {
      return
    }
    if (selectedSkillUsesJsonRisk.value && !riskRuleTestPassed.value) {
      toast('当前规则版本尚未确认测试通过，不能提交审核。')
      return
    }

    const version = normalizeText(reviewSubmitVersion.value)
    const reviewer = normalizeText(reviewSubmitReviewer.value)
    if (!version) {
      toast('请输入送审版本号。')
      return
    }
    if (!reviewer) {
      toast('请选择审核人。')
      return
    }

    actionState.value = 'review-pending'
    try {
      await createAgentAssetReview(
        selectedSkill.value.id,
        {
          version,
          reviewer,
          review_status: 'pending',
          review_note: buildReviewNote('pending')
        },
        { actor: resolveActor() }
      )
      reviewSubmitOpen.value = false
      await refreshCurrentAssets()
      await loadSelectedAssetDetail(selectedSkill.value.id, { silent: true })
      toast(`规则版本 ${version} 已提交给 ${reviewer} 审核。`)
    } catch (error) {
      toast(error?.message || '规则审核提交失败，请稍后重试。')
    } finally {
      actionState.value = ''
    }
  }

  return {
    reviewSubmitOpen,
    reviewSubmitVersion,
    reviewSubmitReviewer,
    reviewSubmitReviewerLoading,
    reviewSubmitReviewerOptions,
    canSubmitReview,
    hasReviewSubmitReviewers,
    canReviewSelected,
    reviewSelectedRule,
    openSubmitReviewDialog,
    closeSubmitReviewDialog,
    submitSelectedRuleForReview
  }
}
