<template>
  <Dialog
    v-model="dialogVisible"
    :title="t('route.SelectInspectionDevice')"
    width="min(1280px, 94vw)"
    class="inspect-route-select-dialog"
    @close="handleClose">
    <template #title>
      <div class="dialog-title mb-4">
        <div class="dialog-title__icon"><Icon icon="ep:guide" /></div>
        <div>
          <div class="dialog-title__text">{{ t('route.SelectInspectionDevice') }}</div>
          <div class="dialog-title__subtitle">筛选并选择需要加入计划的巡检设备路线</div>
        </div>
      </div>
    </template>

    <div class="dialog-content">
      <el-form
        ref="queryFormRef"
        :model="queryParams"
        size="default"
        label-width="84px"
        class="query-panel">
        <div class="query-row">
          <el-form-item :label="t('monitor.deviceName')" prop="deviceName">
            <el-input
              v-model="queryParams.deviceName"
              :placeholder="t('iotDevice.nameHolder')"
              clearable
              class="query-control"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item :label="t('iotDevice.code')" prop="deviceCode">
            <el-input
              v-model="queryParams.deviceCode"
              :placeholder="t('iotDevice.codeHolder')"
              clearable
              class="query-control"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item :label="t('route.RouteName')" prop="routeName">
            <el-input
              v-model="queryParams.routeName"
              :placeholder="t('route.nHolder')"
              clearable
              class="query-control"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item :label="t('iotDevice.dept')" prop="deptId">
            <el-tree-select
              v-model="queryParams.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              filterable
              clearable
              placeholder="请选择部门"
              class="query-control" />
          </el-form-item>
        </div>
        <el-form-item class="query-actions">
          <el-button type="primary" @click="handleQuery">
            <Icon icon="ep:search" class="mr-5px" />{{ t('chooseMaintain.search') }}
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px" />{{ t('chooseMaintain.reset') }}
          </el-button>
        </el-form-item>
      </el-form>

      <div v-if="selectedRows.length > 0" class="selected-panel">
        <div class="selected-panel__label">已选 {{ selectedRows.length }} 条路线</div>
        <div class="selected-panel__tags">
          <el-tag
            v-for="item in selectedRows"
            :key="`${item.id}-${item.deviceCode || ''}`"
            closable
            @close="removeTag(item)">
            {{ item.deviceCode }} - {{ item.routeName }}
          </el-tag>
        </div>
      </div>

      <section class="table-section">
        <ZmTable
          :loading="loading"
          :data="list"
          :max-height="380"
          show-border
          settings-cache-key="pms-inspect-plan-route-select"
          @row-click="selectRow">
          <ZmTableColumn :label="t('workOrderMaterial.select')" :width="64" hide-in-column-settings>
            <template #default="{ row }">
              <el-checkbox
                :model-value="isSelected(row)"
                class="no-label-checkbox"
                @click.stop="selectRow(row)" />
            </template>
          </ZmTableColumn>
          <ZmTableColumn :label="t('iotDevice.code')" prop="deviceCode" />
          <ZmTableColumn :label="t('iotDevice.name')" prop="deviceName" />
          <ZmTableColumn :label="t('route.RouteName')" prop="routeName" />
          <ZmTableColumn :label="t('iotDevice.dept')" prop="deptName" />
          <ZmTableColumn
            :label="t('common.createTime')"
            prop="createTime"
            :formatter="dateFormatter" />
          <ZmTableColumn :label="t('operationFill.operation')" hide-in-column-settings>
            <template #default="scope">
              <el-button link type="primary" @click.stop="viewRoute(scope.row.itemJson)">
                <Icon icon="ep:view" class="mr-5px" />{{ t('operationFill.view') }}
              </el-button>
            </template>
          </ZmTableColumn>
        </ZmTable>
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList" />
      </section>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <span class="selection-summary">已选择 {{ selectedRows.length }} 条路线</span>
        <div>
          <el-button size="default" @click="dialogVisible = false">取消</el-button>
          <el-button size="default" type="primary" @click="handleConfirm">
            <Icon icon="ep:check" class="mr-5px" />{{ t('chooseMaintain.confirm') }}
          </el-button>
        </div>
      </div>
    </template>

    <RouteInspectItemDrawer
      ref="showDrawer"
      :model-value="drawerVisible"
      @update:model-value="(val) => (drawerVisible = val)" />
  </Dialog>
</template>

<script setup lang="ts">
import { IotDeviceVO } from '@/api/pms/device'
import { dateFormatter } from '@/utils/formatTime'
import { IotInspectRouteApi } from '@/api/pms/inspect/route'
import RouteInspectItemDrawer from '@/views/pms/inspect/plan/RouteInspectItemDrawer.vue'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'

type InspectRouteDeviceRow = IotDeviceVO & {
  routeName: string
  itemJson: string
  createTime: string
  deviceId: number
  item?: string
  standard?: string
}

const { ZmTable, ZmTableColumn } = useTableComponents<InspectRouteDeviceRow>()
const { t } = useI18n() // 国际化
const emit = defineEmits(['choose']) // 定义 success 事件，用于操作成功后的回调
const dialogVisible = ref(false) // 弹窗的是否展示
const loading = ref(true) // 列表的加载中
const queryFormRef = ref() // 搜索的表单
const list = ref<InspectRouteDeviceRow[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const deptList = ref<Tree[]>([]) // 树形结构
const drawerVisible = ref<boolean>(false)
const showDrawer = ref()
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  label: '',
  status: undefined,
  deptId: undefined,
  assetClass: undefined,
  deviceName: undefined,
  deviceCode: undefined,
  routeName: undefined
})

const selectedRows = ref<InspectRouteDeviceRow[]>([])

const isSelected = (row: InspectRouteDeviceRow) =>
  selectedRows.value.some((item) => item.id === row.id && item.deviceCode === row.deviceCode)

const selectRow = (row: InspectRouteDeviceRow) => {
  const index = selectedRows.value.findIndex(
    (item) => item.id === row.id && item.deviceCode === row.deviceCode
  )
  if (index > -1) {
    selectedRows.value.splice(index, 1)
  } else {
    selectedRows.value.push({ ...row })
  }
}

const removeTag = (route: InspectRouteDeviceRow) => {
  const index = selectedRows.value.findIndex(
    (item) => item.id === route.id && item.deviceCode === route.deviceCode
  )
  if (index !== -1) {
    selectedRows.value.splice(index, 1)
  }
}

const handleConfirm = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个')
    return
  }

  emit(
    'choose',
    selectedRows.value.map((row) => ({
      ...row,
      code: row.item,
      name: row.standard
    }))
  )
  dialogVisible.value = false
}

const handleClose = () => {
  selectedRows.value = []
  emit('close')
}

const viewRoute = (itemJson) => {
  drawerVisible.value = true
  showDrawer.value.openDrawer(JSON.parse(itemJson))
}

const open = async (classify) => {
  dialogVisible.value = true
  queryParams.assetClass = classify
  queryParams.deviceName = undefined
  queryParams.deviceCode = undefined
  await getList()
  selectedRows.value = []
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
}
defineExpose({ open })

const getList = async () => {
  loading.value = true
  list.value = []
  try {
    const data = await IotInspectRouteApi.getDeviceIotInspectRoutePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}
</script>
<style lang="scss" scoped>
@media (width <= 1400px) {
  .inspect-route-select-dialog .query-row {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (width <= 768px) {
  .inspect-route-select-dialog .dialog-title__subtitle {
    display: none;
  }

  .inspect-route-select-dialog .query-panel,
  .inspect-route-select-dialog .query-row,
  .inspect-route-select-dialog .query-actions,
  .inspect-route-select-dialog .query-control {
    width: 100%;
  }

  .inspect-route-select-dialog .query-row {
    grid-template-columns: minmax(0, 1fr);
  }

  .inspect-route-select-dialog .query-actions :deep(.el-form-item__content) {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    width: 100%;
  }

  .inspect-route-select-dialog .query-actions :deep(.el-button) {
    width: 100%;
  }

  .inspect-route-select-dialog .selected-panel {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}

.dialog-title {
  display: flex;
  align-items: center;
  min-width: 0;
}

.dialog-title__icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 38px;
  height: 38px;
  margin-right: 12px;
  font-size: 18px;
  color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-7);
  border-radius: 8px;
}

.dialog-title__text {
  font-size: 17px;
  font-weight: 600;
  line-height: 24px;
  color: var(--el-text-color-primary);
}

.dialog-title__subtitle {
  margin-top: 1px;
  font-size: 12px;
  line-height: 18px;
  color: var(--el-text-color-secondary);
}

.dialog-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding-top: 8px;
}

.query-panel {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: var(--el-fill-color-extra-light);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  gap: 12px 20px;
}

.query-row {
  display: grid;
  grid-template-columns: repeat(4, minmax(0, 1fr));
  min-width: 0;
  flex: 1 1 880px;
  gap: 12px 16px;
}

.query-actions {
  flex: 0 0 auto;
}

.query-actions :deep(.el-form-item__content) {
  display: flex;
  gap: 8px;
}

.query-actions :deep(.el-button) {
  margin-left: 0;
}

.query-control {
  width: 100%;
}

.query-panel :deep(.el-form-item) {
  margin-bottom: 0;
}

.query-panel :deep(.el-form-item__label) {
  white-space: nowrap;
}

.selected-panel {
  display: flex;
  align-items: center;
  padding: 10px 14px;
  background: var(--el-color-primary-light-9);
  border: 1px solid var(--el-color-primary-light-8);
  border-radius: 8px;
  gap: 12px;
}

.selected-panel__label {
  font-weight: 600;
  color: var(--el-color-primary);
  white-space: nowrap;
  flex: 0 0 auto;
}

.selected-panel__tags {
  display: flex;
  flex-wrap: wrap;
  min-width: 0;
  gap: 6px;
  transform: translateY(1.5px);
}

.table-section {
  padding: 12px 12px 0;
  overflow: hidden;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
}

.table-section :deep(.pagination-container) {
  padding: 12px 8px;
}

.no-label-checkbox :deep(.el-checkbox__label) {
  display: none;
}

.dialog-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.selection-summary {
  font-size: 13px;
  color: var(--el-text-color-secondary);
}
</style>
