<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px" label-width="68px">
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="queryParams.categoryName" class="!w-240px" clearable placeholder="请输入分类名称"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button @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="openCreate" v-hasPermi="['iot:check-template:create']">
          <Icon icon="ep:plus" class="mr-5px" />
          新增模板
        </el-button>
        <el-button type="success" plain @click="exportAll" v-hasPermi="['iot:check-template:export']">
          <Icon icon="ep:download" class="mr-5px" />
          导出
        </el-button>
        <el-button type="warning" plain @click="importAll" v-hasPermi="['iot:check-template:import']">
          <Icon icon="ep:upload" class="mr-5px" />
          导入
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="分类名称" align="center" prop="categoryName" />
      <el-table-column label="项目数量" align="center" width="120">
        <template #default="{ row }">{{ row.items?.length || 0 }}</template>
      </el-table-column>
      <el-table-column label="最后更新" align="center" width="180">
        <template #default="{ row }">{{ formatDate(row.updateTime) }}</template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="200px">
        <template #default="{ row }">
          <el-button link type="primary" @click="editRow(row)" v-hasPermi="['iot:check-template:update']">
            编辑
          </el-button>
          <el-button link type="success" @click="previewRow(row)" v-hasPermi="['iot:check-template:query']">
            预览
          </el-button>
          <el-button link type="danger" @click="removeRow(row)" v-hasPermi="['iot:check-template:delete']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <el-dialog v-model="editVisible" :title="editMode === 'create' ? '新增模板' : '编辑模板'" width="520px"
    :close-on-click-modal="false">
    <el-form :model="form" label-width="120px">
      <el-form-item label="分类名称">
        <el-select v-model="form.categoryName" filterable placeholder="请选择分类名称" style="width: 100%">
          <el-option v-for="c in categoryList" :key="c.id" :label="c.name" :value="c.name" />
        </el-select>
      </el-form-item>
      <el-form-item label="检查项目">
        <!-- <div class="text-gray-500 mb-8px">点击下方按钮配置检查项目</div> -->
        <el-button type="primary" plain @click="openItemsEditor">配置检查项目</el-button>
        <div v-if="form.items.length > 0" class="mt-8px">
          <!-- <div class="text-12px text-gray-500 mb-4px">当前配置：</div>
          <div v-for="(it, i) in form.items" :key="i" class="text-12px">{{ i + 1 }}. {{ it.name }}{{ it.desc ? `
            (${it.desc})` : '' }}</div> -->
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="editVisible = false">取消</el-button>
        <el-button type="primary" @click="saveRow">保存</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 检查项目配置弹窗 -->
  <Execute v-model="itemsEditorVisible" :categoryName="form.categoryName" :items="form.items"
    :title="editMode === 'create' ? '新增检查项目' : '编辑检查项目'" @save="onItemsSave" />

  <el-dialog v-model="previewVisible" title="模板预览" width="820px">
    <div v-if="previewItems.length === 0" class="text-gray">暂无项目</div>
    <div v-else>
      <div class="preview-header mb-16px">
        <div class="text-14px text-gray-500">预览效果：展示实际点检时的交互体验</div>
      </div>
      <el-card shadow="never">
        <template #header>
          <div class="card-header flex items-center justify-between">
            <span>本次点检项目</span>
          </div>
        </template>

        <div v-for="(item, idx) in previewItems" :key="idx" class="item-row">
          <div class="item-left">
            <div class="item-name flex items-center">
              <span class="mr-8px">{{ idx + 1 }}.</span>
              <span style="font-weight: 600; color: #1f2937;">{{ item.name }}</span>
              <el-text v-if="item.desc" type="info" class="ml-16px text-12px"
                style="color: #6b7280; background-color: #f9fafb; padding: 4px 8px; border-radius: 4px; margin-left: 16px;">{{
                  item.desc }}</el-text>
            </div>
          </div>
          <div class="item-right">
            <el-radio-group v-model="previewResults[idx]" @change="onPreviewResultChange(idx)">
              <el-radio label="ok">正常</el-radio>
              <el-radio label="bad">异常</el-radio>
            </el-radio-group>
          </div>
          <div v-if="previewResults[idx] === 'bad'" class="issue-area">
            <el-input v-model="previewIssueDescs[idx]" type="textarea" :rows="2" placeholder="请描述异常" />
            <el-upload class="mt-8px" action="" list-type="picture-card" :file-list="previewPhotos[idx]" :limit="10"
              multiple accept="image/*" disabled>
              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </div>
        </div>
      </el-card>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ProductCategoryApi, ProductCategoryVO } from '@/api/iot/product/category'
import Execute from './Execute.vue'
import { Plus } from '@element-plus/icons-vue'

/** 点检模板管理 */
defineOptions({ name: 'IoTCheckTemplateManage' })

// const message = useMessage() // 消息弹窗
// const { t } = useI18n() // 国际化

interface Row {
  id: number
  categoryName: string
  items: Array<{ name: string; desc?: string }>
  updateTime?: string
}

const loading = ref(true) // 列表的加载中
const list = ref<Row[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  categoryName: undefined as string | undefined
})
const queryFormRef = ref() // 搜索的表单

const editVisible = ref(false)
const previewVisible = ref(false)
const itemsEditorVisible = ref(false)
const editMode = ref<'create' | 'edit'>('create')
const form = reactive<{ id?: number; categoryName: string; items: Array<{ name: string; desc?: string }> }>({ categoryName: '', items: [] })
const previewItems = ref<Array<{ name: string; desc?: string }>>([])
const previewResults = ref<string[]>([])
const previewIssueDescs = ref<string[]>([])
const previewPhotos = ref<any[][]>([])
const categoryList = ref<ProductCategoryVO[]>([])

onMounted(async () => {
  await getList()
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 从数据库获取产品分类列表
    const data = await ProductCategoryApi.getProductCategoryPage({
      pageNo: 1,
      pageSize: 100,
      hasTemplate: true
    })

    // 下拉选项应为全部分类，不仅限有模板
    try {
      const allCats = await ProductCategoryApi.getSimpleProductCategoryList()
      categoryList.value = (allCats as any)?.list || (allCats as any) || []
    } catch (e) {
      categoryList.value = []
    }

    let allRows = (data.list || [])
      .map((category: any) => {
        let items: Array<{ name: string; desc?: string }> = []
        try {
          // 使用相同的字段名逻辑
          const templateField = category.inspectTemplate || category.inspectionTemplate || category.template
          items = JSON.parse(templateField || '[]')
        } catch (e) {
          console.error('解析模板失败:', e)
        }
        return {
          id: category.id,
          categoryName: category.name,
          items,
          updateTime: category.updateTime || category.createTime
        }
      })
      .sort((a, b) => a.categoryName.localeCompare(b.categoryName))

    // 搜索过滤
    if (queryParams.categoryName) {
      const searchTerm = (queryParams.categoryName as string).toLowerCase()
      allRows = allRows.filter(row =>
        row.categoryName.toLowerCase().includes(searchTerm)
      )
    }

    // 分页
    total.value = allRows.length
    const start = (queryParams.pageNo - 1) * queryParams.pageSize
    const end = start + queryParams.pageSize
    list.value = allRows.slice(start, end)
  } catch (e: any) {
    console.error('获取模板列表失败:', e)
    ElMessage.error('获取模板列表失败：' + (e?.message || '未知错误'))
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

function openCreate() {
  editMode.value = 'create'
  Object.assign(form, { id: undefined, categoryName: '', items: [] })
  editVisible.value = true
}

function editRow(row: Row) {
  editMode.value = 'edit'
  Object.assign(form, { id: row.id, categoryName: row.categoryName, items: JSON.parse(JSON.stringify(row.items)) })
  editVisible.value = true
}

async function saveRow() {
  try {
    if (!form.categoryName) return ElMessage.warning('分类名称必选')
    const arr = (form.items || []).map(it => ({ name: (it.name || '').trim(), desc: (it.desc || '').trim() }))
    if (!arr.length) return ElMessage.warning('请至少新增一个检查项')

    // 找到对应的分类ID
    const category = categoryList.value.find(c => c.name === form.categoryName)
    if (!category) {
      ElMessage.error('未找到对应的产品分类')
      return
    }

    // 保存到数据库
    await ProductCategoryApi.updateTemplate(category.id, JSON.stringify(arr))
    ElMessage.success('已保存')
    editVisible.value = false
    getList()
  } catch (e: any) {
    ElMessage.error('保存失败：' + (e?.message || ''))
  }
}

function removeRow(row: Row) {
  ElMessageBox.confirm('确认删除该分类的模板吗？', '提示').then(async () => {
    try {
      // 清空数据库中的模板
      await ProductCategoryApi.updateTemplate(row.id, '')
      ElMessage.success('已删除')
      getList()
    } catch (e: any) {
      ElMessage.error('删除失败：' + (e?.message || ''))
    }
  }).catch(() => { })
}

function previewRow(row: Row) {
  previewItems.value = row.items || []
  // 初始化预览数据
  previewResults.value = new Array(previewItems.value.length).fill('ok')
  previewIssueDescs.value = new Array(previewItems.value.length).fill('')
  previewPhotos.value = new Array(previewItems.value.length).fill([])
  previewVisible.value = true
}

function onPreviewResultChange(idx: number) {
  if (previewResults.value[idx] !== 'bad') {
    previewIssueDescs.value[idx] = ''
    previewPhotos.value[idx] = []
  }
}

function openItemsEditor() {
  itemsEditorVisible.value = true
}

function onItemsSave(items: Array<{ name: string; desc?: string }>) {
  form.items = items
}

// 格式化日期
function formatDate(timestamp: string | number | undefined): string {
  if (!timestamp) return '-'

  try {
    // 如果是字符串，先转换为数字
    const time = typeof timestamp === 'string' ? parseInt(timestamp) : timestamp

    // 检查是否是有效的时间戳
    if (isNaN(time) || time <= 0) return '-'

    // 创建日期对象
    const date = new Date(time)

    // 检查日期是否有效
    if (isNaN(date.getTime())) return '-'

    // 格式化为 YYYY-MM-DD HH:mm:ss
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (e) {
    console.error('日期格式化失败:', e)
    return '-'
  }
}


async function exportAll() {
  try {
    // 从数据库获取所有模板
    const data = await ProductCategoryApi.getProductCategoryPage({
      pageNo: 1,
      pageSize: 100
    })

    const templates: any = {}
    data.list?.forEach((category: any) => {
      if (category.inspectTemplate) {
        templates[category.name] = JSON.parse(category.inspectTemplate)
      }
    })

    const blob = new Blob([JSON.stringify(templates, null, 2)], { type: 'application/json' })
    const a = document.createElement('a')
    a.href = URL.createObjectURL(blob)
    a.download = 'iot_check_templates.json'
    a.click()
  } catch (e: any) {
    ElMessage.error('导出失败：' + (e?.message || ''))
  }
}

function importAll() {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'application/json'
  input.onchange = () => {
    const file = input.files?.[0]
    if (!file) return
    const reader = new FileReader()
    reader.onload = async () => {
      try {
        const text = String(reader.result || '{}')
        const obj = JSON.parse(text)
        if (!obj || typeof obj !== 'object') throw new Error('格式错误')

        // 批量导入到数据库
        for (const [categoryName, items] of Object.entries(obj)) {
          const category = categoryList.value.find(c => c.name === categoryName)
          if (category && Array.isArray(items)) {
            await ProductCategoryApi.updateTemplate(category.id, JSON.stringify(items))
          }
        }

        ElMessage.success('导入成功')
        getList()
      } catch (e: any) {
        ElMessage.error('导入失败：' + (e?.message || ''))
      }
    }
    reader.readAsText(file)
  }
  input.click()
}
</script>

<style scoped>
.mt-8px {
  margin-top: 8px;
}

.mb-8px {
  margin-bottom: 8px;
}

.mb-4px {
  margin-bottom: 4px;
}

.mb-16px {
  margin-bottom: 16px;
}

.text-gray {
  color: #909399;
}

.text-gray-500 {
  color: #909399;
}

.text-12px {
  font-size: 12px;
}

.text-14px {
  font-size: 14px;
}

.name {
  font-weight: 600;
}

.desc {
  color: #666;
  font-size: 12px;
}

.card-header {
  font-weight: 600;
}

.item-row {
  border-bottom: 1px solid #f0f0f0;
  padding: 12px 0;
}

.item-left {
  margin-bottom: 8px;
}

.item-name {
  font-weight: 600;
}

.item-right {
  margin: 8px 0;
}

.issue-area {
  margin-top: 8px;
}
</style>
