<template>
  <MyLayout>
          <el-card v-show="state.showQuery" class="my-query-box mt8" shadow="never" :body-style="{ paddingBottom: '0' }">
        <el-form :inline="true" label-width="auto" @submit.stop.prevent>
          <el-form-item label="关键词">
            <el-input v-model="state.filter.keyWord" placeholder="设备编号、资产编号" @keyup.enter="onQuery" />
          </el-form-item>
          <el-form-item label="设备型号">
            <el-select v-model="state.filter.model" placeholder="请选择设备型号" clearable style="width: 150px">
              <el-option
                v-for="model in state.modelOptions"
                :key="model.value"
                :label="model.label"
                :value="model.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="房间">
            <el-select v-model="state.filter.roomID" placeholder="请选择房间" clearable style="width: 150px">
              <el-option
                v-for="room in state.roomOptions"
                :key="room.id"
                :label="room.roomName"
                :value="room.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="onQuery"> 查询 </el-button>
            <el-button v-auth="'api:admin:usp-scale:add'" type="primary" icon="ele-Plus" @click="onAdd"> 新增 </el-button>
          </el-form-item>
        </el-form>
      </el-card>

    <el-card class="my-fill mt8" shadow="never">
      <div class="my-tools-box mb8 my-flex my-flex-between">
        <div>
        </div>
      </div>
      <el-table
        v-if="state.showUspscaleList"
        :data="state.uspscaleListData"
        style="width: 100%"
        v-loading="state.loading"
        row-key="id"
        default-expand-all
        border
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="deviceNo" label="设备编号" min-width="100" show-overflow-tooltip />
        <el-table-column prop="assetNo" label="资产编号" min-width="100" show-overflow-tooltip />
        <el-table-column prop="model" label="型号" min-width="90" show-overflow-tooltip>
          <template #default="{ row }">
            {{ getModelName(row.model) }}
          </template>
        </el-table-column>
        <el-table-column prop="specification" label="规格" min-width="80" show-overflow-tooltip />
        <el-table-column prop="roomID" label="房间" width="120" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            {{ getRoomName(row.roomID) }}
          </template>
        </el-table-column>
        <el-table-column label="维护标记" width="100" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag type="warning" v-if="row.maintenanceFlag">维护中</el-tag>
            <el-tag type="success" v-else>正常</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="补料地秤" width="100" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag type="primary" v-if="row.isFeedingScale">是</el-tag>
            <el-tag type="info" v-else>否</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag type="success" v-if="row.enabled">启用</el-tag>
            <el-tag type="danger" v-else>禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" header-align="center" align="center">
          <template #default="{ row }">
            <el-button
              v-if="auth('api:admin:usp-scale:update')"
              icon="ele-EditPen"
              size="small"
              text
              type="primary"
              @click="onEdit(row)"
              >编辑</el-button
            >
            <el-button
              v-if="auth('api:admin:usp-scale:soft-delete')"
              icon="ele-Delete"
              size="small"
              text
              type="danger"
              @click="onDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="my-flex my-flex-end" style="margin-top: 10px">
        <el-pagination
          v-model:currentPage="state.pageInput.currentPage"
          v-model:page-size="state.pageInput.pageSize"
          :total="state.total"
          :page-sizes="[10, 20, 50, 100]"
          size="small"
          background
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>

    <uspscale-form ref="uspscaleFormRef" :title="state.uspscaleFormTitle"></uspscale-form>
  </MyLayout>
</template>

<script lang="ts" setup name="admin/uspscale">
import { ref, reactive, onMounted, getCurrentInstance, onBeforeMount, defineAsyncComponent } from 'vue'
import { UspscaleGetListOutput, PageInputUspscaleGetPageInput, UspscaleGetPageOutput, RoomGetPageOutput, PageInputRoomGetPageInput } from '/@/api/admin/data-contracts'
import { UspscaleApi } from '/@/api/admin/UspscaleApi'
import { RoomApi } from '/@/api/admin/Room'
import eventBus from '/@/utils/mitt'
import { auth } from '/@/utils/authFunction'

// 引入组件
const UspscaleForm = defineAsyncComponent(() => import('./components/uspscale-form.vue'))

const { proxy } = getCurrentInstance() as any

const uspscaleFormRef = ref()

const state = reactive({
  loading: false,
  uspscaleFormTitle: '',
  filter: {
    keyWord: '',
    model: '',
    roomID: undefined as number | undefined,
    stDate: '',
    edDate: '',
  },
  total: 0,
  pageInput: {
    currentPage: 1,
    pageSize: 20,
  } as PageInputUspscaleGetPageInput,
  uspscaleListData: [] as Array<UspscaleGetPageOutput>,
  roomOptions: [] as Array<RoomGetPageOutput>,
  modelOptions: [
    { label: 'CAIS2-U 1500kg', value: '001' },
    { label: 'METTLER', value: '3' },
    { label: 'OHAUS', value: '5' }
  ],
  showQuery: true,
  showUspscaleList: true,
})

onMounted(() => {
  getRoomOptions()
  Query()
  eventBus.off('refreshRoom')
  eventBus.on('refreshRoom', () => {
    Query()
  })
})

onBeforeMount(() => {
  eventBus.off('refreshRoom')
})

const onChangeUspscaleList = () => {
  state.showUspscaleList = !state.showUspscaleList
  if (state.showUspscaleList) {
    Query()
  }
}

const onQuery = () => {
  Query()
}

const getRoomOptions = async () => {
  try {
    const roomPageInput = {
      currentPage: 1,
      pageSize: 1000, // 获取足够多的数据
      filter: {
        keyWord: '',
      }
    } as PageInputRoomGetPageInput

    const res = await new RoomApi().getPage(roomPageInput)
    if (res?.success) {
      state.roomOptions = res.data?.list ?? []
    }
  } catch (error) {
    console.error('获取房间列表失败:', error)
  }
}

const getRoomName = (roomID: number) => {
  const room = state.roomOptions.find(r => r.id === roomID)
  return room ? room.roomName : `未知房间(${roomID})`
}

const getModelName = (modelValue: string) => {
  const model = state.modelOptions.find(m => m.value === modelValue)
  return model ? model.label : modelValue
}

const Query = async () => {
  state.loading = true
  state.pageInput.filter = state.filter
  const res = await new UspscaleApi().getPage(state.pageInput).catch(() => {
    state.loading = false
  })

  state.uspscaleListData = res?.data?.list ?? []
  state.total = res?.data?.total ?? 0
  state.loading = false
}

const onAdd = () => {
  state.uspscaleFormTitle = '新增地秤'
  uspscaleFormRef.value.open({
    id: 0,
    enabled: true,
    deviceNo: '',
    assetNo: '',
    model: '',
    specification: '',
    roomID: undefined,
    principalId: undefined,
    maintenanceFlag: false,
    warningLowerLimit: 0,
    subSystemIP: '',
    subSystemIPPort: '',
    deviceIP: '',
    deviceIPPort: '',
    scalePrecision: 0,
    serviceName: '',
    isFeedingScale: false
  })
}

const onEdit = (row: UspscaleGetListOutput) => {
  state.uspscaleFormTitle = '编辑地秤'
  uspscaleFormRef.value.open(row)
}

const onDelete = (row: UspscaleGetListOutput) => {
  proxy.$modal
    .confirmDelete(`确定要删除设备【${row.deviceNo || row.assetNo || '未知设备'}】?`)
    .then(async () => {
      await new UspscaleApi().softDelete({ id: row.id }, { loading: true })
      Query()
    })
    .catch(() => {})
}

const onSizeChange = (val: number) => {
  state.pageInput.currentPage = 1
  state.pageInput.pageSize = val
  onQuery()
}

const onCurrentChange = (val: number) => {
  state.pageInput.currentPage = val
  onQuery()
}
</script>

<style scoped lang="scss"></style>
