<template>
  <Dialog
    v-model="dialogVisible"
    :title="t('route.selectInspectionItems')"
    width="min(1200px, 92vw)"
    class="inspect-item-select-dialog"
    @close="handleClose">
    <template #title>
      <div class="dialog-title mb-4">
        <div class="dialog-title__icon"><Icon icon="ep:finished" /></div>
        <div>
          <div class="dialog-title__text">{{ t('route.selectInspectionItems') }}</div>
          <div class="dialog-title__subtitle">筛选并选择需要加入路线的巡检项目</div>
        </div>
      </div>
    </template>

    <div class="dialog-content">
      <el-form
        ref="queryFormRef"
        :model="queryParams"
        size="default"
        label-width="88px"
        class="query-panel">
        <div class="query-row">
          <el-form-item :label="t('inspect.InspectionItems')" prop="item">
            <el-input
              v-model="queryParams.item"
              :placeholder="t('inspect.itemHolder')"
              clearable
              class="query-control"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item :label="t('common.createTime')" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              :start-placeholder="t('info.start')"
              :end-placeholder="t('info.end')"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="query-control query-control--date" />
          </el-form-item>
        </div>
        <el-form-item class="query-actions">
          <el-button type="primary" @click="handleQuery">
            <Icon icon="ep:search" class="mr-5px" />{{ t('operationFill.search') }}
          </el-button>
          <el-button @click="resetQuery">
            <Icon icon="ep:refresh" class="mr-5px" />{{ t('operationFill.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.item }}
          </el-tag>
        </div>
      </div>

      <section class="table-section">
        <ZmTable
          :loading="loading"
          :data="list"
          :max-height="360"
          show-border
          settings-cache-key="pms-inspect-route-item-select"
          @row-click="handleRowClick">
          <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="toggleRow(row)" />
            </template>
          </ZmTableColumn>
          <ZmTableColumn :label="t('inspect.InspectionItems')" prop="item" />
          <ZmTableColumn :label="t('inspect.InspectionStandards')" prop="standard" />
          <ZmTableColumn :label="t('iotDevice.brand')" prop="brandName" />
          <ZmTableColumn :label="t('fileInfo.appendix')" prop="urls">
            <template #default="scope">
              <el-button
                v-if="scope.row.urls"
                link
                type="primary"
                @click.stop="openWeb(scope.row.urls)">
                <Icon size="18" icon="ep:view" />
              </el-button>
              <span v-else>-</span>
            </template>
          </ZmTableColumn>
          <ZmTableColumn :label="t('common.sort')" prop="sort" />
          <ZmTableColumn
            :label="t('common.createTime')"
            prop="createTime"
            :formatter="dateFormatter" />
        </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('workOrderMaterial.confirm') }}
          </el-button>
        </div>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { useCache } from '@/hooks/web/useCache'
import { IotInspectItemApi, IotInspectItemVO } from '@/api/pms/inspect/item'
import { useTableComponents } from '@/components/ZmTable/useTableComponents'
const { ZmTable, ZmTableColumn } = useTableComponents<IotInspectItemVO>()
const { t } = useI18n() // 国际化
const emit = defineEmits(['choose']) // 定义 success 事件，用于操作成功后的回调
const dialogVisible = ref(false) // 弹窗的是否展示
const loading = ref(true) // 列表的加载中
const queryFormRef = ref() // 搜索的表单
const list = ref<IotInspectItemVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 20,
  item: undefined,
  deptId: undefined,
  deviceClassify: undefined,
  brandName: undefined,
  deviceId: undefined,
  createTime: undefined
})
const openWeb = (url) => {
  window.open(
    'http://1.94.244.160:8012/onlinePreview?url=' + encodeURIComponent(Base64.encode(url))
  )
}
const removeTag = (route) => {
  const index = selectedRows.value.findIndex(
    (item) => item.id === route.id && item.deviceCode === route.deviceCode
  )
  if (index !== -1) {
    selectedRows.value.splice(index, 1)
  }
}
const selectedRows = ref<IotInspectItemVO[]>([]) // 多选数据（存储所有选中行的数组）

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

// 多选 切换行选中状态
const toggleRow = (row: IotInspectItemVO) => {
  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 handleRowClick = (row) => {
  toggleRow(row)
}
const open = async (classify, id, brandName) => {
  dialogVisible.value = true
  selectedRows.value = []
  queryParams.createTime = undefined
  queryParams.item = undefined
  queryParams.pageNo = 1
  queryParams.deviceId = undefined
  // if (id) {
  //   queryParams.deviceId = id
  //   await getList()
  //   if (list.value.length === 0) {
  //     queryParams.deviceId = undefined
  //     queryParams.deviceClassify = classify
  //     await getList()
  //   }
  // } else {
  //   queryParams.deviceClassify = classify
  //   await getList()
  // }
  queryParams.deviceId = id
  queryParams.deviceClassify = classify
  queryParams.brandName = brandName
  await getList()
}
defineExpose({ open })
const { wsCache } = useCache()
const getList = async () => {
  loading.value = true
  try {
    const data = await IotInspectItemApi.getIotInspectRouteItemPage(queryParams)
    list.value = data.list
    list.value = list.value.sort((a, b) => {
      return a.sort - b.sort
    })
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

  // emit('choose', selectedRows.value);
  emit(
    'choose',
    selectedRows.value.map((row) => ({
      ...row,
      // 确保返回必要字段
      code: row.item,
      name: row.standard
    }))
  )
  dialogVisible.value = false
}

// 关闭时清空选择
const handleClose = () => {
  selectedRows.value = []
  emit('close')
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}
</script>
<style lang="scss" scoped>
.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: flex;
  flex: 1 1 auto;
  flex-wrap: wrap;
  align-items: center;
  min-width: 0;
  gap: 12px 20px;
}

.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: 190px;
}

.query-control--date {
  width: 240px;
}

.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 {
  flex: 0 0 auto;
  font-weight: 600;
  color: var(--el-color-primary);
  white-space: nowrap;
}

.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);
}

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

  .query-panel,
  .query-row,
  .query-row :deep(.el-form-item),
  .query-actions,
  .query-control,
  .query-control--date {
    width: 100%;
  }

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

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

  .selected-panel {
    flex-direction: column;
    gap: 8px;
  }
}
</style>
