<template>
  <div>
    <div class="mb-16"><el-button type="primary" @click="handleAdd">+ 新增地址</el-button></div>
    <el-form :inline="true" class="mb-16">
      <el-form-item label="品牌"><el-select v-model="query.brandId" clearable><el-option v-for="b in brandList" :key="b.id" :label="b.brandName" :value="b.id"/></el-select></el-form-item>
      <el-form-item><el-button type="primary" @click="loadData">查询</el-button><el-button @click="resetQuery">重置</el-button></el-form-item>
    </el-form>
    <el-table :data="tableData" border stripe v-loading="loading">
      <el-table-column prop="name" label="名称"><template #default="{row}"><el-link type="primary" @click="goDetail(row.id)">{{row.name}}</el-link></template></el-table-column>
      <el-table-column prop="url" label="URL" min-width="200" show-overflow-tooltip/>
      <el-table-column prop="brandName" label="品牌" align="center"/>
      <el-table-column prop="collectInterval" label="采集间隔" align="center"/>
      <el-table-column label="状态" align="center"><template #default="{row}"><el-tag :type="row.isEnabled?'success':'danger'" size="small">{{row.isEnabled?'启用':'停用'}}</el-tag></template></el-table-column>
      <el-table-column prop="lastCollectTime" label="最后采集"/>
      <el-table-column prop="machineCount" label="机床数" align="center"/>
      <el-table-column prop="failCount" label="连续失败" align="center"><template #default="{row}"><el-tag :type="row.failCount===0?'success':row.failCount<=3?'warning':'danger'" size="small">{{row.failCount}} 次</el-tag></template></el-table-column>
      <el-table-column label="操作" width="120" align="center"><template #default="{row}">
        <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
        <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
      </template></el-table-column>
    </el-table>
      <el-dialog v-model="dialogVisible" :title="editingId?'编辑地址':'新增地址'" width="600px" destroy-on-close>
        <el-form :model="form" label-width="100px">
          <el-form-item label="名称" required><el-input v-model="form.name"/></el-form-item>
          <el-form-item label="URL" required><el-input v-model="form.url"/></el-form-item>
          <el-form-item label="品牌" required><el-select v-model="form.brandId"><el-option v-for="b in brandList" :key="b.id" :label="b.brandName" :value="b.id"/></el-select></el-form-item>
          <!-- 关联机床区域 -->
          <el-form-item label="关联机床">
            <el-checkbox-group v-model="form.machineIds">
              <el-checkbox v-for="m in machineList" :key="m.machineId" :label="m.machineId">{{m.machineName}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="采集间隔" required><el-input-number v-model="form.collectInterval" :min="5"/></el-form-item>
        </el-form>
        <template #footer><el-button @click="dialogVisible=false">取消</el-button><el-button type="primary" :loading="submitting" @click="handleSubmit">保存</el-button></template>
      </el-dialog>
    </div>
</template>
<script setup lang="ts">
import {ref, reactive, onMounted, watch} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage,ElMessageBox} from 'element-plus'
import request from '@/utils/request'
import {useMockMode} from '@/composables/useMockMode'
const router=useRouter();const{isMock}=useMockMode()
import type { ApiResponse, Brand, Workshop, CollectAddress } from '@/types'
const loading=ref(false);const tableData=ref<CollectAddress[]>([]);const brandList=ref<Brand[]>([])
const dialogVisible=ref(false);const submitting=ref(false);const editingId=ref<number|null>(null)
const query=reactive({brandId:undefined as number|undefined})
const form=reactive({name:'',url:'',brandId:undefined as number|undefined,collectInterval:30,machineIds: [] as number[]})
// 机床列表（关联机床）
const machineList=ref<{ machineId:number; machineName:string }[]>([])
// 加载某品牌的机床列表
async function loadMachinesForBrandName(brandName:string){ if(!brandName){ machineList.value = []; return } const r: ApiResponse<{ items: { machineId:number; machineName:string }[] }> = await request.get('/admin/machine/list', { params: { brandName } }); machineList.value = r.data?.items || [] }
function resetQuery(){query.brandId=undefined;loadData()}
function goDetail(id:number){router.push((isMock.value?'/mock/collect-address/':'/collect-address/')+id)}
async function loadData(){loading.value=true;try{const r:any=await request.get('/admin/collect-address');tableData.value=r.data?.items||[]}finally{loading.value=false}}
function handleAdd(){editingId.value=null;Object.assign(form,{name:'',url:'',brandId:undefined,collectInterval:30,machineIds: []});dialogVisible.value=true}
function handleEdit(row:any){editingId.value=row.id;Object.assign(form,row);dialogVisible.value=true}
async function handleSubmit(){submitting.value=true;try{await request[editingId.value?'put':'post'](editingId.value?`/admin/collect-address/${editingId.value}`:'/admin/collect-address',{...form});ElMessage.success('保存成功');dialogVisible.value=false;loadData()}finally{submitting.value=false}}
async function handleDelete(row:any){await ElMessageBox.confirm('确定删除【'+row.name+'】？此操作不可恢复。','提示',{type:'warning'});await request.delete(`/admin/collect-address/${row.id}`);ElMessage.success('已删除');loadData()}
async function loadDrops(){const r:any=await request.get('/admin/brand/list');brandList.value=r.data?.items||[]}
onMounted(()=>{loadData();loadDrops()})
// 监听品牌变化，自动加载对应机床
watch(() => form.brandId, async (newVal)=>{
  const b = brandList.value.find((bb:any)=> bb.id===newVal)
  const brandName = b?.brandName ?? ''
  await loadMachinesForBrandName(brandName)
  form.machineIds = []
}, { immediate: true })
</script>
