<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="请输入设备编号/资产编号" 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="model" label="设备型号" width="100">
          <template #default="{ row }">
            {{ getDeviceModelDesc(row.model) }}
          </template>
        </el-table-column>
        <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="roomId" label="房间" width="100">
          <template #default="{ row }">
            {{ getRoomName(row.roomID) }}
          </template>
        </el-table-column>
        <el-table-column prop="roomId" label="负责人" width="200">
          <template #default="{ row }">
            {{ getPrincipalName(row.principalId) }}
          </template>
        </el-table-column>
        <el-table-column prop="deviceStatus" label="设备状态" width="100">
          <template #default="{ row }">
            <el-tag>
              {{ getDeviceStatusDesc(row.deviceStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" label="创建时间" min-width="160" show-overflow-tooltip />
        <el-table-column label="操作" width="240" 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 icon="ele-Bell" size="small" text type="warning" @click="openAlarmSetting(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" />
    <alarm-setting-form ref="alarmSettingRef" />
  </my-layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeMount, defineAsyncComponent } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ReactorApi } from '../../../api/admin/ReactorApi'
import { RoomApi } from '/@/api/admin/Room'
import { UserApi } from '/@/api/admin/User'
import { DictApi } from '/@/api/admin/Dict'
import eventBus from '/@/utils/mitt'
import type {
  ReactorPageInput,
  ReactorDto,
  ReactorTypeEnumItem
} from '/@/api/types/reactorType'

const AlarmSettingForm = defineAsyncComponent(() => import('./components/alarm-setting-form.vue'))
const ReactorForm = defineAsyncComponent(() => import('./components/reactor-form.vue'))

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

const state = reactive({
  loading: false,
  formTitle: '',
  total: 0,
  filter: {
    keyWord: '',
    stDate: '',
    edDate: '',
    roomId: undefined as number | undefined
  },
  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[],
  deviceModelOptions: [] as Array<{ id: string; name: string }>,
})


/** 查询列表 */
const getList = async () => {
  loading.value = true
  state.pageInput.filter = state.filter
  try {

    console.log(state.filter);
    const res = await new ReactorApi().getPage(state.pageInput)
    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.id)
}

/** 删除按钮操作 */
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 getDeviceStatusOptions = async () => {
  try {
    const res = await new ReactorApi().getDeviceStatusEnumList()
    state.deviceStatusOptions = res.data ?? []
  } catch (error) {
    console.error('获取设备状态枚举列表失败:', error)
  }
}

/** 获取房间列表 */
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 {
    const res = await new UserApi().getPage({
      currentPage: 1,
      pageSize: 1000,
      filter: {}
    })

    state.principalOptions = res.data?.list?.map((item: any) => ({
      id: item.id,
      name: item.userName
    })) || []
  } catch (error) {
    console.error('获取用户列表失败:', error)
  }
}

const getDeviceModelOptions = async () => {
  try {
    const res = await new DictApi().getList(['ReactorModel'])
    state.deviceModelOptions = res.data?.reactorModel?.map((item: any) => ({
      id: item.value,
      name: item.name
    })) || []
  }
  catch (error) {
    console.error('获取设备型号列表失败:', error)
  }
}

/** 获取设备型号描述 */
const getDeviceModelDesc = (value: string) => {
  const item = state.deviceModelOptions.find(item => item.id === value)
  return item?.name || '未知'
}

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

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

/** 获取负责人名称 */
const getPrincipalName = (value: number) => {
  const item = state.principalOptions.find(item => item.id === value)
  return item?.name || '未知'
}

function openAlarmSetting(row: ReactorDto) {
  alarmSettingRef.value?.open(row)
}

onMounted(() => {
  getRoomOptions()
  getPrincipalOptions()
  getDeviceStatusOptions()
  getDeviceModelOptions()

  getList()
  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>
