<script lang="ts" setup>
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { checkPermi } from '@/utils/permission'
import { dateFormatter, rangeShortcuts } from '@/utils/formatTime'
import { CommonStatusEnum } from '@/utils/constants'
import * as DeviceTemplateApi from '@/api/pms/devicetemplate'
import DeviceCategoryTree from '@/components/DeviceCategoryTree/index.vue'
import TemplateForm from './TemplateForm.vue'
import { useTreeStore } from '@/store/modules/attrTemplateTreeStore'

defineOptions({ name: 'DeviceAttrsTemplate' })

type DeviceTemplateRow = Omit<DeviceTemplateApi.DeviceAttrTemplateVO, 'status'> & {
  status?: number
  deviceCategoryName?: string
  createTime?: string
}

interface QueryParams extends PageParam {
  name?: string
  code?: string
  status?: number
  deviceCategoryId?: number
  createTime?: string[]
}

const treeStore = useTreeStore()
const message = useMessage()
const { t } = useI18n()
const { push } = useRouter()
const { ZmTable, ZmTableColumn } = useTableComponents<DeviceTemplateRow>()

const loading = ref(true)
const total = ref(0)
const list = ref<DeviceTemplateRow[]>([])
const queryParams = reactive<QueryParams>({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  code: undefined,
  status: undefined,
  deviceCategoryId: undefined,
  createTime: []
})
const queryFormRef = ref()

const selectedId = computed(() => treeStore.selectedId)

const normalizeStatus = (status: unknown) => {
  const value = Number(status)
  if (value === CommonStatusEnum.ENABLE || value === CommonStatusEnum.DISABLE) {
    return value
  }
  return undefined
}

const isValidStatus = (status: unknown) => normalizeStatus(status) !== undefined

const getList = async () => {
  loading.value = true
  try {
    const data = await DeviceTemplateApi.getDeviceTemplatePage(queryParams)
    list.value = data.list.map((item: DeviceTemplateRow) => ({
      ...item,
      status: normalizeStatus(item.status)
    }))
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

const handleSizeChange = (val: number) => {
  queryParams.pageSize = val
  handleQuery()
}

const handleCurrentChange = (val: number) => {
  queryParams.pageNo = val
  getList()
}

const handleDeviceCategoryTreeNodeClick = async (row: Tree) => {
  treeStore.setSelectedId(row.id)
  queryParams.deviceCategoryId = row.id
  queryParams.pageNo = 1
  await getList()
}

const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

const openDetail = (row: DeviceTemplateRow) => {
  push({
    name: 'DeviceAttrTemplateModel',
    params: {
      id: row.deviceCategoryId,
      templateName: row.name,
      categoryName: row.deviceCategoryName
    }
  })
}

const getStatusText = (status: unknown) => {
  const value = normalizeStatus(status)
  if (value === CommonStatusEnum.ENABLE) return '启用'
  if (value === CommonStatusEnum.DISABLE) return '停用'
  return '未知'
}

const handleStatusChange = async (
  row: DeviceTemplateRow,
  nextStatus: string | number | boolean
) => {
  const status = normalizeStatus(nextStatus)
  const oldStatus = normalizeStatus(row.status)
  if (
    !row.id ||
    !row.name ||
    status === undefined ||
    oldStatus === undefined ||
    status === oldStatus
  ) {
    return
  }

  try {
    await message.confirm(`确认要${getStatusText(status)}"${row.name}"属性模板吗?`)
    row.status = status
    await DeviceTemplateApi.updateDeviceTemplateStatus(row.id, status)
    await getList()
  } catch {
    row.status = oldStatus
  }
}

const handleCommand = (command: string, row: DeviceTemplateRow) => {
  switch (command) {
    case 'handleDelete':
      handleDelete(row.id!)
      break
    default:
      break
  }
}

const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await DeviceTemplateApi.deleteDeviceTemplate(id)
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

onMounted(() => {
  getList()
})
</script>

<template>
  <div
    class="grid grid-cols-[auto_1fr] grid-rows-[auto_1fr] gap-4 h-[calc(100vh-20px-var(--top-tool-height)-var(--tags-view-height)-var(--app-footer-height))]"
  >
    <DeviceCategoryTree
      v-model="queryParams.deviceCategoryId"
      :show-title="false"
      @node-click="handleDeviceCategoryTreeNodeClick"
      class="row-span-2"
    />

    <el-form
      ref="queryFormRef"
      :model="queryParams"
      size="default"
      label-width="68px"
      class="bg-white dark:bg-[#1d1e1f] rounded-lg shadow px-8 py-3 gap-6 flex items-center justify-between flex-wrap min-w-0"
    >
      <div class="flex items-center gap-6 flex-wrap">
        <el-form-item label="模板名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入模板名称"
            clearable
            class="!w-200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="模板编码" prop="code">
          <el-input
            v-model="queryParams.code"
            placeholder="请输入模板编码"
            clearable
            class="!w-200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            class="!w-180px"
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker
            v-model="queryParams.createTime"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="rangeShortcuts"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-320px"
          />
        </el-form-item>
      </div>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />搜索
        </el-button>
        <el-button @click="resetQuery"> <Icon icon="ep:refresh" class="mr-5px" />重置 </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['rq:iot-device-template:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />新增
        </el-button>
      </el-form-item>
    </el-form>

    <div class="bg-white dark:bg-[#1d1e1f] shadow rounded-lg flex flex-col p-4 min-w-0">
      <div class="flex-1 relative min-h-0">
        <el-auto-resizer class="absolute">
          <template #default="{ width, height }">
            <ZmTable
              :data="list"
              :loading="loading"
              :width="width"
              :height="height"
              :max-height="height"
              show-border
            >
              <ZmTableColumn
                type="index"
                label="序号"
                :width="60"
                fixed="left"
                hide-in-column-settings
              />
              <ZmTableColumn prop="code" label="模板编码" fixed="left" />
              <ZmTableColumn prop="name" label="模板名称" fixed="left" />
              <ZmTableColumn prop="deviceCategoryName" label="设备分类名称" />
              <ZmTableColumn
                prop="status"
                label="状态"
                :real-value="(row) => getStatusText(row.status)"
                :width="90"
              >
                <template #default="{ row }">
                  <el-switch
                    v-if="isValidStatus(row.status)"
                    :model-value="row.status"
                    :active-value="0"
                    :inactive-value="1"
                    :disabled="!checkPermi(['rq:iot-device-template:update'])"
                    @change="(status) => handleStatusChange(row, status)"
                  />
                  <el-tag v-else type="info">未知</el-tag>
                </template>
              </ZmTableColumn>
              <ZmTableColumn
                prop="createTime"
                label="创建时间"
                :formatter="dateFormatter"
                width="180"
              />
              <ZmTableColumn label="操作" width="220" fixed="right" action>
                <template #default="{ row }">
                  <div class="flex items-center justify-center gap-2">
                    <el-button type="primary" link @click="openDetail(row)">
                      <Icon icon="ep:view" class="mr-3px" />查看
                    </el-button>
                    <el-button
                      type="primary"
                      link
                      @click="openForm('update', row.id)"
                      v-hasPermi="['rq:iot-device-template:update']"
                    >
                      <Icon icon="ep:edit" class="mr-3px" />修改
                    </el-button>
                    <el-dropdown
                      @command="(command) => handleCommand(command, row)"
                      v-hasPermi="['rq:iot-device-template:delete']"
                    >
                      <el-button type="primary" link>
                        <Icon icon="ep:more-filled" class="mr-3px" />更多
                      </el-button>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item
                            command="handleDelete"
                            v-if="checkPermi(['rq:iot-device-template:delete'])"
                          >
                            <Icon icon="ep:delete" class="mr-5px" />删除
                          </el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </template>
              </ZmTableColumn>
            </ZmTable>
          </template>
        </el-auto-resizer>
      </div>

      <div class="h-8 mt-2 flex items-center justify-end">
        <el-pagination
          v-show="total > 0"
          size="default"
          :current-page="queryParams.pageNo"
          :page-size="queryParams.pageSize"
          :background="true"
          :page-sizes="[10, 20, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <TemplateForm ref="formRef" :category_id="selectedId" @success="getList" />
</template>

<style scoped>
:deep(.el-form-item) {
  margin-bottom: 0;
}
</style>
