<template>
  <div class="sms-signature-page">
    <div class="page-header">
      <div class="header-info">
        <div class="header-icon">
          <svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="#67c23a" stroke-width="1.8">
            <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/>
            <polyline points="14 2 14 8 20 8"/>
            <path d="M9 15l2 2 4-4"/>
          </svg>
        </div>
        <div>
          <h2 class="header-title">短信签名管理</h2>
          <p class="header-desc">管理用户提交的短信签名，审核通过后方可使用</p>
        </div>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon> 新增签名
        </el-button>
      </div>
    </div>

    <!-- 筛选栏 -->
    <div class="filter-bar">
      <el-select v-model="queryParams.service_id" placeholder="选择主控服务" style="width: 200px" @change="handleSearch">
        <el-option v-for="s in serviceOptions" :key="s.id" :label="s.name" :value="s.id" />
      </el-select>
      <el-select v-model="queryParams.status" placeholder="全部状态" clearable style="width: 140px" @change="handleSearch">
        <el-option label="草稿" :value="0" />
        <el-option label="审核中" :value="1" />
        <el-option label="已通过" :value="2" />
        <el-option label="已驳回" :value="3" />
      </el-select>
      <el-input
        v-if="filterUserInfo"
        :model-value="`${filterUserInfo.user_name} (ID: ${queryParams.user_id})`"
        readonly
        style="width: 200px"
      >
        <template #suffix>
          <el-icon class="clear-icon" @click="clearFilterUser"><Close /></el-icon>
        </template>
        <template #prefix><el-icon><User /></el-icon></template>
      </el-input>
      <el-input v-else placeholder="筛选用户" readonly style="width: 140px" @click="filterUserSelectorVisible = true">
        <template #prefix><el-icon><User /></el-icon></template>
      </el-input>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="handleReset">重置</el-button>
    </div>

    <!-- 卡片列表 -->
    <div v-loading="loading" class="signature-cards">
      <div v-if="!tableData.length && !loading" class="empty-state">
        <el-empty description="暂无签名数据" :image-size="80" />
      </div>
      <div v-for="item in tableData" :key="item.ID" class="sig-card" :class="`status-${item.status}`">
        <div class="sig-card-header">
          <div class="sig-card-title">
            <span class="sig-title-text">{{ item.title }}</span>
            <el-tag :type="statusTagType(item.status)" size="small" effect="dark">{{ statusText(item.status) }}</el-tag>
          </div>
          <span class="sig-card-id">#{{ item.ID }}</span>
        </div>

        <div class="sig-card-body">
          <div class="sig-card-info">
            <div class="sig-info-row">
              <span class="sig-label">申请人</span>
              <span class="sig-value">{{ item.applicant_name || '-' }}</span>
            </div>
            <div class="sig-info-row">
              <span class="sig-label">用户</span>
              <el-link type="primary" :underline="false" @click="$router.push({ path: '/user/detail', query: { user_id: item.user_id } })">ID: {{ item.user_id }}</el-link>
            </div>
            <div class="sig-info-row">
              <span class="sig-label">公司</span>
              <span class="sig-value">{{ item.applicant_company || '-' }}</span>
            </div>
            <div class="sig-info-row">
              <span class="sig-label">身份证</span>
              <span class="sig-value sig-id-card">{{ item.applicant_id_card || '-' }}</span>
            </div>
            <div class="sig-info-row">
              <span class="sig-label">创建时间</span>
              <span class="sig-value">{{ formatDate(item.CreatedAt) }}</span>
            </div>
            <div v-if="item.reject_reason" class="sig-info-row reject-row">
              <span class="sig-label">驳回原因</span>
              <span class="sig-value reject-text">{{ item.reject_reason }}</span>
            </div>
          </div>
          <div class="sig-card-license">
            <el-image
              v-if="item.license_url"
              :src="item.license_url"
              :preview-src-list="[item.license_url]"
              fit="cover"
              class="license-img"
              preview-teleported
            />
            <div v-else class="license-placeholder">
              <el-icon :size="24"><Picture /></el-icon>
              <span>无资质证明</span>
            </div>
          </div>
        </div>

        <div class="sig-card-footer">
          <el-button size="small" @click="handleDetail(item)">详情</el-button>
          <el-button type="primary" size="small" @click="handleEdit(item)">编辑</el-button>
          <el-button v-if="item.status === 0" type="warning" size="small" @click="handleSubmit(item)">提交审核</el-button>
          <el-button v-if="item.status === 1" type="success" size="small" @click="handleApprove(item)">通过</el-button>
          <el-button v-if="item.status === 1" type="danger" size="small" plain @click="handleReject(item)">驳回</el-button>
          <el-button type="danger" size="small" plain @click="handleDelete(item)">删除</el-button>
        </div>
      </div>
    </div>

    <el-pagination
      v-model:current-page="queryParams.page"
      v-model:page-size="queryParams.count"
      :page-sizes="[10, 20, 50]"
      layout="total, sizes, prev, pager, next"
      :total="total"
      @size-change="fetchList"
      @current-change="fetchList"
      background
      class="pagination"
    />

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增签名' : '编辑签名'" width="560px" append-to-body destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="110px">
        <el-form-item label="主控服务" prop="service_id">
          <el-select v-model="form.service_id" placeholder="选择服务" style="width: 100%" :disabled="dialogType === 'edit'">
            <el-option v-for="s in serviceOptions" :key="s.id" :label="s.name" :value="s.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户" prop="user_id">
          <el-input
            v-if="selectedUserInfo"
            :model-value="`${selectedUserInfo.user_name} (ID: ${form.user_id})`"
            readonly
          >
            <template #suffix>
              <el-icon v-if="dialogType === 'add'" class="clear-icon" @click="clearUser"><Close /></el-icon>
            </template>
            <template #append>
              <el-button @click="userSelectorVisible = true" :disabled="dialogType === 'edit'"><el-icon><User /></el-icon></el-button>
            </template>
          </el-input>
          <el-input v-else placeholder="请选择用户" readonly @click="openUserSelector">
            <template #append>
              <el-button @click="openUserSelector" :disabled="dialogType === 'edit'"><el-icon><User /></el-icon></el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="签名标题" prop="title">
          <el-input v-model="form.title" placeholder="如：某某公司" maxlength="30" show-word-limit />
        </el-form-item>

        <el-divider content-position="left">申请人资料</el-divider>
        <el-form-item label="申请人姓名">
          <el-input v-model="form.applicant_name" placeholder="申请人真实姓名（可选）" />
        </el-form-item>
        <el-form-item label="申请人身份证号" prop="applicant_id_card">
          <el-input v-model="form.applicant_id_card" placeholder="申请人身份证号（可选）" />
        </el-form-item>

        <el-divider content-position="left">主体资料</el-divider>
        <el-form-item label="主体名称">
          <el-input v-model="form.applicant_company" placeholder="企业/主体名称（可选）" />
        </el-form-item>
        <el-form-item label="统一社会信用代码">
          <el-input v-model="form.credit_code" placeholder="统一社会信用代码（可选）" />
        </el-form-item>
        <el-form-item label="营业执照URL">
          <el-input v-model="form.license_url" placeholder="营业执照图片地址（可选）" />
        </el-form-item>

        <el-divider content-position="left">法人资料</el-divider>
        <el-form-item label="法人姓名">
          <el-input v-model="form.legal_person_name" placeholder="法人姓名（可选）" />
        </el-form-item>
        <el-form-item label="法人手机号" prop="legal_person_phone">
          <el-input v-model="form.legal_person_phone" placeholder="法人手机号（可选）" />
        </el-form-item>
        <el-form-item label="法人身份证号" prop="legal_person_id_card">
          <el-input v-model="form.legal_person_id_card" placeholder="法人身份证号（可选）" />
        </el-form-item>

        <el-divider content-position="left">经办人资料</el-divider>
        <el-form-item label="经办人手机号" prop="agent_phone">
          <el-input v-model="form.agent_phone" placeholder="经办人手机号（可选）" />
        </el-form-item>
        <el-form-item label="身份证正面URL">
          <el-input v-model="form.agent_id_card_front_url" placeholder="经办人身份证正面图片地址（可选）" />
        </el-form-item>
        <el-form-item label="身份证反面URL">
          <el-input v-model="form.agent_id_card_back_url" placeholder="经办人身份证反面图片地址（可选）" />
        </el-form-item>

        <el-divider content-position="left">承诺函</el-divider>
        <el-form-item label="承诺函URL">
          <el-input v-model="form.commitment_letter_url" placeholder="签署盖章后的承诺函照片地址（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleFormSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 驳回原因对话框 -->
    <el-dialog v-model="rejectDialogVisible" title="驳回签名" width="420px" append-to-body>
      <el-form label-width="80px">
        <el-form-item label="驳回原因">
          <el-input v-model="rejectReason" type="textarea" :rows="3" placeholder="请输入驳回原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button type="danger" :loading="submitting" @click="confirmReject">确认驳回</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailVisible" title="签名详情" width="640px" append-to-body destroy-on-close>
      <div v-if="detailData" class="detail-wrap">
        <el-descriptions title="基础信息" :column="2" border size="small">
          <el-descriptions-item label="签名标题">{{ detailData.title || '-' }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="statusTagType(detailData.status)" size="small" effect="dark">{{ statusText(detailData.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="用户">
            <el-link type="primary" :underline="false" @click="$router.push({ path: '/user/detail', query: { user_id: detailData.user_id } })">ID: {{ detailData.user_id }}</el-link>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(detailData.CreatedAt) }}</el-descriptions-item>
          <el-descriptions-item v-if="detailData.reject_reason" label="驳回原因" :span="2">
            <span class="reject-text">{{ detailData.reject_reason }}</span>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="申请人资料" :column="2" border size="small" class="detail-section">
          <el-descriptions-item label="申请人姓名">{{ detailData.applicant_name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="申请人身份证号">{{ detailData.applicant_id_card || '-' }}</el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="主体资料" :column="2" border size="small" class="detail-section">
          <el-descriptions-item label="主体名称">{{ detailData.applicant_company || '-' }}</el-descriptions-item>
          <el-descriptions-item label="统一社会信用代码">{{ detailData.credit_code || '-' }}</el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="法人资料" :column="2" border size="small" class="detail-section">
          <el-descriptions-item label="法人姓名">{{ detailData.legal_person_name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="法人手机号">{{ detailData.legal_person_phone || '-' }}</el-descriptions-item>
          <el-descriptions-item label="法人身份证号" :span="2">{{ detailData.legal_person_id_card || '-' }}</el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="经办人资料" :column="2" border size="small" class="detail-section">
          <el-descriptions-item label="经办人手机号">{{ detailData.agent_phone || '-' }}</el-descriptions-item>
        </el-descriptions>

        <div class="detail-section detail-images-title">证件与文件</div>
        <div class="detail-images">
          <div class="detail-img-item">
            <span class="detail-img-label">营业执照</span>
            <el-image v-if="detailData.license_url" :src="detailData.license_url" :preview-src-list="[detailData.license_url]" fit="cover" class="detail-img" preview-teleported />
            <div v-else class="detail-img-empty">未上传</div>
          </div>
          <div class="detail-img-item">
            <span class="detail-img-label">身份证正面</span>
            <el-image v-if="detailData.agent_id_card_front_url" :src="detailData.agent_id_card_front_url" :preview-src-list="[detailData.agent_id_card_front_url]" fit="cover" class="detail-img" preview-teleported />
            <div v-else class="detail-img-empty">未上传</div>
          </div>
          <div class="detail-img-item">
            <span class="detail-img-label">身份证反面</span>
            <el-image v-if="detailData.agent_id_card_back_url" :src="detailData.agent_id_card_back_url" :preview-src-list="[detailData.agent_id_card_back_url]" fit="cover" class="detail-img" preview-teleported />
            <div v-else class="detail-img-empty">未上传</div>
          </div>
          <div class="detail-img-item">
            <span class="detail-img-label">承诺函</span>
            <el-image v-if="detailData.commitment_letter_url" :src="detailData.commitment_letter_url" :preview-src-list="[detailData.commitment_letter_url]" fit="cover" class="detail-img" preview-teleported />
            <div v-else class="detail-img-empty">未上传</div>
          </div>
        </div>
        <div class="detail-file-row">
          <span class="detail-img-label">申请文件</span>
          <el-button
            v-if="getApplicationFileUrl(detailData)"
            link
            type="primary"
            :loading="applicationFileDownloading"
            @click="downloadApplicationFile(detailData)"
          >
            <el-icon v-if="!applicationFileDownloading"><Download /></el-icon>
            下载申请文件
          </el-button>
          <span v-else class="detail-empty-text">暂无可下载文件</span>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 表单用户选择器 -->
    <UserListSelector
      v-model="userSelectorVisible"
      :current-user-id="form.user_id"
      @confirm="handleUserSelect"
    />
    <!-- 筛选用户选择器 -->
    <UserListSelector
      v-model="filterUserSelectorVisible"
      :current-user-id="queryParams.user_id ? Number(queryParams.user_id) : undefined"
      @confirm="handleFilterUserSelect"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, User, Close, Picture, Download } from '@element-plus/icons-vue'
import { formatDate } from '@/utils/tool'
import {
  getSmsServiceList,
  getSmsSignatureList, createSmsSignature, updateSmsSignature, deleteSmsSignature,
  submitSmsSignature, approveSmsSignature, rejectSmsSignature
} from '@/api/admin/smsService'
import UserListSelector from '@/components/admin/UserListSelector.vue'

const loading = ref(false)
const submitting = ref(false)
const tableData = ref([])
const total = ref(0)
const serviceOptions = ref([])

const queryParams = reactive({ service_id: null, page: 1, count: 10, user_id: '', status: null })

const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)

const createEmptyForm = () => ({
  service_id: null,
  user_id: null,
  title: '',
  // 主体资料
  applicant_company: '',
  credit_code: '',
  license_url: '',
  // 法人资料
  legal_person_name: '',
  legal_person_phone: '',
  legal_person_id_card: '',
  // 经办人资料
  applicant_name: '',
  agent_phone: '',
  applicant_id_card: '',
  agent_id_card_front_url: '',
  agent_id_card_back_url: '',
  commitment_letter_url: ''
})

const form = reactive(createEmptyForm())
const originalEditForm = ref(null)

// 非必填字段：仅当填写时才校验格式，接口未声明必填的字段不设为必填
const validatePhone = (rule, value, callback) => {
  if (value && !/^1[3-9]\d{9}$/.test(value)) {
    callback(new Error('请输入正确的手机号'))
  } else {
    callback()
  }
}
const validateIdCard = (rule, value, callback) => {
  if (value && !/(^\d{15}$)|(^\d{17}[\dXx]$)/.test(value)) {
    callback(new Error('请输入正确的身份证号'))
  } else {
    callback()
  }
}

const formRules = {
  service_id: [{ required: true, message: '请选择服务', trigger: 'change' }],
  user_id: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
  title: [{ required: true, message: '请输入签名标题', trigger: 'blur' }],
  legal_person_phone: [{ validator: validatePhone, trigger: 'blur' }],
  agent_phone: [{ validator: validatePhone, trigger: 'blur' }],
  legal_person_id_card: [{ validator: validateIdCard, trigger: 'blur' }],
  applicant_id_card: [{ validator: validateIdCard, trigger: 'blur' }]
}

const rejectDialogVisible = ref(false)
const rejectReason = ref('')
const currentRow = ref(null)

const detailVisible = ref(false)
const detailData = ref(null)
const applicationFileDownloading = ref(false)

const userSelectorVisible = ref(false)
const selectedUserInfo = ref(null)
const filterUserSelectorVisible = ref(false)
const filterUserInfo = ref(null)

const statusText = (s) => ({ 0: '草稿', 1: '审核中', 2: '已通过', 3: '已驳回' }[s] || '未知')
const statusTagType = (s) => ({ 0: 'info', 1: 'warning', 2: 'success', 3: 'danger' }[s] || 'info')

const loadServices = async () => {
  try {
    const res = await getSmsServiceList({ page: 1, count: 199 })
    const body = res.data
    if (body.code === 200) {
      const list = body.data?.data || body.data || []
      serviceOptions.value = Array.isArray(list) ? list : []
      if (serviceOptions.value.length && !queryParams.service_id) {
        queryParams.service_id = serviceOptions.value[0].id
      }
    }
  } catch (e) { console.error(e) }
}

const fetchList = async () => {
  if (!queryParams.service_id) return
  loading.value = true
  try {
    const params = { service_id: queryParams.service_id, page: queryParams.page, count: queryParams.count }
    if (queryParams.user_id) params.user_id = Number(queryParams.user_id)
    if (queryParams.status !== null && queryParams.status !== '') params.status = queryParams.status
    const res = await getSmsSignatureList(params)
    if (res.data.code === 200) {
      const d = res.data.data
      tableData.value = d?.data || d || []
      total.value = d?.all_count || 0
    }
  } catch (e) { ElMessage.error('获取签名列表失败') }
  finally { loading.value = false }
}

const handleFilterUserSelect = (user) => {
  queryParams.user_id = String(user.user_id)
  filterUserInfo.value = user
  handleSearch()
}
const clearFilterUser = () => {
  queryParams.user_id = ''
  filterUserInfo.value = null
  handleSearch()
}

const handleSearch = () => { queryParams.page = 1; fetchList() }
const handleReset = () => { queryParams.user_id = ''; queryParams.status = null; filterUserInfo.value = null; queryParams.page = 1; fetchList() }

const openUserSelector = () => {
  if (dialogType.value === 'edit') return
  userSelectorVisible.value = true
}

const handleUserSelect = (user) => {
  form.user_id = user.user_id
  selectedUserInfo.value = user
}

const clearUser = () => {
  form.user_id = null
  selectedUserInfo.value = null
}

const handleDetail = (row) => {
  detailData.value = row
  detailVisible.value = true
}

const getSignatureService = (row) => {
  const serviceId = row.service_id || queryParams.service_id
  return serviceOptions.value.find(item => String(item.id) === String(serviceId))
}

const getApplicationFileUrl = (row) => {
  if (!row?.ID || !row?.application_file_url) return ''
  const service = getSignatureService(row)
  const endpoint = String(service?.host || '').replace(/\/+$/, '')
  if (!endpoint) return ''
  return `${endpoint}/api/sms/admin/signature/${row.ID}/application-file`
}

const getDownloadFilename = (headers, signatureId) => {
  const disposition = headers?.['content-disposition'] || ''
  const utf8Match = disposition.match(/filename\*=UTF-8''([^;]+)/i)
  const plainMatch = disposition.match(/filename="?([^";]+)"?/i)
  const encodedName = utf8Match?.[1] || plainMatch?.[1]
  if (!encodedName) return `签名申请文件_${signatureId}.xlsx`
  try {
    return decodeURIComponent(encodedName)
  } catch {
    return encodedName
  }
}

const downloadApplicationFile = async (row) => {
  const url = getApplicationFileUrl(row)
  if (!url || applicationFileDownloading.value) return

  const service = getSignatureService(row)
  const endpoint = String(service?.host || '').replace(/\/+$/, '')
  const serviceToken = service?.serviceToken || service?.service_token
  if (!serviceToken) {
    ElMessage.error('当前短信平台未配置 Service Token')
    return
  }

  applicationFileDownloading.value = true
  try {
    const loginResponse = await axios.post(
      `${endpoint}/api/auth/service-token-login`,
      { service_token: serviceToken },
      { timeout: 15000 }
    )
    const loginBody = loginResponse.data || {}
    const platformToken = loginBody.data?.token
    if (loginBody.code !== 200 || !platformToken) {
      throw new Error(loginBody.message || '短信平台 Token 获取失败')
    }

    const response = await axios.get(url, {
      headers: { Authorization: `Bearer ${platformToken}` },
      responseType: 'blob',
      timeout: 60000
    })
    const contentType = response.headers?.['content-type'] || ''
    if (contentType.includes('application/json')) {
      const body = JSON.parse(await response.data.text())
      throw new Error(body.message || body.msg || '下载申请文件失败')
    }

    const objectUrl = window.URL.createObjectURL(response.data)
    const link = document.createElement('a')
    link.href = objectUrl
    link.download = getDownloadFilename(response.headers, row.ID)
    document.body.appendChild(link)
    link.click()
    link.remove()
    window.URL.revokeObjectURL(objectUrl)
  } catch (error) {
    ElMessage.error(error.message || '下载申请文件失败')
  } finally {
    applicationFileDownloading.value = false
  }
}

const handleAdd = () => {
  dialogType.value = 'add'
  selectedUserInfo.value = null
  originalEditForm.value = null
  Object.assign(form, createEmptyForm(), { service_id: queryParams.service_id })
  delete form.signature_id
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  selectedUserInfo.value = { user_id: row.user_id, user_name: `用户${row.user_id}` }
  Object.assign(form, createEmptyForm(), {
    service_id: queryParams.service_id,
    signature_id: row.ID,
    user_id: row.user_id,
    title: row.title,
    applicant_company: row.applicant_company || '',
    credit_code: row.credit_code || '',
    license_url: row.license_url || '',
    legal_person_name: row.legal_person_name || '',
    legal_person_phone: row.legal_person_phone || '',
    legal_person_id_card: row.legal_person_id_card || '',
    applicant_name: row.applicant_name || '',
    agent_phone: row.agent_phone || '',
    applicant_id_card: row.applicant_id_card || '',
    agent_id_card_front_url: row.agent_id_card_front_url || '',
    agent_id_card_back_url: row.agent_id_card_back_url || '',
    commitment_letter_url: row.commitment_letter_url || ''
  })
  originalEditForm.value = { ...form }
  dialogVisible.value = true
}

const handleFormSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    submitting.value = true
    try {
      let res
      if (dialogType.value === 'add') {
        res = await createSmsSignature({ ...form })
      } else {
        const data = {
          service_id: form.service_id,
          signature_id: form.signature_id
        }
        const editableFields = [
          'title',
          'applicant_name',
          'applicant_id_card',
          'applicant_company',
          'license_url',
          'credit_code',
          'legal_person_name',
          'legal_person_phone',
          'legal_person_id_card',
          'agent_phone',
          'agent_id_card_front_url',
          'agent_id_card_back_url',
          'commitment_letter_url'
        ]
        editableFields.forEach((field) => {
          if (form[field] !== originalEditForm.value?.[field]) {
            data[field] = form[field]
          }
        })
        res = await updateSmsSignature(data)
      }
      if (res.data.code === 200) {
        ElMessage.success(dialogType.value === 'add' ? '创建成功' : '修改成功')
        dialogVisible.value = false
        fetchList()
      } else { ElMessage.error(res.data.message || '操作失败') }
    } catch (e) { ElMessage.error('操作失败') }
    finally { submitting.value = false }
  })
}

const handleSubmit = (row) => {
  ElMessageBox.confirm(`确认提交签名「${row.title}」进行审核？`, '提交审核', { type: 'info' }).then(async () => {
    try {
      const res = await submitSmsSignature({ service_id: queryParams.service_id, signature_id: row.ID })
      if (res.data.code === 200) { ElMessage.success('已提交审核'); fetchList() }
      else { ElMessage.error(res.data.message || '提交失败') }
    } catch { ElMessage.error('提交失败') }
  }).catch(() => {})
}

const handleApprove = (row) => {
  ElMessageBox.confirm(`确认通过签名「${row.title}」？`, '审核通过', { type: 'success' }).then(async () => {
    try {
      const res = await approveSmsSignature({ service_id: queryParams.service_id, signature_id: row.ID })
      if (res.data.code === 200) { ElMessage.success('已通过'); fetchList() }
      else { ElMessage.error(res.data.message || '操作失败') }
    } catch { ElMessage.error('操作失败') }
  }).catch(() => {})
}

const handleReject = (row) => {
  currentRow.value = row
  rejectReason.value = ''
  rejectDialogVisible.value = true
}

const confirmReject = async () => {
  if (!rejectReason.value.trim()) { ElMessage.warning('请输入驳回原因'); return }
  submitting.value = true
  try {
    const res = await rejectSmsSignature({ service_id: queryParams.service_id, signature_id: currentRow.value.ID, reject_reason: rejectReason.value })
    if (res.data.code === 200) { ElMessage.success('已驳回'); rejectDialogVisible.value = false; fetchList() }
    else { ElMessage.error(res.data.message || '驳回失败') }
  } catch { ElMessage.error('驳回失败') }
  finally { submitting.value = false }
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除签名「${row.title}」？`, '删除', { type: 'warning' }).then(async () => {
    try {
      const res = await deleteSmsSignature({ service_id: queryParams.service_id, signature_id: row.ID })
      if (res.data.code === 200) { ElMessage.success('删除成功'); fetchList() }
      else { ElMessage.error(res.data.message || '删除失败') }
    } catch { ElMessage.error('删除失败') }
  }).catch(() => {})
}

onMounted(async () => {
  await loadServices()
  fetchList()
})
</script>

<style scoped>
.sms-signature-page { padding: 20px; }
.page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.header-info { display: flex; align-items: center; gap: 14px; }
.header-icon { width: 48px; height: 48px; border-radius: 12px; background: #f0f9eb; display: flex; align-items: center; justify-content: center; }
.header-title { margin: 0; font-size: 20px; color: #303133; }
.header-desc { margin: 4px 0 0; font-size: 13px; color: #909399; }
.header-actions { display: flex; gap: 10px; }
.filter-bar { display: flex; gap: 10px; margin-bottom: 16px; align-items: center; flex-wrap: wrap; }
.pagination { margin-top: 16px; justify-content: flex-end; }
.clear-icon { cursor: pointer; color: #909399; transition: color 0.2s; }
.clear-icon:hover { color: #f56c6c; }

/* 卡片列表 */
.signature-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(420px, 1fr));
  gap: 16px;
  min-height: 200px;
}

.empty-state {
  grid-column: 1 / -1;
  display: flex;
  justify-content: center;
  padding: 40px 0;
}

.sig-card {
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 10px;
  padding: 18px;
  transition: all 0.25s;
  display: flex;
  flex-direction: column;
}
.sig-card:hover {
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
  border-color: #d9d9d9;
  transform: translateY(-2px);
}
.sig-card.status-1 { border-left: 3px solid #e6a23c; }
.sig-card.status-2 { border-left: 3px solid #67c23a; }
.sig-card.status-3 { border-left: 3px solid #f56c6c; }

.sig-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 14px;
}
.sig-card-title {
  display: flex;
  align-items: center;
  gap: 10px;
}
.sig-title-text {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}
.sig-card-id {
  font-size: 12px;
  color: #c0c4cc;
}

.sig-card-body {
  display: flex;
  gap: 16px;
  flex: 1;
  margin-bottom: 14px;
}
.sig-card-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}
.sig-info-row {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 13px;
}
.sig-label {
  color: #909399;
  min-width: 56px;
  flex-shrink: 0;
}
.sig-value {
  color: #303133;
  word-break: break-all;
}
.sig-id-card {
  font-family: monospace;
  font-size: 12px;
  color: #606266;
}
.reject-row .sig-value {
  color: #f56c6c;
}
.reject-text { color: #f56c6c; }

.sig-card-license {
  flex-shrink: 0;
  width: 90px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.license-img {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  cursor: pointer;
}
.license-placeholder {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  background: #f5f7fa;
  border: 1px dashed #dcdfe6;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  color: #c0c4cc;
  font-size: 11px;
}

.sig-card-footer {
  display: flex;
  gap: 8px;
  padding-top: 12px;
  border-top: 1px solid #f0f2f5;
  flex-wrap: wrap;
}

/* 详情弹窗 */
.detail-wrap { max-height: 60vh; overflow-y: auto; padding-right: 4px; }
.detail-section { margin-top: 16px; }
.detail-images-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
}
.detail-images {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}
.detail-img-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
}
.detail-img-label {
  font-size: 12px;
  color: #909399;
}
.detail-img {
  width: 140px;
  height: 90px;
  border-radius: 6px;
  border: 1px solid #ebeef5;
  cursor: pointer;
}
.detail-img-empty {
  width: 140px;
  height: 90px;
  border-radius: 6px;
  background: #f5f7fa;
  border: 1px dashed #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
  font-size: 12px;
}
.detail-file-row {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 16px;
}
.detail-empty-text { color: #c0c4cc; font-size: 13px; }
</style>
