<template>
  <div>
    <!-- 查询条件区 -->
    <el-form :inline="true" label-width="90px" class="filter-bar" style="margin-bottom:12px;" :model="filters">
      <el-form-item label="日期">
        <el-date-picker v-model="filters.dateRange" type="daterange" value-format="YYYY-MM-DD" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>
      <el-form-item label="车间">
        <el-select v-model="filters.workshopId" placeholder="请选择车间" clearable style="min-width:220px">
          <el-option v-for="w in options.workshops" :key="w.value ?? w.id" :label="w.label ?? w.name" :value="w.value ?? w.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="机床">
        <el-select v-model="filters.machineId" placeholder="请选择机床" clearable filterable style="min-width:220px">
          <el-option v-for="m in options.machines" :key="m.value ?? m.id" :label="m.label ?? m.name" :value="m.value ?? m.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="工人">
        <el-select v-model="filters.workerId" placeholder="请选择工人" clearable filterable style="min-width:220px">
          <el-option v-for="wk in options.workers" :key="wk.value ?? wk.id" :label="wk.label ?? wk.name" :value="wk.value ?? wk.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="程序名">
        <el-input v-model="filters.programName" placeholder="输入程序名" style="width:240px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loadData">查询</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </el-form-item>
      <el-form-item style="margin-left:auto">
        <el-button type="success" icon="el-icon-download" @click="exportData">导出</el-button>
      </el-form-item>
    </el-form>

    <!-- 指标卡片 -->
    <el-row :gutter="20" style="margin-bottom:20px">
      <el-col :span="6"><el-card shadow="hover"><div style="text-align:center;padding:10px"><div style="color:#909399;font-size:14px">总产量</div><div style="font-size:28px;font-weight:bold">{{summary.totalQuantity?.toLocaleString()}}</div></div></el-card></el-col>
      <el-col :span="6"><el-card shadow="hover"><div style="text-align:center;padding:10px"><div style="color:#909399;font-size:14px">运行机床</div><div style="font-size:28px;font-weight:bold">{{summary.activeMachineCount}}</div></div></el-card></el-col>
      <el-col :span="6"><el-card shadow="hover"><div style="text-align:center;padding:10px"><div style="color:#909399;font-size:14px">切削总时</div><div style="font-size:28px;font-weight:bold">{{summary.totalCuttingTime}}</div></div></el-card></el-col>
      <el-col :span="6"><el-card shadow="hover"><div style="text-align:center;padding:10px"><div style="color:#909399;font-size:14px">平均产量</div><div style="font-size:28px;font-weight:bold">{{summary.avgQuantityPerMachine}}</div></div></el-card></el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table :data="tableData" border stripe v-loading="loading">
      <el-table-column prop="date" label="日期"/>
      <el-table-column prop="machineName" label="机床"/>
      <el-table-column prop="programName" label="程序名" show-overflow-tooltip/>
      <el-table-column label="产量" align="center"><template #default="{row}">{{row.quantity ?? '-'}}</template></el-table-column>
      <el-table-column prop="runTime" label="运行时间" align="center"/>
      <el-table-column prop="cuttingTime" label="切削时间" align="center"/>
      <el-table-column label="日状态" align="center"><template #default="{row}"><el-tag :type="row.dataStatus==='normal'?'info':row.dataStatus==='offline'?'danger':'warning'" size="small">{{row.dataStatus==='normal'?'正常':row.dataStatus==='offline'?'离线':'缺失'}}</el-tag></template></el-table-column>
      <el-table-column label="修正" align="center"><template #default="{row}">{{row.isAdjusted?'✓':'-'}}</template></el-table-column>
      <el-table-column label="操作" width="180" align="center"><template #default="{row}">
        <div style="white-space:nowrap">
          <el-button link type="primary" @click="handleAdjust(row)">修正</el-button>
          <el-button link type="primary" @click="showHistory(row)">修正历史</el-button>
        </div>
      </template></el-table-column>
    </el-table>
    <el-pagination v-model:current-page="page.page" v-model:page-size="page.pageSize" :page-sizes="[20,50,100]" :total="page.total" background layout="total,sizes,prev,pager,next,jumper"/>

    <!-- 修正历史弹窗 -->
    <el-dialog v-model="historyVisible" :title="historyTitle" width="600px" destroy-on-close>
      <template v-if="historyRows.length > 0">
        <el-table :data="historyRows" border>
          <el-table-column prop="createdAt" label="修正时间" width="180"/>
          <el-table-column prop="oldValue" label="修正前产量" width="120"/>
          <el-table-column prop="newValue" label="修正后产量" width="120"/>
          <el-table-column prop="reason" label="修正原因"/>
          <el-table-column prop="operator" label="操作人" width="120"/>
        </el-table>
      </template>
      <template v-else>
        <div style="text-align:center; padding:20px; color:#909399">暂无修正记录</div>
      </template>
      <template #footer>
        <el-button @click="historyVisible=false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 修正产量弹窗 -->
    <el-dialog v-model="adjustVisible" title="修正产量" width="450px" destroy-on-close>
      <el-form label-width="100px">
        <el-form-item label="当前产量">
          <el-input-number v-model="adjustForm.currentQty" :disabled="true" style="width:200px" />
        </el-form-item>
        <el-form-item label="修正后产量">
          <el-input-number v-model="adjustForm.newQty" :min="0" style="width:200px" />
        </el-form-item>
        <el-form-item label="修正原因">
          <el-input v-model="adjustForm.reason" type="textarea" :rows="3" placeholder="请输入修正原因" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="adjustVisible=false">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="doAdjust">确认修正</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import type { ProductionRecord, ProductionDashboardSummary } from '@/types'

// 表格数据与加载状态
const loading = ref(false)
const tableData = ref<Array<any>>([])
const summary = ref<ProductionDashboardSummary>({} as ProductionDashboardSummary)
// 分页
const page = reactive({ page: 1, pageSize: 20, total: 0 })
// 筛选条件
const filters = reactive({
  dateRange: [] as string[],
  workshopId: '',
  machineId: '',
  workerId: '',
  programName: ''
})
// 下拉项数据
  const options = reactive({ workshops: [] as Array<{ id: string | number; name: string; value?: string | number; label?: string }>, machines: [] as Array<{ id: string | number; name: string; value?: string | number; label?: string }>, workers: [] as Array<{ id: string | number; name: string; value?: string | number; label?: string }> })

// 导出/修正历史相关
const historyVisible = ref(false)
const historyRows = ref<Array<any>>([])
const historyTitle = ref('修正历史')
const historyLoading = ref(false)
const adjustVisible = ref(false)
const submitting = ref(false)
const adjustForm = reactive({ currentQty: 0, newQty: 0, reason: '', id: 0 })

// 导出数据
async function exportData() {
  if (isMockMode()) {
    // Mock 模式不执行实际导出
    ElMessage.info('Mock模式不支持导出')
    return
  }
  const params = new URLSearchParams({
    dateFrom: filters.dateRange?.[0] ?? '',
    dateTo: filters.dateRange?.[1] ?? '',
    workshopId: filters.workshopId ?? '',
    machineId: filters.machineId ?? '',
    workerId: filters.workerId ?? '',
    programName: filters.programName ?? '',
    page: String(page.page),
    pageSize: String(page.pageSize)
  }).toString()
  window.open('/admin/production/export?' + params, '_blank')
}

// 读取Mock/实际模式标志（基于当前路径判断是否为 Mock 模式）
const isMockMode = () => location.pathname.startsWith('/mock')

// 数据加载：包含汇总与明细，带筛选参数
async function loadData() {
  loading.value = true
  try {
    const params = {
      page: page.page,
      pageSize: page.pageSize,
      startDate: filters.dateRange?.[0] ?? '',
      endDate: filters.dateRange?.[1] ?? '',
      workshopId: filters.workshopId ?? '',
      machineId: filters.machineId ?? '',
      workerId: filters.workerId ?? '',
      programName: filters.programName ?? ''
    }
    const [s, d] = await Promise.all([
      request.get<ProductionDashboardSummary>('/admin/production/daily-summary', { params }),
      request.get<{ items: ProductionRecord[]; total: number }>('/admin/production/daily', { params })
    ])
    summary.value = s.data || {}
    tableData.value = d.data?.items ?? []
    page.total = d.data?.total ?? 0
  } finally {
    loading.value = false
  }
}

function resetFilters() {
  const end = new Date()
  const start = new Date()
  start.setDate(end.getDate() - 6)
  const fmt = (d: Date) => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
  filters.dateRange = [fmt(start), fmt(end)]
  filters.workshopId = ''
  filters.machineId = ''
  filters.workerId = ''
  filters.programName = ''
  // 重新加载数据
  loadData()
}

// 初始化：加载筛选项与数据，设置默认日期为今天
async function init() {
  // 默认今天
  const today = new Date()
  const fmt = (d: Date) => `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`
  filters.dateRange = [fmt(today), fmt(today)]
  // 加载筛选项
  try {
    const [ws, mc, wr] = await Promise.all([
      request.get<{ items: any[] }>('/admin/workshop/list'),
      request.get<{ items: any[] }>('/admin/machine/list'),
      request.get<{ items: any[] }>('/admin/worker/list')
    ])
    options.workshops = ws.data?.items ?? []
    options.machines = mc.data?.items ?? []
    options.workers = wr.data?.items ?? []
  } catch {
    // 保持容错，无法获取下拉项时不阻塞页面
  }
  // 初始加载数据
  loadData()
}

// 打开历史弹窗，按记录ID拉取历史数据
async function showHistory(row: ProductionRecord) {
  historyRows.value = []
  historyVisible.value = true
  historyTitle.value = `修正历史 - ${row.machineName} - ${row.date}`
  historyLoading.value = true
  try {
    const res = await request.get<{ items: any[] }>(`/admin/production/${row.id}/adjustment-history`)
    historyRows.value = res.data?.items ?? []
  } finally {
    historyLoading.value = false
  }
}

// 修正产量弹窗：同原有实现，保持风格
async function doAdjust(){
  await ElMessageBox.confirm('确定修正产量？修正后将记录审计日志。','提示',{type:'warning'})
  submitting.value = true
  try{
    await request.post('/admin/production/adjust', adjustForm)
    ElMessage.success('修正成功')
    adjustVisible.value = false
    loadData()
  } finally{
    submitting.value = false
  }
}

// 进入修正弹窗，初始化表单
function handleAdjust(row: ProductionRecord){
  adjustForm.currentQty = row.quantity ?? 0
  adjustForm.newQty = row.quantity ?? 0
  adjustForm.reason = ''
  adjustForm.id = row.id
  adjustVisible.value = true
}

onMounted(init)

// 监听页码和每页条数变化，自动重新加载数据
watch([() => page.page, () => page.pageSize], () => {
  loadData()
})
</script>
