<template>
  <div class="repair-order-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">
          <el-icon>
            <Tools/>
          </el-icon>
          维修工单管理
        </h2>
        <el-tag type="info" size="small">共 {{ total }} 条记录</el-tag>
      </div>
      <div class="header-right">
        <el-button type="primary" :icon="Plus" @click="handleAdd" v-hasPermi="['repairOrder:repairOrder:add']">
          新建工单
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="statistics-cards">
      <el-col :xs="24" :sm="12" :md="6" v-for="stat in statisticsData" :key="stat.type">
        <div class="stat-card" :class="`stat-${stat.type}`">
          <div class="stat-icon">
            <el-icon>
              <component :is="stat.icon"/>
            </el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stat.value }}</div>
            <div class="stat-label">{{ stat.label }}</div>
          </div>
          <div class="stat-trend" v-if="stat.trend">
            <span :class="stat.trend > 0 ? 'up' : 'down'">
              {{ stat.trend > 0 ? '+' : '' }}{{ stat.trend }}%
            </span>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 搜索和操作区 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="工单编号" prop="orderNo">
              <el-input
                  v-model="queryParams.orderNo"
                  placeholder="请输入工单编号"
                  clearable
                  :prefix-icon="Search"
                  @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="项目名称" prop="projectName">
              <el-input
                  v-model="queryParams.projectName"
                  placeholder="请输入项目名称"
                  clearable
                  :prefix-icon="Search"
                  @keyup.enter="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="工单状态" prop="orderStatus">
              <el-select
                  v-model="queryParams.orderStatus"
                  placeholder="请选择工单状态"
                  clearable
                  style="width: 100%;min-width: 180px"
              >
                <el-option
                    v-for="dict in repair_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                >
                  <div class="status-option">
                    <span class="status-dot" :class="`status-${dict.value}`"></span>
                    <span>{{ dict.label }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="6">
            <el-form-item label="派单时间" prop="dateRange">
              <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  :shortcuts="dateShortcuts"
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" class="search-buttons">
            <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
            <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
            <!--            <el-button type="text" @click="toggleAdvanced">
                          {{ showAdvanced ? '收起' : '高级筛选' }}
                          <el-icon><component :is="showAdvanced ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
                        </el-button>-->
          </el-col>
        </el-row>
      </el-form>

      <!-- 操作按钮组 -->
      <div class="table-operations">
        <div class="operations-left">
          <el-button
              type="success"
              plain
              :icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['repairOrder:repairOrder:edit']"
          >修改
          </el-button>
          <el-button
              type="danger"
              plain
              :icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['repairOrder:repairOrder:remove']"
          >删除
          </el-button>
          <el-button
              type="warning"
              plain
              :icon="Download"
              @click="handleExport"
              v-hasPermi="['repairOrder:repairOrder:export']"
          >导出
          </el-button>
        </div>
        <div class="operations-right">
          <el-tooltip content="刷新" placement="top">
            <el-button :icon="Refresh" circle @click="getList"/>
          </el-tooltip>
          <el-tooltip content="显示/隐藏搜索" placement="top">
            <el-button :icon="showSearch ? View : Hide" circle @click="showSearch = !showSearch"/>
          </el-tooltip>
          <el-tooltip content="列设置" placement="top">
            <el-button :icon="Setting" circle/>
          </el-tooltip>
        </div>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
          v-loading="loading"
          :data="repairOrderList"
          @selection-change="handleSelectionChange"
          stripe
          :row-class-name="tableRowClassName"
          :default-sort="{ prop: 'assignTime', order: 'descending' }"
      >
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="工单编号" align="center" prop="orderNo" width="120">
          <template #default="scope">
            <el-link type="primary" @click="showDetail(scope.row)">
              {{ scope.row.orderNo }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column label="工单内容" align="left" prop="orderContent" min-width="200" show-overflow-tooltip/>
        <el-table-column label="项目名称" align="center" prop="projectName" min-width="150" show-overflow-tooltip/>
        <el-table-column label="派单时间" align="center" prop="assignTime" width="180" sortable>
          <template #default="scope">
            <div class="time-cell">
              <el-icon>
                <Clock/>
              </el-icon>
              <span>{{ parseTime(scope.row.assignTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="责任人" align="center" prop="finishBy" width="160">
          <template #default="scope">
            <div class="user-info" v-if="scope.row.finishBy">
              <el-avatar size="small">{{ scope.row.finishBy.charAt(0) }}</el-avatar>
              <span>{{ scope.row.finishBy }}</span>
            </div>
            <el-tag v-else type="info" size="small">未分配</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="工单状态" align="center" prop="orderStatus" width="100">
          <template #default="scope">
            <el-tag
                :type="getStatusType(scope.row.orderStatus)"
                effect="dark"
                size="small"
            >
              {{ getStatusText(scope.row.orderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="完成时间" align="center" prop="finishTime" width="160">
          <template #default="scope">
            <span v-if="scope.row.finishTime">
              {{ parseTime(scope.row.finishTime, '{y}-{m}-{d} {h}:{i}') }}
            </span>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column label="附件" align="center" prop="annex" width="80">
          <template #default="scope">
            <el-button
                v-if="scope.row.annex"
                type="primary"
                link
                :icon="Paperclip"
                @click="downloadFile(scope.row.annex)"
            >
              下载
            </el-button>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="showDetail(scope.row)">
              详情
            </el-button>
            <el-button
                v-if="canDispatch(scope.row)"
                link
                type="warning"
                size="small"
                @click="handleUpdate(scope.row)"
            >
              派单
            </el-button>
            <el-dropdown trigger="click" style="margin-left: 10px">
              <el-button link type="primary" size="small">
                更多
                <el-icon>
                  <ArrowDown/>
                </el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                      :icon="Delete"
                      @click="handleDelete(scope.row)"
                      v-hasPermi="['repairOrder:repairOrder:remove']"
                  >
                    删除
                  </el-dropdown-item>
                  <el-dropdown-item
                      :icon="DocumentCopy"
                      @click="handleCopy(scope.row)"
                  >
                    复制
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
    </el-card>

    <!-- 工单详情抽屉 -->
    <el-drawer
        v-model="detailVisible"
        :title="`工单详情 - ${detailData.orderNo}`"
        direction="rtl"
        size="50%"
        class="detail-drawer"
    >
      <div class="detail-header">
        <el-tag :type="getStatusType(detailData.orderStatus)" size="large">
          {{ getStatusText(detailData.orderStatus) }}
        </el-tag>
        <el-button-group>
          <el-button :icon="Edit" @click="handleUpdateFromDetail" v-if="canDispatch(detailData)">编辑</el-button>
          <el-button :icon="Printer" @click="handlePrint">打印</el-button>
        </el-button-group>
      </div>

      <el-descriptions :column="2" border class="detail-descriptions">
        <el-descriptions-item label="工单编号">
          <span class="detail-value">{{ detailData.orderNo }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="项目名称">
          {{ detailData.projectName }}
        </el-descriptions-item>
        <el-descriptions-item label="工单内容" :span="2">
          <div class="content-box">{{ detailData.orderContent }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="派单时间">
          <div class="time-info">
            <el-icon>
              <Clock/>
            </el-icon>
            {{ parseTime(detailData.assignTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="完成时间">
          <div class="time-info" v-if="detailData.finishTime">
            <el-icon>
              <CircleCheck/>
            </el-icon>
            {{ parseTime(detailData.finishTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
          </div>
          <el-tag v-else type="info" size="small">未完成</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="责任人">
          <div class="user-detail" v-if="detailData.finishBy">
            <el-avatar>{{ detailData.finishBy.charAt(0) }}</el-avatar>
            <span>{{ detailData.finishBy }}</span>
          </div>
          <el-tag v-else type="warning" size="small">待分配</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="工单状态">
          <el-tag :type="getStatusType(detailData.orderStatus)" size="small">
            {{ getStatusText(detailData.orderStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="工单备注" :span="2">
          <div class="remark-box">{{ detailData.orderRemark || '暂无备注' }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="创建人">{{ detailData.createBy || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(detailData.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新人">{{ detailData.updateBy || '-' }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ parseTime(detailData.updateTime) }}</el-descriptions-item>
      </el-descriptions>

      <div v-if="detailData.annex" class="attachment-section">
        <h4>附件信息</h4>
        <div class="attachment-list">
          <div
              v-for="(filePath, index) in getFileList(detailData.annex)"
              :key="index"
              class="attachment-item"
          >
            <el-icon>
              <Document/>
            </el-icon>
            <span>{{ getFileName(filePath) }}</span>
            <el-button type="primary" link @click="downloadFile(filePath)">
              下载
            </el-button>
          </div>
        </div>
      </div>

      <!-- 操作日志 -->
      <div class="operation-log">
        <h4>操作记录</h4>
        <el-timeline v-if="operationLogs.length > 0">
          <el-timeline-item
              v-for="(log, index) in operationLogs"
              :key="index"
              :timestamp="log.operateTime"
              :type="getLogType(log.operateType)"
              placement="top"
          >
            <div class="log-content">
              <span class="log-user">{{ log.operateUser }}</span>
              <span class="log-action">{{ log.operateDesc }}</span>
            </div>
          </el-timeline-item>
        </el-timeline>
        <el-empty v-else description="暂无操作记录" :image-size="80"/>
      </div>
    </el-drawer>

    <!-- 添加或修改维修工单对话框 -->
    <el-dialog
        :title="title"
        v-model="open"
        width="800px"
        append-to-body
        :close-on-click-modal="false"
        class="order-dialog"
    >
      <el-form ref="repairOrderRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工单编号" prop="orderNo">
              <el-input
                  v-model="form.orderNo"
                  placeholder="请输入工单编号"
                  :disabled="isEdit"
              >
                <template #prefix>
                  <el-icon>
                    <Tickets/>
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input
                  v-model="form.projectName"
                  placeholder="请输入项目名称"
                  :disabled="isEdit"
              >
                <template #prefix>
                  <el-icon>
                    <OfficeBuilding/>
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="工单内容" prop="orderContent">
          <el-input
              v-model="form.orderContent"
              type="textarea"
              :rows="4"
              placeholder="请详细描述工单内容"
              :disabled="isEdit"
              maxlength="500"
              show-word-limit
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12" v-if="isEdit">
            <el-form-item label="派单时间" prop="assignTime">
              <el-date-picker
                  v-model="form.assignTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="派单时间"
                  disabled
                  style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="责任人" prop="userId">
              <el-select
                  v-model="form.userId"
                  placeholder="请选择责任人"
                  clearable
                  filterable
                  style="width: 100%"
              >
                <el-option
                    v-for="user in userOptions"
                    :key="user.userId"
                    :label="user.nickName || user.userName"
                    :value="user.userId"
                >
                  <div class="user-option">
                    <div class="user-info">
                      <span class="user-name">{{ user.nickName || user.userName }}</span>
                    </div>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="附件上传" prop="annex">
          <file-upload
              v-model="form.annex"
              :on-remove="handleRemoveFile"
              :limit="5"
              :file-size="10"
          />
        </el-form-item>

        <el-form-item label="工单备注" prop="orderRemark">
          <el-input
              v-model="form.orderRemark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
              maxlength="200"
              show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            {{ isEdit ? '派 单' : '确 定' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="RepairOrder">
import {ref, reactive, toRefs, onMounted, computed} from 'vue';
import {
  listRepairOrder,
  getRepairOrder,
  delRepairOrder,
  addRepairOrder,
  updateRepairOrder,
  deleteFile,
  getRepairOrderStatistics,
  getRepairOrderLogs
} from "@/api/repairOrder/repairOrder";
import {listUser} from "@/api/system/user";
import {ElMessage, ElMessageBox, ElLoading} from 'element-plus';
// 导入图标
import {
  Tools,
  Plus,
  Download,
  Edit,
  Delete,
  Search,
  Refresh,
  View,
  Hide,
  Setting,
  Clock,
  CircleCheck,
  Paperclip,
  ArrowDown,
  ArrowUp,
  DocumentCopy,
  Printer,
  Document,
  Tickets,
  OfficeBuilding,
  InfoFilled,
  Warning,
  Loading
} from '@element-plus/icons-vue';

const {proxy} = getCurrentInstance();
const {repair_status} = proxy.useDict('repair_status');

// 响应式变量
const repairOrderList = ref([]);
const open = ref(false);
const loading = ref(true);
const submitLoading = ref(false);
const showSearch = ref(true);
const showAdvanced = ref(false);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const userOptions = ref([]);
const detailVisible = ref(false);
const detailData = ref({});
const isEdit = ref(false);
const selectedRows = ref([]);
const dateRange = ref([]);
const operationLogs = ref([]);

// 统计数据
const statisticsData = ref([
  {
    type: 'total',
    label: '工单总数',
    value: 0,
    icon: 'DocumentCopy',
    trend: 0
  },
  {
    type: 'pending',
    label: '待处理',
    value: 0,
    icon: 'Warning',
    trend: 0
  },
  {
    type: 'processing',
    label: '处理中',
    value: 0,
    icon: 'Loading',
    trend: 0
  },
  {
    type: 'completed',
    label: '已完成',
    value: 0,
    icon: 'CircleCheck',
    trend: 0
  },
]);

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    },
  },
  {
    text: '最近一月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    },
  },
  {
    text: '最近三月',
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
      return [start, end];
    },
  },
];
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    orderContent: null,
    projectName: null,
    orderStatus: null,
  },
  rules: {
    orderNo: [
      {required: true, message: "工单编号不能为空", trigger: "blur"}
    ],
    orderContent: [
      {required: true, message: "工单内容不能为空", trigger: "blur"}
    ],
    projectName: [
      {required: true, message: "项目名称不能为空", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);

// 获取统计数据
async function getStatistics() {
  try {
    // 如果后端没有统计接口，可以通过查询所有数据来统计
    const response = await getRepairOrderStatistics();

    // 更新统计数据
    statisticsData.value[0].value = response.data.total || 0; // 总数
    statisticsData.value[1].value = response.data.pending || 0; // 待处理
    statisticsData.value[2].value = response.data.processing || 0; // 处理中
    statisticsData.value[3].value = response.data.completed || 0; // 已完成

    // 计算趋势（这里模拟数据，实际应该对比上期数据）
    statisticsData.value.forEach(stat => {
      stat.trend = Math.floor(Math.random() * 30) - 15; // 随机生成-15到15的趋势
    });
  } catch (error) {
    console.error('获取统计数据失败:', error);
  }
}

// 获取操作日志
async function getOperationLogs(orderId) {
  try {
    // 模拟操作日志数据，实际应该从后端获取
    const response = await getRepairOrderLogs(orderId);
    operationLogs.value = response.data.map(log => ({
      logId: log.log_id,
      operateUser: log.operate_user,
      operateType: log.operate_type,
      operateDesc: log.operate_desc,
      orderId: log.order_id,
      operateTime: log.operate_time
    }));

    // 按时间倒序排序
    operationLogs.value.sort((a, b) => new Date(b.operateTime) - new Date(a.operateTime));
  } catch (error) {
    console.error('获取操作日志失败:', error);
    operationLogs.value = [];
  }
}

// 获取日志类型
function getLogType(type) {
  const typeMap = {
    'create': 'primary',
    'assign': 'warning',
    'update': 'info',
    'complete': 'success'
  };
  return typeMap[type] || 'info';
}

// 获取状态类型
function getStatusType(status) {
  const statusMap = {
    '0': 'warning',
    '1': 'primary',
    '2': 'success'
  };
  return statusMap[status] || 'info';
}

// 获取状态文本
function getStatusText(status) {
  const dict = repair_status.value.find(item => item.value === status);
  return dict ? dict.label : '未知';
}

// 判断是否可以派单
function canDispatch(row) {
  // admin 可以编辑所有工单
  const isAdmin = proxy.$auth.hasRole('admin');
  if (isAdmin) return true;
  return row.orderStatus === '0' || row.orderStatus === '1';
}

// 表格行样式
function tableRowClassName({row}) {
  if (row.orderStatus === '0') {
    return 'warning-row';
  } else if (row.orderStatus === '2') {
    return 'success-row';
  }
  return '';
}

// 获取文件名
// 将逗号分隔的文件路径字符串转换为数组
function getFileList(annexString) {
  if (!annexString) return [];
  // 分割字符串并去除每个路径的前后空格
  return annexString.split(',').map(path => path.trim()).filter(path => path);
}

// 获取文件数量
function getFileCount(annexString) {
  if (!annexString) return 0;
  return getFileList(annexString).length;
}

// 修改原有的 getFileName 方法（如果需要的话）
function getFileName(url) {
  if (!url) return '';
  const parts = url.trim().split('/');
  return parts[parts.length - 1] || '附件';
}

// 切换高级筛选
function toggleAdvanced() {
  showAdvanced.value = !showAdvanced.value;
}

// 显示详情
async function showDetail(row) {
  detailData.value = {...row};
  detailVisible.value = true;
  // 获取操作日志
  await getOperationLogs(row.id);
}

// 从详情页编辑
function handleUpdateFromDetail() {
  detailVisible.value = false;
  handleUpdate(detailData.value);
}

// 打印功能
function handlePrint() {
  window.print();
}

// 复制工单
function handleCopy(row) {
  const newForm = {...row};
  delete newForm.id;
  newForm.orderNo = `${row.orderNo}-COPY-${Date.now()}`;
  newForm.orderStatus = '0'; // 复制的工单状态为待处理
  newForm.finishBy = null;
  newForm.finishTime = null;
  newForm.userId = null;
  form.value = newForm;
  isEdit.value = false;
  open.value = true;
  title.value = "复制工单";
}

// 下载文件
/*function downloadFile(url) {
  if (!url) {
    ElMessage.warning('暂无附件');
    return;
  }
  window.open(import.meta.env.VITE_APP_BASE_API + url);
}*/
// 下载文件
async function downloadFile(url) {
  if (!url) {
    ElMessage.warning('暂无附件');
    return;
  }

  // 将逗号分隔的URL字符串转换为数组
  const urls = url.split(',').map(u => u.trim()).filter(u => u);

  if (urls.length === 0) {
    ElMessage.warning('暂无附件');
    return;
  }

  const loading = ElLoading.service({
    lock: true,
    text: `正在下载文件 (0/${urls.length})...`,
    background: 'rgba(0, 0, 0, 0.7)',
  });

  let successCount = 0;
  let failCount = 0;

  try {
    for (let i = 0; i < urls.length; i++) {
      const currentUrl = urls[i];

      // 更新加载提示
      loading.setText(`正在下载文件 (${i + 1}/${urls.length})...`);

      try {
        const response = await fetch(import.meta.env.VITE_APP_BASE_API + currentUrl, {
          method: 'GET',
          headers: {
            'Authorization': 'Bearer ',// + getToken(),
          }
        });

        if (!response.ok) {
          throw new Error('下载失败');
        }

        const blob = await response.blob();
        const fileName = currentUrl.split('/').pop() || `download_${i + 1}`;
        const fileExt = fileName.split('.').pop().toLowerCase();

        const mimeTypes = {
          'txt': 'text/plain;charset=utf-8',
          'pdf': 'application/pdf',
          'doc': 'application/msword',
          'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          'xls': 'application/vnd.ms-excel',
          'xlsx': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          'ppt': 'application/vnd.ms-powerpoint',
          'pptx': 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
        };

        const typedBlob = new Blob([blob], {
          type: mimeTypes[fileExt] || 'application/octet-stream'
        });

        const downloadUrl = window.URL.createObjectURL(typedBlob);
        const link = document.createElement('a');
        link.href = downloadUrl;
        link.download = fileName;
        link.style.display = 'none';

        document.body.appendChild(link);
        link.click();

        setTimeout(() => {
          window.URL.revokeObjectURL(downloadUrl);
          document.body.removeChild(link);
        }, 100);

        successCount++;

        // 添加延迟，避免同时触发太多下载
        if (i < urls.length - 1) {
          await new Promise(resolve => setTimeout(resolve, 500));
        }
      } catch (error) {
        console.error(`下载文件失败: ${currentUrl}`, error);
        failCount++;
      }
    }

    if (successCount > 0 && failCount === 0) {
      ElMessage.success(`成功下载 ${successCount} 个文件`);
    } else if (successCount > 0 && failCount > 0) {
      ElMessage.warning(`成功下载 ${successCount} 个文件，失败 ${failCount} 个`);
    } else {
      ElMessage.error('所有文件下载失败');
    }
  } catch (error) {
    console.error('下载过程出错:', error);
    ElMessage.error('下载失败，请重试');
  } finally {
    loading.close();
  }
}

/** 查询维修工单列表 */
async function getList() {
  loading.value = true;
  try {
    const params = {...queryParams.value};

    // 处理日期范围
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0];
      params.endDate = dateRange.value[1];
    }

    const response = await listRepairOrder(params);
    repairOrderList.value = response.rows;
    total.value = response.total;

    // 获取统计数据
    await getStatistics();
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error('获取工单列表失败');
  } finally {
    loading.value = false;
  }
}

// 删除附件
function handleRemoveFile(file) {
  ElMessageBox.confirm('确认删除该附件吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteFile(file.url).then(() => {
      form.value.annex = null;
      ElMessage.success("删除成功");
    }).catch(() => {
      ElMessage.error("删除失败");
    });
  }).catch(() => {
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderNo: null,
    orderContent: null,
    projectName: null,
    assignTime: null,
    finishTime: null,
    finishBy: null,
    annex: null,
    userId: null,
    orderStatus: '0', // 默认待处理
    orderRemark: null,
  };
  proxy.resetForm("repairOrderRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  dateRange.value = [];
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
  selectedRows.value = selection;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  isEdit.value = false;
  open.value = true;
  title.value = "新建维修工单";
  // 生成工单编号
  form.value.orderNo = `WO${new Date().getTime()}`;
  form.value.assignTime = parseTime(new Date());
}

// 获取用户列表
async function getUserList() {
  try {
    const response = await listUser();
    userOptions.value = response.rows || [];
  } catch (error) {
    console.error('获取用户列表失败:', error);
  }
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();

  // 获取当前用户角色信息
  const isAdmin = proxy.$auth.hasRole('admin'); // 检查是否是admin角色

  // 如果不是admin，则检查工单状态
  if (!isAdmin) {
    isEdit.value = true;
    if (row && row.id) {
      if (row.orderStatus === '2') {
        ElMessage.warning("该工单已完成，无法修改");
        return;
      }
    } else if (selectedRows.value.length > 0) {
      const selectedRow = selectedRows.value[0];
      if (selectedRow.orderStatus === '2') {
        ElMessage.warning("该工单已完成，无法修改");
        return;
      }
    }
  }
  isEdit.value = true;

  const _id = row.id || ids.value;

  try {
    const response = await getRepairOrder(_id);
    form.value = response.data;
    open.value = true;
    title.value = "派单处理";
  } catch (error) {
    ElMessage.error("获取工单信息失败");
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["repairOrderRef"].validate(valid => {
    debugger
    if (valid) {
      submitLoading.value = true;

      // 设置责任人信息
      if (form.value.userId) {
        const user = userOptions.value.find(u => u.userId === form.value.userId);
        if (user) {
          form.value.finishBy = user.nickName || user.userName;
        }
      }

      // 如果是派单，更新状态为处理中
      if (isEdit.value && form.value.userId) {
        form.value.orderStatus = '1';
        form.value.assignTime = new Date();
      }

      const submitFn = form.value.id != null ? updateRepairOrder : addRepairOrder;
      const successMsg = form.value.id != null ? "派单成功" : "新增成功";

      submitFn(form.value).then(response => {
        ElMessage.success(successMsg);
        open.value = false;
        getList();
      }).catch(() => {
        ElMessage.error("操作失败");
      }).finally(() => {
        submitLoading.value = false;
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  const deletePromises = [];

  ElMessageBox.confirm('确定要删除选中的工单吗？删除后不可恢复！', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 处理附件删除
    if (Array.isArray(ids.value) && ids.value.length > 0) {
      repairOrderList.value.forEach(item => {
        if (ids.value.includes(item.id) && item.annex) {
          deletePromises.push(deleteFile(item.annex));
        }
      });
    } else if (row.annex) {
      deletePromises.push(deleteFile(row.annex));
    }

    // 先删除附件，再删除工单
    return Promise.all(deletePromises).then(() => {
      return delRepairOrder(_ids);
    });
  }).then(() => {
    getList();
    ElMessage.success("删除成功");
  }).catch((error) => {
    if (error !== 'cancel') {
      ElMessage.error("删除失败");
    }
  });
}

/** 导出按钮操作 */
function handleExport() {
  ElMessageBox.confirm('确定要导出工单数据吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    proxy.download('repairOrder/repairOrder/export', {
      ...queryParams.value
    }, `维修工单_${new Date().getTime()}.xlsx`);
  });
}

// 初始化
onMounted(() => {
  getList();
  getUserList();
});
</script>

<style scoped lang="scss">
.repair-order-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);

  // 页面标题
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;

      .page-title {
        font-size: 24px;
        font-weight: 600;
        color: #303133;
        margin: 0;
        display: flex;
        align-items: center;

        .el-icon {
          margin-right: 8px;
          color: #409eff;
        }
      }
    }
  }

  // 统计卡片
  .statistics-cards {

    .stat-card {
      background: #fff;
      border-radius: 8px;
      padding: 20px;
      position: relative;
      overflow: hidden;
      transition: all 0.3s;
      margin-bottom: 16px;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.08);
      }

      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 4px;
        height: 100%;
        background: currentColor;
      }

      &.stat-total {
        color: #409eff;

        .stat-icon {
          background: #e6f2ff;
        }
      }

      &.stat-pending {
        color: #e6a23c;

        .stat-icon {
          background: #fdf6ec;
        }
      }

      &.stat-processing {
        color: #909399;

        .stat-icon {
          background: #f4f4f5;
        }
      }

      &.stat-completed {
        color: #67c23a;

        .stat-icon {
          background: #e8f5e9;
        }
      }

      .stat-icon {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 12px;

        .el-icon {
          font-size: 24px;
        }
      }

      .stat-content {
        .stat-value {
          font-size: 32px;
          font-weight: 600;
          line-height: 1;
          margin-bottom: 8px;
        }

        .stat-label {
          font-size: 14px;
          color: #909399;
        }
      }

      .stat-trend {
        position: absolute;
        top: 20px;
        right: 20px;
        font-size: 14px;

        .up {
          color: #67c23a;
        }

        .down {
          color: #f56c6c;
        }
      }
    }
  }

  // 搜索卡片
  .search-card {
    margin-bottom: 20px;

    :deep(.el-card__body) {
      padding-bottom: 0;
    }

    .search-buttons {
      text-align: right;
      margin-bottom: 20px;
    }

    .table-operations {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 0;
      border-top: 1px solid #ebeef5;

      .operations-left {
        display: flex;
        gap: 10px;
      }

      .operations-right {
        display: flex;
        gap: 8px;
      }
    }
  }

  // 表格卡片
  .table-card {
    :deep(.el-card__body) {
      padding: 0;
    }

    .el-table {
      :deep(.el-table__header) {
        th {
          background-color: #f5f7fa;
          color: #303133;
          font-weight: 600;
        }
      }

      :deep(.warning-row) {
        background-color: #fef0f0;
      }

      :deep(.success-row) {
        background-color: #f0f9ff;
      }

      .time-cell {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 4px;

        .el-icon {
          color: #909399;
        }
      }

      .user-info {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;

        .el-avatar {
          background-color: #409eff;
          color: #fff;
          font-size: 12px;
        }
      }

      .text-muted {
        color: #c0c4cc;
      }
    }
  }

  // 状态选项样式
  .status-option {
    display: flex;
    align-items: center;
    gap: 8px;

    .status-dot {
      width: 8px;
      height: 8px;
      border-radius: 50%;

      &.status-0 {
        background-color: #e6a23c;
      }

      &.status-1 {
        background-color: #409eff;
      }

      &.status-2 {
        background-color: #67c23a;
      }
    }
  }

  // 详情抽屉
  .detail-drawer {
    :deep(.el-drawer__header) {
      margin-bottom: 0;
      padding-bottom: 0;
    }

    .detail-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20px 20px;
      border-bottom: 1px solid #ebeef5;
    }

    .detail-descriptions {
      margin: 20px;

      .detail-value {
        font-weight: 600;
        color: #409eff;
      }

      .content-box {
        background: #f5f7fa;
        padding: 12px;
        border-radius: 4px;
        line-height: 1.6;
      }

      .time-info {
        display: flex;
        align-items: center;
        gap: 4px;

        .el-icon {
          color: #909399;
        }
      }

      .user-detail {
        display: flex;
        align-items: center;
        gap: 8px;

        .el-avatar {
          background-color: #409eff;
          color: #fff;
        }
      }

      .remark-box {
        background: #fef0f0;
        padding: 12px;
        border-radius: 4px;
        color: #e6a23c;
      }
    }

    .attachment-section {
      margin: 20px;

      h4 {
        margin: 0 0 12px 0;
        font-size: 16px;
        color: #303133;
      }

      .attachment-list {
        background: #f5f7fa;
        padding: 16px;
        border-radius: 4px;

        .attachment-item {
          display: flex;
          align-items: center;
          gap: 8px;

          .el-icon {
            color: #909399;
            font-size: 20px;
          }

          span {
            flex: 1;
          }
        }
      }
    }

    .operation-log {
      margin: 20px;

      h4 {
        margin: 0 0 16px 0;
        font-size: 16px;
        color: #303133;
      }

      .log-content {
        .log-user {
          font-weight: 500;
          color: #409eff;
          margin-right: 8px;
        }

        .log-action {
          color: #606266;
        }
      }
    }
  }

  // 对话框样式
  .order-dialog {
    :deep(.el-dialog__header) {
      background-color: #f5f7fa;
      padding: 20px;

      .el-dialog__title {
        font-size: 18px;
        color: #303133;
      }
    }

    :deep(.el-dialog__body) {
      padding: 20px;
    }

    .user-option {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 4px 0;

      .el-avatar {
        background-color: #409eff;
        color: #fff;
        flex-shrink: 0;
      }

      .user-info {
        flex: 1;

        .user-name {
          display: block;
          font-weight: 500;
          color: #303133;
        }

        .user-dept {
          display: block;
          font-size: 12px;
          color: #909399;
          margin-top: 2px;
        }
      }
    }

    .upload-container {
      .upload-tip {
        display: flex;
        align-items: center;
        gap: 4px;
        margin-top: 8px;
        color: #909399;
        font-size: 12px;

        .el-icon {
          color: #e6a23c;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .repair-order-container {
    padding: 10px;

    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 10px;

      .header-left {
        width: 100%;
      }
    }

    .detail-drawer {
      :deep(.el-drawer) {
        width: 90% !important;
      }
    }
  }
}

// 全局样式调整
:deep(.el-select-dropdown) {
  min-width: 240px !important;
}

:deep(.pagination-container) {
  padding: 20px;
  background: #fff;
}

.attachment-section {
  margin: 20px;

  h4 {
    margin: 0 0 12px 0;
    font-size: 16px;
    color: #303133;
  }

  .attachment-list {
    background: #f5f7fa;
    padding: 16px;
    border-radius: 4px;

    .attachment-item {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 8px 0;

      &:not(:last-child) {
        border-bottom: 1px solid #e4e7ed;
      }

      .el-icon {
        color: #909399;
        font-size: 20px;
      }

      span {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}

</style>
