<template>
  <div style="padding: 10px;">
    <a-row style="height: 100%;" :gutter="[8, 8]">
      <a-col :span="5">
        <a-card :bordered="true" style="width:100%;height:100%;">
          <Left 
            @searchData="handleLeftSearch"
            @resetData="handleLeftReset"
          />
        </a-card>
      </a-col>
      <a-col :span="19">
        <!-- 时间搜索表单 -->
        <div style="margin-bottom: 16px; padding: 12px; background: #f9f9f9; border-radius: 4px;">
          <a-row :gutter="16" align="middle">
            <a-col :span="16">
              <div style="display: flex; align-items: center; gap: 16px;">
                <div style="display: flex; align-items: center;">
                  <span style="margin-right: 8px;">开始日期：</span>
                  <a-date-picker v-model:value="searchForm.startTime" style="width: 150px;" />
                </div>
                <div style="display: flex; align-items: center;">
                  <span style="margin-right: 8px;">结束日期：</span>
                  <a-date-picker v-model:value="searchForm.endTime" style="width: 150px;" />
                </div>
                <div style="display: flex; align-items: center;">
                  <span style="margin-right: 8px;">指标名称：</span>
                  <a-input v-model:value="searchForm.mtrcName" placeholder="请输入指标名称" style="width: 150px;" />
                </div>
              </div>
            </a-col>
            <a-col :span="8">
              <a-space :size="5" style="margin-left:0px;">
                <a-button type="primary" @click="handleSearch" :loading="gridOptions.loading">查询</a-button>
                <a-button @click="resetSearch">重置</a-button>
              </a-space>
            </a-col>
          </a-row>
        </div>
        
        <vxe-grid 
          v-bind="gridOptions" 
          ref="tableRef" 
          @page-change="handlePageChange"
        >
          <template #toolbarButtons>
            <div style="margin:2px 20px;size:15px">指标填报列表：</div>
            <vxe-button size="small" @click="handleApproval(1)" :loading="batchLoading">审批通过</vxe-button>
            <vxe-button size="small" @click="handleApproval(2)" :loading="batchLoading">审批未通过</vxe-button>

            <div style="margin:auto">
              共搜索到 <span class="count-number">{{ totalRecords }}</span> 条记录
            </div>
          </template>
          <template #active="{ row }">
            <vxe-button mode="text" status="primary" @click="saveApproval(row.reportId, 1)" :loading="row._loading">通过</vxe-button>
            <vxe-button mode="text" status="error" @click="saveApproval(row.reportId, 2)" :loading="row._loading">退回</vxe-button>
          </template>
          <template #mtrcName="{ row }">
            <a @click="showChartModal(row)" style="color: #409eff; cursor: pointer;">
              {{ row.mtrcName }}
            </a>
          </template>
        </vxe-grid>
      </a-col>
    </a-row>
    
    <!-- 图表弹窗组件 -->
    <MetricChartModal
      v-model:visible="chartModalVisible"
      :title="chartModalTitle"
      :row="currentRow"
      @cancel="handleModalClose"
    />
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, ref, computed } from 'vue'
import type { VxeGridProps, VxeGridInstance } from 'vxe-table'
import { debounce } from 'lodash-es'
import { dataApprovalList, batchSaveApproval } from '../MetricReport.api'
import Left from './left.vue'
import MetricChartModal from './components/MetricChartModal.vue'
import { VXETable } from 'vxe-table'

interface RowVO {
  id: number
  name: string
  role: string
  sex: string
  age: number
  address: string
}

const tableRef = ref<VxeGridInstance>()
const totalRecords = ref(0)
const batchLoading = ref(false)

// 图表弹窗
const chartModalVisible = ref(false)
const chartModalTitle = ref('')
const currentRow = ref<any>(null)

// 搜索表单
const searchForm = reactive({
  startTime: null,
  endTime: null,
  mtrcName: ''
})

// 左侧筛选条件
const leftFormData = ref({})

// 存储所有原始数据
const allData = ref<any[]>([])

// 防抖搜索函数
const debouncedSearch = debounce(() => {
  handleSearch()
}, 500)

// 表格配置
const gridOptions = reactive<VxeGridProps<RowVO>>({
  border: true,
  showOverflow: true,
  keepSource: true,
  maxHeight: "750px",
  loading: false,
  exportConfig: {},
  columnConfig: {
    resizable: true
  },
  // 分页配置 - 前端分页模式
  pagerConfig: {
    enabled: true,
    pageSize: 10,
    currentPage: 1,
    total: 0,
    pageSizes: [10, 20, 50, 100],
    layouts: ['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes', 'Total'],
    perfect: true
  },
  // 工具栏配置
  toolbarConfig: {
    refresh: true,
    export: true,
    zoom: true,
    custom: true,
    slots: {
      buttons: 'toolbarButtons'
    }
  },
  // 列配置
  columns: [
    { type: 'seq', width: 50 },
    { type: 'checkbox', width: 50 },
    { field: 'reportId', title: 'id', visible: false },
    { field: 'mtrcNo', title: '指标编码', sortable: true },
    { field: 'mtrcName', title: '指标名称', showOverflow: true, slots: { default: 'mtrcName' } },
    { field: 'collFreq', title: '采集频率' },
    { field: 'timeName', title: '填报时间' },
    { field: 'riskLevel', title: '风险等级' },
    { field: 'domainName', title: '所属领域', showOverflow: true },
    { field: 'mtrcCtp', title: '指标类型' },
    { field: 'fillVals', title: '填报值' },
    { field: 'appSta', title: '状态' },
    { field: 'active', title: '审批', width: 150, fixed: 'right', slots: { default: 'active' } }
  ],
  // 单元格样式
  cellStyle({ row, column }) {
    if (column.field === 'appSta') {
      if (row.appSta == '通过') {
        return { color: 'blue' }
      } else if (row.appSta == '未通过') {
        return { color: 'red' }
      }
    } else if (column.field === 'riskLevel') {
      if (row.riskLevel == '低风险') {
        return { color: '#73D13D' }
      } else if (row.riskLevel == '中风险') {
        return { color: '#FA8C16' }
      } else if (row.riskLevel == '高风险') {
        return { color: '#CF1322' }
      }
    }
  },
  data: []
})

// 更新当前页数据
const updatePageData = () => {
  const { currentPage, pageSize } = gridOptions.pagerConfig!
  const start = (currentPage - 1) * pageSize
  const end = start + pageSize
  gridOptions.data = allData.value.slice(start, end)
  
  // 更新分页总记录数
  gridOptions.pagerConfig!.total = allData.value.length
  totalRecords.value = allData.value.length
}

// 加载数据
async function loadData() {
  if (gridOptions.loading) return
  
  // 合并所有搜索条件
  const searchParams = {
    ...leftFormData.value,
    startTime: searchForm.startTime,
    endTime: searchForm.endTime,
    mtrcName: searchForm.mtrcName
  }
  
  console.log('加载数据参数:', searchParams)
  
  gridOptions.loading = true
  try {
    const res = await dataApprovalList(searchParams)
    console.log('返回数据:', res)
    
    // 处理返回数据
    if (Array.isArray(res)) {
      allData.value = res
    } else if (res && res.records) {
      allData.value = res.records
    } else if (res && res.data) {
      allData.value = res.data
    } else {
      allData.value = []
    }
    
    // 重置到第一页
    gridOptions.pagerConfig!.currentPage = 1
    
    // 更新表格数据
    updatePageData()
    
  } catch (error) {
    console.error('加载数据失败:', error)
    allData.value = []
    gridOptions.data = []
    totalRecords.value = 0
    gridOptions.pagerConfig!.total = 0
  } finally {
    gridOptions.loading = false
  }
}

// 处理分页变化
const handlePageChange = ({ currentPage, pageSize }: { currentPage: number, pageSize: number }) => {
  console.log('分页变化:', currentPage, pageSize)
  
  // 更新分页配置
  gridOptions.pagerConfig!.currentPage = currentPage
  gridOptions.pagerConfig!.pageSize = pageSize
  
  // 前端分页：直接从 allData 中切片
  updatePageData()
}

// 处理左侧搜索
function handleLeftSearch(params) {
  console.log('左侧搜索:', params)
  leftFormData.value = { ...params }
  loadData() // 重新从后端获取数据
}

// 处理左侧重置
function handleLeftReset() {
  console.log('左侧重置')
  leftFormData.value = {}
  searchForm.startTime = null
  searchForm.endTime = null
  loadData() // 重新从后端获取数据
}

// 处理搜索
async function handleSearch() {
  console.log('执行搜索')
  await loadData() // 重新从后端获取数据
}

// 重置搜索
function resetSearch() {
  searchForm.startTime = null
  searchForm.endTime = null
  searchForm.mtrcName = ''
  handleSearch()
}

// 批量审批
async function handleApproval(appSta: number) {
  const $table = tableRef.value
  if (!$table) return
  
  const selectRecords = $table.getCheckboxRecords()
  if (selectRecords.length === 0) {
    VXETable.modal.message({ content: '请至少选择一条记录', status: 'warning' })
    return
  }
  
  const ids = selectRecords.map(item => item.reportId)
  
  batchLoading.value = true
  try {
    await batchSaveApproval({
      ids: ids,
      appSta: appSta
    })
    VXETable.modal.message({ content: '操作成功', status: 'success' })
    
    // 重新加载数据
    await loadData()
    
    // 清空选中
    $table.clearCheckboxRow()
  } catch (error) {
    console.error('批量审批失败:', error)
    VXETable.modal.message({ content: '操作失败', status: 'error' })
  } finally {
    batchLoading.value = false
  }
}

// 单个审批
async function saveApproval(id: number, sta: number) {
  const row = gridOptions.data.find(item => item.reportId === id)
  if (row) {
    row._loading = true
  }
  
  try {
    await batchSaveApproval({
      ids: [id],
      appSta: sta
    })
    VXETable.modal.message({ content: '操作成功', status: 'success' })
    
    // 重新加载数据
    await loadData()
  } catch (error) {
    console.error('审批失败:', error)
    VXETable.modal.message({ content: '操作失败', status: 'error' })
  } finally {
    if (row) {
      row._loading = false
    }
  }
}

// 显示图表弹窗
function showChartModal(row: any) {
  currentRow.value = row
  chartModalTitle.value = `指标详情 - ${row.mtrcName}`
  chartModalVisible.value = true
}

// 处理弹窗关闭
function handleModalClose() {
  chartModalVisible.value = false
}

onMounted(async () => {
  await loadData()
})

defineExpose({
  loadData,
  refreshData: loadData
})
</script>

<style scoped>
.count-number {
  font-weight: bold;
  color: #409eff;
  font-size: 16px;
  margin: 0 4px;
}

:deep(.ant-modal) {
  top: 20px;
}

:deep(.ant-modal-content) {
  height: 90vh;
  display: flex;
  flex-direction: column;
}

:deep(.ant-modal-body) {
  flex: 1;
  overflow: auto;
  padding: 24px;
}

:deep(.ant-tabs-tabpane) {
  transition: none !important;
  height: 100%;
}

:deep(.ant-table-wrapper) {
  height: 100%;
}

:deep(.ant-table-body) {
  overflow-y: auto !important;
}
</style>