<template>
  <div v-loading="loading">
    <el-form inline>
      <el-form-item>
        <el-button type="success" icon="Plus" @click="openDialog('add')">新增</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Refresh" @click="fetchData">刷新</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="list" size="small" height="505" border stripe>
      <el-table-column label="编码" align="center" width="120" prop="device_code" />
      <el-table-column label="名称" align="center" width="180" prop="device_name" />
      <el-table-column label="连接方式" align="center" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.connect_type === 'tcp' ? 'primary' : 'warning'">
            {{ scope.row.connect_type === 'tcp' ? 'TCP' : '串口' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="IP地址" align="center" width="150" prop="ip_address" />
      <el-table-column label="端口" align="center" width="100" prop="port" />
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'online' ? 'success' : 'danger'">
            {{ scope.row.status === 'online' ? '在线' : '离线' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="启用" align="center" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.is_active ? 'success' : 'danger'">
            {{ scope.row.is_active ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="280" fixed="right">
        <template #default="scope">
          <el-button text type="success" icon="Link" @click="handleConnect(scope.row)">连接</el-button>
          <el-button text type="primary" icon="Edit" @click="openDialog('edit', scope.row)">修改</el-button>
          <el-button text type="primary" icon="Delete" @click="handleDelete(scope.row.ID)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="display: flex; justify-content: flex-end; margin-top: 10px">
      <el-pagination
        v-model:current-page="query.page"
        v-model:page-size="query.page_size"
        :page-sizes="[10, 30, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="fetchData"
        @size-change="onSizeChange"
      />
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑设备' : '新增设备'"
      width="600"
    >
      <el-form label-width="150">
        <el-form-item label="设备编码：">
          <el-input v-model="form.device_code" />
        </el-form-item>
        <el-form-item label="设备名称：">
          <el-input v-model="form.device_name" />
        </el-form-item>
        <el-form-item label="关联通道：">
          <el-select v-model="form.channel_id" placeholder="请选择通道" clearable>
            <el-option
              v-for="item in channelList"
              :key="item.ID"
              :label="item.channel_name"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="连接方式：">
          <el-select v-model="form.connect_type">
            <el-option label="TCP" value="tcp" />
            <el-option label="串口" value="serial" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.connect_type === 'tcp'" label="IP地址：">
          <el-input v-model="form.ip_address" />
        </el-form-item>
        <el-form-item v-if="form.connect_type === 'tcp'" label="端口：">
          <el-input v-model="form.port" type="number" />
        </el-form-item>
        <el-form-item v-if="form.connect_type === 'serial'" label="串口名：">
          <el-input v-model="form.com_port" />
        </el-form-item>
        <el-form-item v-if="form.connect_type === 'serial'" label="波特率：">
          <el-input v-model="form.baud_rate" type="number" />
        </el-form-item>
        <el-form-item label="启用：">
          <el-switch v-model="form.is_active" />
        </el-form-item>
        <el-form-item label="备注：">
          <el-input v-model="form.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import {
  obtainDeviceList,
  addDevice,
  editDevice,
  deleteDevice,
  joinDevice,
} from '@/api/device'
import { obtainChannelList } from '@/api/channel'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  parkId: {
    type: Number,
    default: 0,
  },
})

const loading = ref(false)
const list = ref([])
const total = ref(0)
const channelList = ref([])
const query = reactive({
  parking_lot_id: 0,
  page: 1,
  page_size: 10,
})

const fetchData = async () => {
  if (!props.parkId || props.parkId === 0) {
    list.value = []
    total.value = 0
    return
  }
  loading.value = true
  query.parking_lot_id = props.parkId
  try {
    const res = await obtainDeviceList({ ...query })
    if (res.code === 0) {
      list.value = res.data.list || []
      total.value = res.data.total || 0
    }
  } finally {
    loading.value = false
  }
}

const fetchChannelList = async () => {
  if (!props.parkId || props.parkId === 0) return
  const res = await obtainChannelList({ parking_lot_id: props.parkId, page: 1, page_size: 999 })
  if (res.code === 0) {
    channelList.value = res.data.list || []
  }
}

const onSizeChange = (val) => {
  query.page_size = val
  query.page = 1
  fetchData()
}

// Dialog
const dialogVisible = ref(false)
const isEdit = ref(false)
const form = reactive({
  id: 0,
  device_code: '',
  device_name: '',
  baud_rate: 0,
  ip_address: '',
  port: 0,
  com_port: '',
  description: '',
  connect_type: 'tcp',
  is_active: false,
  channel_id: null,
})

const openDialog = (mode, row) => {
  isEdit.value = mode === 'edit'
  fetchChannelList()
  if (mode === 'edit' && row) {
    form.id = row.ID
    form.device_code = row.device_code
    form.device_name = row.device_name
    form.baud_rate = row.baud_rate
    form.ip_address = row.ip_address
    form.port = row.port
    form.com_port = row.com_port
    form.description = row.description
    form.connect_type = row.connect_type
    form.is_active = row.is_active
    form.channel_id = row.channel_id || null
  } else {
    form.id = 0
    form.device_code = ''
    form.device_name = ''
    form.baud_rate = 0
    form.ip_address = ''
    form.port = 0
    form.com_port = ''
    form.description = ''
    form.connect_type = 'tcp'
    form.is_active = false
    form.channel_id = null
  }
  dialogVisible.value = true
}

const submitForm = async () => {
  if (!form.device_code || !form.device_name) {
    ElMessage.error('请填写完整信息')
    return
  }
  form.baud_rate = Number(form.baud_rate)
  form.port = Number(form.port)
  if (isEdit.value) {
    const res = await editDevice(form)
    if (res.code === 0) {
      ElMessage.success('编辑成功')
      dialogVisible.value = false
      await fetchData()
    } else {
      ElMessage.error(res.data?.msg || '编辑失败')
    }
  } else {
    const res = await addDevice(form)
    if (res.code === 0) {
      ElMessage.success('新增成功')
      dialogVisible.value = false
      await fetchData()
    } else {
      ElMessage.error(res.data?.msg || '新增失败')
    }
  }
}

const handleConnect = async (row) => {
  const res = await joinDevice(row.ID)
  if (res.code === 0) {
    ElMessage.success('连接成功')
  } else {
    ElMessage.error(res.data?.msg || '连接失败')
  }
}

const handleDelete = (id) => {
  ElMessageBox.confirm('确定删除该设备吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const res = await deleteDevice(id)
      if (res.code === 0) {
        ElMessage.success('删除成功')
        await fetchData()
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

watch(
  () => props.parkId,
  (val) => {
    query.page = 1
    fetchData()
  },
  { immediate: true }
)
</script>
