<template>
  <el-drawer
    :append-to-body="true"
    :model-value="modelValue"
    :show-close="false"
    direction="rtl"
    :size="computedSize"
    class="person-log-drawer"
    :before-close="handleClose"
    @update:model-value="$emit('update:modelValue', $event)">
    <template #header>
      <div class="drawer-header">
        <div class="drawer-header__main">
          <div class="drawer-header__icon">
            <Icon icon="ep:user" :size="22" />
          </div>
          <div>
            <div class="drawer-title">{{ t('configDevice.adjustmentRecords') }}</div>
            <div class="drawer-subtitle">查看设备责任人调整前后的变化记录</div>
          </div>
        </div>
        <el-button circle size="default" @click="handleClose">
          <Icon icon="ep:close" />
        </el-button>
      </div>
    </template>

    <template v-if="deviceId">
      <div v-loading="loading" class="drawer-body">
        <section class="info-card record-card">
          <div class="info-card__header">
            <div class="info-card__title">
              <span class="info-card__marker"></span>
              <span>{{ t('configDevice.adjustmentRecords') }}</span>
            </div>
            <span class="record-total">共 {{ total }} 条</span>
          </div>

          <div class="info-card__body record-card__body">
            <ZmTable
              :data="devicePersons"
              :loading="loading"
              :show-border="true"
              settings-cache-key="pms-device-person-log"
              class="record-table">
              <ZmTableColumn
                prop="deviceName"
                :label="t('deviceStatus.deviceName')"
                min-width="170" />
              <ZmTableColumn
                prop="deviceCode"
                :label="t('deviceStatus.deviceCode')"
                min-width="150" />
              <ZmTableColumn
                prop="oldPersonNames"
                :label="t('deviceStatus.beforePerson')"
                min-width="170" />
              <ZmTableColumn
                prop="newPersonNames"
                :label="t('deviceStatus.afterPerson')"
                min-width="170" />
              <ZmTableColumn
                prop="reason"
                :label="t('configDevice.reasonForAdjustment')"
                min-width="220"
                align="left" />
              <ZmTableColumn
                prop="creatorName"
                :label="t('deviceStatus.adjuster')"
                min-width="130" />
              <ZmTableColumn
                :label="t('deviceStatus.adjustTime')"
                prop="createTime"
                min-width="170"
                :formatter="dateFormatter" />
            </ZmTable>

            <Pagination
              v-show="total > 0"
              :total="total"
              v-model:page="queryParams.pageNo"
              v-model:limit="queryParams.pageSize"
              @pagination="handlePagination" />
          </div>
        </section>
      </div>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
import { dateFormatter } from '@/utils/formatTime'
import { IotDevicePersonLogApi, type IotDevicePersonLogVO } from '@/api/pms/iotdevicepersonlog'

type DevicePersonLogRow = IotDevicePersonLogVO & {
  deviceName?: string
  deviceCode?: string
  oldPersonNames?: string
  newPersonNames?: string
  creatorName?: string
  createTime?: string
}

const { t } = useI18n()
const { ZmTable, ZmTableColumn } = useTableComponents<DevicePersonLogRow>()
const emit = defineEmits(['update:modelValue', 'add', 'delete'])

defineOptions({
  name: 'DevicePersonLogDrawer'
})

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  createTime: [],
  deviceId: undefined as number | undefined,
  name: '',
  code: ''
})

const windowWidth = ref(window.innerWidth)
const computedSize = computed(() => {
  if (windowWidth.value <= 768) return '100%'
  return windowWidth.value > 1200 ? '60%' : '80%'
})

const loading = ref(false)
const total = ref(0)
const devicePersons = ref<DevicePersonLogRow[]>([])

const props = defineProps({
  modelValue: Boolean,
  deviceId: Number
})

const updateWindowWidth = () => {
  windowWidth.value = window.innerWidth
}

const loadDevicePersons = async (deviceId: number, resetPage = true) => {
  queryParams.deviceId = deviceId
  if (resetPage) {
    queryParams.pageNo = 1
  }
  try {
    loading.value = true
    const data = await IotDevicePersonLogApi.getIotDevicePersonLogPage(queryParams)
    devicePersons.value = data.list || []
    total.value = data.total || 0
  } catch (error) {
    ElMessage.error('数据加载失败')
  } finally {
    loading.value = false
  }
}

const handlePagination = (pagination: any) => {
  queryParams.pageNo = pagination.page
  queryParams.pageSize = pagination.limit
  if (props.deviceId) {
    loadDevicePersons(props.deviceId, false)
  }
}

const openDrawer = () => {
  emit('update:modelValue', true)
}

const closeDrawer = () => {
  handleClose()
}

const handleClose = () => {
  emit('update:modelValue', false)
  devicePersons.value = []
  total.value = 0
}

defineExpose({ openDrawer, closeDrawer, loadDevicePersons })

onMounted(() => {
  window.addEventListener('resize', updateWindowWidth)
})

onUnmounted(() => {
  window.removeEventListener('resize', updateWindowWidth)
})
</script>

<style lang="scss" scoped>
.drawer-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16px;
  width: 100%;
  padding-right: 4px;
}

.drawer-header__main {
  display: flex;
  align-items: center;
  min-width: 0;
}

.drawer-header__icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 42px;
  height: 42px;
  margin-right: 12px;
  color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-7);
  border-radius: 6px;
}

.drawer-title {
  font-size: 18px;
  font-weight: 600;
  line-height: 24px;
  color: var(--el-text-color-primary);
}

.drawer-subtitle {
  margin-top: 4px;
  font-size: 13px;
  color: var(--el-text-color-secondary);
}

.drawer-body {
  display: flex;
  flex-direction: column;
  gap: 16px;
  min-height: 100%;
}

.info-card {
  overflow: hidden;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 6px;
}

.info-card__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 56px;
  padding: 0 20px;
  background: #f4f9ff;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.info-card__title {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.info-card__marker {
  width: 4px;
  height: 18px;
  margin-right: 10px;
  background: var(--el-color-primary);
  border-radius: 4px;
}

.info-card__body {
  padding: 20px;
}

.record-card {
  flex: 1;
  min-height: 0;
}

.record-total {
  font-size: 13px;
  color: var(--el-text-color-secondary);
}

.record-card__body {
  display: flex;
  flex-direction: column;
  min-height: 420px;
}

.record-table {
  flex: 1;
  width: 100%;
}

:global(.person-log-drawer .el-drawer__body) {
  padding: 0 24px 24px;
}

:global(.person-log-drawer .el-drawer__header) {
  padding: 24px;
  margin-bottom: 0;
}

@media (width <= 768px) {
  :global(.person-log-drawer .el-drawer__body) {
    padding: 0 16px 16px;
  }
}
</style>
