<template>
  <my-layout>
    <el-card class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
      <el-form :inline="true" label-width="auto" :label-position="'left'" @submit.stop.prevent>
        <el-form-item label="关键字" prop="keyWord">
          <el-input v-model="state.filter.keyWord" placeholder="请输入设备编号/资产编号/产品ID/型号" clearable style="width: 300px" @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="房间" prop="roomID">
          <el-select v-model="state.filter.roomID" placeholder="请选择房间" clearable style="width: 200px">
            <el-option v-for="item in state.roomOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker v-model="state.filter.stDate" type="datetime" placeholder="选择开始时间"
            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 180px" />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker v-model="state.filter.edDate" type="datetime" placeholder="选择结束时间"
            format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" style="width: 180px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="ele-Search" @click="handleQuery">查询</el-button>
          <el-button v-auth="'api:admin:equ-reactor:add'" type="primary" icon="ele-Plus" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="my-fill mt8" shadow="never">
      <el-table v-loading="loading" :data="state.reactorList" row-key="id" style="width: 100%" border>
        <el-table-column prop="deviceNo" label="设备编号" min-width="120" show-overflow-tooltip />
        <el-table-column prop="assetNo" label="资产编号" min-width="120" show-overflow-tooltip />
        <el-table-column prop="productID" label="产品ID" min-width="120" show-overflow-tooltip />
        <el-table-column prop="model" label="型号" min-width="120" show-overflow-tooltip />
        <el-table-column prop="specification" label="规格" min-width="120" show-overflow-tooltip />
        <el-table-column prop="capacity" label="容量(g)" min-width="100" show-overflow-tooltip />
        <el-table-column prop="roomName" label="房间名称" min-width="120" show-overflow-tooltip />
        <el-table-column prop="principalName" label="负责人" min-width="100" show-overflow-tooltip />
        <el-table-column prop="deviceStatus" label="设备状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getDeviceStatusType(row.deviceStatus)">
              {{ getDeviceStatusDesc(row.deviceStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="维护标志" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getMaintenanceFlagType(row.maintenanceFlag)">
              {{ row.maintenanceFlagDesc }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否维护中" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isMaintenance ? 'warning' : 'info'">
              {{ row.isMaintenance ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间" min-width="160" show-overflow-tooltip />
        <el-table-column label="操作" width="180" fixed="right" header-align="center" align="center">
          <template #default="{ row }">
            <el-button v-auth="'api:admin:equ-reactor:update'" icon="ele-EditPen" size="small" text type="primary"
              @click="handleEdit(row)">编辑</el-button>
            <el-button v-auth="'api:admin:equ-reactor:soft-delete'" icon="ele-Delete" size="small" text type="danger"
              @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="my-flex my-flex-end" style="margin-top: 10px">
        <el-pagination v-model:current-page="state.pageInput.currentPage" v-model:page-size="state.pageInput.pageSize"
          :total="state.total" :page-sizes="[10, 20, 50, 100]" size="small" background @size-change="handleSizeChange"
          @current-change="handleCurrentChange" layout="total, sizes, prev, pager, next, jumper" />
      </div>
    </el-card>

    <reactor-form ref="formRef" :title="state.formTitle" @ok="getList" />
  </my-layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeMount } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ReactorApi } from '/@/api/admin/reactor'
import { RoomApi } from '/@/api/admin/Room'
import eventBus from '/@/utils/mitt'
import type {
  ReactorPageInput,
  ReactorDto,
  ReactorTypeEnumItem
} from '/@/api/types/ReactorType'
import { DeviceStatusEnum, MaintenanceFlagEnum } from '/@/api/types/ReactorType'

import ReactorForm from './components/reactor-form.vue'

const loading = ref(false)
const formRef = ref()

const state = reactive({
  loading: false,
  formTitle: '',
  total: 0,
  filter: {
    keyWord: '',
    stDate: '',
    edDate: '',
    deviceStatus: undefined as number | undefined,
    maintenanceFlag: undefined as number | undefined,
    principalId: undefined as number | undefined,
    roomID: undefined as number | undefined,
    status: undefined as number | undefined,
    isMaintenance: undefined as boolean | undefined,
    pageIndex: 1,
    pageSize: 10
  },
  pageInput: {
    currentPage: 1,
    pageSize: 20,
  } as ReactorPageInput,
  reactorList: [] as Array<ReactorDto>,
  roomOptions: [] as Array<{ id: number; name: string }>,
  principalOptions: [] as Array<{ id: number; name: string }>,
  deviceStatusOptions: [] as ReactorTypeEnumItem[]
})

/** 获取设备状态枚举列表 */
const getDeviceStatusOptions = async () => {
  try {
    const res = await new ReactorApi().getDeviceStatusEnumList()
    state.deviceStatusOptions = res.data ?? []
  } catch (error) {
    console.error('获取设备状态枚举列表失败:', error)
  }
}

/** 获取设备状态描述 */
const getDeviceStatusDesc = (value: number) => {
  const item = state.deviceStatusOptions.find(item => item.value === value)
  return item?.label || '未知'
}

/** 获取设备状态类型 */
const getDeviceStatusType = (value: number) => {
  switch (value) {
    case DeviceStatusEnum.Normal:
      return 'success'
    case DeviceStatusEnum.Fault:
      return 'danger'
    case DeviceStatusEnum.Maintenance:
      return 'warning'
    default:
      return 'info'
  }
}

/** 获取维护标志描述 */
const getMaintenanceFlagDesc = (flag: MaintenanceFlagEnum) => {
  const flagMap = {
    [MaintenanceFlagEnum.None]: '无',
    [MaintenanceFlagEnum.Regular]: '定期维护',
    [MaintenanceFlagEnum.Emergency]: '紧急维护'
  }
  return flagMap[flag] || '未知'
}

/** 获取维护标志标签类型 */
const getMaintenanceFlagType = (flag: MaintenanceFlagEnum) => {
  const typeMap = {
    [MaintenanceFlagEnum.None]: 'info',
    [MaintenanceFlagEnum.Regular]: 'warning',
    [MaintenanceFlagEnum.Emergency]: 'danger'
  }
  return typeMap[flag] || 'info'
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  state.filter.pageIndex = state.pageInput.currentPage ?? 1
  state.filter.pageSize = state.pageInput.pageSize ?? 20
  try {
    const res = await new ReactorApi().getPage(state.filter)
    state.reactorList = res.data?.list || []
    state.total = res.data?.total || 0
  } catch (error) {
    console.error('获取列表失败:', error)
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  state.pageInput.currentPage = 1
  getList()
}

/** 新增按钮操作 */
const handleAdd = () => {
  state.formTitle = '新增反应器'
  formRef.value?.open()
}

/** 修改按钮操作 */
const handleEdit = (row: ReactorDto) => {
  state.formTitle = '编辑反应器'
  formRef.value?.open(row)
}

/** 删除按钮操作 */
const handleDelete = (row: ReactorDto) => {
  ElMessageBox.confirm('确认要删除该记录吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await new ReactorApi().softDelete({ id: row.id! })
      if (res.success) {
        ElMessage.success('删除成功')
        getList()
      }
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

/** 每页条数改变 */
const handleSizeChange = (val: number) => {
  state.pageInput.pageSize = val
  getList()
}

/** 当前页改变 */
const handleCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  getList()
}

/** 获取房间列表 */
const getRoomOptions = async () => {
  try {
    const res = await new RoomApi().getPage({
      currentPage: 1,
      pageSize: 1000,
      filter: {}
    })
    state.roomOptions = res.data?.list?.map((item: any) => ({
      id: item.id,
      name: item.roomName
    })) || []
  } catch (error) {
    console.error('获取房间列表失败:', error)
  }
}

/** 获取负责人列表 */
const getPrincipalOptions = async () => {
  try {
    // TODO: 调用获取负责人列表API
    state.principalOptions = [
      { id: 1, name: '张三' },
      { id: 2, name: '李四' }
    ]
  } catch (error) {
    console.error('获取负责人列表失败:', error)
  }
}

onMounted(() => {
  getList()
  getRoomOptions()
  getPrincipalOptions()
  getDeviceStatusOptions()
  eventBus.on('refreshReactor', getList)
})

onBeforeMount(() => {
  eventBus.off('refreshReactor')
})
</script>

<style lang="scss" scoped>
.my-query-box {
  :deep(.el-form-item) {
    margin-bottom: 16px;
  }
}

.my-fill {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.my-flex {
  display: flex;
}

.my-flex-end {
  justify-content: flex-end;
}

.mt8 {
  margin-top: 8px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
