<template>
  <div class="device-info-wrap">
    <EdfsWrap class="device-info-from-wrap">
      <div class="from">
        <div class="from-input">
          <div class="from-row">
            <div class="label">设备序列:</div>
            <el-input
              v-model="queryParams.serialNo"
              placeholder="请输入设备序列号"
              clearable
              @keyup.enter="handleQuery"
            />
          </div>
          <div class="from-row">
            <div class="label">设备名称:</div>
            <el-input
              v-model="queryParams.name"
              placeholder="请输入设备名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </div>

          <div class="from-row">
            <div class="label">注册时段:</div>
            <el-date-picker
              v-model="queryParams.createTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </div>
          <div class="from-row">
            <div class="label">设备类别:</div>
            <el-cascader
              class="input"
              v-model="queryParams.categoryId"
              :options="categoryTreeData"
              :props="{
                checkStrictly: true,
                value: 'id',
                label: 'name',
              }"
            />
          </div>

          <div class="btn-group">
            <el-button @click="addDevice"><Icon icon="ep:plus" />添加设备</el-button>

            <el-button @click="handleQuery"><Icon icon="ep:search" />搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" />重置</el-button>
          </div>
        </div>
      </div>
    </EdfsWrap>
    <EdfsWrap title="设备信息列表" class="device-info-table">
      <EdfsTable
        class="table"
        v-loading="loading"
        :data="list"
        ref="tableRef"
        :highlight-current-row="true"
        :page-total="total"
        :current-page="queryParams.pageNo"
        :page-size="queryParams.pageSize"
        row-class-name="row"
        @pageCurrentChange="handleJump"
      >
        <template v-for="(col, idx) in deviceTableCol" :key="idx">
          <el-table-column
            v-if="col.prop.endsWith('Time')"
            :label="col.label"
            :min-width="col.minWidth"
          >
            <template #default="scope">
              {{ dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="col.prop === 'status'"
            :prop="col.prop"
            :label="col.label"
            :min-width="col.minWidth"
          >
            <template #default="scope">
              {{ DeviceStatus[scope.row.status] }}
            </template>
          </el-table-column>
          <el-table-column
            v-else
            :prop="col.prop"
            :label="col.label"
            :min-width="col.minWidth"
          />
        </template>

        <el-table-column label="操作" width="190" align="center">
          <template #default="scope">
            <EdfsButton
              link
              type="primary"
              inner-text="查看"
              @click="onView(scope.row)"
            /><el-divider direction="vertical" />
            <EdfsButton
              link
              type="primary"
              inner-text="编辑基础信息"
              @click="editDevice(scope.row, 'info')"
              v-if="scope.row.status < 2"
            />
            <EdfsButton
              link
              type="primary"
              inner-text="测试结果录入"
              @click="editDevice(scope.row, 'test')"
              v-if="scope.row.status === 1"
            />
            <EdfsButton
              link
              type="primary"
              inner-text="出库"
              @click="editDevice(scope.row, 'delivery')"
              v-if="scope.row.status === 2"
            />

            <EdfsButton
              link
              type="primary"
              inner-text="设备报修"
              @click="editDevice(scope.row, 'maintain')"
              v-if="scope.row.status === 3"
            />
          </template>
        </el-table-column>
      </EdfsTable>
    </EdfsWrap>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import EdfsWrap from '@/components/dashboard/Edfs-wrap.vue'
import EdfsTable from '@/components/dashboard/Edfs-table/index.vue'
import EdfsButton from '@/components/dashboard/Edfs-button/index.vue'
import { isResError } from '@/hooks/useMessage'
import { dateFormatter } from '@/utils/formatTime'
import type { TableColumnCtx } from 'element-plus'
import { useRouter } from 'vue-router'
import { getDevicePage, type IDevice } from '@/api/module/eam/device'
import { deviceTableCol, DeviceStatus } from './utils'
import { getCategoryTree, type ICategoryTree } from '@/api/module/eam/device/category'

const loading = ref(true)
const total = ref(0)
const list = ref<IDevice[]>([])
const queryParams = reactive({
  pageNo: 1,
  pageSize: undefined,
  serialNo: undefined,
  name: undefined,
  status: undefined,
  categoryId: [],
  createTime: [],
})
const tableRef = ref()
const getList = async () => {
  if (!queryParams.pageSize) {
    queryParams.pageSize = tableRef.value.getSize()
  }
  loading.value = true

  const options = {
    ...queryParams,
    categoryId: queryParams.categoryId?.[queryParams.categoryId.length - 1],
  }

  const res = await getDevicePage(options)

  if (!isResError(res)) {
    list.value = res.data.list
    total.value = res.data.total
  }

  loading.value = false
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
function handleJump(page: number) {
  queryParams.pageNo = page
  getList()
}

function resetQuery() {
  queryParams.serialNo = undefined
  queryParams.name = undefined
  queryParams.status = undefined
  queryParams.categoryId = []
  queryParams.createTime = []
  handleQuery()
}

const categoryTreeData = ref<ICategoryTree[]>([])
async function loadDeviceTypeTree() {
  const res = await getCategoryTree()
  if (!isResError(res)) {
    categoryTreeData.value = res.data
  }
}

interface SpanMethodProps {
  row: any
  column: TableColumnCtx<any>
  rowIndex: number
  columnIndex: number
}

const formRef = ref()
const openForm = (type: string, id?: number) => {}
onMounted(() => {
  getList()
  loadDeviceTypeTree()
})

const router = useRouter()

function editDevice(row: any, type: string) {
  router.push({
    path: '/device/deviceOperation',
    query: { action: 'update', type, id: row.id },
  })
}
function addDevice() {
  router.push({ path: '/device/deviceOperation', query: { action: 'create' } })
}
function onView(row: any) {
  router.push({ path: '/device/deviceOperation', query: { action: 'view', id: row.id } })
}
</script>

<style lang="scss" scoped>
.device-info-wrap {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  row-gap: 10px;
  .device-info-from-wrap {
    height: auto;
    width: 100%;
    .from {
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      height: 100%;
      width: 100%;
      .from-input {
        display: flex;
        width: 100%;
        column-gap: 20px;
        row-gap: 10px;
        flex-wrap: wrap;
        .from-row {
          min-width: 270px;
          display: flex;
          align-items: center;
          column-gap: 4px;
          .label {
            white-space: nowrap;
            width: 70px;
            color: var(--label-color);
          }
        }
      }
    }
  }
  .device-info-table {
    flex: 1;
    .table {
      height: 100%;
    }
  }
}
</style>
