<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="channel_code" />
      <el-table-column label="名称" align="center" width="200" prop="channel_name" />
      <el-table-column label="方向" align="center" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.direction === 'in' ? 'success' : scope.row.direction === 'out' ? 'danger' : 'warning'">
            {{ scope.row.direction === 'in' ? '进场' : scope.row.direction === 'out' ? '出场' : '进出' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="允许临时车" align="center" width="140">
        <template #default="scope">
          <el-tag :type="scope.row.allow_temporary ? 'success' : 'danger'">
            {{ scope.row.allow_temporary ? '允许' : '禁止' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="关联岗亭ID" align="center" width="120" prop="booth_id" />
      <el-table-column label="备注" align="center" prop="description" />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <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="140">
        <el-form-item label="通道编码：">
          <el-input v-model="form.channel_code" />
        </el-form-item>
        <el-form-item label="通道名称：">
          <el-input v-model="form.channel_name" />
        </el-form-item>
        <el-form-item label="方向：">
          <el-radio-group v-model="form.direction">
            <el-radio value="in">进场</el-radio>
            <el-radio value="out">出场</el-radio>
            <el-radio value="inout">进出</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="允许临时车：">
          <el-switch v-model="form.allow_temporary" />
        </el-form-item>
        <el-form-item label="关联岗亭：">
          <el-select v-model="form.booth_id" placeholder="请选择岗亭" clearable>
            <el-option
              v-for="item in boothList"
              :key="item.ID"
              :label="item.booth_name"
              :value="item.ID"
            />
          </el-select>
        </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 {
  obtainChannelList,
  addChannel,
  editChannel,
  deleteChannel,
} from '@/api/channel'
import { obtainGuardBoothList } from '@/api/guardBooth'
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 boothList = 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 obtainChannelList({ ...query })
    if (res.code === 0) {
      list.value = res.data.list || []
      total.value = res.data.total || 0
    }
  } finally {
    loading.value = false
  }
}

const fetchBoothList = async () => {
  if (!props.parkId || props.parkId === 0) return
  const res = await obtainGuardBoothList({ parking_lot_id: props.parkId, page: 1, page_size: 999 })
  if (res.code === 0) {
    boothList.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,
  channel_code: '',
  channel_name: '',
  direction: 'in',
  allow_temporary: false,
  description: '',
  booth_id: null,
})

const openDialog = (mode, row) => {
  isEdit.value = mode === 'edit'
  fetchBoothList()
  if (mode === 'edit' && row) {
    form.id = row.ID
    form.channel_code = row.channel_code
    form.channel_name = row.channel_name
    form.direction = row.direction
    form.allow_temporary = row.allow_temporary
    form.description = row.description
    form.booth_id = row.booth_id || null
  } else {
    form.id = 0
    form.channel_code = ''
    form.channel_name = ''
    form.direction = 'in'
    form.allow_temporary = false
    form.description = ''
    form.booth_id = null
  }
  dialogVisible.value = true
}

const submitForm = async () => {
  if (!form.channel_code || !form.channel_name) {
    ElMessage.error('请填写完整信息')
    return
  }
  if (isEdit.value) {
    const res = await editChannel(form)
    if (res.code === 0) {
      ElMessage.success('编辑成功')
      dialogVisible.value = false
      await fetchData()
    }
  } else {
    const res = await addChannel(form)
    if (res.code === 0) {
      ElMessage.success('新增成功')
      dialogVisible.value = false
      await fetchData()
    }
  }
}

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

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