<script setup lang="ts">
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
import { IotDeviceApi, IotDeviceVO } from '@/api/pms/device'
import { useUserStore } from '@/store/modules/user'
import download from '@/utils/download'
import { rangeShortcuts } from '@/utils/formatTime'
import DevicePersonLogDrawer from '@/views/pms/device/personlog/DevicePersonLogDrawer.vue'

defineOptions({ name: 'IotDevicePerson' })

type DevicePersonRow = IotDeviceVO & {
  responsibleNames?: string
}

interface QueryParams extends PageParam {
  deptId?: number
  deviceCode?: string
  deviceName?: string
  setFlag?: string
  nickname?: string
  createTime?: string[]
}

const { t } = useI18n()
const { push } = useRouter()
const { ZmTable, ZmTableColumn } = useTableComponents<DevicePersonRow>()

const rootDeptId = 156
const deptId = useUserStore().getUser.deptId || rootDeptId

const initQuery: QueryParams = {
  pageNo: 1,
  pageSize: 10,
  deptId: undefined,
  deviceCode: undefined,
  deviceName: undefined,
  setFlag: '',
  nickname: '',
  createTime: []
}

const queryParams = reactive<QueryParams>({ ...initQuery })
const queryFormRef = ref()
const loading = ref(false)
const exportLoading = ref(false)
const list = ref<DevicePersonRow[]>([])
const total = ref(0)

const resultOptions = computed(() => [
  {
    label: '全部',
    value: 'A'
  },
  {
    label: '是',
    value: 'Y'
  },
  {
    label: '否',
    value: 'N'
  }
])

const getList = async () => {
  loading.value = true
  try {
    const data = await IotDeviceApi.responsiblePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

const resetQuery = () => {
  Object.assign(queryParams, { ...initQuery })
  queryFormRef.value?.resetFields()
  handleQuery()
}

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

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

const handleDeptNodeClick = async (row: Tree) => {
  queryParams.deptId = row.id
  queryParams.pageNo = 1
  await getList()
}

const openForm = () => {
  push({
    name: 'ConfigDevicePerson',
    query: {
      deptId: queryParams.deptId
    }
  })
}

const handleDetail = (id: number) => {
  push({ name: 'DeviceDetailInfo', params: { id } })
}

const currentDeviceId = ref<number>()
const drawerVisible = ref(false)
const showDrawer = ref()

const handleView = async (deviceId: number) => {
  currentDeviceId.value = deviceId
  drawerVisible.value = true
  nextTick(() => {
    showDrawer.value?.loadDevicePersons(deviceId)
  })
}

const handleExport = async () => {
  exportLoading.value = true
  try {
    const data = await IotDeviceApi.exportIotDevicePerson(queryParams)
    download.excel(data, '设备责任人.xls')
  } finally {
    exportLoading.value = false
  }
}

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))]"
  >
    <DeptTreeSelect
      :top-id="rootDeptId"
      :deptId="deptId"
      v-model="queryParams.deptId"
      :init-select="false"
      :show-title="false"
      request-api="getSimpleDeptList"
      @node-click="handleDeptNodeClick"
      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="t('devicePerson.deviceCode')" prop="deviceCode">
          <el-input
            v-model="queryParams.deviceCode"
            :placeholder="t('devicePerson.codeHolder')"
            clearable
            class="!w-180px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item :label="t('devicePerson.deviceName')" prop="deviceName">
          <el-input
            v-model="queryParams.deviceName"
            :placeholder="t('devicePerson.nameHolder')"
            clearable
            class="!w-180px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item
          :label="t('devicePerson.responsiblePerson')"
          prop="setFlag"
          label-width="120px"
        >
          <el-select
            v-model="queryParams.setFlag"
            :placeholder="t('devicePerson.choose')"
            clearable
            class="!w-140px"
          >
            <el-option
              v-for="dict in resultOptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="t('devicePerson.rp')" prop="nickname">
          <el-input
            v-model="queryParams.nickname"
            :placeholder="t('devicePerson.nicknameHolder')"
            clearable
            class="!w-180px"
            @keyup.enter="handleQuery"
          />
        </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="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="rangeShortcuts"
            :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
            class="!w-220px"
          />
        </el-form-item>
      </div>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />{{ t('devicePerson.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />{{ t('devicePerson.reset') }}
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm"
          v-hasPermi="['pms:iot-device-person-log:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" />{{ t('devicePerson.setUp') }}
        </el-button>
        <el-button type="success" plain :loading="exportLoading" @click="handleExport">
          <Icon icon="ep:download" 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="t('monitor.serial')"
                :width="70"
                fixed="left"
                hide-in-column-settings
              />
              <ZmTableColumn prop="deviceCode" :label="t('monitor.deviceCode')" fixed="left" />
              <ZmTableColumn prop="deviceName" :label="t('monitor.deviceName')" fixed="left">
                <template #default="{ row }">
                  <el-link :underline="false" type="primary" @click="handleDetail(row.id)">
                    {{ row.deviceName }}
                  </el-link>
                </template>
              </ZmTableColumn>
              <ZmTableColumn prop="deptName" :label="t('devicePerson.dept')" />
              <ZmTableColumn prop="responsibleNames" :label="t('devicePerson.rp')" />
              <ZmTableColumn :label="t('devicePerson.operation')" width="150" fixed="right" action>
                <template #default="{ row }">
                  <el-button
                    link
                    type="primary"
                    @click="handleView(row.id)"
                    v-hasPermi="['rq:iot-device:query']"
                  >
                    {{ t('devicePerson.adjustmentRecords') }}
                  </el-button>
                </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>

  <DevicePersonLogDrawer
    ref="showDrawer"
    :model-value="drawerVisible"
    :device-id="currentDeviceId"
    @update:model-value="(val) => (drawerVisible = val)"
  />
</template>

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