<template>
  <div class="app-container">
    <!-- 权限验证组件 -->
    <PermissionVerify ref="permissionVerify" />

    <!-- 主内容区域 - 权限验证通过后才显示 -->
    <template v-if="isAuthenticated">
      <div class="header-section">
        <div class="header-content">
          <div class="title-area" @click="navigateHome">
            <h1 class="page-title">接口调用记录查询</h1>
            <p class="page-subtitle">MOM接口数据查询系统</p>
          </div>
          <div class="header-actions">
            <div style="display: flex; align-items: center; color: #fff; opacity: 0.95;">
              登录人：{{ loginUserName }}
            </div>
            <el-button type="danger" icon="SwitchButton" @click="handleLogout" size="small">
              退出登录
            </el-button>
          </div>
        </div>
      </div>

      <!-- 查询条件区域 -->
      <div class="search-section">
        <div class="search-card">
          <div class="search-form">
            <!-- 第一行 -->
            <div class="form-row">
              <div class="form-item">
                <label class="form-label">工位号：</label>
                <el-select @change="handleSearch();" v-model="searchForm.stationNumber" placeholder="请选择工位号" filterable
                  clearable class="form-input">
                  <el-option v-for="item in stationList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
              <div class="form-item">
                <label class="form-label">工件编号：</label>
                <el-input @change="handleSearch();" v-model="searchForm.workpieceNumber" placeholder="请输入工件编号" clearable
                  class="form-input" />
              </div>
            </div>

            <!-- 第二行 -->
            <div class="form-row">
              <div class="form-item">
                <label class="form-label">时间范围：</label>
                <el-date-picker @change="handleSearch();" v-model="searchForm.dateRange" type="datetimerange"
                  range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss" :default-time="[
                    new Date(2000, 1, 1, 0, 0, 0),
                    new Date(2000, 1, 1, 23, 59, 59)
                  ]" class="form-date-picker" />
              </div>
              <div class="form-item form-actions">
                <el-button type="primary" icon="Search" @click="handleSearch" :loading="loading">
                  查询
                </el-button>
                <!-- <el-button icon="Refresh" @click="handleReset">
                重置时间
              </el-button> -->
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 数据展示区域 -->
      <div class="data-section">
        <div class="data-card">
          <el-table v-loading="loading" :data="tableData" :height="tableHeight" border stripe style="width: 100%"
            :header-cell-style="{
              background: '#f5f7fa',
              color: '#303133',
              fontWeight: 'bold',
              textAlign: 'center'
            }" :cell-style="{ textAlign: 'center' }">
            <el-table-column type="index" label="序号" width="60" fixed="left" />
            <!-- <el-table-column prop="ID" label="ID" width="80" /> -->
            <el-table-column prop="发动机号" label="工件编号" width="260" show-overflow-tooltip />
            <el-table-column prop="工位号" label="工位号" width="100" />
            <el-table-column prop="工位名称" label="工位名称" width="140" show-overflow-tooltip />
            <!-- <el-table-column prop="接口名称" label="接口名称" width="220" show-overflow-tooltip /> -->
            <el-table-column prop="接口说明" label="接口说明" show-overflow-tooltip min-width="140" />
            <el-table-column prop="是否启用" label="是否启用" width="90">
              <template #default="scope">
                <el-tag :type="scope.row.是否启用 == '1' ? 'success' : 'danger'" size="small">
                  {{ scope.row.是否启用 }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="请求时间" label="请求时间" width="190" />
            <!-- <el-table-column prop="返回时间" label="返回时间" width="190" /> -->
            <el-table-column prop="返回代码" label="返回代码" width="100" fixed="right">
              <template #default="scope">
                <el-tag :type="scope.row.返回代码 === '0' ? 'success' : 'warning'" size="small">
                  {{ scope.row.返回代码 }}
                </el-tag>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="累积用时" label="累积用时(ms)" width="110" /> -->
            <!-- <el-table-column prop="操作时间" label="操作时间" width="160" /> -->
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="scope">
                <el-button link type="warning" size="small" @click="handleUpdateReturnCode(scope.row)">
                  修改返回代码
                </el-button>
                <el-button link type="primary" size="small" @click="handleViewDetail(scope.row)">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>

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

      <!-- 详情对话框 -->
      <el-dialog v-model="detailDialog.visible" title="接口调用详情" width="800px" :close-on-click-modal="false">
        <div class="detail-content">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="ID">{{ detailDialog.data.ID }}</el-descriptions-item>
            <el-descriptions-item label="发动机号">{{ detailDialog.data.发动机号 }}</el-descriptions-item>
            <el-descriptions-item label="工位号">{{ detailDialog.data.工位号 }}</el-descriptions-item>
            <el-descriptions-item label="工位名称">{{ detailDialog.data.工位名称 }}</el-descriptions-item>
            <!-- <el-descriptions-item label="接口名称" :span="2">{{ detailDialog.data.接口名称 }}</el-descriptions-item> -->
            <el-descriptions-item label="接口说明" :span="2">{{ detailDialog.data.接口说明 }}</el-descriptions-item>
            <el-descriptions-item label="请求时间">{{ detailDialog.data.请求时间 }}</el-descriptions-item>
            <el-descriptions-item label="返回时间">{{ detailDialog.data.返回时间 }}</el-descriptions-item>
            <el-descriptions-item label="返回代码">{{ detailDialog.data.返回代码 }}</el-descriptions-item>
            <el-descriptions-item label="累积用时">{{ detailDialog.data.累积用时 }}ms</el-descriptions-item>
          </el-descriptions>
          <div style="margin: 5px 0; display: flex;">
            <el-button
              type="primary"
              :disabled="detailDialog.data.返回代码 === '0'"
              @click="handleApiRetry(detailDialog.data)"
            >
              接口重试
            </el-button>
            <el-button
              type="warning"
              :disabled="detailDialog.data.返回代码 === '0'"
              @click="handleFlowRetry(detailDialog.data)"
            >
              流程重试
            </el-button>
          </div>
          <el-tabs v-model="detailDialog.activeTab" class="detail-tabs">
            <el-tab-pane label="请求内容" name="request">
              <div class="code-block">
                <pre>{{ detailDialog.data.请求内容 || '无' }}</pre>
              </div>
            </el-tab-pane>
            <el-tab-pane label="返回内容" name="response">
              <div class="code-block">
                <pre>{{ detailDialog.data.返回内容 || '无' }}</pre>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-dialog>
    </template>

    <!-- 未登录时显示提示 -->
    <div v-else class="auth-loading">
      <i class="el-icon-loading"></i>
      <p>正在进行权限验证...</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, inject, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PermissionVerify from '@/components/PermissionVerify.vue'
import Cookie from 'js-cookie'
import { useRouter } from 'vue-router'

// 注入数据库执行方法
const ExecDatabaseByParam = inject('ExecDatabaseByParam')
const CreateData = inject('CreateData')
const ExecDatabase = inject('ExecDatabase')
const ExecHttpRequest = inject('ExecHttpRequest')

// 路由
const router = useRouter()

// 返回导航首页
const navigateHome = () => {
    router.push('/')
}

// 权限验证相关
const isAuthenticated = ref(false)
const permissionVerify = ref(null)
const userInfo = ref({})

// 响应式数据
const loading = ref(false)
const stationList = ref([])
const tableData = ref([])
const tableHeight = ref(500)

// 搜索表单
const searchForm = reactive({
  stationNumber: '',
  workpieceNumber: '',
  dateRange: []
})

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 50,
  total: 0
})

// 详情对话框
const detailDialog = reactive({
  visible: false,
  data: {},
  activeTab: 'request'
})

const loginUserName = computed(() => Cookie.get('userName') || userInfo.value.姓名 || userInfo.value.userName || '-')

// 计算表格高度
const calculateTableHeight = () => {
  // 窗口高度 - 头部 - 搜索区域 - 分页 - 边距
  tableHeight.value = window.innerHeight - 280
}

// 权限验证
const checkPermission = async () => {
  console.log('checkPermission called')

  try {
    // 优先检查Cookie是否已登录
    const cookieUserId = Cookie.get('userId')
    const cookieUserName = Cookie.get('userName')
    if (cookieUserId && cookieUserName) {
      isAuthenticated.value = true
      userInfo.value = { UserID: cookieUserId, 姓名: cookieUserName }
      ElMessage.success(`欢迎 ${cookieUserName} 登录系统`)
      await initializeData()
      return
    }

    console.log('Calling permissionVerify.show...')
    const result = await permissionVerify.value.show({
      title: '接口查询系统登录',
      promptText: '请刷卡进行身份验证',
      permissionLevel: '高级刷卡权限'
    })

    console.log('Permission verify result:', result)

    if (result.success) {
      isAuthenticated.value = true
      userInfo.value = result.data
      ElMessage.success(`欢迎 ${result.data.姓名 || result.data.userName || '用户'} 登录系统`)

      // 权限验证成功后初始化页面数据
      await initializeData()
    }
  } catch (error) {
    console.error('Permission verify error:', error)

    if (error.cancelled) {
      ElMessage.warning('已取消登录')
      // 可以选择跳转到其他页面或关闭窗口
    } else {
      ElMessage.error('权限验证失败')
    }
  }
}

// 初始化
onMounted(async () => {
  console.log('Index page mounted')

  // 使用 setTimeout 确保组件完全加载
  setTimeout(() => {
    console.log('Checking permissionVerify ref:', permissionVerify.value)

    if (permissionVerify.value) {
      console.log('PermissionVerify component found, injecting methods...')

      // 为权限验证组件注入必要的方法
      permissionVerify.value.setCreateData(CreateData)
      permissionVerify.value.setExecDatabase(ExecDatabase)
      permissionVerify.value.setStore({
        state: {
          station: { stationNumber: '' },
          user: { name: Cookie.get('userName') || '' }
        }
      })

      console.log('Methods injected, calling checkPermission...')
      // 进行权限验证（含Cookie免登录）
      checkPermission()
    } else {
      console.error('PermissionVerify component not found!')
      ElMessage.error('权限验证组件初始化失败')
    }
  }, 500) // 增加延迟时间确保组件加载
})

// 初始化数据（权限验证通过后调用）
const initializeData = async () => {
  calculateTableHeight()
  window.addEventListener('resize', calculateTableHeight)

  // 获取URL参数 - 处理hash路由的情况
  let urlParams;
  let stationNo = '';
  let workpieceNo = '';

  // 检查是否是hash路由
  if (window.location.hash && window.location.hash.includes('?')) {
    // 处理 http://localhost:5173/#/?stationNo=xxx&workpieceNo=xxx 格式
    const hashParts = window.location.hash.split('?');
    if (hashParts.length > 1) {
      urlParams = new URLSearchParams(hashParts[1]);
      stationNo = urlParams.get('stationNo');
      workpieceNo = urlParams.get('workpieceNo');
    }
  } else {
    // 处理 http://localhost:5173/?stationNo=xxx&workpieceNo=xxx#/ 格式
    urlParams = new URLSearchParams(window.location.search);
    stationNo = urlParams.get('stationNo');
    workpieceNo = urlParams.get('workpieceNo');
  }

  // 始终设置默认时间范围为今天
  const today = new Date()
  const startTime = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0)
  const endTime = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59)
  searchForm.dateRange = [
    formatDate(startTime, 'yyyy-MM-dd HH:mm:ss'),
    formatDate(endTime, 'yyyy-MM-dd HH:mm:ss')
  ]

  // 加载工位列表
  await loadStationList()

  // 如果URL有参数，设置默认值
  if (stationNo) searchForm.stationNumber = stationNo
  if (workpieceNo) searchForm.workpieceNumber = workpieceNo

  // 执行查询
  await handleSearch()
}

// 格式化日期
const formatDate = (date, format) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return format
    .replace('yyyy', year)
    .replace('MM', month)
    .replace('dd', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

// 加载工位列表
const loadStationList = async () => {
  try {
    const param = []
    const response = await ExecDatabaseByParam('11', 'MES_计划BOM_工位与名称_查询', param)
    if (response.data && response.data.length > 0) {
      stationList.value = response.data.map(item => ({
        label: `${item.工位号} - ${item.工位名称 || ''}`,
        value: item.工位号
      }))
    }
  } catch (error) {
    console.error('加载工位列表失败:', error)
    ElMessage.error('加载工位列表失败')
  }
}

// 查询数据
const handleSearch = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const param = []
    param[0] = ['工位号', searchForm.stationNumber || '']
    param[1] = ['工件编号', searchForm.workpieceNumber || '']
    param[2] = ['开始时间', searchForm.dateRange[0] || '']
    param[3] = ['结束时间', searchForm.dateRange[1] || '']
    param[4] = ['PageCurrent', pagination.currentPage]
    param[5] = ['PageSize', pagination.pageSize]
    param[6] = ['PageCount', '0', 'int', '1']
    param[7] = ['ItemCount', '0', 'int', '1']

    const response = await ExecDatabaseByParam('11', 'MOM_接口_Moby_视图_分页_查询', param)

    if (response.data && response.data.result) {
      tableData.value = response.data.result
      // 获取总数
      if (response.data.output && response.data.output.length > 0) {
        pagination.total = parseInt(response.data.output[0].ItemCount) || 0
      }
    } else {
      tableData.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 重置查询条件
const handleReset = () => {
  searchForm.stationNumber = ''
  searchForm.workpieceNumber = ''
  // 重置为今天
  const today = new Date()
  const startTime = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0)
  const endTime = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59)
  searchForm.dateRange = [
    formatDate(startTime, 'yyyy-MM-dd HH:mm:ss'),
    formatDate(endTime, 'yyyy-MM-dd HH:mm:ss')
  ]
  pagination.currentPage = 1
  tableData.value = []
  pagination.total = 0
  handleSearch();
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.currentPage = 1
  handleSearch()
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  handleSearch()
}

// 查看详情
const handleViewDetail = (row) => {
  detailDialog.data = row
  detailDialog.visible = true
  detailDialog.activeTab = 'request'
}

// 接口重试
const handleApiRetry = async (row) => {
  try {
    const retryData = {
      MsgId: Math.random().toString(36).substring(2), // 随机生成UUID
      UserId: Number(Cookie.get('userId') || userInfo.value.UserID || 0),
      ID: row.ID,
      OpName: row.工位号 || '',
      EngineID: row.发动机号 || ''
    }

    const response = await ExecHttpRequest(
      window.g.API_MES_Controller_URL + '/ApiFailRetry',
      'post',
      retryData
    )

    // 检查返回结果
    if (response.data && response.data.Code === '200') {
      ElMessage.success('接口重试请求已发送')
      // 关闭详情对话框
      detailDialog.visible = false
      // 刷新数据
      await handleSearch()
    } else {
      // 处理失败情况
      const errorMessage = response.data?.Message || '接口重试失败'
      ElMessage.error(errorMessage)
      console.error('接口重试失败:', response.data)
    }
  } catch (error) {
    console.error('接口重试失败:', error)
    ElMessage.error('接口重试失败，请稍后重试')
  }
}

// 流程重试
const handleFlowRetry = async (row) => {
  try {
    const retryData = {
      MsgId: Math.random().toString(36).substring(2), // 随机生成UUID
      UserId: Number(Cookie.get('userId') || userInfo.value.UserID || 0),
      OpName: row.工位号 || '',
      EngineID: row.发动机号 || ''
    }

    const response = await ExecHttpRequest(
      window.g.API_MES_Controller_URL + '/ApiFailRetry',
      'post',
      retryData
    )

    // 检查返回结果
    if (response.data && response.data.Code === '200') {
      ElMessage.success('流程重试请求已发送')
      // 关闭详情对话框
      detailDialog.visible = false
      // 刷新数据
      await handleSearch()
    } else {
      // 处理失败情况
      const errorMessage = response.data?.Message || '流程重试失败'
      ElMessage.error(errorMessage)
      console.error('流程重试失败:', response.data)
    }
  } catch (error) {
    console.error('流程重试失败:', error)
    ElMessage.error('流程重试失败，请稍后重试')
  }
}

// 修改返回代码
const handleUpdateReturnCode = async (row) => {
  try {
    const { value } = await ElMessageBox.prompt(
      `当前返回代码：${row.返回代码 ?? '无'}\n请输入新的返回代码：`,
      '修改返回代码',
      {
        confirmButtonText: '确认修改',
        cancelButtonText: '取消',
        inputValue: row.返回代码 || '',
        inputPlaceholder: '请输入返回代码，如0',
      }
    )
    const newCode = (value ?? '').trim()
    if (newCode === '') {
      ElMessage.warning('返回代码不能为空')
      return
    }
    const param = [
      ['ID', row.ID],
      ['返回代码', newCode]
    ]
    const data = CreateData('12', 'MOM_接口_Moby_修改返回代码', param)
    const res = await ExecDatabase(data)
    if (res.data && res.data.length > 0 && res.data[0].result === '1') {
      ElMessage.success('返回代码修改成功')
      await handleSearch()
    } else {
      ElMessage.error(res.data?.[0]?.msg || '修改失败')
    }
  } catch (e) {
    if (e !== 'cancel') {
      console.error('修改返回代码失败:', e)
      ElMessage.error('修改返回代码失败')
    }
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    isAuthenticated.value = false
    userInfo.value = {}
    tableData.value = []
    pagination.total = 0

    // 清理登录Cookie
    Cookie.remove('userId')
    Cookie.remove('userName')

    ElMessage.success('已退出登录')

    // 重新返回首页
    router.push('/')
  } catch {
    // 用户取消
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  width: 100%;
  height: 100vh;
  background: #f0f2f5;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

// 头部样式
.header-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .page-title {
    font-size: 24px;
    font-weight: 600;
    margin: 0 0 5px 0;
  }

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .title-area {
    cursor: pointer;
    transition: opacity 0.2s;

    &:hover {
      opacity: 0.85;
    }
  }

  .page-title {
    font-size: 24px;
    font-weight: 600;
    margin: 0 0 5px 0;
  }

  .page-subtitle {
    font-size: 14px;
    opacity: 0.9;
    margin: 0;
  }

  .header-actions {
    display: flex;
    gap: 10px;
  }
}

// 权限验证加载样式
.auth-loading {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  color: #909399;

  i {
    font-size: 40px;
    margin-bottom: 20px;
  }

  p {
    font-size: 16px;
  }
}

// 查询区域样式
.search-section {
  padding: 20px;

  .search-card {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

    .search-form {
      .form-row {
        display: flex;
        gap: 20px;
        margin-bottom: 15px;

        &:last-child {
          margin-bottom: 0;
        }
      }

      .form-item {
        display: flex;
        align-items: center;
        flex: 1;

        &.form-actions {
          flex: none;
          justify-content: flex-end;
        }
      }

      .form-label {
        width: 80px;
        flex-shrink: 0;
        text-align: right;
        color: #606266;
        font-size: 14px;
      }

      .form-input {
        flex: 1;
        min-width: 200px;
      }

      .form-date-picker {
        flex: 1;
        min-width: 360px;
      }
    }
  }
}

// 数据区域样式
.data-section {
  flex: 1;
  padding: 0 20px 20px;
  overflow: hidden;

  .data-card {
    background: white;
    border-radius: 8px;
    padding: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
    height: 100%;
    display: flex;
    flex-direction: column;

    :deep(.el-table) {
      flex: 1;

      .el-table__cell {
        padding: 8px 0;
      }
    }
  }
}

// 分页样式
.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  margin-top: 20px;
}

// 详情对话框样式
.detail-content {
  .detail-tabs {
    margin-top: 20px;
  }

  .code-block {
    background: #f5f7fa;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 15px;
    max-height: 300px;
    overflow: auto;

    pre {
      margin: 0;
      font-family: 'Consolas', 'Monaco', monospace;
      font-size: 13px;
      line-height: 1.5;
      white-space: pre-wrap;
      word-break: break-all;
    }
  }
}

// 响应式适配
@media (max-width: 1200px) {
  .search-form {
    .form-row {
      flex-wrap: wrap;
    }

    .form-item {
      min-width: 300px;
      margin-bottom: 10px;
    }
  }
}
</style>