<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="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
            </svg>
            广告自动划配置管理
          </h2>
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增配置
          </el-button>
        </div>
      </div>

      <!-- 数据统计 -->
      <div class="grid grid-cols-1 md:grid-cols-3 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">{{ pagination.total }}</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="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 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">{{ confList.length }}</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="M5 13l4 4L19 7" />
              </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">总页数</p>
              <p class="text-2xl font-bold text-purple-700">{{ totalPages }}</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="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
              </svg>
            </div>
          </div>
        </div>
      </div>

      <!-- 搜索筛选 -->
      <div class="mb-6 p-4 bg-gray-50 rounded-lg">
        <el-form :inline="true" :model="queryForm" class="flex flex-wrap gap-4">
          <el-form-item label="名称">
            <el-input v-model="queryForm.ruleName" placeholder="请输入名称" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table
        :data="confList"
        style="width: 100%"
        v-loading="loading"
        stripe
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="px-6 py-3">
              <el-table :data="parseRules(row.rules)" border size="small">
                <el-table-column label="广告" width="90">
                  <template #default="{ row: r }">
                    <el-tag size="small" :type="r.newAd === 1 ? 'success' : 'warning'">{{ r.newAd === 1 ? '新广告' : '老广告' }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="规则类型" width="110">
                  <template #default="{ row: r }">
                    <el-tag size="small" :type="r.type === 1 ? 'primary' : 'info'">{{ r.type === 1 ? 'ROI规则' : '粉价规则' }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="最小成本" prop="minCost" width="100" />
                <el-table-column label="最小ROI" width="100">
                  <template #default="{ row: r }">
                    {{ r.type === 1 ? r.minIor : '-' }}
                  </template>
                </el-table-column>
                <el-table-column label="最大粉价" width="100">
                  <template #default="{ row: r }">
                    {{ r.type === 2 ? r.scanMaxCost : '-' }}
                  </template>
                </el-table-column>
                <el-table-column label="说明" min-width="100">
                  <template #default="{ row: r }">
                    {{ getDesc(r) }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="ruleName" label="规则名称" width="120" />
        <el-table-column prop="adGroupId" label="广告组ID" width="120">
        </el-table-column>
        <el-table-column prop="newAdDays" label="新广告天数" width="120" />
        <el-table-column prop="dailyBudgetLevel" label="日预算等级" width="200" show-overflow-tooltip>
          <template #default="{ row }">
            {{ JSON.parse(row.dailyBudgetLevel).map(r => r/100).join(',') }}
          </template>
        </el-table-column>
        <el-table-column label="规则数量" width="100">
          <template #default="{ row }">
            <el-tag @click="handleEdit(row)" size="small" type="info">{{ getRulesCount(row.rules) }} 条</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="260" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="warning" size="small" link @click="handleExecute(row)">执行规则</el-button>
            <el-button type="primary" size="small" link @click="handleShowLog(row)">执行日志</el-button>
            <el-button type="danger" size="small" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-6 flex justify-end">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

  </div>

  <!-- 执行日志弹窗 -->
  <el-dialog
    v-model="logDialog.visible"
    title="执行日志"
    width="80%"
    destroy-on-close
  >
    <el-table
      ref="logTableRef"
      :data="logList"
      v-loading="logLoading"
      border
      size="small"
      style="width: 100%"
      row-key="id"
      lazy
      :load="loadChildLog"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <!-- <el-table-column prop="parentLogId" label="父日志ID" width="80" /> -->
      <el-table-column prop="logType" label="日志类型" width="80" />
      <el-table-column prop="adPlanConfId" label="广告配置ID" width="80" >
          <template #default="{ row }">
            <el-button v-if="row.adPlanConfId > 0" type="primary" size="small" link @click="handleShowDetail(row)">
              {{ row.adPlanConfId }}
            </el-button>
            <span v-else>-</span>
          </template>
        </el-table-column>
      <el-table-column label="状态" width="90">
        <template #default="{ row }">
          <el-tag :type="getStatusTagType(row.executeStatus)" size="small">
            {{ getStatusText(row.executeStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="总广告数" prop="adCount" width="90" />
      <el-table-column label="执行数" prop="suspendCount" width="80" />
      <el-table-column label="执行时间" width="170">
        <template #default="{ row }">
          {{ formatDate(row.executeTime) }}
        </template>
      </el-table-column>
      <el-table-column label="成功时间" width="170">
        <template #default="{ row }">
          {{ formatDate(row.successTime) }}
        </template>
      </el-table-column>
      <el-table-column label="执行结果" prop="executeResult" min-width="160" show-overflow-tooltip />
      <el-table-column label="暂停的计划" prop="suspendAdGroupIds" width="120" show-overflow-tooltip/>
    </el-table>
    <div class="mt-4 flex justify-end">
      <el-pagination
        v-model:current-page="logPagination.page"
        v-model:page-size="logPagination.pageSize"
        :page-sizes="[10, 20, 50]"
        :total="logPagination.total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleLogSizeChange"
        @current-change="handleLogPageChange"
      />
    </div>
  </el-dialog>
</template>

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

import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getAdAutoConfList,
  deleteAdAutoConf,
  batchDeleteAdAutoConf,
  executeAdAutoConf,
  getExecuteLogList,
  getChildLog
} from '@/api/adAutoConf'
// 响应式数据
const loading = ref(false)
const confList = ref([])
const selectedRows = ref([])
const router = useRouter()

// 查询表单
const queryForm = reactive({
  ruleName: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 计算属性
const totalPages = computed(() => {
  return Math.ceil(pagination.total / pagination.pageSize)
})

const getDesc = (rule) => {
  if (rule.type === 1) {
    const costPart = rule.minCost > 0 ? `消耗 > ${rule.minCost}元 且 ` : ''
    return `${rule.newAd === 1 ? '新广告' : '老广告'}：${costPart}ROI < ${rule.minIor} 时暂停`
  } else {
    const costPart = rule.minCost > 0 ? `消耗 > ${rule.minCost}元 且 ` : ''
    return `${rule.newAd === 1 ? '新广告' : '老广告'}：${costPart}粉价 > ${rule.scanMaxCost}元 时暂停`
  }
}

// 获取规则数量
const parseRules = (rulesJson) => {
  if (!rulesJson) return []
  try {
    const rules = JSON.parse(rulesJson)
    return Array.isArray(rules) ? rules : []
  } catch (e) {
    return []
  }
}

const getRulesCount = (rulesJson) => {
  if (!rulesJson) return 0
  try {
    const rules = JSON.parse(rulesJson)
    return Array.isArray(rules) ? rules.length : 0
  } catch (e) {
    return 0
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 1:
      return '成功'
    case 2:
      return '失败'
    default:
      return '-'
  }
}

const getStatusTagType = (status) => {
  switch (status) {
    case 1:
      return 'success'
    case 2:
      return 'danger'
    default:
      return ''
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const handleShowDetail = (row) => {
  router.push(`/ad-plan-conf/detail?id=${row.adPlanConfId}`)
}

// 加载列表
const loadList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.page,
      size: pagination.pageSize
    }
    if (queryForm.ruleName) {
      params.ruleName = queryForm.ruleName
    }
    const response = await getAdAutoConfList(params)
    if (response.success) {
      confList.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.message || '加载列表失败')
    }
  } catch (error) {
    console.error('加载列表失败:', error)
    ElMessage.error('加载列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  pagination.page = 1
  loadList()
}

// 重置
const handleReset = () => {
  queryForm.ruleName = ''
  handleQuery()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增 - 跳转到新增页面
const handleAdd = () => {
  router.push('/ad-auto-conf/edit')
}

// 编辑 - 跳转到编辑页面
const handleEdit = (row) => {
  router.push(`/ad-auto-conf/edit?id=${row.id}`)
}

// 执行规则
const handleExecute = (row) => {
  ElMessageBox.confirm('确定要执行该规则吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const response = await executeAdAutoConf(row.id)
    if (response.success) {
      ElMessage.success(response.message || '执行成功')
    } else {
      ElMessage.error(response.message || '执行失败')
    }
  })
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该配置吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const response = await deleteAdAutoConf(row.id)
    if (response.success) {
      ElMessage.success('删除成功')
      loadList()
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个配置吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const ids = selectedRows.value.map(item => item.id)
    const response = await batchDeleteAdAutoConf(ids)
    if (response.success) {
      ElMessage.success('批量删除成功')
      loadList()
    } else {
      ElMessage.error(response.message || '批量删除失败')
    }
  })
}

// 分页大小改变
const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize
  pagination.page = 1
  loadList()
}

// 当前页改变
const handleCurrentChange = (newPage) => {
  pagination.page = newPage
  loadList()
}

// 执行日志弹窗
const logDialog = reactive({ visible: false, confId: null })
const logLoading = ref(false)
const logList = ref([])
const logPagination = reactive({ page: 1, pageSize: 10, total: 0 })
const logTableRef = ref(null)

// 懒加载子日志
const loadChildLog = async (row, treeNode, resolve) => {
  try {
    const response = await getChildLog({
      confId: logDialog.confId,
      parentId: row.id
    })
    if (response.success) {
      resolve(response.data || [])
    } else {
      resolve([])
    }
  } catch (e) {
    resolve([])
  }
}

// 加载执行日志
const loadLogList = async () => {
  logLoading.value = true
  try {
    const response = await getExecuteLogList({
      page: logPagination.page,
      size: logPagination.pageSize,
      confId: logDialog.confId
    })
    if (response.success) {
      logList.value = (response.data.records || []).map(item => ({ ...item, hasChildren: true }))
      logPagination.total = response.data.total || 0
      // 默认展开第一行
      if (logList.value.length > 0 && logTableRef.value) {
        setTimeout(() => {
          logTableRef.value.toggleRowExpansion(logList.value[0], true)
        }, 0)
      }
    } else {
      ElMessage.error(response.message || '加载日志失败')
    }
  } catch (error) {
    console.error('加载日志失败:', error)
    ElMessage.error('加载日志失败')
  } finally {
    logLoading.value = false
  }
}

// 显示执行日志
const handleShowLog = (row) => {
  logDialog.confId = row.id
  logDialog.visible = true
  logPagination.page = 1
  loadLogList()
}

// 日志分页大小改变
const handleLogSizeChange = (newSize) => {
  logPagination.pageSize = newSize
  logPagination.page = 1
  loadLogList()
}

// 日志当前页改变
const handleLogPageChange = (newPage) => {
  logPagination.page = newPage
  loadLogList()
}

// 页面加载时获取列表
onMounted(() => {
  loadList()
})
</script>

<style scoped>
</style>
