<template>
  <div class="task-management-container">
    <h2>巡检任务管理</h2>

    <!-- 顶部操作区 -->
    <div class="top-operation">
      <el-button type="danger" @click="deleteTasks" :disabled="selectedTasks.length === 0">删除</el-button>
      <el-button type="primary" @click="openTaskDrawer">新建巡检任务</el-button>
      <el-button @click="goBack">返回上一级</el-button>
    </div>

    <!-- 中间任务列表 -->
    <div class="task-list">
      <el-table :data="tasks" style="width: 100%" v-loading=loading @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="taskName" label="任务名" width="180"></el-table-column>
        <el-table-column prop="taskDescription" label="任务说明"></el-table-column>
        <el-table-column prop="baselineImage" label="巡检基准图" width="120">
          <template slot-scope="scope">
            <el-image :src="scope.row.baselineImage" fit="cover" style="width: 80px; height: 60px; cursor: pointer"
              @click="previewImage(scope.row.baselineImage)">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="small" @click="viewTask(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="editTask(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 任务配置抽屉 -->
    <el-drawer title="巡检任务配置" :visible.sync="drawerVisible" size="80%" direction="rtl">
      <div class="task-config">
        <el-button v-if="!isViewMode" type="info" @click="resetForm"
          style="position: absolute; top: 20px; right: 20px">重置</el-button>

        <!-- 任务基本信息配置区域 -->
        <el-form :model="taskForm" label-width="120px">
          <el-form-item label="任务名称" required>
            <el-input v-model="taskForm.taskName" placeholder="例如：2026黑龙江机房A区巡检任务" :disabled="isViewMode"></el-input>
          </el-form-item>
          <el-form-item label="任务完成基准图">
            <template v-if="isViewMode">
              <template v-if="taskForm.baselineImage">
                <el-image :src="taskForm.baselineImage" fit="cover" style="width: 120px; height: 80px; cursor: pointer"
                  @click="previewImage(taskForm.baselineImage)"></el-image>
              </template>
              <template v-else>
                <div class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </template>
            </template>
            <el-upload v-else class="avatar-uploader" :action="uploadUrl" :show-file-list="false"
              :on-success="handleAvatarSuccess">
              <img style="width: 55px; height: 55px; " v-if="taskForm.baselineImage" :src="taskForm.baselineImage"
                class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <!-- <div class="upload-tip">上传附件3（巡检对照基准图），并与当前任务进行关联</div> -->
          </el-form-item>
          <el-form-item label="任务描述">
            <el-input v-model="taskForm.taskDescription" type="textarea" placeholder="简要描述任务的说明和特点" rows="3"
              :disabled="isViewMode"></el-input>
          </el-form-item>
        </el-form>

        <!-- 巡检项配置区域 -->
        <div class="indicator-config">
          <h3 style="margin-top: 30px; margin-bottom: 20px;">
            <span style="color: red">*</span>指标分类配置
            <el-button v-if="!isViewMode" type="primary" size="small" @click="openAddCategoryDialog"
              style="margin-left: 20px">添加分类</el-button>
          </h3>

          <div v-for="(category, categoryIndex) in taskForm.categories" :key="categoryIndex" class="category-item">
            <div class="category-header">
              <p >{{ category.categoryName }}</p>
              <el-button size="small" @click="openAddItemDialog(categoryIndex)" :disabled="isViewMode">+</el-button>
              <el-button size="small" type="danger" @click="removeCategory(categoryIndex)" :disabled="isViewMode">删除</el-button>
            </div>

            <div v-if="category.expanded" class="category-content">
              <div v-for="(item, itemIndex) in category.items" :key="itemIndex" class="item-row">
                <p style="margin-left: 20px;">{{ item.itemName }}</p>
                <el-button size="mini" type="danger" @click="removeItem(categoryIndex, itemIndex)" :disabled="isViewMode" style="margin-left: 10px">删除</el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部按钮区 -->
        <div class="bottom-buttons" style="margin-top: 40px; text-align: right;">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button v-if="!isViewMode" type="primary" @click="saveTask">保存配置</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="dialogVisible" title="图片预览" width="600px">
      <img :src="dialogImageUrl" style="width: 100%" />
    </el-dialog>

    <!-- 添加分类对话框 -->
    <el-dialog :visible.sync="categoryDialogVisible" title="添加分类" width="400px">
      <el-form :model="categoryForm" label-width="100px">
        <el-form-item label="指标分类" required>
          <el-input v-model="categoryForm.categoryName" placeholder="请输入分类名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="categoryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCategory">保存</el-button>
      </div>
    </el-dialog>

    <!-- 添加巡检项对话框 -->
    <el-dialog :visible.sync="itemDialogVisible" title="添加巡检项" width="400px">
      <el-form :model="itemForm" label-width="100px">
        <el-form-item label="巡检项名称" required>
          <el-input v-model="itemForm.itemName" placeholder="请输入巡检项名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="itemDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveItem">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getTaskList, addTask, deleteTask, updateTask } from '@/api/newApi/inspection'
export default {
  data() {
    return {
      loading: false,
      uploadUrl: process.env.VUE_APP_BASE_API + '/inspection/saveBenchmarkPhoto',
      tasks: [],
      selectedTasks: [],
      drawerVisible: false,
      dialogVisible: false,
      dialogImageUrl: '',
      isViewMode: false,
      taskForm: {
        taskName: '',
        taskDescription: '',
        status: 1,
        categories: []
      },
      categoryDialogVisible: false,
      itemDialogVisible: false,
      currentCategoryIndex: -1,
      categoryForm: {
        categoryName: ''
      },
      itemForm: {
        itemName: ''
      }
    }
  },
  created() {
    this.getTasks()
  },
  methods: {
    // 获取任务列表
    getTasks() {
      this.loading = true
      getTaskList().then(res => {
        if (res.success) {
          this.loading = false
          this.tasks = res.data
        }
      })
    },
    handleSelectionChange(val) {
      this.selectedTasks = val
    },
    deleteTasks() {
      if (this.selectedTasks.length === 0) return

      this.$confirm('确定要删除选中的任务吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟删除操作
        this.selectedTasks.forEach(task => {
          console.log(task, 'task')
          deleteTask(task.id)
        })
        this.loading = true
        this.$message({ type: 'success', message: '删除成功' })
        setTimeout(() => {
          this.getTasks()
          this.loading = false
        }, 2000);
      }).catch(() => {
        this.$message({ type: 'info', message: '取消删除' })
      })
    },
    openTaskDrawer() {
      this.resetForm()
      this.isViewMode = false
      this.drawerVisible = true
    },
    editTask(task) {
      this.isViewMode = false
      // 创建深拷贝，避免修改原数据
      this.taskForm = JSON.parse(JSON.stringify(task))
      // 确保categories属性存在
      if (!this.taskForm.categories) {
        this.taskForm.categories = []
      }
      // 确保每个分类都有expanded属性
      this.taskForm.categories.forEach(category => {
        if (category.expanded === undefined) {
          category.expanded = true
        }
      })
      // 确保status属性存在
      if (this.taskForm.status === undefined) {
        this.taskForm.status = 1
      }
      this.drawerVisible = true
    },
    viewTask(task) {
      console.log(task, 'task')
      this.isViewMode = true
      // 创建深拷贝，避免修改原数据
      this.taskForm = JSON.parse(JSON.stringify(task))
      // 确保categories属性存在
      if (!this.taskForm.categories) {
        this.taskForm.categories = []
      }
      // 确保每个分类都有expanded属性
      this.taskForm.categories.forEach(category => {
        if (category.expanded === undefined) {
          category.expanded = true
        }
      })
      // 确保status属性存在
      if (this.taskForm.status === undefined) {
        this.taskForm.status = 1
      }
      this.drawerVisible = true
    },
    goBack() {
      this.$router.push('/inspection/index')
    },
    resetForm() {
      this.taskForm = {
        taskName: '',
        taskDescription: '',
        status: 1,
        categories: []
      }
    },
    openAddCategoryDialog() {
      if (this.isViewMode) return
      this.categoryForm = {
        categoryName: ''
      }
      this.categoryDialogVisible = true
    },
    saveCategory() {
      if (this.isViewMode) return
      if (!this.categoryForm.categoryName) {
        this.$message({ type: 'error', message: '请输入分类名称' })
        return
      }
      
      this.taskForm.categories.push({
        categoryName: this.categoryForm.categoryName,
        expanded: true,
        items: []
      })
      
      this.categoryDialogVisible = false
    },
    openAddItemDialog(categoryIndex) {
      if (this.isViewMode) return
      this.currentCategoryIndex = categoryIndex
      this.itemForm = {
        itemName: ''
      }
      this.itemDialogVisible = true
    },
    saveItem() {
      if (this.isViewMode) return
      if (!this.itemForm.itemName) {
        this.$message({ type: 'error', message: '请输入巡检项名称' })
        return
      }
      
      this.taskForm.categories[this.currentCategoryIndex].items.push({
        itemName: this.itemForm.itemName,
        checked: true
      })
      
      this.itemDialogVisible = false
    },
    removeCategory(categoryIndex) {
      if (this.isViewMode) return
      this.taskForm.categories.splice(categoryIndex, 1)
    },
    removeItem(categoryIndex, itemIndex) {
      if (this.isViewMode) return
      this.taskForm.categories[categoryIndex].items.splice(itemIndex, 1)
    },
    handleAvatarSuccess(res, file) {
      console.log(res)
      this.taskForm.baselineImage = "http://10.130.22.73:1090/stage-api" + res.data
      this.$forceUpdate()
      console.log(this.taskForm.baselineImage)
    },
    saveTask() {
      // 验证表单
      if (!this.taskForm.taskName) {
        this.$message({ type: 'error', message: '请填写任务名称' })
        return
      }
      
      // 确保每个分类都有名称，且每个分类下至少有一个巡检项
      for (let i = 0; i < this.taskForm.categories.length; i++) {
        const category = this.taskForm.categories[i]
        if (!category.categoryName) {
          this.$message({ type: 'error', message: `请填写第${i + 1}个分类的名称` })
          return
        }
        if (category.items.length === 0) {
          this.$message({ type: 'error', message: `请为第${i + 1}个分类添加至少一个巡检项` })
          return
        }
        // 确保每个巡检项都有名称
        for (let j = 0; j < category.items.length; j++) {
          const item = category.items[j]
          if (!item.itemName) {
            this.$message({ type: 'error', message: `请填写第${i + 1}个分类下第${j + 1}个巡检项的名称` })
            return
          }
        }
      }
      
      // 调用API保存任务
      const savePromise = this.taskForm.id ? updateTask(this.taskForm) : addTask(this.taskForm)
      savePromise.then(res => {
        if (res.success || res.code === 200) {
          this.$message({ type: 'success', message: this.taskForm.id ? '更新成功' : '保存成功' })
          this.getTasks()
          this.drawerVisible = false
        } else {
          this.$message({ type: 'error', message: (this.taskForm.id ? '更新' : '保存') + '失败：' + (res.message || '未知错误') })
        }
      }).catch(err => {
        this.$message({ type: 'error', message: (this.taskForm.id ? '更新' : '保存') + '失败：网络错误' })
      })
    },
    previewImage(url) {
      this.dialogImageUrl = url
      this.dialogVisible = true
    }
  }
}
</script>

<style scoped>
.task-management-container {
  padding: 20px;
}

.top-operation {
  margin-bottom: 20px;
}

.top-operation .el-button {
  margin-right: 10px;
}

.task-list {
  margin-top: 20px;
}

.image-slot {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 60px;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

.task-config {
  padding: 20px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.category-item {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.category-header {
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.category-header .el-checkbox {
  flex: 1;
  margin-right: 10px;
}

.category-content {
  margin-top: 10px;
  margin-left: 10px;
}

.item-row {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.item-row .el-checkbox {
  flex: 1;
}

.item-row .el-button {
  margin-left: 10px;
}
</style>