<template>
  <div class="space-y-6">
    <!-- 主卡片 -->
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
      <div class="border-b border-gray-200 pb-4 mb-6">
        <div class="flex items-center justify-between">
          <h2 class="text-xl font-semibold text-gray-800 flex items-center gap-2">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-blue-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
            </svg>
            广告账户列表
          </h2>
          <div class="flex items-center gap-3">
            <el-select
              v-model="selectedOrgAccountId"
              placeholder="选择组织账户"
              clearable
              filterable
              style="width: 250px"
              @change="handleOrgAccountChange"
            >
              <el-option
                v-for="auth in orgAccounts"
                :key="auth.accountId"
                :label="`${auth.accountId} (${auth.accountType || ''})`"
                :value="auth.accountId"
              />
            </el-select>
            <el-button 
              type="primary" 
              @click="handleSync"
              :loading="syncing"
              :disabled="!selectedOrgAccountId"
            >
              <el-icon><Refresh /></el-icon>
              同步账户
            </el-button>
          </div>
        </div>
      </div>

      <!-- 数据统计 -->
      <div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
        <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg p-4 border border-blue-200">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-blue-600 mb-1">总账户数</p>
              <p class="text-2xl font-bold text-blue-700">{{ accountList.length }}</p>
            </div>
            <div class="p-3 bg-blue-200 rounded-lg">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-blue-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
              </svg>
            </div>
          </div>
        </div>
        <div class="bg-gradient-to-br from-green-50 to-green-100 rounded-lg p-4 border border-green-200">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-green-600 mb-1">竞价广告账户</p>
              <p class="text-2xl font-bold text-green-700">{{ bidAccountCount }}</p>
            </div>
            <div class="p-3 bg-green-200 rounded-lg">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
              </svg>
            </div>
          </div>
        </div>
        <div class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-lg p-4 border border-purple-200">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-purple-600 mb-1">微信MP账户</p>
              <p class="text-2xl font-bold text-purple-700">{{ mpAccountCount }}</p>
            </div>
            <div class="p-3 bg-purple-200 rounded-lg">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-purple-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
              </svg>
            </div>
          </div>
        </div>
        <div class="bg-gradient-to-br from-yellow-50 to-yellow-100 rounded-lg p-4 border border-yellow-200">
          <div class="flex items-center justify-between">
            <div>
              <p class="text-sm text-yellow-600 mb-1">有备注</p>
              <p class="text-2xl font-bold text-yellow-700">{{ commentAccountCount }}</p>
            </div>
            <div class="p-3 bg-yellow-200 rounded-lg">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-yellow-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
            </div>
          </div>
        </div>
      </div>

      <!-- 账户列表表格 -->
      <el-table
        :data="accountList"
        style="width: 100%"
        v-loading="loading"
        stripe
        border
      >
        <el-table-column prop="accountId" label="广告账户ID" width="150" />
        <el-table-column prop="corporationName" label="企业名称" width="200" />
        <el-table-column label="账户类型" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.isBid" type="success" size="small">竞价广告</el-tag>
            <el-tag v-if="row.isMp" type="info" size="small" style="margin-left: 5px">微信MP</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="comment" label="备注" width="200" show-overflow-tooltip />
        <el-table-column prop="commentUserId" label="备注用户ID" width="120" />
        <el-table-column label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleViewDetail(row)"
            >
              <el-icon><View /></el-icon>
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页组件 -->
      <div class="mt-6 flex justify-end">
        <el-pagination
        v-if="total > 0"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        style="justify-content: flex-end"
        />
      </div>
    </div>

    <!-- 账户详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="广告账户详情"
      width="600px"
    >
      <el-descriptions :column="1" border v-if="currentAccount">
        <el-descriptions-item label="账户ID">
          {{ currentAccount.accountId }}
        </el-descriptions-item>
        <el-descriptions-item label="组织账户ID">
          {{ currentAccount.orgAccountId }}
        </el-descriptions-item>
        <el-descriptions-item label="企业名称">
          {{ currentAccount.corporationName }}
        </el-descriptions-item>
        <el-descriptions-item label="是否竞价广告账户">
          <el-tag :type="currentAccount.isBid ? 'success' : 'info'">
            {{ currentAccount.isBid ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="是否微信MP账户">
          <el-tag :type="currentAccount.isMp ? 'success' : 'info'">
            {{ currentAccount.isMp ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注用户ID">
          {{ currentAccount.commentUserId || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="备注内容">
          {{ currentAccount.comment || '无' }}
        </el-descriptions-item>
        <el-descriptions-item label="备注列表">
          <pre v-if="currentAccount.commentList" style="margin: 0; white-space: pre-wrap; word-break: break-all;">{{ formatJSON(currentAccount.commentList) }}</pre>
          <span v-else>无</span>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(currentAccount.createTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDate(currentAccount.updateTime) }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
defineOptions({
  name: 'Account'
})

import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { syncAccounts, getAccountList, getAllAccounts } from '@/api/account'
import { getAuthList } from '@/api/auth'
import {
  Refresh,
  User,
  TrendCharts,
  ChatDotRound,
  Document,
  View
} from '@element-plus/icons-vue'

// 数据
const loading = ref(false)
const syncing = ref(false)
const accountList = ref([])
const orgAccounts = ref([])
const selectedOrgAccountId = ref(null)
const detailDialogVisible = ref(false)
const currentAccount = ref(null)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 计算属性
const bidAccountCount = computed(() => {
  return accountList.value.filter(account => account.isBid).length
})

const mpAccountCount = computed(() => {
  return accountList.value.filter(account => account.isMp).length
})

const commentAccountCount = computed(() => {
  return accountList.value.filter(account => account.comment).length
})

// 方法
const loadOrgAccounts = async () => {
  try {
    const res = await getAuthList()
    console.log('组织账户列表:', res)
    if (res.success) {
      orgAccounts.value = res.data || []
    }
  } catch (error) {
    console.error('加载组织账户失败:', error)
    ElMessage.error('加载组织账户失败')
  }
}

const loadAllAccounts = async () => {
  loading.value = true
  try {
    const res = await getAllAccounts()
    if (res.success) {
      accountList.value = res.data || []
      total.value = res.data?.length || 0
    } else {
      ElMessage.error(res.message || '加载账户列表失败')
    }
  } catch (error) {
    console.error('加载账户列表失败:', error)
    ElMessage.error('加载账户列表失败')
  } finally {
    loading.value = false
  }
}

const handleOrgAccountChange = async () => {
  currentPage.value = 1 // 重置页码
  await loadAccountList()
}

const loadAccountList = async () => {
  
  loading.value = true
  try {
    const res = await getAccountList(selectedOrgAccountId.value, currentPage.value, pageSize.value)
    if (res.success) {
      accountList.value = res.data || []
      total.value = res.total || 0
    } else {
      ElMessage.error(res.message || '加载账户列表失败')
    }
  } catch (error) {
    console.error('加载账户列表失败:', error)
    ElMessage.error('加载账户列表失败')
  } finally {
    loading.value = false
  }
}

// 分页方法
const handleSizeChange = async (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  await loadAccountList()
}

const handleCurrentChange = async (newPage) => {
  currentPage.value = newPage
  await loadAccountList()
}

const handleSync = () => {
  if (!selectedOrgAccountId.value) {
    ElMessage.warning('请先选择组织账户')
    return
  }

  ElMessageBox.confirm(
    '确定要同步该组织账户下的广告账户信息吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    syncing.value = true
    const res = await syncAccounts(selectedOrgAccountId.value)
    syncing.value = false
    if (res.data.success) {
      ElMessage.success(res.data.message || '同步成功')
      currentPage.value = 1
      await loadAccountList()
    } else {
      ElMessage.error(res.data.message || '同步失败')
    }
  })
}

const handleViewDetail = (account) => {
  currentAccount.value = account
  detailDialogVisible.value = true
}

const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleString('zh-CN')
}

const formatJSON = (jsonStr) => {
  if (!jsonStr) return ''
  try {
    return JSON.stringify(JSON.parse(jsonStr), null, 2)
  } catch {
    return jsonStr
  }
}

// 生命周期
onMounted(() => {
  loadOrgAccounts()
})
</script>

<style scoped>
/* 使用Tailwind CSS类替代自定义样式 */
</style>
