<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="-mb-15px" label-width="68px">
      <el-form-item label="设备名称" prop="deviceName">
        <el-input v-model="queryParams.deviceName" class="!w-240px" clearable placeholder="请输入设备名称"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="queryParams.name" class="!w-240px" clearable placeholder="请输入任务名称"
          @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="频率类型" prop="frequencyType">
        <el-select v-model="queryParams.frequencyType" class="!w-240px" clearable placeholder="请选择频率类型">
          <el-option label="每日" value="DAILY" />
          <el-option label="每周" value="WEEKLY" />
          <el-option label="每月" value="MONTHLY" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" class="!w-240px" clearable placeholder="请选择状态">
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </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="openForm('create')" v-hasPermi="['iot:inspection-task:create']">
          <Icon icon="ep:plus" 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="name" min-width="150" />
      <el-table-column label="设备名称" align="center" prop="deviceName" min-width="120" />
      <el-table-column label="频率类型" align="center" prop="frequencyType" width="100">
        <template #default="{ row }">
          <el-tag :type="getFrequencyTypeTag(row.frequencyType)">
            {{ getFrequencyTypeLabel(row.frequencyType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="执行时间" align="center" prop="windowStart" width="120">
        <template #default="{ row }">
          {{ row.windowStart }} - {{ row.windowEnd }}
        </template>
      </el-table-column>
      <el-table-column label="生效时间" align="center" prop="effectiveStart" width="120">
        <template #default="{ row }">
          {{ formatDate(row.effectiveStart) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="250" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="openForm('update', row.id)"
            v-hasPermi="['iot:inspection-task:update']">
            编辑
          </el-button>
          <el-button link type="info" @click="openForm('detail', row.id)" v-hasPermi="['iot:inspection-task:query']">
            查看
          </el-button>
          <el-button link type="success" @click="handleRebuildInstance(row)"
            v-hasPermi="['iot:inspection-instance:rebuild']">
            发布任务
          </el-button>
          <el-button link type="danger" @click="handleDelete(row.id)" v-hasPermi="['iot:inspection-task:delete']">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination :total="total" v-model:page="paginationPage" v-model:limit="paginationSize" @pagination="getList" />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <Dialog v-model="formVisible" :title="formTitle" width="600px">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" v-loading="formLoading">
      <ProductSelector v-model="selectedProduct" form-item label="选择产品" prop="deviceId" :required="true"
        @update:model-value="handleProductChange" />
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入任务名称" />
      </el-form-item>
      <el-form-item label="频率类型" prop="frequencyType">
        <el-select v-model="formData.frequencyType" placeholder="请选择频率类型" @change="handleFrequencyTypeChange">
          <el-option label="每日" value="DAILY" />
          <el-option label="每周" value="WEEKLY" />
          <el-option label="每月" value="MONTHLY" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="formData.frequencyType === 'WEEKLY'" label="执行星期" prop="weekdays">
        <el-checkbox-group v-model="formData.weekdays">
          <el-checkbox :label="1">周一</el-checkbox>
          <el-checkbox :label="2">周二</el-checkbox>
          <el-checkbox :label="3">周三</el-checkbox>
          <el-checkbox :label="4">周四</el-checkbox>
          <el-checkbox :label="5">周五</el-checkbox>
          <el-checkbox :label="6">周六</el-checkbox>
          <el-checkbox :label="7">周日</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item v-if="formData.frequencyType === 'MONTHLY'" label="执行日期" prop="monthDays">
        <el-select v-model="formData.monthDays" multiple placeholder="请选择执行日期">
          <el-option v-for="day in 31" :key="day" :label="`${day}日`" :value="day" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间窗口" prop="windowStart">
        <div class="flex items-center gap-2">
          <el-time-picker v-model="formData.windowStart" placeholder="开始时间" format="HH:mm" value-format="HH:mm"
            style="width: 120px" />
          <span>至</span>
          <el-time-picker v-model="formData.windowEnd" placeholder="结束时间" format="HH:mm" value-format="HH:mm"
            style="width: 120px" />
        </div>
      </el-form-item>
      <el-form-item label="生效开始时间" prop="effectiveStart">
        <el-date-picker v-model="formData.effectiveStart" type="datetime" placeholder="选择生效开始时间"
          value-format="YYYY-MM-DDTHH:mm:ss" />
      </el-form-item>
      <el-form-item label="生效结束时间" prop="effectiveEnd">
        <el-date-picker v-model="formData.effectiveEnd" type="datetime" placeholder="选择生效结束时间"
          value-format="YYYY-MM-DDTHH:mm:ss" />
      </el-form-item>
      <el-form-item label="指派用户ID" prop="assigneeUserId">
        <el-input v-model="formData.assigneeUserId" placeholder="请输入指派用户ID" />
      </el-form-item>
      <el-form-item label="指派用户名称" prop="assigneeUserName">
        <el-input v-model="formData.assigneeUserName" placeholder="请输入指派用户名称" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入任务描述" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="formVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="formLoading">确定</el-button>
    </template>
  </Dialog>

  <!-- 详情弹窗 -->
  <Dialog v-model="detailVisible" title="任务详情" width="600px">
    <el-descriptions :column="2" border>
      <el-descriptions-item label="任务名称">{{ detailData.name }}</el-descriptions-item>
      <el-descriptions-item label="设备名称">{{ detailData.deviceName }}</el-descriptions-item>
      <el-descriptions-item label="设备ID">{{ detailData.deviceId }}</el-descriptions-item>
      <el-descriptions-item label="频率类型">
        <el-tag :type="getFrequencyTypeTag(detailData.frequencyType)">
          {{ getFrequencyTypeLabel(detailData.frequencyType) }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item v-if="detailData.weekdays" label="执行星期">
        {{detailData.weekdays.map(d => ['', '周一', '周二', '周三', '周四', '周五', '周六', '周日'][d]).join('、')}}
      </el-descriptions-item>
      <el-descriptions-item v-if="detailData.monthDays" label="执行日期">
        {{detailData.monthDays.map(d => `${d}日`).join('、')}}
      </el-descriptions-item>
      <el-descriptions-item label="时间窗口">{{ detailData.windowStart }} - {{ detailData.windowEnd
      }}</el-descriptions-item>
      <el-descriptions-item label="生效开始时间">{{ formatDate(detailData.effectiveStart || '') }}</el-descriptions-item>
      <el-descriptions-item label="生效结束时间">{{ formatDate(detailData.effectiveEnd || '') }}</el-descriptions-item>
      <el-descriptions-item label="指派用户ID">{{ detailData.assigneeUserId || '-' }}</el-descriptions-item>
      <el-descriptions-item label="指派用户名称">{{ detailData.assigneeUserName || '-' }}</el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="detailData.status === 1 ? 'success' : 'danger'">
          {{ detailData.status === 1 ? '启用' : '禁用' }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="创建时间" :span="2">{{ formatDate(detailData.createTime || '') }}</el-descriptions-item>
      <el-descriptions-item label="描述" :span="2">{{ detailData.description || '-' }}</el-descriptions-item>
    </el-descriptions>
  </Dialog>

  <!-- 重建实例弹窗 -->
  <Dialog v-model="rebuildVisible" title="发布任务" width="500px">
    <el-form ref="rebuildFormRef" :model="rebuildData" :rules="rebuildRules" label-width="120px">
      <el-form-item label="任务名称">
        <el-input v-model="rebuildData.name" disabled />
      </el-form-item>
      <el-form-item label="开始日期" prop="dateFrom">
        <el-date-picker v-model="rebuildData.dateFrom" type="date" placeholder="选择开始日期" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="结束日期" prop="dateTo">
        <el-date-picker v-model="rebuildData.dateTo" type="date" placeholder="选择结束日期" value-format="YYYY-MM-DD" />
      </el-form-item>
      <el-form-item label="强制发布">
        <el-switch v-model="rebuildData.forceRecreate" />
        <div class="text-12px text-gray-500 mt-1">开启后将删除已经发布的任务并重新发布</div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="rebuildVisible = false">取消</el-button>
      <el-button type="primary" @click="submitRebuild" :loading="rebuildLoading">确定</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import * as InspectionTaskApi from '@/api/iot/inspection/task'
import * as InspectionInstanceApi from '@/api/iot/inspection/instance'
import type { InspectionTaskVO, InspectionTaskPageReqVO } from '@/api/iot/inspection/task'
import type { ProductVO } from '@/api/iot/product/product'
import { ProductApi } from '@/api/iot/product/product'
import ProductSelector from '@/components/ProductSelector/index.vue'

defineOptions({ name: 'InspectionTask' })

const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const list = ref<InspectionTaskVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const paginationPage = ref(1) // 分页页码
const paginationSize = ref(10) // 分页大小
const queryParams = reactive<InspectionTaskPageReqVO>({
  pageNo: '1',
  pageSize: '10',
  deviceName: undefined,
  name: undefined,
  frequencyType: undefined,
  status: undefined
})
const queryFormRef = ref() // 搜索的表单

// 表单相关
const formVisible = ref(false)
const formLoading = ref(false)
const formType = ref<'create' | 'update' | 'detail'>('create')
const formRef = ref<FormInstance>()
const formData = ref<InspectionTaskVO>({
  deviceId: '',
  deviceName: '',
  name: '',
  frequencyType: 'DAILY',
  windowStart: '08:00',
  windowEnd: '17:00',
  effectiveStart: '',
  assigneeUserId: '',
  assigneeUserName: '',
  status: 1,
  description: ''
})

// 产品选择相关
const selectedProduct = ref<ProductVO | null>(null)
const formRules = reactive({
  name: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
  frequencyType: [{ required: true, message: '频率类型不能为空', trigger: 'change' }],
  windowStart: [{ required: true, message: '开始时间不能为空', trigger: 'change' }],
  windowEnd: [{ required: true, message: '结束时间不能为空', trigger: 'change' }],
  effectiveStart: [{ required: true, message: '生效开始时间不能为空', trigger: 'change' }]
})

// 详情相关
const detailVisible = ref(false)
const detailData = ref<InspectionTaskVO>({} as InspectionTaskVO)

// 重建实例相关
const rebuildVisible = ref(false)
const rebuildLoading = ref(false)
const rebuildFormRef = ref<FormInstance>()
const rebuildData = ref({
  taskId: 0,
  name: '',
  dateFrom: '',
  dateTo: '',
  forceRecreate: false
})
const rebuildRules = reactive({
  dateFrom: [{ required: true, message: '开始日期不能为空', trigger: 'change' }],
  dateTo: [{ required: true, message: '结束日期不能为空', trigger: 'change' }]
})

const formTitle = computed(() => {
  switch (formType.value) {
    case 'create':
      return '新增点检任务'
    case 'update':
      return '编辑点检任务'
    case 'detail':
      return '查看点检任务'
    default:
      return ''
  }
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 同步分页参数
    queryParams.pageNo = paginationPage.value.toString()
    queryParams.pageSize = paginationSize.value.toString()

    const data = await InspectionTaskApi.getInspectionTaskPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

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

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

/** 打开表单弹窗 */
const openForm = async (type: 'create' | 'update' | 'detail', id?: number) => {
  formType.value = type
  formVisible.value = true
  resetForm()

  if (type !== 'create' && id) {
    formLoading.value = true
    try {
      const data = await InspectionTaskApi.getInspectionTask(id)

      // 转换时间戳为日期时间字符串
      const processedData = {
        ...data,
        effectiveStart: data.effectiveStart ? new Date(data.effectiveStart).toISOString().slice(0, 19).replace('T', 'T') : '',
        effectiveEnd: data.effectiveEnd ? new Date(data.effectiveEnd).toISOString().slice(0, 19).replace('T', 'T') : '',
        createTime: data.createTime ? new Date(data.createTime).toISOString().slice(0, 19).replace('T', 'T') : '',
        updateTime: data.updateTime ? new Date(data.updateTime).toISOString().slice(0, 19).replace('T', 'T') : ''
      }

      formData.value = processedData

      // 如果有设备ID，需要查找对应的产品
      if (processedData.deviceId) {
        try {
          const product = await ProductApi.getProduct(parseInt(processedData.deviceId))
          selectedProduct.value = product
        } catch (error) {
          console.error('获取产品信息失败:', error)
          selectedProduct.value = null
        }
      } else {
        selectedProduct.value = null
      }

      if (type === 'detail') {
        detailData.value = processedData
        formVisible.value = false
        detailVisible.value = true
        return
      }
    } finally {
      formLoading.value = false
    }
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    deviceId: '',
    deviceName: '',
    name: '',
    frequencyType: 'DAILY',
    windowStart: '08:00',
    windowEnd: '17:00',
    effectiveStart: '',
    assigneeUserId: '',
    assigneeUserName: '',
    status: 1,
    description: ''
  }
  selectedProduct.value = null
  formRef.value?.resetFields()
}

/** 处理产品选择变化 */
const handleProductChange = (product: ProductVO | null) => {
  if (product) {
    formData.value.deviceId = product.id.toString()
    formData.value.deviceName = product.name
  } else {
    formData.value.deviceId = ''
    formData.value.deviceName = ''
  }
}

/** 提交表单 */
const submitForm = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return

  formLoading.value = true
  try {
    const data = { ...formData.value }

    // 转换日期时间字符串为时间戳
    if (data.effectiveStart) {
      data.effectiveStart = String(new Date(data.effectiveStart).getTime())
    }
    if (data.effectiveEnd) {
      data.effectiveEnd = String(new Date(data.effectiveEnd).getTime())
    }

    if (formType.value === 'create') {
      await InspectionTaskApi.createInspectionTask(data)
      message.success('创建成功')
    } else {
      await InspectionTaskApi.updateInspectionTask(data)
      message.success('更新成功')
    }
    formVisible.value = false
    await getList()
  } finally {
    formLoading.value = false
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定删除该点检任务吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await InspectionTaskApi.deleteInspectionTask(id)
    message.success('删除成功')
    await getList()
  } catch (error) {
    if (error !== 'cancel') {
      message.error('删除失败')
    }
  }
}

/** 重建实例 */
const handleRebuildInstance = (row: InspectionTaskVO) => {
  rebuildData.value = {
    taskId: row.id!,
    name: row.name,
    dateFrom: '',
    dateTo: '',
    forceRecreate: false
  }
  rebuildVisible.value = true
}

/** 提交重建实例 */
const submitRebuild = async () => {
  if (!rebuildFormRef.value) return
  const valid = await rebuildFormRef.value.validate()
  if (!valid) return

  rebuildLoading.value = true
  try {
    await InspectionInstanceApi.rebuildInspectionInstance(rebuildData.value)
    message.success('发布任务成功')
    rebuildVisible.value = false
  } finally {
    rebuildLoading.value = false
  }
}

/** 频率类型变化处理 */
const handleFrequencyTypeChange = (value: string) => {
  if (value === 'WEEKLY') {
    formData.value.weekdays = [1, 2, 3, 4, 5] // 默认工作日
    formData.value.monthDays = undefined
  } else if (value === 'MONTHLY') {
    formData.value.monthDays = [1, 15] // 默认每月1号和15号
    formData.value.weekdays = undefined
  } else {
    formData.value.weekdays = undefined
    formData.value.monthDays = undefined
  }
}

/** 获取频率类型标签 */
const getFrequencyTypeTag = (type: string) => {
  switch (type) {
    case 'DAILY':
      return 'primary'
    case 'WEEKLY':
      return 'success'
    case 'MONTHLY':
      return 'warning'
    default:
      return 'info'
  }
}

/** 获取频率类型标签文本 */
const getFrequencyTypeLabel = (type: string) => {
  switch (type) {
    case 'DAILY':
      return '每日'
    case 'WEEKLY':
      return '每周'
    case 'MONTHLY':
      return '每月'
    default:
      return type
  }
}

/** 格式化日期 */
const formatDate = (date: string | number) => {
  if (!date) return '-'
  // 如果是时间戳（数字），直接转换；如果是字符串，先转换为Date
  const dateObj = typeof date === 'number' ? new Date(date) : new Date(date)
  return dateObj.toLocaleString()
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.flex {
  display: flex;
}

.items-center {
  align-items: center;
}

.gap-2 {
  gap: 0.5rem;
}

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

.text-gray-500 {
  color: #6b7280;
}

.mt-1 {
  margin-top: 0.25rem;
}
</style>
