<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 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-form-item label="申请人姓名">
          <el-input v-model="form.applicant_name" placeholder="申请人真实姓名" />
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="form.applicant_id_card" placeholder="申请人身份证号" />
        </el-form-item>
        <el-form-item label="公司名称">
          <el-input v-model="form.applicant_company" placeholder="申请人公司（可选）" />
        </el-form-item>
        <el-form-item label="营业执照URL">
          <el-input v-model="form.license_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>

    <!-- 表单用户选择器 -->
    <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 { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, User, Close, Picture } 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 form = reactive({ service_id: null, user_id: null, title: '', applicant_name: '', applicant_id_card: '', applicant_company: '', license_url: '' })
const formRules = {
  service_id: [{ required: true, message: '请选择服务', trigger: 'change' }],
  user_id: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
  title: [{ required: true, message: '请输入签名标题', trigger: 'blur' }]
}

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

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 handleAdd = () => {
  dialogType.value = 'add'
  selectedUserInfo.value = null
  Object.assign(form, { service_id: queryParams.service_id, user_id: null, title: '', applicant_name: '', applicant_id_card: '', applicant_company: '', license_url: '' })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  selectedUserInfo.value = { user_id: row.user_id, user_name: `用户${row.user_id}` }
  Object.assign(form, {
    service_id: queryParams.service_id,
    signature_id: row.ID,
    user_id: row.user_id,
    title: row.title,
    applicant_name: row.applicant_name || '',
    applicant_id_card: row.applicant_id_card || '',
    applicant_company: row.applicant_company || '',
    license_url: row.license_url || ''
  })
  dialogVisible.value = true
}

const handleFormSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return
    submitting.value = true
    try {
      const data = { ...form }
      let res
      if (dialogType.value === 'add') {
        res = await createSmsSignature(data)
      } else {
        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;
}
</style>
