<script setup>
import { h, onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  NButton,
  NForm,
  NFormItem,
  NInput,
  NTag,
  NSelect,
  NDatePicker,
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'

import { formatDate, renderIcon } from '@/utils'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import AuditDetail from './components/AuditDetail.vue'
import { STATUS_OPTIONS, getStatusConfig } from './constants'
import { formatAmount } from './utils'

defineOptions({ name: '审核列表' })

const router = useRouter()
const route = useRoute()
const $table = ref(null)
const queryItems = ref({})

// 列表与详情公共方法
const renderStatus = (status) => {
  const config = getStatusConfig(status)
  return h(NTag, { type: config.type }, { default: () => config.text })
}

// 列定义
const columns = [
  { title: '编号', key: 'id', width: 80, align: 'center' },
  {
    title: '手机号',
    key: 'phone',
    width: 120,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '微信号',
    key: 'wechat',
    width: 120,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '评估结果',
    key: 'valuation_result',
    width: 120,
    align: 'center',
    render(row) {
      return formatAmount(row.valuation_result)
    },
  },
  {
    title: '提交时间',
    key: 'created_at',
    width: 160,
    align: 'center',
    render(row) {
      return formatDate(row.created_at)
    },
  },
  {
    title: '审核时间',
    key: 'reviewed_at',
    width: 160,
    align: 'center',
    render(row) {
      return row.reviewed_at ? formatDate(row.reviewed_at) : '-'
    },
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    align: 'center',
    render(row) {
      return renderStatus(row.status)
    },
  },
  {
    title: '操作',
    key: 'actions',
    width: 120,
    align: 'center',
    fixed: 'right',
    render(row) {
      if (row.status === 'pending') {
        return h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            onClick: () => goToDetail(row, 'approve'),
          },
          {
            default: () => '审核',
            icon: renderIcon('mdi:check-circle-outline', { size: 16 }),
          }
        )
      }
      if (row.status === 'approved') {
        return h(
          NButton,
          {
            size: 'small',
            type: 'info',
            onClick: () => goToDetail(row, 'view'),
          },
          {
            default: () => '查看',
            icon: renderIcon('mdi:eye-outline', { size: 16 }),
          }
        )
      }
      return null
    },
  },
]

// 详情页状态
const isDetailView = ref(false)
const detailLoading = ref(false)
const detailData = ref(null)
const detailMode = ref('view')

// 审核备注弹窗
const approvalModalVisible = ref(false)
const approvalModalTitle = ref('审核估值评估')
const approvalForm = ref({
  valuation_id: null,
  admin_notes: '',
  action: 'approve',
})
const approvalFormRef = ref(null)

// 文案设置弹窗
const contentModalVisible = ref(false)
const contentForm = ref({
  content: '',
})
const contentFormRef = ref(null)

onMounted(() => {
  $table.value?.handleSearch()
})

// 格式化金额
// 查看详情
function goToDetail(row, mode = 'view') {
  const nextQuery = { ...route.query, detailId: String(row.id), mode }
  router.push({ query: nextQuery })
}

function resetDetailState() {
  isDetailView.value = false
  detailLoading.value = false
  detailData.value = null
  detailMode.value = 'view'
}

async function loadDetail(detailId, mode = 'view') {
  const parsedId = Number(detailId)
  if (!parsedId) {
    resetDetailState()
    return
  }
  detailMode.value = mode === 'approve' ? 'approve' : 'view'
  isDetailView.value = true
  detailLoading.value = true
  try {
    const { data } = await api.getValuationById({ valuation_id: parsedId })
    detailData.value = data
    approvalForm.value.valuation_id = parsedId
  } catch (error) {
    $message?.error(error?.message || '获取详情失败')
    backToList()
  } finally {
    detailLoading.value = false
  }
}

function backToList() {
  const nextQuery = { ...route.query }
  delete nextQuery.detailId
  delete nextQuery.mode
  router.replace({ query: nextQuery })
  $table.value?.handleSearch()
}

function openApprovalModal(action) {
  approvalForm.value.action = action
  approvalForm.value.admin_notes = ''
  approvalModalTitle.value = action === 'approve' ? '通过审核' : '拒绝审核'
  approvalModalVisible.value = true
}

// 文案设置弹窗
function handleAddContent() {
  contentForm.value = { content: '' }
  contentModalVisible.value = true
}

function handleContentSave() {
  contentFormRef.value?.validate((errors) => {
    if (!errors) {
      contentModalVisible.value = false
      $message?.success('文案上传并通知成功')
    }
  })
}

// 审核处理
async function handleApprovalSubmit() {
  try {
    await approvalFormRef.value?.validate()
    const action = approvalForm.value.action
    const apiCall = action === 'approve' ? api.approveValuation : api.rejectValuation
    await apiCall({
      valuation_id: approvalForm.value.valuation_id,
      admin_notes: approvalForm.value.admin_notes,
    })
    $message?.success(action === 'approve' ? '审核通过成功' : '审核拒绝成功')
    approvalModalVisible.value = false
    backToList()
  } catch (error) {
    if (error?.message) {
      $message?.error(error.message)
    }
  }
}

const approvalRules = {
  admin_notes: [
    { required: true, message: '请输入审核备注', trigger: ['input', 'blur'] },
  ],
}

const contentRules = {
  content: [
    { required: true, message: '请输入文案内容', trigger: ['input', 'blur'] },
  ],
}

watch(
  () => [route.query.detailId, route.query.mode],
  ([detailId, mode]) => {
    if (detailId) {
      loadDetail(detailId, mode)
    } else {
      resetDetailState()
    }
  },
  { immediate: true }
)
</script>

<template>
  <CommonPage show-footer title="审核列表">
    <template v-if="!isDetailView">
      <CrudTable
        ref="$table"
        v-model:query-items="queryItems"
        :columns="columns"
        :get-data="api.getValuationList"
      >
        <template #queryBar>
          <QueryBarItem label="手机号" :label-width="80">
            <NInput
              v-model:value="queryItems.phone"
              clearable
              type="text"
              placeholder="请输入手机号"
              style="width: 200px"
              @keypress.enter="$table?.handleSearch()"
            />
          </QueryBarItem>
          <QueryBarItem label="微信号" :label-width="80">
            <NInput
              v-model:value="queryItems.wechat"
              clearable
              type="text"
              placeholder="请输入微信号"
              style="width: 200px"
              @keypress.enter="$table?.handleSearch()"
            />
          </QueryBarItem>
          <QueryBarItem label="提交时间" :label-width="80">
            <NDatePicker
              v-model:value="queryItems.created_at"
              type="daterange"
              clearable
              placeholder="请选择提交时间"
              style="width: 280px"
              @update:value="$table?.handleSearch()"
            />
          </QueryBarItem>
          <QueryBarItem label="审核时间" :label-width="80">
            <NDatePicker
              v-model:value="queryItems.reviewed_at"
              type="daterange"
              clearable
              placeholder="请选择审核时间"
              style="width: 280px"
              @update:value="$table?.handleSearch()"
            />
          </QueryBarItem>
          <QueryBarItem label="状态" :label-width="80">
            <NSelect
              v-model:value="queryItems.status"
              :options="STATUS_OPTIONS"
              placeholder="请选择状态"
              clearable
              style="width: 200px"
              @update:value="$table?.handleSearch()"
            />
          </QueryBarItem>
        </template>

        <template #action>
          <NButton type="primary" @click="handleAddContent">
            <TheIcon icon="mdi:plus" :size="18" class="mr-5" />
            新增文案设置
          </NButton>
        </template>
      </CrudTable>
    </template>

    <template v-else>
      <AuditDetail
        :detail-data="detailData"
        :loading="detailLoading"
        :mode="detailMode"
        @back="backToList"
        @approve="openApprovalModal('approve')"
        @reject="openApprovalModal('reject')"
      />
    </template>

    <!-- 审核弹窗 -->
    <CrudModal v-model:visible="approvalModalVisible" :title="approvalModalTitle" :show-footer="false">
      <NForm
        ref="approvalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="100"
        :model="approvalForm"
        :rules="approvalRules"
      >
        <NFormItem label="审核备注" path="admin_notes">
          <NInput
            v-model:value="approvalForm.admin_notes"
            type="textarea"
            :rows="4"
            placeholder="请输入审核备注"
          />
        </NFormItem>
        <NFormItem>
          <div class="modal-actions">
            <NButton @click="approvalModalVisible = false">取消</NButton>
            <NButton type="primary" @click="handleApprovalSubmit">
              {{ approvalForm.action === 'approve' ? '确认通过' : '确认拒绝' }}
            </NButton>
          </div>
        </NFormItem>
      </NForm>
    </CrudModal>

    <!-- 文案设置弹窗 -->
    <CrudModal v-model:visible="contentModalVisible" title="新增文案设置" :show-footer="false">
      <NForm
        ref="contentFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="contentForm"
        :rules="contentRules"
      >
        <NFormItem label="文案" path="content">
          <NInput
            v-model:value="contentForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入文案内容"
          />
        </NFormItem>
        <NFormItem>
          <div class="modal-actions">
            <NButton @click="contentModalVisible = false">取消</NButton>
            <NButton type="primary" @click="handleContentSave">上传并通知</NButton>
          </div>
        </NFormItem>
      </NForm>
    </CrudModal>
  </CommonPage>
</template>

<style scoped>
.modal-actions {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
