<template>
  <div>
    <div class="operation-inspection">
      <div class="navigation-tabs">
        <div class="nav-tab" @click="handleInspection1">待办事项</div>
        <div class="nav-tab active" @click="handleInspection2">巡检管理</div>
        <div class="nav-tab" @click="handleInspection3">试验管理</div>
        <div class="nav-tab" @click="handleInspection4">报修管理</div>
        <div class="nav-tab" @click="handleInspection5">抢修管理</div>
        <div class="nav-tab" @click="handleInspection6">工单管理</div>
        <div class="nav-tab" @click="handleInspection7">运维组织</div>
      </div>
      <TitleComponent title="运维巡检管理" subtitle="制定巡检计划，安排巡检任务，跟进巡检记录"></TitleComponent>

      <!-- 选项卡和按钮组合 -->
      <div class="tabs-wrapper">
        <div style="display: flex; align-items: center; gap: 10px">
          <el-button type="primary" @click="handleInspectionManagement1">巡检计划</el-button>
          <el-button type="primary" @click="handleInspectionManagement2">巡检任务</el-button>
          <el-button type="primary" @click="handleInspectionManagement3">巡检记录</el-button>
        </div>
      </div>
      <!-- 筛选栏 -->
      <div class="filter-bar">
        <div class="filter-item">
          <el-select v-model="planType" placeholder="计划类型" clearable>
            <el-option label="全部类型" value="all"></el-option>
            <el-option label="每日巡检" value="1"></el-option>
            <el-option label="每周巡检" value="2"></el-option>
            <el-option label="每月巡检" value="3"></el-option>
          </el-select>
        </div>
        <div class="filter-item">
          <el-select v-model="status" placeholder="全部状态" clearable>
            <el-option label="全部状态" value="all"></el-option>
            <el-option label="启用中" value="enabled"></el-option>
            <el-option label="已停用" value="disabled"></el-option>
          </el-select>
        </div>
        <div class="filter-item">
          <el-select v-model="inspectionObject" placeholder="巡检对象" clearable>
            <el-option label="全部对象" value="all"></el-option>
            <el-option label="服务器" value="1"></el-option>
            <el-option label="网络设备" value="2"></el-option>
            <el-option label="应用系统" value="3"></el-option>
            <el-option label="基础设施" value="4"></el-option>
          </el-select>
        </div>
        <div class="filter-actions">
          <el-button type="primary" class="search-btn" @click="handleSearch">搜索</el-button>
          <el-button type="primary" icon="el-icon-plus" class="create-btn" @click="handleCreate">手动创建计划</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <div class="table-wrapper">
        <el-table :data="pagedTableData" stripe style="width: 100%" highlight-current-row class="custom-table">
          <el-table-column align="center" prop="name" label="计划名称" style="width: 14.2%"></el-table-column>
          <el-table-column align="center" prop="type" label="类型" style="width: 14.2%"></el-table-column>
          <el-table-column align="center" prop="object" label="巡检对象" style="width: 14.2%"></el-table-column>
          <el-table-column align="center" prop="frequency" label="频率" style="width: 14.2%"></el-table-column>
          <el-table-column align="center" prop="status" label="状态" style="width: 14.2%">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'enabled' ? 'success' : 'info'" class="status-tag">
                {{ scope.row.status === 'enabled' ? '启用中' : '已停用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="responsible" label="负责人" style="width: 14.2%"></el-table-column>
          <el-table-column align="center" label="操作" style="width: 14.2%" fixed="right">
            <template #default="scope">
              <el-button type="text" @click="handleEdit(scope.row)" class="action-btn">编辑</el-button>
              <el-button type="text" @click="handleDetail(scope.row)" class="action-btn">详情</el-button>
              <el-button
                type="text"
                @click="handleEnable(scope.row)"
                class="action-btn"
                :class="{ 'text-success': scope.row.status === 'disabled', 'text-danger': scope.row.status === 'enabled' }"
              >
                {{ scope.row.status === 'enabled' ? '停用' : '启用' }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页区域 -->
      <div class="pagination-section">
        <div class="pagination-info">
          显示第{{ (currentPage - 1) * pageSize + 1 }}到{{ Math.min(currentPage * pageSize, total) }}条，共有{{ total }}条记录
        </div>
        <div class="pagination-controls">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            background
          >
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 创建/编辑计划弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" class="create-plan-dialog" center :show-close="true">
      <el-form :model="createForm" :rules="createFormRules" ref="createFormRef" label-width="150px" class="custom-form">
        <!-- 第一行：计划名称 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="计划名称*" prop="planName">
              <el-input v-model="createForm.planName" placeholder="请输入计划名称" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：计划类型、巡检对象类型 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划类型*" prop="planType">
              <el-select v-model="createForm.planType" placeholder="请选择计划类型" style="width: 100%">
                <el-option label="每日巡检" value="1" />
                <el-option label="每周巡检" value="2" />
                <el-option label="每月巡检" value="3" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡检对象类型*" prop="objectType">
              <el-select v-model="createForm.objectType" placeholder="请选择对象类型" style="width: 100%">
                <el-option label="服务器" value="1" />
                <el-option label="网络设备" value="2" />
                <el-option label="应用系统" value="3" />
                <el-option label="基础设施" value="4" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：开始日期、结束日期 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始日期*" prop="startDate">
              <el-date-picker
                v-model="createForm.startDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期*" prop="endDate">
              <el-date-picker
                v-model="createForm.endDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行：巡检频率 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="巡检频率*" prop="frequencyType" class="frequency-item">
              <el-radio-group v-model="createForm.frequencyType" @change="handleFrequencyChange">
                <el-radio :label="'daily'" class="frequency-radio">每天</el-radio>
                <el-radio :label="'weekly'" class="frequency-radio">每周</el-radio>
                <el-radio :label="'monthly'" class="frequency-radio">每月</el-radio>
              </el-radio-group>

              <!-- 每周-选择周几 -->
              <el-select
                v-model="createForm.weekDay"
                placeholder="选择周几"
                style="margin-left: 10px; width: 120px"
                v-if="createForm.frequencyType === 'weekly'"
              >
                <el-option label="周一" value="1"></el-option>
                <el-option label="周二" value="2"></el-option>
                <el-option label="周三" value="3"></el-option>
                <el-option label="周四" value="4"></el-option>
                <el-option label="周五" value="5"></el-option>
                <el-option label="周六" value="6"></el-option>
                <el-option label="周日" value="7"></el-option>
              </el-select>

              <!-- 每月-选择几号 -->
              <el-select
                v-model="createForm.monthDay"
                placeholder="选择几号"
                style="margin-left: 10px; width: 120px"
                v-if="createForm.frequencyType === 'monthly'"
              >
                <el-option v-for="day in 31" :key="day" :label="`${day}号`" :value="day"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行：计划开始时间、持续时间(分钟) -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划开始时间*" prop="planBeginTime">
              <el-time-picker v-model="createForm.planBeginTime" placeholder="选择时间" format="HH:mm" value-format="HH:mm" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="持续时间(分钟)*" prop="duration">
              <el-input v-model.number="createForm.duration" placeholder="请输入持续时间" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第六行：负责人 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="负责人*" prop="person">
              <el-select v-model="createForm.person" placeholder="请选择负责人" style="width: 100%">
                <el-option v-for="user in userList" :key="user.value" :label="user.label" :value="user.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第七行：巡检项 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="巡检项*" prop="inspectionItemId">
              <el-checkbox-group v-model="createForm.inspectionItemId" class="inspection-item-group">
                <el-checkbox v-for="item in inspectionItemList" :key="item.value" :label="item.value" style="margin-right: 20px; margin-bottom: 10px">
                  {{ item.label }}
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第八行：状态 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="状态*" prop="status">
              <el-select v-model="createForm.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="启用" value="1" />
                <el-option label="停用" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第九行：备注说明 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="备注说明" prop="remark">
              <el-input v-model="createForm.remark" type="textarea" placeholder="请输入备注" rows="3" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelCreatePlan">取消</el-button>
          <el-button type="primary" @click="submitCreatePlan">保存任务</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// 表单引用
const createFormRef = ref(null);
import { ref, computed, reactive, onMounted } from 'vue';
import router from '@/router';
import TitleComponent from './TitleComponent.vue';
import { useRoute } from 'vue-router';
import { addxunjian, xunjianlist, delxunjian, updatexunjian, xunjianUserlist, xunjianItemlist } from '@/api/zhinengxunjian/xunjian';
import { ElMessage, ElMessageBox } from 'element-plus';
// 激活的选项卡
const activeTab = ref('plan');
// 计划类型
const planType = ref('all');
// 状态
const status = ref('all');
// 巡检对象
const inspectionObject = ref('all');
// 表格数据
const tableData = ref([]);
// 当前页码
const currentPage = ref(1);
// 每页条数 - 与分页控件默认值保持一致
const pageSize = ref(10);
// 总条数
const total = ref(0);
// 负责人列表
const userList = ref([]);
// 巡检项列表
const inspectionItemList = ref([]);

// 从API获取巡检计划列表
const getInspectionList = async () => {
  try {
    const response = await xunjianlist({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      planType: planType.value === 'all' ? '' : planType.value,
      status: status.value === 'all' ? '' : status.value === 'enabled' ? '1' : '2',
      objectType: inspectionObject.value === 'all' ? '' : inspectionObject.value
    });

    // 处理接口返回的数据
    if (response.code === 200) {
      // 确保rows是数组
      const rows = Array.isArray(response.rows) ? response.rows : response.data?.rows || [];
      // 确保total是数字
      const totalCount = Number(response.total) || Number(response.data?.total) || 0;

      tableData.value = rows.map((item) => ({
        id: item.id || '', // 接口返回的id是字符串类型
        name: String(item.planName || '未知名称'), // 转换为字符串，避免数字显示问题
        type: getPlanTypeText(item.planType),
        object: getObjectTypeText(item.objectType),
        frequency: item.inspectionFrequency || '未知频率',
        status: item.status === '1' ? 'enabled' : 'disabled',
        responsible: item.nickName || '未知负责人', // 使用nickName作为负责人名称
        originalData: { ...item } // 深拷贝原始数据
      }));

      total.value = totalCount;
    } else {
      console.warn('接口返回非成功状态:', response.code, response.msg);
      ElMessage.warning(`获取数据失败: ${response.msg || '未知错误'}`);
    }
  } catch (error) {
    console.error('获取巡检计划列表失败:', error);
    ElMessage.error('获取巡检计划列表失败');
  }
};

// 获取计划类型文本
const getPlanTypeText = (type) => {
  const typeMap = {
    '1': '每日巡检',
    '2': '每周巡检',
    '3': '每月巡检'
  };
  return typeMap[type] || '未知类型';
};

// 获取对象类型文本
const getObjectTypeText = (type) => {
  const typeMap = {
    '1': '服务器',
    '2': '网络设备',
    '3': '应用系统',
    '4': '基础设施'
  };
  return typeMap[type] || '未知对象';
};

// 页面挂载时获取数据
onMounted(() => {
  getInspectionList();
});

// 计算属性：根据当前页码和每页条数获取分页后的数据
const pagedTableData = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return tableData.value.slice(startIndex, endIndex);
});

// 每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置到第一页
  getInspectionList();
};

// 当前页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getInspectionList();
};

// 搜索按钮点击事件
const handleSearch = () => {
  currentPage.value = 1;
  getInspectionList();
};

// 获取负责人列表
const getUsersList = async () => {
  try {
    // 发起请求
    const response = await xunjianUserlist();
    // 简化数据提取逻辑，只关注可能包含用户数据的地方
    const userRows =
      response?.data?.rows && Array.isArray(response.data.rows)
        ? response.data.rows
        : response?.rows && Array.isArray(response.rows)
        ? response.rows
        : Array.isArray(response)
        ? response
        : [];

    // 提取userName，其他字段忽略
    userList.value = userRows
      .filter((item) => item && typeof item === 'object') // 过滤无效数据
      .map((item, index) => ({
        label: item.userName || `用户${index + 1}`, // 优先用userName，无则兜底
        value: item.id || `id_${index}` // 确保有value值
      }));

    // 空数据处理
    if (userList.value.length === 0) {
      userList.value = [{ label: '默认用户', value: 'default' }];
    }
  } catch (error) {
    console.error('获取用户失败:', error);
    userList.value = [{ label: '默认用户', value: 'default' }];
  }
};

// 获取巡检项列表
const getInspectionItemsList = async () => {
  try {
    const response = await xunjianItemlist();
    console.log('巡检项接口返回数据:', response);

    if (response && response.code === 200) {
      // 即使data不存在，也尝试获取rows（兼容不同返回格式）
      const rows = response.rows || (response.data && response.data.rows) || [];

      inspectionItemList.value = rows.map((item) => ({
        label: item.name || `未命名项(${item.id})`,
        value: item.id
      }));

      console.log(`成功加载${inspectionItemList.value.length}个巡检项`);
    } else {
      inspectionItemList.value = [];
      console.warn('获取巡检项列表失败，响应码:', response?.code);
    }
  } catch (error) {
    console.error('获取巡检项列表失败:', error);
    ElMessage.error('获取巡检项列表失败');
    inspectionItemList.value = [];
  }
};

// 编辑
const handleEdit = async (row) => {
  try {
    // 打开弹窗前先获取数据
    await getUsersList();
    await getInspectionItemsList();

    // 填充表单数据
    const originalData = row.originalData;
    createForm.planName = originalData.planName || '';
    createForm.planType = originalData.planType || '';
    createForm.objectType = originalData.objectType || '';
    createForm.startDate = originalData.beginTime ? originalData.beginTime.substring(0, 10) : '';
    createForm.endDate = originalData.endTime ? originalData.endTime.substring(0, 10) : '';
    createForm.planBeginTime = originalData.planBeginTime || '';
    createForm.duration = originalData.duration || 60;
    createForm.person = originalData.person || '';
    createForm.status = originalData.status || '1';
    createForm.remark = originalData.remark || '';

    // 处理巡检项ID（从字符串转回数组）
    if (originalData.inspectionItemId) {
      createForm.inspectionItemId =
        typeof originalData.inspectionItemId === 'string'
          ? originalData.inspectionItemId.split(',').filter((id) => id.trim())
          : Array.isArray(originalData.inspectionItemId)
          ? originalData.inspectionItemId
          : [];
    } else {
      createForm.inspectionItemId = [];
    }

    // 根据频率描述设置频率相关字段
    const frequencyDesc = originalData.inspectionFrequency || '';
    if (frequencyDesc.includes('每天')) {
      createForm.frequencyType = 'daily';
    } else if (frequencyDesc.includes('每周')) {
      createForm.frequencyType = 'weekly';
      // 提取周几（简单实现，假设格式为"每周X"）
      const weekDayMatch = frequencyDesc.match(/每周(.)/);
      if (weekDayMatch) {
        const weekdays = ['一', '二', '三', '四', '五', '六', '日'];
        const weekDayIndex = weekdays.indexOf(weekDayMatch[1]);
        if (weekDayIndex !== -1) {
          createForm.weekDay = String(weekDayIndex + 1);
        }
      }
    } else if (frequencyDesc.includes('每月')) {
      createForm.frequencyType = 'monthly';
      // 提取几号（简单实现，假设格式为"每月X号"）
      const monthDayMatch = frequencyDesc.match(/每月(\d+)号/);
      if (monthDayMatch) {
        createForm.monthDay = monthDayMatch[1];
      }
    }

    // 记录当前编辑的数据ID
    editingId.value = row.id;

    // 打开弹窗
    dialogVisible.value = true;
    dialogTitle.value = '编辑巡检计划';
  } catch (error) {
    console.error('编辑数据加载失败:', error);
    ElMessage.error('加载编辑数据失败');
  }
};

// 详情
const handleDetail = (row) => {
  console.log('详情', row);
};

// 启用/停用 - 优化后的实现
const handleEnable = async (row) => {
  try {
    // 1. 获取当前行的原始数据和状态
    const originalData = row.originalData || {};
    const currentStatus = originalData.status || '1'; // 当前状态：1=启用，2=停用
    const targetStatus = currentStatus === '1' ? '2' : '1'; // 目标状态：启用→停用，停用→启用
    const statusText = targetStatus === '1' ? '启用' : '停用'; // 状态文本用于提示

    // 2. 显示确认对话框
    await ElMessageBox.confirm(`确定要${statusText}该巡检计划吗？`, '操作确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });

    // 3. 调用接口修改状态（仅传递id和status核心参数）
    const response = await updatexunjian({
      id: row.id, // 必传：当前巡检计划的ID
      status: targetStatus // 必传：目标状态（1=启用，2=停用）
    });

    // 4. 处理接口响应
    if (response.code === 200) {
      // 4.1 提示操作成功
      ElMessage.success(`已成功${statusText}该巡检计划`);

      // 4.2 同步本地数据（表格实时更新，无需重新请求列表）
      // 更新原始数据的状态
      if (originalData) {
        originalData.status = targetStatus;
      }
      // 更新表格行的状态（用于标签显示）
      row.status = targetStatus === '1' ? 'enabled' : 'disabled';
    } else {
      // 4.3 接口返回失败时提示
      ElMessage.error(`${statusText}失败：${response.msg || '服务器异常'}`);
    }
  } catch (error) {
    // 5. 捕获网络或代码错误，用户取消操作时也会进入这里
    if (error !== 'cancel') {
      // 排除用户主动取消的情况
      console.error('启用/停用操作失败:', error);
      ElMessage.error('操作失败，请检查网络或重试');
    }
  }
};

// 选项卡切换
const handleTabChange = (newTab, oldTab) => {
  // 可以在这里添加选项卡切换时的逻辑
  console.log('选项卡切换:', newTab, oldTab);
  return true;
};

// 创建/编辑计划弹窗相关
const dialogVisible = ref(false);
const dialogTitle = ref('新建巡检计划');
const editingId = ref('');
const createForm = reactive({
  planName: '',
  planType: '',
  objectType: '',
  startDate: '',
  endDate: '',
  frequencyType: 'daily', // 频率类型：daily/weekly/monthly
  weekDay: '', // 周几 (1-7)
  monthDay: '', // 几号 (1-31)
  planBeginTime: '',
  duration: 60,
  person: '',
  inspectionItemId: [], // 巡检项多选
  status: '1', // 默认启用
  remark: ''
});

// 频率变化处理函数
const handleFrequencyChange = () => {
  // 切换频率类型时清空不相关的选择
  if (createForm.frequencyType !== 'weekly') {
    createForm.weekDay = '';
  }
  if (createForm.frequencyType !== 'monthly') {
    createForm.monthDay = '';
  }
};

// 创建计划表单验证规则
const createFormRules = computed(() => ({
  planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
  planType: [{ required: true, message: '请选择计划类型', trigger: 'change' }],
  objectType: [{ required: true, message: '请选择对象类型', trigger: 'change' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  frequencyType: [{ required: true, message: '请选择巡检频率', trigger: 'change' }],
  weekDay: [
    {
      required: createForm.frequencyType === 'weekly',
      message: '请选择周几',
      trigger: 'change'
    }
  ],
  monthDay: [
    {
      required: createForm.frequencyType === 'monthly',
      message: '请选择几号',
      trigger: 'change'
    }
  ],
  planBeginTime: [{ required: true, message: '请选择计划开始时间', trigger: 'change' }],
  duration: [
    { required: true, message: '请输入持续时间', trigger: 'blur' },
    { type: 'number', min: 1, message: '持续时间必须大于0', trigger: 'blur' }
  ],
  person: [{ required: true, message: '请选择负责人', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}));

// 打开创建弹窗
const handleCreate = async () => {
  // 打开弹窗前先获取数据
  await getUsersList();
  await getInspectionItemsList();
  dialogVisible.value = true;
  dialogTitle.value = '新建巡检计划';
};

// 提交创建/编辑计划
const submitCreatePlan = async () => {
  try {
    const valid = await createFormRef.value.validate();
    if (valid) {
      // 构建频率描述
      let frequencyDesc = '';
      if (createForm.frequencyType === 'daily') {
        frequencyDesc = '每天';
      } else if (createForm.frequencyType === 'weekly') {
        const weekdays = ['一', '二', '三', '四', '五', '六', '日'];
        frequencyDesc = `每周${weekdays[createForm.weekDay - 1]}`;
      } else if (createForm.frequencyType === 'monthly') {
        frequencyDesc = `每月${createForm.monthDay}号`;
      }

      // 构建提交数据，匹配API接口要求
      const submitData = {
        projectId: 1,
        createDept: 0, // 默认值
        createBy: 0, // 默认值
        createTime: editingId.value ? undefined : new Date().toISOString(), // 编辑时不更新创建时间
        updateBy: 0, // 默认值
        updateTime: new Date().toISOString(), // 当前时间
        params: {}, // 空对象
        planName: createForm.planName,
        planType: createForm.planType,
        objectType: createForm.objectType,
        beginTime: createForm.startDate + 'T00:00:00.000Z', // 转换为ISO格式
        endTime: createForm.endDate + 'T23:59:59.999Z', // 转换为ISO格式
        inspectionFrequency: frequencyDesc, // 使用构建的频率描述
        planBeginTime: createForm.planBeginTime,
        duration: createForm.duration,
        person: createForm.person,
        inspectionItemId: createForm.inspectionItemId.length > 0 ? createForm.inspectionItemId.join(',') : '', // 转换为逗号隔开的字符串
        status: createForm.status,
        remark: createForm.remark || ''
      };

      // 如果是编辑模式，添加id字段
      let response;
      if (editingId.value) {
        submitData.id = editingId.value;
        // 调用更新巡检计划接口
        response = await updatexunjian(submitData);
      } else {
        // 调用添加巡检计划接口
        response = await addxunjian(submitData);
      }

      if (response.code === 200) {
        ElMessage.success(editingId.value ? '更新成功' : '创建成功');
        dialogVisible.value = false;
        resetForm();
        // 重新获取列表数据
        getInspectionList();
      } else {
        ElMessage.error(response.msg || (editingId.value ? '更新失败' : '创建失败'));
      }
    }
  } catch (error) {
    console.error(editingId.value ? '更新巡检计划失败:' : '创建巡检计划失败:', error);
    ElMessage.error(editingId.value ? '更新失败，请重试' : '创建失败，请重试');
  }
};

// 取消创建计划
const cancelCreatePlan = () => {
  dialogVisible.value = false;
  resetForm();
};

// 重置表单
const resetForm = () => {
  if (createFormRef.value) {
    createFormRef.value.resetFields();
    // 手动重置多选框等特殊字段
    createForm.inspectionItemId = [];
    createForm.duration = 60;
    createForm.status = '1'; // 重置为默认启用
    createForm.frequencyType = 'daily'; // 重置频率类型为每天
    createForm.planType = ''; // 清空计划类型
    createForm.weekDay = '';
    createForm.monthDay = '';
    // 重置编辑状态
    editingId.value = '';
    dialogTitle.value = '新建巡检计划';
  }
};

// 导航相关方法
const handleInspection1 = () => {
  router.push('/rili/rili');
};
const handleInspection2 = () => {
  router.push('/rili/InspectionManagement');
};
const handleInspection3 = () => {
  router.push('/rili/shiyanguanli');
};
const handleInspection4 = () => {
  router.push('/rili/baoxiuguanli');
};
const handleInspection5 = () => {
  router.push('/rili/qiangxiuguanli');
};
const handleInspection6 = () => {
  router.push('/rili/gongdanliebiao');
};
const handleInspection7 = () => {
  router.push('/rili/renyuanzhuangtai');
};

// 子选项卡相关方法
const handleInspectionManagement1 = () => {
  router.push('/rili/InspectionManagement');
};
const handleInspectionManagement2 = () => {
  router.push('/rili/xunjianrenwu');
};
const handleInspectionManagement3 = () => {
  router.push('/rili/xunjianjihua');
};
</script>

<style scoped>
/* 基础样式保持不变 */
.operation-inspection {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 标题区域样式 */
.title-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

/* 选项卡样式 */
.tabs-wrapper {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

/* 筛选栏样式 */
.filter-bar {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-item {
  flex-shrink: 0;
}

.filter-bar .el-select {
  width: 150px;
  height: 36px;
}

.filter-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.search-btn,
.create-btn {
  height: 36px;
  border-radius: 4px;
}

/* 表格样式 */
.table-wrapper {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.custom-table {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.custom-table th {
  background-color: #fafafa;
  font-weight: 500;
  color: #606266;
  text-align: left;
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
}

.custom-table td {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  color: #303133;
}

.status-tag {
  padding: 4px 8px;
  font-size: 12px;
  border-radius: 4px;
}

.action-btn {
  color: #409eff;
  font-size: 12px;
  padding: 4px 8px;
}

.action-btn:hover {
  color: #66b1ff;
  background-color: #ecf5ff;
}

/* 操作按钮样式优化 */
.text-danger {
  color: #f56c6c !important;
}

.text-danger:hover {
  color: #f78989 !important;
  background-color: #fef0f0 !important;
}

.text-success {
  color: #67c23a !important;
}

.text-success:hover {
  color: #85ce61 !important;
  background-color: #f0f9eb !important;
}

/* 分页区域样式 */
.pagination-section {
  background-color: #fff;
  padding: 16px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-info {
  font-size: 14px;
  color: #606266;
}

/* 导航栏样式 */
.navigation-tabs {
  display: flex;
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  padding: 2px;
}

.nav-tab {
  padding: 12px 24px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
  border-right: 1px solid #f0f0f0;
  flex: 1;
  text-align: center;
}

.nav-tab:last-child {
  border-right: none;
}

.nav-tab:hover {
  color: #409eff;
  background-color: #ecf5ff;
}

.nav-tab.active {
  background-color: #409eff;
  color: #fff;
  box-shadow: 0 2px 4px rgba(64, 158, 255, 0.3);
}

/* 弹窗样式 */
.create-plan-dialog .el-dialog__body {
  padding: 20px 30px;
  max-height: 70vh;
  overflow-y: auto;
}

.custom-form .el-form-item {
  margin-bottom: 15px;
}

/* 频率选择样式 */
.frequency-item .el-radio-group {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 5px;
}

.frequency-radio {
  padding: 5px 0;
}

/* 巡检项样式 */
.inspection-item-group {
  display: flex;
  flex-wrap: wrap;
}

/* 底部按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .filter-bar {
    flex-direction: column;
    align-items: stretch;
  }

  .filter-actions {
    margin-left: 0;
    justify-content: flex-end;
  }
}
</style>
