<template>
  <div>
    <div class="mb-16">
      <el-button type="primary" @click="handleAdd">+ 新增地址</el-button>
      <el-button v-if="selectedRows.length" size="default" @click="batchToggle(1)">批量启用({{ selectedRows.length }})</el-button>
      <el-button v-if="selectedRows.length" size="default" @click="batchToggle(0)">批量停用({{ selectedRows.length }})</el-button>
      <el-button v-if="selectedRows.length" size="default" type="danger" @click="handleBatchDelete">批量删除({{ selectedRows.length }})</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" @selection-change="(rows: CollectAddress[]) => selectedRows = rows">
      <el-table-column type="selection" width="50" fixed="left" align="center" />
      <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}">
        <div style="white-space:nowrap">
          <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button link type="danger" :disabled="row.machineCount>0" @click="handleDelete(row)">删除</el-button>
        </div>
      </template></el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" :title="editingId?'编辑地址':'新增地址'" width="900px" 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" @change="onBrandChange">
            <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-transfer
            v-model="form.machineIds"
            :data="transferMachines"
            :titles="['同品牌机床', '已关联']"
            :props="{ key: 'id', label: 'label' }"
            filterable
            filter-placeholder="搜索机床"
          >
            <template #default="{ option }">
              <span>
                <span :style="dotStyle(option)"></span>
                {{ option.name }}
                <template v-if="option.deviceCode"> ({{ option.deviceCode }})</template>
              </span>
            </template>
          </el-transfer>
          <div class="transfer-legend">
            <span><span class="status-dot online"></span>在线</span>
            <span><span class="status-dot offline"></span>离线</span>
            <span><span class="status-dot disabled-dot"></span>停用</span>
          </div>
        </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} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage,ElMessageBox} from 'element-plus'
import request from '@/utils/request'
import {useMockMode} from '@/composables/useMockMode'
import type { ApiResponse, Brand, CollectAddress } from '@/types'
const router=useRouter();const{isMock}=useMockMode()
const loading=ref(false);const tableData=ref<CollectAddress[]>([]);const brandList=ref<Brand[]>([]);const selectedRows=ref<CollectAddress[]>([])
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[]})
interface TransferMachine { id: number; name: string; label: string; deviceCode?: string; isOnline: number; isEnabled: number }
const transferMachines=ref<TransferMachine[]>([])

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:[]})
  transferMachines.value=[]
  dialogVisible.value=true
}

async function handleEdit(row: any){
  editingId.value=row.id
  Object.assign(form,{name:row.name,url:row.url,brandId:row.brandId,collectInterval:row.collectInterval,machineIds:[]})
  // 加载穿梭框数据 + 已关联机床
  await loadTransferData(row.brandId, row.id)
  dialogVisible.value=true
}

/** 品牌切换时重新加载穿梭框 */
async function onBrandChange(){
  form.machineIds=[]
  await loadTransferData(form.brandId, editingId.value ?? undefined)
}

/** 加载穿梭框：同品牌全部机床 */
async function loadTransferData(brandId?: number, addressId?: number){
  if(!brandId){ transferMachines.value=[]; return }
  try{
    const brandName = brandList.value.find((b: any) => b.id === brandId)?.brandName ?? ''
    const rAll: any = await request.get('/admin/machine', {params: {brandName, pageSize: 999}})
    const allMachines = rAll.data?.items ?? []
    // 当前地址已关联的机床
    if(addressId){
      try{
        const rOwn: any = await request.get(`/admin/collect-address/${addressId}/machines`)
        const items = rOwn.data?.items ?? []
        form.machineIds = items.map((m: any) => m.machineId)
      }catch{}
    }
    transferMachines.value = allMachines
      .map((m: any) => ({ id: m.id, name: m.name, label: m.name, deviceCode: m.deviceCode, isOnline: m.isOnline, isEnabled: m.isEnabled }))
  }catch{ transferMachines.value=[] }
}

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');brandList.value=r.data?.items||[]}

async function batchToggle(isEnabled:number){
  await ElMessageBox.confirm('确定对选中的'+selectedRows.value.length+'项操作？','提示',{type:'warning'})
  for(const row of selectedRows.value){
    if((isEnabled===1&&!row.isEnabled)||(isEnabled===0&&row.isEnabled)){
      await request.put(`/admin/collect-address/${row.id}/toggle`)
    }
  }
  ElMessage.success('操作成功');loadData()
}

async function handleBatchDelete(){
  await ElMessageBox.confirm('确定删除选中的'+selectedRows.value.length+'个采集地址？此操作不可恢复。','提示',{type:'warning'})
  await request.post('/admin/collect-address/batch-delete',{ids:selectedRows.value.map((r:any)=>r.id)})
  ElMessage.success('批量删除成功');loadData()
}

/** 机床状态色点 */
function dotStyle(m: TransferMachine): Record<string, string> {
  const color = !m.isEnabled ? '#f56c6c' : m.isOnline ? '#67c23a' : '#c0c4cc'
  return { display: 'inline-block', width: '8px', height: '8px', borderRadius: '50%', marginRight: '6px', verticalAlign: 'middle', backgroundColor: color }
}

onMounted(()=>{loadData();loadDrops()})
</script>
<style scoped>
.status-dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 6px; vertical-align: middle; }
.status-dot.online { background-color: #67c23a; }
.status-dot.offline { background-color: #c0c4cc; }
.status-dot.disabled-dot { background-color: #f56c6c; }
.transfer-legend { display: flex; gap: 16px; margin-top: 8px; font-size: 12px; color: #909399; align-items: center; }
.transfer-legend .status-dot { margin-right: 4px; }
</style>
