无人机管理后台前端(已迁走)
张含笑
2025-11-22 1a007aecdbeef0ec7adcc1478e2143236c19a0de
Merge remote-tracking branch 'refs/remotes/origin/feature/v8.0/8.0.3' into test
2 files modified
5 files added
8790 ■■■■■ changed files
src/api/tickets/ticket.js 10 ●●●● patch | view | raw | blame | history
src/views/tickets/ticket-copy.vue 2535 ●●●●● patch | view | raw | blame | history
src/views/tickets/ticket.vue 3735 ●●●● patch | view | raw | blame | history
src/views/tickets/ticketComponent/CreateTicketDialog.vue 710 ●●●●● patch | view | raw | blame | history
src/views/tickets/ticketComponent/DispatchDialog.vue 244 ●●●●● patch | view | raw | blame | history
src/views/tickets/ticketComponent/RecheckDialog.vue 117 ●●●●● patch | view | raw | blame | history
src/views/tickets/ticketComponent/TicketDetailDialog.vue 1439 ●●●●● patch | view | raw | blame | history
src/api/tickets/ticket.js
@@ -73,14 +73,20 @@
}
// 新增接口:获取状态统计数据
export const getstatusCount = (params) => {
export const getstatusCount1 = (params) => {
  return request({
    url: '/drone-device-core/jobEvent/getstatusCount',
    method: 'get',
    params,
  })
}
export const getstatusCount = (data) => {
  return request({
    url: '/drone-device-core/jobEvent/getstatusCount',
    method: 'post',
    data,
  })
}
export const getStepInfo = (eventNum) => {
  return request({
    url: '/drone-device-core/jobEvent/getStepInfo',
src/views/tickets/ticket-copy.vue
New file
@@ -0,0 +1,2535 @@
<template>
  <basic-container>
    <el-tabs v-model="activeTab" @tab-click="handleTabChange">
      <el-tab-pane
        v-for="tab in filteredTabs"
        :key="tab.name"
        :label="`${tab.label} (${tab.count})`"
        :name="tab.name"
      >
        <basic-main-content>
          <!-- 查询条件筛选栏 -->
          <div class="ztzf-form-search">
            <el-form :model="filters" inline>
              <el-row :gutter="24">
                <el-col :span="4">
                  <el-form-item label="关键字:">
                    <el-input
                      v-model="filters.keyword"
                      placeholder="请输入关键字"
                      class="filter-item"
                      clearable
                      @clear="handleKeyWords"
                      @keyup.enter="handleSearch"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="5">
                  <el-form-item label="选择日期:">
                  <el-date-picker
                    v-model="filters.dateRange"
                    type="daterange"
                    class="filter-item"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :default-value="datePickerDefaultVal"
                  >
                  </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="选择状态:">
                  <el-select
                  :disabled="activeTab !== 'all'"
                    v-model="filters.status"
                    placeholder="请选择状态"
                    class="filter-item"
                    clearable
                    @change="handleSearch"
                  >
                    <el-option
                      v-for="item in statuses"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="选择算法:">
                  <el-tree-select
                    style="z-index: 1000"
                    :teleported="false"
                    class="custom-tree-select"
                    :style="{ width: pxToRem(186) }"
                    v-model="dictKey"
                    :data="dataList"
                    :default-expanded-keys="[dictKey]"
                    :props="treePropsSF"
                    :render-after-expand="false"
                    :default-checked-keys="checkedKeys"
                    node-key="id"
                    multiple
                    show-checkbox
                    collapse-tags
                    collapse-tags-tooltip
                    clearable
                    @check="handleCheck"
                    @clear="handleClear"
                  />
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item label="复核状态:">
                  <el-select
                    v-model="filters.isReview"
                    placeholder="请选择复核状态"
                    class="filter-item"
                    clearable
                    @change="handleSearch"
                  >
                    <el-option
                      v-for="item in reviewStatuses"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="3">
                  <el-button type="primary" icon="el-icon-search" @click="handleSearch"
                    >搜索</el-button
                  >
                  <el-button icon="el-icon-refresh" @click="handleReset">清空</el-button>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <!-- 表格部分 -->
          <avue-crud
            class="ztzf-public-general-avue-crud"
            ref="avueCrud"
            v-model="tableData"
            :option="option"
            :data="tableData"
            v-model:page="page"
            @size-change="sizeChange"
            @current-change="handleCurrentChange"
            @refresh-change="refreshChange"
            :table-loading="loading"
            @selection-change="handleSelectionChange"
            :permission="permissionList"
            v-if="activeTab === tab.name"
          >
            <template #orderNumber="{ row }">
              <el-tooltip-copy :content="row.orderNumber" :showCopyText="true" textAlign="left">
                {{ row.orderNumber }}
              </el-tooltip-copy>
            </template>
            <template #orderName="{ row }">
              <el-tooltip-copy :content="row.orderName" :showCopyText="true" textAlign="left">
                {{ row.orderName }}
              </el-tooltip-copy>
            </template>
            <template #menu-left>
              <el-button
                v-if="(activeTab === 'all' || activeTab === 'myTickets') && permissionList.addBtn"
                type="primary"
                icon="el-icon-plus"
                @click="handleAdd"
                >新建工单
              </el-button>
              <el-button
                v-if="activeTab === 'pending' && permissionList.reviewBtn"
                type="success"
                icon="el-icon-check"
                @click="openReviewDialog"
                >批量审核
              </el-button>
              <el-button
                v-if="permissionList.exportBtn"
                type="success"
                plain
                icon="el-icon-download"
                @click="exportData"
                >导出
              </el-button>
            </template>
            <template #menu="{ row }">
              <template v-if="row.status === -1">
                <el-button type="text" icon="el-icon-edit" @click="handleEdit(row)">编辑</el-button>
                <el-button
                  type="text"
                  icon="el-icon-delete"
                  class="danger-button"
                  @click="handleDelete(row)"
                  >删除
                </el-button>
              </template>
              <template v-else>
                <el-button type="text" icon="el-icon-view" @click="handleViewDetail(row)"
                  >详情
                </el-button>
              </template>
              <template  v-if="row.status === 4 && activeTab === 'completed'">
                <el-button type="text" icon="el-icon-download"  @click="exportTheTick(row)"
                  >导出
                </el-button>
              </template>
              <template v-if="permission.tickets_repeat_review">
                <el-button
                  v-if="row.status === 4 && row.isReview !== 1"
                  type="text"
                  icon="el-icon-check"
                  @click="reCheck(row)"
                  >复核
                </el-button>
              </template>
            </template>
            <template #status="{ row }">
              <span
                :style="getStatusTagType(row.status) ? 'color:' + getStatusTagType(row.status) : ''"
              >
                {{ mapStatus(row.status) }}
              </span>
            </template>
            <template #keyData="{ row }">
              <span>{{ row.address }}</span>
            </template>
            <template #isReview="{ row }">
              <span>{{ showIsReviewText(row) }}</span>
            </template>
          </avue-crud>
        </basic-main-content>
      </el-tab-pane>
    </el-tabs>
    <!-- 新建工单对话框 -->
        <create-ticket-dialog
        v-model="dialogVisible"
        :departments="departments"
        :department-users="departmentUsers"
        :types="types"
        :all-algorithms="allAlgorithms"
        :edit-data="editFormData"
        :map-center="inputMapShowDefaultCenter"
        @create-success="handleCreateSuccess"
        @draft-success="handleDraftSuccess"
        @create-error="handleCreateError"
      />
    <!-- 工单详情对话框 -->
      <ticket-detail-dialog
        v-model="detailVisible"
        :current-detail="currentDetail"
        :current-index="currentIndex"
        :total-items="tableData.length"
        :algorithms="algorithms2"
        :types="types"
        :permission="permission"
        :step-status-list="stepStatusList"
        :work-type="workType"
        @detail-success="handleDetailSuccess"
        @detail-error="handleDetailError"
        @prev-item="handlePrevItem"
        @next-item="handleNextItem"
        @update:current-detail="handleCurrentDetailUpdate"
        @approve-and-dispatch="handleApproveAndDispatch"
      />
    <!-- 派发工单对话框 -->
      <dispatch-dialog
        v-model="dispatchDialogVisible"
        :current-detail="currentDetail"
        :departments="departments"
        :department-users="departmentUsers"
        :algorithms="algorithms"
        :types="types"
        @dispatch-success="handleDispatchSuccess"
        @dispatch-error="handleDispatchError"
      />
    <!-- 添加在其他 dialog 组件之后 -->
    <el-dialog
      v-model="reviewDialogVisible"
      title="批量审核"
      width="1100"
      append-to-body
      class="ztzf-dialog-mange"
      custom-class="review-dialog"
      @close="cancleBatchReject"
    >
      <div class="review-container">
        <div class="review-image-wrapper">
          <!-- 修改左右箭头的显示条件 -->
          <el-button
            v-if="selections.length > 1 && currentReviewImage"
            class="arrow-button left"
            @click="handlePrevImage"
            icon="el-icon-arrow-left"
          >
          </el-button>
          <div class="review-image-container">
            <!-- <el-image v-if="currentReviewImage" :src="getThumbUrl(currentReviewImage)" fit="fill"
              :preview-src-list="getImageList()" :initial-index="currentImageIndex - 1" class="preview-image"
              style="cursor: pointer"> -->
            <el-image
              v-if="currentReviewImage"
              :src="getPreviewUrl(currentReviewImage)"
              fit="fill"
              :initial-index="currentImageIndex - 1"
              class="preview-image"
              style="cursor: pointer"
            >
              <template #error>
                <div class="image-error">
                  <i class="el-icon-picture-outline"></i>
                  <span>图片加载失败</span>
                </div>
              </template>
            </el-image>
            <div v-else class="no-image">暂无图片</div>
          </div>
          <!-- 修改右箭头的显示条件 -->
          <el-button
            v-if="selections.length > 1 && currentReviewImage"
            class="arrow-button right"
            @click="handleNextImage"
            icon="el-icon-arrow-right"
          >
          </el-button>
        </div>
        <!-- 修改分页器的显示条件 -->
        <div class="review-pagination" v-if="selections.length > 1 && currentReviewImage">
          <el-pagination
            small
            layout="prev, pager, next"
            hide-on-single-page
            :total="selections.length"
            :current-page="currentImageIndex"
            :page-size="1"
            @current-change="handleImagePageChange"
          >
          </el-pagination>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleBatchApprove" icon="el-icon-check"
            >通过
          </el-button>
          <el-button type="danger" @click="handleBatchReject" icon="el-icon-close"
            >不通过
          </el-button>
          <el-button @click="cancleBatchReject" icon="el-icon-circle-close">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 复核弹出层 -->
    <recheck-dialog
  v-model="reCheckDialog"
  :recheck-data="reCheckData"
  @recheck-success="handleRecheckSuccess"
/>
  </basic-container>
</template>
<script>
import { pxToRem, pxToRemNum } from '@/utils/rem';
import { getSmallImg, getShowImg } from '@/utils/util';
import { ElMessageBox, ElLoading } from 'element-plus';
import { calculateDefaultRange } from '@/utils/util';
import { gcj02ToWgs84, wgs84ToGcj02 } from '@/utils/coordinateTransformation';
import _ from 'lodash';
import {
  getList,
  createTicket,
  getTicketInfo,
  flowEvent,
  getstatusCount,
  getStepInfo,
  exportTheTicket
} from '@/api/tickets/ticket';
import { getSFDictionaryTree } from '@/api/job/task';
import { export_json_to_excel } from '@/utils/exportExcel';
import geoJson from '@/assets/geoJson.json';
import { mapGetters } from 'vuex';
import { getAdcodeObj } from '@/utils/disposeData';
import elTooltipCopy from '@/components/ElTooltipCopy.vue';
import getBaseConfig from '@/buildConfig/config';
import CreateQRcode from '@/components/CreateQRcode/CreateQRcode.vue';
import { CircleClose } from '@element-plus/icons-vue';
import RecheckDialog from '@/views/tickets/ticketComponent/RecheckDialog.vue';
import DispatchDialog from '@/views/tickets/ticketComponent/DispatchDialog.vue';
import CreateTicketDialog from '@/views/tickets/ticketComponent/CreateTicketDialog.vue';
import TicketDetailDialog from '@/views/tickets/ticketComponent/TicketDetailDialog.vue';
const { envName } = getBaseConfig();
function regExp(label, name) {
  var reg = new RegExp(label + '=([^&]*)(&|$)', 'g');
  return name.match(reg)[0].split('=')[1];
}
export default {
  components: { elTooltipCopy, CreateQRcode,RecheckDialog,DispatchDialog,CreateTicketDialog,TicketDetailDialog, },
  name: 'TicketPage',
  data() {
    return {
      currentIndex: null, // 当前显示的数据索引
      finalizeLoading: false,
      createoredit: '',
      activeTab: 'all',
      // tabs 只保留静态结构,不做权限判断
      tabs: [
        { label: '全部工单', name: 'all', value: null, count: 0 },
        { label: '待审核', name: 'pending', value: 2, count: 0 },
        { label: '待处理', name: 'processing', value: 0, count: 0 },
        { label: '处理中', name: 'inProgress', value: 3, count: 0 },
        { label: '已完成', name: 'completed', value: 4, count: 0 },
        // { label: "已完结", name: "closed", value: 5, count: 0 },
        { label: '我的工单', name: 'myTickets', value: null, count: 0 },
      ],
      filters: {
        keyword: '',
        department: '',
        type: '',
        dateRange: [],
        status: '',
        algorithm: '', // 新增算法筛选字段
        isReview: '', // 添加复核状态筛选字段
      },
      departments: [],
      types: [],
      allAlgorithms: [],
      handlers: [
        { label: '处理人A', value: 'handlerA' },
        { label: '处理人B', value: 'handlerB' },
      ],
      algorithms: [],
      algorithms2: [],
      algorithms3: [],
      statuses: [
        { label: '待审核', value: '2' },
        { label: '待处理', value: '0' },
        { label: '处理中', value: '3' },
        { label: '已完成', value: '4' },
      ],
      reviewStatuses: [
        { label: '否', value: 0 },
        { label: '是', value: 1 },
      ],
      tableData: [],
      option: {
        border: true,
        stripe: false,
        selection: true, // 添加多选功能
        index: true, // 保留序号功能
        indexLabel: '序号',
        indexWidth: 60,
        menuWidth: 150,
        searchMenuSpan: 6,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        menu: true,
        page: true,
        height: 'auto',
        calcHeight: 196,
        column: [
          // { label: "序号", prop: "id", width: 70 },
          { label: '工单编号', prop: 'orderNumber', width: 170 },
          { label: '工单名称', prop: 'orderName', width: 150, overHidden: true, tooltip: true },
          { label: '所属部门', prop: 'department', overHidden: true, tooltip: true },
          { label: '发起任务时间', prop: 'startTime', width: 160, overHidden: true },
          { label: '关联算法', prop: 'aiType', overHidden: true, tooltip: true },
          {
            label: '工单类型',
            prop: 'type',
            width: 110,
            overHidden: true,
            tooltip: true,
            type: 'select',
            dicData: [],
          },
          {
            label: '工单内容',
            prop: 'content',
            slot: true,
            width: 152,
            overHidden: true,
          },
          { label: '创建人', prop: 'creator', width: 120, overHidden: true },
          { label: '处理人', prop: 'handler', width: 120, overHidden: true },
          {
            slot: true,
            hide: envName === 'jiangwu' ? true : false,
            label: '复核状态',
            prop: 'isReview',
            width: 90,
          },
          { label: '工单状态', prop: 'status', slot: true, width: 90 },
        ],
      },
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      dialogVisible: false,
       editFormData: null, // 专门用于存储编辑数据的对象
        createoredit: '', // 可以删除这个字段,因为组件内部会判断
      detailVisible: false,
      currentDetail: {},
      departmentUsers: {},
      loading: false,
      globalCounts: {},
      mapLoaded: false,
      isFetching: false,
      mapParams: {
        zoom: 15,
        center: null, // 初始设为 null,等待动态设置
      },
      dispatchDepartment: '', // 新增:派发部门
      dispatchHandler: '', // 新增:派发处理人
      dispatchDialogVisible: false, // 新增:派发对话框可见性
      stepInfos: [], // 新增:存储步骤信息
      fixedStatuses: ['2', '0', '3', '4'], // 固定的五个状态
      userNameToIdMap: {}, // 新增用户名到ID的映射
      workType: 0, // 新增:当前工单work_type
      selections: [], // 添加选中行数据数组
      reviewDialogVisible: false, // 新增:审核对话框可见性
      currentReviewImage: '', // 新增:当前审核图片
      currentImageIndex: 1, // 新增:当前图片索引
      totalTime: '',
      isShowInfo: false,
      // 配置时间选择器默认配置
      datePickerDefaultVal: calculateDefaultRange(),
      // 复核弹窗
      reCheckDialog: false,
      reCheckData: {}, // 专门用于存储复核数据的对象
      treePropsSF: {
        label: 'dictValue',
        value: 'id',
        children: 'children',
      },
      dictKey: '',
      dataList: [],
      checkedKeys: [],
    };
  },
  created() {
    this.inputMapShowDefaultCenter = null;
    this.loadAMapScripts();
    this.fetchDropdownData();
  },
  mounted() {
    this.getAlgorithmList();
    const href = this.$route.href;
    if (this.$route?.query?.status !== undefined && this.$route?.query?.status !== null) {
      this.filters.status = this.$route?.query?.status + '';
      this.$router.replace({});
    }
    let curQueryParams = {};
    let isTabProcessed = false;
    if (href.indexOf('?') != -1 && href.split('?').length > 0) {
      curQueryParams = href
        .split('?')[1]
        .split('&')
        .reduce((pre, cur) => {
          let newArr = cur.split('=');
          pre[newArr[0]] = newArr[1];
          return pre;
        }, {});
      const { orderNumber = undefined, day = undefined, tab = undefined } = curQueryParams;
      // 日历传值
      if (day) {
        const date = new Date(day + 'T00:00:00+08:00');
        const dateArray = [date, date];
        const handler = {
          get(target, prop) {
            if (typeof prop === 'string' && /^\d+$/.test(prop)) {
              const index = parseInt(prop);
              const dateObj = target[index];
              return dateObj.toDateString() + ' 00:00:00 GMT+0800 (中国标准时间)';
            }
            return Reflect.get(target, prop);
          },
        };
        const proxyArray = new Proxy(dateArray, handler);
        this.filters.dateRange = proxyArray;
      }
      if (orderNumber) {
        this.filters.keyword = orderNumber;
        this.$nextTick(() => {
          this.isShowInfo = true;
          const find = this.$store.state.tags.bsTagList.find(i => i.path === '/tickets/ticket');
          find && (find.query = {});
        });
      }
      if (tab) {
        const isTabValid = this.filteredTabs.some(t => t.name === tab);
        if (isTabValid) {
          this.activeTab = tab;
          this.handleTabChangeAfterJump();
          isTabProcessed = true;
          const find = this.$store.state.tags.bsTagList.find(i => i.path === '/tickets/ticket');
          find && (find.query = {});
        }
      }
    }
    this.fetchTabCounts(); // 新增:初始化时获取 tab 数据
    this.fetchTableData();
  },
  computed: {
    CircleClose() {
      return CircleClose;
    },
    firstRowData() {
      return this.tableData.length > 0 ? this.tableData[0] : null;
    },
    availableHandlers() {
      return this.form.department ? this.departmentUsers[this.form.department] || [] : [];
    },
    availableDispatchHandlers() {
      return this.dispatchForm.department
        ? this.departmentUsers[this.dispatchForm.department] || []
        : [];
    },
    dynamicFixedStatuses() {
      // 直接使用接口返回的 stepInfos
      return this.stepInfos.map(step => String(step.status));
    },
    ...mapGetters(['userInfo', 'permission']),
    // 动态过滤tabs,保证isShow为true/false
    filteredTabs() {
      // 统一处理权限,undefined视为false
      const tabStatus = this.permission?.tickets_tab_status === true;
      const tabPending = this.permission?.tickets_tab_pending === true;
      const tabMyTickets = this.permission?.tickets_tab_mytickets === true;
      return this.tabs
        .map(tab => {
          if (tab.name === 'all') {
            return { ...tab, isShow: true };
          }
          if (tab.name === 'pending') {
            return { ...tab, isShow: tabPending };
          }
          if (['processing', 'inProgress', 'completed', 'closed'].includes(tab.name)) {
            return { ...tab, isShow: tabStatus };
          }
          if (tab.name === 'myTickets') {
            return { ...tab, isShow: tabMyTickets };
          }
          return { ...tab, isShow: false };
        })
        .filter(tab => tab.isShow);
    },
    permissionList() {
      // 可根据实际后端权限key调整
      return {
        addBtn: this.validData(this.permission.tickets_add, false),
        delBtn: this.validData(this.permission.tickets_delete, false),
        exportBtn: this.validData(this.permission.tickets_export, false),
        reviewBtn: this.validData(this.permission.tickets_review, false),
      };
    },
    stepStatusList() {
      // “我发起的工单”tab用默认流程,其它tab用接口返回的stepInfos
      if (this.activeTab === 'myTickets') {
        if (this.workType === 1) {
          return ['3', '4'];
        }
        return this.fixedStatuses;
      }
      // 其它tab直接用接口返回的stepInfos
      return this.stepInfos.map(step => String(step.status));
    },
    showIsReviewText() {
      return row => {
        if (['4'].includes(String(row.status))) return row.isReview === 1 ? '是' : '否';
        return '/';
      };
    },
    popupShowImage() {
      return list => {
        return list.map(item => ({
          ...item,
          url: getShowImg(item.url),
        }));
      };
    },
  },
  methods: {
    handleCheck(data, { checkedKeys, checkedNodes }) {
      this.checkedKeys = checkedKeys;
      // 获取所有选中节点的 dictKey
      const selectedDictKeys = checkedNodes.map(node => node.dictKey).filter(Boolean);
      this.filters.type = selectedDictKeys;
      this.fetchTableData();
    },
    // 算法
    getAlgorithmList() {
      getSFDictionaryTree({ code: 'SF' }).then(res => {
        if (res.data.code === 200) {
          const result = res.data.data[0].children;
          // 过滤第一层数据
          const filteredData = result.map(item => {
            // 过滤第二层数据
            const children = item.children?.map(child => ({
              ...child,
              children: [], // 清空第三层数据
            }));
            return {
              ...item,
              children: children || [],
            };
          });
          this.dataList = filteredData;
        }
      });
    },
    handleSFNodeClick(data) {
      this.filters.type = '';
      this.filters.algorithm = '';
      this.filters.type = data.dictKey;
      // 更新列表请求
      this.fetchTableData();
    },
    handleClear() {
      this.dictKey = '';
      this.filters.algorithm = '';
      this.filters.type = '';
      this.fetchTableData();
    },
    handleCellClick(row, column) {
      console.log(row, column.no);
      if (column.no === 2) {
        navigator.clipboard.writeText(row.orderNumber).then(() => {
          this.$message.success('复制工单编号成功');
        });
      } else if (column.no === 3) {
        navigator.clipboard.writeText(row.orderName).then(() => {
          this.$message.success('复制工单名称成功');
        });
      } else if (column.no === 4) {
        navigator.clipboard.writeText(row.department).then(() => {
          this.$message.success('复制所属部门成功');
        });
      }
    },
     // 上一项
    handlePrevItem() {
      this.currentIndex = Math.max(0, this.currentIndex - 1);
      this.updateCurrentDetail();
    },
    // 下一项
    handleNextItem() {
      this.currentIndex = Math.min(this.tableData.length - 1, this.currentIndex + 1);
      this.updateCurrentDetail();
    },
    // 更新当前详情
    updateCurrentDetail() {
      this.currentDetail = this.tableData[this.currentIndex];
      this.currentDetail.mediaUrl = this.currentDetail.photo_url;
      this.currentDetail.updatePhotoUrl = this.currentDetail.update_photo_url;
      this.currentDetail.processingDetail = this.currentDetail.processingDetail;
      this.currentDetail.showQR = false;
      this.currentDetail.latAndLon = _.round(this.currentDetail.location[0], 6) + ',' + _.round(this.currentDetail.location[1], 6);
       this.getStepInfoData(this.currentDetail.orderNumber);
   },
    // 更新当前详情数据
    handleCurrentDetailUpdate(updatedDetail) {
      this.currentDetail = updatedDetail;
    },
    // 受理并派发
    handleApproveAndDispatch(detail) {
      this.currentDetail = detail;
      this.dispatchDialogVisible = true;
    },
    async loadAMapScripts() {
      try {
        const areaCode = this.userInfo.detail.areaCode;
        const subAreaCode = areaCode ? areaCode.substring(0, 6) : '';
        const adcodeObj = getAdcodeObj(geoJson, 'adcode', subAreaCode);
        // console.log('区域代码:', subAreaCode);
        // 直接从返回对象中获取正确的路径
        const center = adcodeObj?.payload?.objects?.collection?.geometries?.[0]?.properties?.center;
        if (Array.isArray(center) && center.length === 2) {
          this.inputMapShowDefaultCenter = center;
        } else {
          // 如果找不到中心点,尝试使用 bbox 的中心点
          const bbox = adcodeObj?.payload?.bbox;
          if (Array.isArray(bbox) && bbox.length === 4) {
            const centerX = (bbox[0] + bbox[2]) / 2;
            const centerY = (bbox[1] + bbox[3]) / 2;
            this.inputMapShowDefaultCenter = [centerX, centerY];
          } else {
            this.inputMapShowDefaultCenter = [115.861365, 28.621311];
          }
        }
        this.mapParams.center = [...this.inputMapShowDefaultCenter];
        this.mapLoaded = true;
      } catch (error) {
        this.$message.error('地图加载失败,请检查网络或API Key配置');
      }
    },
    async fetchDropdownData() {
      try {
        const response = await getTicketInfo();
        const { dept_data, event_type, ai_type, info } = response.data.data;
        this.departments = dept_data.map(item => ({
          label: item.dept_name,
          value: item.id,
        }));
        this.departmentUsers = dept_data.reduce((acc, dept) => {
          acc[dept.id] = dept.user_data || [];
          return acc;
        }, {});
        this.types = Object.entries(event_type).map(([key, value]) => ({
          label: value,
          value: key,
        }));
        const columnType = this.findObject(this.option.column, 'type');
        columnType.dicData = this.types;
        this.allAlgorithms = info;
        console.log('工单类型', this.types);
        console.log('关联算法', this.allAlgorithms);
        // 确保算法数据的映射一致
        this.algorithms =
          ai_type?.map(item => ({
            dict_key: item.dict_key,
            dict_value: item.dict_value,
            // 同时添加 label 和 value 以兼容两处使用
            label: item.dict_value,
            value: item.dict_key,
          })) || [];
        this.algorithms2 = _.cloneDeep(this.algorithms);
        // 构建用户ID和名称的映射关系
        this.userNameToIdMap = {};
        dept_data.forEach(dept => {
          (dept.user_data || []).forEach(user => {
            this.userNameToIdMap[user.name] = user.id;
          });
        });
      } catch (error) {
        this.$message.error('加载下拉框数据失败');
      }
    },
    // 获取表格数据
    async fetchTableData() {
      if (this.isFetching) return;
      this.isFetching = true;
      this.loading = true;
      try {
        const currentTab = this.tabs.find(tab => tab.name === this.activeTab);
        const params = {
          // word_order_types: this.filters.type || undefined,
          ai_types: this.filters.type || undefined, // 算法使用该字段筛选
          status:
            currentTab?.name === 'myTickets'
              ? undefined
              : this.filters.status !== ''
              ? Number(this.filters.status)
              : currentTab?.value,
          event_name: this.filters.keyword || undefined,
          dept_id: this.filters.department || undefined,
          start_date: this.filters.dateRange?.[0]
            ? this.formatDate(this.filters.dateRange[0])
            : undefined,
          end_date: this.filters.dateRange?.[1]
            ? this.formatDate(this.filters.dateRange[1]).replace('00:00:00', '23:59:59')
            : undefined,
          current: Number(this.page.currentPage), // 使用当前页码
          size: Number(this.page.pageSize), // 使用每页条数
          ai_type: this.filters.algorithm || undefined, // 添加算法参数
          // 添加 is_draft 参数,仅在"我发起的"标签页时设置为1
          is_draft: currentTab?.name === 'myTickets' ? 1 : undefined,
          user_id: currentTab?.name === 'myTickets' ? this.userInfo.user_id : undefined,
          is_review: this.filters.isReview === '' ? undefined : this.filters.isReview, // 添加复核状态查询参数
       source:1  ,//数据来源
       };
        const response = await getList(params);
        if (!response?.data?.data?.records) {
          throw new Error('接口返回数据格式不正确');
        }
        const { total, records } = response.data.data;
        let filteredRecords = records;
        // 如果是"我发起的"tab,过滤数据
        // if (currentTab?.name === 'myTickets') {
        //   filteredRecords = records.filter(item =>
        //     String(item.create_user_id) === String(item.user_id)
        //   );
        // }
        this.tableData = filteredRecords.map(item => {
          const longitude = Number(item.longitude) || 0;
          const latitude = Number(item.latitude) || 0;
          return {
            id: item.id,
            orderNumber: item.event_num, // 修改这里:优先使用 event_num
            orderName: item.event_name,
            department:
              this.departments.find(d => d.value === item.dept_id)?.label || item.dept_name,
            startTime: item.job_create_time || '/',
            aiType: item.ai_types,
            content: item.content, // 将后端返回的 content 映射为 content
            type: item.work_order_type_dict_key,
            keyData:
              !isNaN(longitude) && !isNaN(latitude)
                ? `${longitude.toFixed(6)}, ${latitude.toFixed(6)}`
                : '未知位置',
            address: item.address,
            creator: item.event_num?.slice(0, 2) === 'AI' ? '智飞agent' : item.create_user,
            handler: item.update_user || '未分配',
            status: Number(item.status || 0),
            // 保存原始字段
            photo_url: item.photo_url || '', // 保存原始 photo_url
            video_url: item.video_url || '', // 保存原始 video_url
            location: !isNaN(longitude) && !isNaN(latitude) ? [longitude, latitude] : null,
            processing_details: item.processing_details || '', // 添加处理详情字段
            update_photo_url: item.update_photo_url || '', // 添加处理图片字段
            work_type: item.work_type !== undefined ? Number(item.work_type) : 0, // 保留work_type字段并转为数字
            job_name: item.job_name || '',
            job_create_time: item.job_create_time || '',
            isReview: item.is_review, // 添加复核状态字段映射
          };
        });
        // 更新总数显示
        this.page.total = total || 0;
        // 是否弹出详情页
        if (this.isShowInfo) {
          this.handleViewDetail(this.firstRowData);
          this.isShowInfo = false; // 生效一次
        }
        await this.fetchTabCounts();
      } catch (error) {
        this.$message.error(error.message || '获取数据失败');
        this.tableData = [];
        this.page.total = 0;
      } finally {
        this.loading = false;
        this.isFetching = false;
      }
    },
 handleTypeChange(typeValue) {
      // this.form.algorithm = [];
      if (!typeValue) {
        // 未选择类型时清空算法列表
        this.algorithms2 = [];
        this.algorithms3 = [];
        return;
      }
      const matchedCategory = this.allAlgorithms.find(category => category.dict_key === typeValue);
      if (
        !matchedCategory ||
        !matchedCategory.algorithms ||
        matchedCategory.algorithms.length === 0
      ) {
        // 无匹配的算法时清空
        this.algorithms2 = [];
         this.algorithms3 = [];
        this.$message.info('该工单类型暂无关联算法');
        return;
      }
      this.algorithms2 = matchedCategory.algorithms.map(algo => ({
        label: algo.dict_value,
        value: algo.dict_key,
        dict_key: algo.dict_key,
        dict_value: algo.dict_value,
      }));
        this.algorithms3 = matchedCategory.algorithms.map(algo => ({
        label: algo.dict_value,
        value: algo.dict_key,
        dict_key: algo.dict_key,
        dict_value: algo.dict_value,
      }));
    },
    formatDate(date) {
      if (!date) return undefined;
      const d = new Date(date);
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(
        d.getDate()
      ).padStart(2, '0')} 00:00:00`;
    },
    mapStatus(status) {
      const statusTextMap = {
        '-1': '草稿', // 添加草稿状态
        2: '待审核',
        0: '待处理',
        3: '处理中',
        4: '已完成',
      };
      return statusTextMap[status] || '未知状态';
    },
    getStatusTagType(status) {
      // 草稿不加颜色
      if (status === -1 || status === '-1') return '';
      // 状态颜色映射
      const colorMap = {
        0: '#FF7411', // 待处理-淡红
        3: '#FFC300', // 处理中-更淡红
        2: '#FF472F', // 待审核-橙色
        4: '#0291A1', // 已完成-淡蓝
      };
      return colorMap[String(status)] || '';
    },
    async fetchTabCounts() {
      try {
        // 判断是否有部门筛选
        let params = {};
        if (this.filters.department) {
          params.deptId = this.filters.department;
        }
        const response = await getstatusCount(params);
        const { statusCount, totalCount, userCount } = response.data.data;
        this.tabs.forEach(tab => {
          if (tab.name === 'all') {
            tab.count = totalCount || 0; // 总工单数
          } else if (tab.name === 'myTickets') {
            tab.count = userCount || 0; // 我发起的工单数
          } else {
            tab.count = statusCount[String(tab.value)] || 0; // 根据状态值映射
          }
        });
      } catch (error) {
        this.$message.error('获取 tab 数据失败');
      }
    },
    handleTabChange(tab) {
      this.activeTab = tab.props?.name || tab.name;
      const isReview = this.findObject(this.option.column, 'isReview');
      // 根据条件切换显隐
      isReview.hide = !['all', 'completed', 'myTickets'].includes(this.activeTab);
      this.handleReset();
      this.page.currentPage = 1;
      this.fetchTableData();
      this.fetchTabCounts(); // 切换 tab 时重新获取数据
    },
    //新增 跳转后触发的Tab切换
    handleTabChangeAfterJump() {
      const isReview = this.findObject(this.option.column, 'isReview');
      isReview.hide = !['all', 'completed', 'myTickets'].includes(this.activeTab);
      this.handleReset();
      this.page.currentPage = 1;
      this.fetchTableData();
      this.fetchTabCounts();
    },
    handleSearch() {
      this.page.currentPage = 1;
      this.fetchTableData();
      this.fetchTabCounts();
    },
    handleReset() {
      this.dictKey = '';
      this.filters = {
        keyword: '',
        department: '',
        type: '',
        dateRange: [],
        status: '',
        algorithm: '', // 重置时清空算法筛选
        isReview: '', // 重置时清空复核状态
      };
      this.page.currentPage = 1;
      this.$router.replace({}); //清除url参数
      this.fetchTableData();
    },
    handleKeyWords() {
      this.$router.replace({}); //清除url参数
    },
    async handleCurrentChange(val) {
      // 先更新页码
      this.page.currentPage = val;
      // 等待 DOM 更新后再请求数据
      await this.$nextTick();
      await this.fetchTableData();
    },
    async sizeChange(val) {
      this.page.pageSize = val;
      this.page.currentPage = 1; // 重置到第一页
      await this.$nextTick();
      await this.fetchTableData();
    },
  handleAdd() {
      this.editFormData = null; // 设置为 null 表示新建模式
      this.dialogVisible = true;
    },
async getStepInfoData(val) {
  try {
  const orderNum = val
    const stepResponse = await getStepInfo(orderNum);
    const steps = Array.isArray(stepResponse.data.data)
      ? stepResponse.data.data
      : stepResponse.data.data?.steps || [];
    const finishedStep = steps.find(s => String(s.status) === '4');
    this.totalTime = finishedStep && finishedStep.total_time ? finishedStep.total_time : '';
    if (this.activeTab !== 'myTickets') {
      this.stepInfos = steps.map(step => ({
        status: String(step.status),
        name: step.name,
        time: step.time,
        create_time: step.create_time,
      }));
    } else {
      const statusArr = this.workType === 1 ? ['3', '4'] : this.fixedStatuses;
      this.stepInfos = statusArr.map(status => {
        const step = steps.find(s => String(s.status) === String(status));
        return {
          status,
          name: step ? step.name : '',
          time: step ? step.time : null,
          create_time: step ? step.create_time : null,
        };
      });
    }
    return true; // 表示成功获取数据
  } catch (error) {
    console.error('获取步骤信息失败:', error);
    // 失败时设置默认步骤信息
    if (this.activeTab === 'myTickets') {
      const statusArr = this.workType === 1 ? ['3', '4'] : this.fixedStatuses;
      this.stepInfos = statusArr.map(status => ({
        status,
        name: status === row.status ? row.handler || '未分配' : '未处理',
        time: status === row.status ? row.startTime || '未知时间' : null,
      }));
    } else {
      this.stepInfos = [];
    }
    return false; // 表示获取数据失败
  }
},
   async handleViewDetail(row) {
  // 找到当前行在tableData中的索引
  this.currentIndex = this.tableData.findIndex(item => item.id === row.id);
  // 先设置workType,直接从row读取
  this.workType = row.work_type !== undefined ? Number(row.work_type) : 0;
  const detailData = {
    ...row,
    processingDetail: row.processing_details || '',
    mediaUrl: row.photo_url || row.video_url || '',
    updatePhotoUrl: row.update_photo_url || '',
    photos: [],
    job_name: row.job_name || '',
  };
  // 获取步骤信息
  await this.getStepInfoData(row.orderNumber);
  this.currentDetail.status = row.status;
  this.currentDetail = {
    ...detailData,
    showQR: false,
    latAndLon: _.round(detailData.location[0], 6) + ',' + _.round(detailData.location[1], 6),
  };
  console.log('this.currentDetail', this.currentDetail);
  this.detailVisible = true;
 this.handleTypeChange(this.currentDetail.type);
  // 重置上传组件的文件列表
  this.$nextTick(() => {
    if (this.$refs.MapContainer && this.$refs.MapContainer.initAddEntity) {
      this.$refs.MapContainer.initAddEntity('point', this.currentDetail.location);
    }
  });
},
 // 详情成功回调
    handleDetailSuccess() {
      this.fetchTableData();
    },
    // 详情错误回调
    handleDetailError(error) {
      console.error('工单操作失败:', error);
    },
    refreshChange() {
      if (this.isFetching) return;
      this.fetchTableData();
    },
    onLoad() {
      if (this.isFetching) return;
      this.fetchTableData();
    },
    async exportData() {
      try {
        this.loading = true;
        let exportData = [];
        // 如果有选中的数据,则导出选中的数据
        if (this.selections.length > 0) {
          exportData = this.selections.map(item => this.formatExportItem(item));
        } else {
          // 没有选中数据时,导出当前页面的数据
          exportData = this.tableData.map(item => this.formatExportItem(item));
        }
        if (exportData.length === 0) {
          this.$message.warning('没有数据可供导出');
          return;
        }
        const headers = [
          '工单编号',
          '工单名称',
          '所属部门',
          '发起时间',
          '关联算法',
          '工单内容',
          '工单类型',
          '经纬度',
          '创建人',
          '处理人',
          '工单状态',
        ];
        export_json_to_excel(headers, exportData, '工单数据');
        this.$message.success('数据导出成功');
      } catch (error) {
        // console.error('导出失败:', error);
        this.$message.error(error.message || '导出失败,请稍后重试');
      } finally {
        this.loading = false;
      }
    },
    formatExportItem(item) {
      const longitude = Number(item.longitude) || Number(item.location?.[0]) || 0;
      const latitude = Number(item.latitude) || Number(item.location?.[1]) || 0;
      return {
        工单编号: item.orderNumber || item.event_num || '',
        工单名称: item.orderName || item.event_name || '',
        所属部门: item.department || item.dept_name || '',
        发起时间: item.startTime || item.create_time || '',
        关联算法: item.aiType || item.ai_types || '',
        工单内容: item.address || item.content || '',
        工单类型:
          this.types.find(t => t.value === (item.type || item.work_order_type_dict_key))?.label ||
          '',
        经纬度:
          !isNaN(longitude) && !isNaN(latitude)
            ? `${longitude.toFixed(6)}, ${latitude.toFixed(6)}`
            : '',
        创建人: item.creator || item.create_user || '',
        处理人: item.handler || item.update_user || '',
        工单状态: this.mapStatus(Number(item.status || 0)),
      };
    },
    markAsCompleted() {
      this.$message.success('工单已标记为完成');
    },
    // 派发成功回调
    handleDispatchSuccess() {
      this.detailVisible = false;
      this.fetchTableData();
    },
    // 派发错误回调
    handleDispatchError(error) {
      // 可以在这里处理错误,或者保持空实现
      console.error('派发失败:', error);
    },
    async finalizeTicket() {
      if (this.finalizeLoading) return;
      this.finalizeLoading = true;
      try {
        // 检查是否上传了图片
        if (!this.currentDetail.photos || !this.currentDetail.photos.length) {
          this.$message.warning('请上传事件处理照片,或飞行任务结束核验工单是否完结');
          return;
        }
        const data = {
          id: this.currentDetail.id,
          status: this.currentDetail.status,
          eventNum: this.currentDetail.orderNumber,
        };
        const file = this.currentDetail.photos[0].raw;
        const response = await flowEvent(data, file);
        if (response.data.code === 0) {
          this.$message.success('工单已完结');
          this.detailVisible = false;
          this.fetchTableData();
        } else {
          throw new Error(response.data.msg || '操作失败');
        }
      } catch (error) {
        console.error('完结工单失败:', error);
        this.$message.error(error.message || '操作失败,请稍后重试');
      } finally {
        this.finalizeLoading = false;
      }
    },
    // 添加编辑方法
    // 编辑工单 - 简化方法
    handleEdit(row) {
      this.editFormData = row; // 设置编辑数据
      this.dialogVisible = true;
    },
    // 创建成功回调
    handleCreateSuccess() {
      this.fetchTableData();
    },
    // 草稿保存成功回调
    handleDraftSuccess() {
      this.fetchTableData();
    },
    // 创建失败回调
    handleCreateError(error) {
      console.error('工单操作失败:', error);
    },
    // 添加删除方法
    handleDelete(row) {
      this.$confirm('确认删除该工单?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          try {
            const response = await flowEvent({
              id: row.id,
              status: 0,
              isDelete: 1,
            });
            if (response.data.code === 0) {
              this.$message.success('删除成功');
              this.fetchTableData();
            } else {
              throw new Error(response.data.msg || '删除失败');
            }
          } catch (error) {
            console.error('删除失败:', error);
            this.$message.error(error.message || '删除失败,请稍后重试');
          }
        })
        .catch(() => {});
    },
    // 添加选择变化处理方法
    handleSelectionChange(selection) {
      this.selections = selection;
      console.log('已选择的行:', selection);
    },
    // 添加全选方法
    handleSelectAll(val) {
      this.$refs.avueCrud.toggleSelection(val);
    },
    // 如果需要手动选中某些行
    setSelection(rows) {
      this.$nextTick(() => {
        rows.forEach(row => {
          this.$refs.avueCrud.toggleSelection(row, true);
        });
      });
    },
    // 清空选择
    clearSelection() {
      this.$refs.avueCrud.clearSelection();
    },
    // 打开审核对话框
    openReviewDialog() {
      if (this.selections.length === 0) {
        this.$message.warning('请先选择要审核的工单');
        return;
      }
      this.currentImageIndex = 1;
      this.updateCurrentReviewImage();
      this.reviewDialogVisible = true;
    },
    // 更新当前审核图片
    updateCurrentReviewImage() {
      // 修正索引范围
      if (!this.selections || this.selections.length === 0) {
        this.currentReviewImage = '';
        this.currentImageIndex = 1;
        return;
      }
      // 如果当前索引超出范围,自动回退到最后一张
      if (this.currentImageIndex > this.selections.length) {
        this.currentImageIndex = this.selections.length;
      }
      if (this.currentImageIndex < 1) {
        this.currentImageIndex = 1;
      }
      const index = this.currentImageIndex - 1;
      if (index >= 0 && index < this.selections.length) {
        const currentItem = this.selections[index];
        this.currentReviewImage = currentItem.photo_url || '';
      } else {
        this.currentReviewImage = '';
      }
    },
    // 处理图片分页变化
    handleImagePageChange(page) {
      if (page > 0 && page <= this.selections.length) {
        this.currentImageIndex = page;
        this.updateCurrentReviewImage();
      }
    },
    // 批量审核通过
    async handleBatchApprove() {
      try {
        if (this.selections.length === 0) {
          this.$message.warning('没有选中的工单');
          return;
        }
        const currentItem = this.selections[this.currentImageIndex - 1];
        if (!currentItem) {
          this.$message.warning('当前工单数据无效');
          return;
        }
        await this.$confirm('确认审核通过当前工单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        const data = {
          id: currentItem.id,
          status: currentItem.status,
          isPass: 0,
          eventNum: currentItem.orderNumber,
        };
        console.log('删除前:', this.selections);
        const response = await flowEvent(data);
        if (response.data.code === 0) {
          this.$message.success('工单审核通过');
          // 创建新的数组而不是修改原数组
          const newSelections = [...this.selections];
          newSelections.splice(this.currentImageIndex - 1, 1);
          // 修正索引并更新图片
          if (newSelections.length > 0) {
            if (this.currentImageIndex > this.selections.length) {
              this.currentImageIndex = this.selections.length;
            }
            this.updateCurrentReviewImage();
          } else {
            this.reviewDialogVisible = false;
            this.currentImageIndex = 1;
            this.currentReviewImage = '';
            this.fetchTableData();
          }
          // 刷新表格数据
          // this.fetchTableData();
          this.selections = newSelections;
        } else {
          throw new Error(response.data.msg || '审核失败');
        }
      } catch (error) {
        if (error === 'cancel') return;
        this.$message.error(error.message || '审核失败,请稍后重试');
      }
    },
    cancleBatchReject() {
      this.reviewDialogVisible = false;
      this.selections = [];
      this.currentImageIndex = 1;
      this.currentReviewImage = '';
      this.fetchTableData();
    },
    // 批量审核不通过
    async handleBatchReject() {
      try {
        if (this.selections.length === 0) {
          this.$message.warning('没有选中的工单');
          return;
        }
        const currentItem = this.selections[this.currentImageIndex - 1];
        if (!currentItem) {
          this.$message.warning('当前工单数据无效');
          return;
        }
        await this.$confirm('确认该工单审核不通过?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
        const data = {
          id: currentItem.id,
          status: currentItem.status,
          isPass: 1,
          eventNum: currentItem.orderNumber,
          eventName: currentItem.orderName,
        };
        const response = await flowEvent(data);
        if (response.data.code === 0) {
          this.$message.success('工单审核不通过');
          // 创建新的数组而不是修改原数组
          const newSelections = [...this.selections];
          newSelections.splice(this.currentImageIndex - 1, 1);
          this.selections = newSelections;
          // 修正索引并更新图片
          if (this.selections.length > 0) {
            if (this.currentImageIndex > this.selections.length) {
              this.currentImageIndex = this.selections.length;
            }
            this.updateCurrentReviewImage();
          } else {
            this.reviewDialogVisible = false;
            this.currentImageIndex = 1;
            this.currentReviewImage = '';
            this.fetchTableData();
          }
          // 刷新表格数据
          // this.fetchTableData();
        } else {
          throw new Error(response.data.msg || '驳回失败');
        }
      } catch (error) {
        if (error === 'cancel') return;
        this.$message.error(error.message || '驳回失败,请稍后重试');
      }
    },
    // 获取所有图片列表用于预览
    getImageList() {
      return this.selections.map(item => this.getPreviewUrl(item.photo_url)).filter(url => url); // 过滤掉空值
    },
    // 处理图片点击
    handleImageClick() {
      // 图片点击事件由 el-image 的预览功能处理
    },
    // 处理上一张图片
    handlePrevImage() {
      if (this.currentImageIndex > 1) {
        this.currentImageIndex--;
        this.updateCurrentReviewImage();
      }
    },
    // 处理下一张图片
    handleNextImage() {
      if (this.currentImageIndex < this.selections.length) {
        this.currentImageIndex++;
        this.updateCurrentReviewImage();
      }
    },
    /**
     * 获取缩略图地址
     * @param {string} url 原图地址
     * @returns {string} 缩略图地址
     */
    getThumbUrl(url) {
      if (!url) return '';
      const lastDot = url.lastIndexOf('.');
      if (lastDot === -1) return url;
      return url.slice(0, lastDot) + '_small' + url.slice(lastDot);
    },
    // 添加新方法:获取预览图地址
    getPreviewUrl(url) {
      if (!url) return '';
      const lastDot = url.lastIndexOf('.');
      if (lastDot === -1) return url;
      return url.slice(0, lastDot) + '_show' + url.slice(lastDot);
    },
    /**
     * 坐标转换方法处理
     * @param goWgs84 是否由国测转换到84,默认false----由84转换到国测
     */
    disposeLocation(goWgs84 = false, data) {
      let lng = '',
        lat = '';
      if (Array.isArray(data.location) && data.location.length > 0) {
        if (goWgs84) {
          lng = data.location?.[0] ? String(data.location[0]) : undefined;
          lat = data.location?.[1] ? String(data.location[1]) : undefined;
          if (lng && lat) {
            [lng, lat] = gcj02ToWgs84(Number(lng), Number(lat));
          }
        } else {
          lng = Number(data.location[0]);
          lat = Number(data.location[1]);
          if (lng && lat) {
            [lng, lat] = wgs84ToGcj02(Number(lng), Number(lat));
          }
        }
      }
      return [String(lng), String(lat)];
    },
    // 复核按钮
  reCheck(row) {
      this.reCheckData = row;
      this.reCheckDialog = true;
    },
 // 复核成功回调
    handleRecheckSuccess() {
      this.page.currentPage = 1;
      this.fetchTableData();
      this.fetchTabCounts();
    },
    // 导出工单报表
    exportTheTick(row){
      const params = {
        num:row.orderNumber
      }
      exportTheTicket(params).then(res=>{
      const elink = document.createElement('a')
      elink.download = row.orderName + '.docx'
      elink.style.display = 'none'
      const blob = new Blob([res.data])
      elink.href = URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      document.body.removeChild(elink)
      })
       this.$message.success('数据导出成功');
    }
  },
  activated() {
    this.handleReset();
  },
};
</script>
<style lang="scss">
.custom-qrcode-popover {
  min-width: 160px !important;
  min-height: 140px !important;
  position: relative;
  .qrcode-content {
    margin-top: 8px;
    .close-btn {
      position: absolute;
      top: 2px;
      right: 2px;
      width: 16px;
      height: 16px;
      line-height: 16px;
      text-align: center;
      cursor: pointer;
      color: #999;
      font-size: 16px;
      z-index: 10;
    }
  }
}
</style>
<style lang="scss" scoped>
::v-deep(.el-tabs) {
  height: 100%;
  display: flex;
  flex-direction: column;
  .el-tabs__header {
    order: 1;
  }
  .el-tabs__content {
    order: 2;
  }
  .el-tabs__content {
    height: 0;
    flex: 1;
    display: flex;
    flex-direction: column;
    .el-tab-pane {
      height: 0;
      flex: 1;
      display: flex;
      flex-direction: column;
    }
  }
}
.filter-bar {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 8px; // 使用 gap 统一设置间距
  .filter-item {
    width: 280px; // 减小宽度
  }
  .date-picker {
    // width: 240px; // 日期选择器宽度适当调整
  }
  .el-button {
    margin-left: 0; // 覆盖 element-ui 默认的按钮间距
  }
}
.uploadImg {
  margin-bottom: 32px;
}
.tableCss {
  width: 100%;
  margin-bottom: 10px;
}
.step-timer {
  position: absolute;
  right: 80%;
  top: 50%;
  transform: translateY(-50%);
  width: 100px;
  margin-left: 4px;
  color: #666;
  font-size: 12px;
}
.event-total-time {
  text-align: center;
  color: #666;
  font-size: 15px;
  margin-bottom: 12px;
}
.action-bar {
  margin-bottom: 16px;
}
.el-dialog {
  .el-form-item {
    margin-bottom: 20px;
  }
}
.el-upload {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  :deep(.el-upload-list__item) {
    transition: all 0.3s ease;
  }
  :deep(.el-upload-list__item:hover) {
    background-color: #f5f7fa;
  }
}
.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 12px;
}
.create-ticket-form {
  padding: 20px 10px;
  .form-section {
    background-color: #fff;
    border-radius: 4px;
    .el-row {
      margin-bottom: 16px;
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
  .location-wrapper {
    width: 100%; // 修改为100%以适应父容器
    height: auto; // 修改为auto以自适应内容
    .map-button {
      width: 100%; // 让按钮填满容器宽度
      height: 36px; // 与其他输入框保持一致的高度
      display: flex;
      align-items: center;
      justify-content: center;
      i {
        margin-right: 4px;
      }
    }
    .location-text {
      margin-top: 8px;
      padding: 8px 12px;
      background-color: #f5f7fa;
      border-radius: 4px;
      color: #606266;
      font-size: 13px;
      line-height: 1.4;
    }
  }
  .upload-wrapper {
    .uploader {
      :deep(.el-upload--picture-card) {
        width: 120px;
        height: 100px;
        line-height: 128px;
      }
      :deep(.el-upload-list__item) {
        width: 120px;
        height: 120px;
      }
    }
    .upload-tip {
      font-size: 12px;
      color: #909399;
      line-height: 1.4;
      margin-top: 8px;
    }
  }
  .el-form-item {
    margin-bottom: 18px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
  }
  // :deep(.el-input__inner) {
  //   height: 36px;
  //   line-height: 36px;
  // }
  :deep(.el-textarea__inner) {
    padding: 8px 12px;
  }
  // :deep(.el-input__inner),
  // :deep(.el-select),
  // :deep(.el-select .el-input) {
  //   width: 100%; // 确保所有输入框和选择框宽度一致
  // }
  .full-width {
    width: 100%;
  }
}
:deep(.el-dialog__body) {
  border-top: 0.1rem solid #f0f0f0;
}
.dialog-footer-new {
  text-align: right;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
  .el-button + .el-button {
    margin-left: 12px;
  }
  .el-button {
    padding: 9px 20px;
    &:last-child {
      margin-left: 12px;
    }
  }
}
.dialog-footer1-new {
  position: sticky;
  bottom: 28px;
  left: 0;
  right: 0;
  background: white;
  z-index: 10;
  padding: 16px 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .el-button + .el-button {
    margin-left: 12px;
  }
  .btngroups {
    margin-left: 12px;
  }
  .el-button {
    padding: 9px 20px;
    &:last-child {
      margin-left: 12px;
      margin-right: 12px;
    }
  }
}
.map-container {
  width: 100%;
  height: 400px;
  margin-bottom: 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  :deep(.el-input-map) {
    height: 100%;
  }
}
.location-info {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  p {
    margin: 5px 0;
    color: #606266;
    font-size: 14px;
  }
}
.map-select {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  .selected-location {
    flex: 1;
    padding: 5px 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
    p {
      margin: 5px 0;
      color: #606266;
      font-size: 14px;
    }
  }
}
.preview-image {
  border-radius: 4px;
  overflow: hidden;
  background-color: #f5f7fa;
}
.image-placeholder,
.image-error,
.no-media {
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  background-color: #f5f7fa;
  border-radius: 4px;
  i {
    font-size: 32px;
    margin-bottom: 8px;
  }
}
.no-media {
  border: 1px dashed #d9d9d9;
}
.detail-container {
  padding: 0 20px;
  .detail-top-title {
    display: flex;
    justify-content: center;
    align-items: center;
    .event-orderNumber {
      margin-right: 10px;
    }
  }
}
.status-flow {
  margin-bottom: 20px;
  .custom-steps {
    .el-step__description {
      position: relative;
      margin: 0;
      padding: 0;
    }
    // 添加发起任务步骤的特殊样式
    .init-step-info {
      display: flex;
      flex-direction: column;
      align-items: center;
      text-align: center;
      width: 130px;
      .creator-name {
        font-size: 14px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 4px;
      }
      .create-time {
        font-size: 10px;
        color: #909399;
      }
    }
    // 保持其他步骤的原有样式
    .step-info {
      display: flex;
      margin: 0;
      padding: 0;
      justify-content: space-between;
      align-items: center;
      width: 200px;
      .process-time {
        font-size: 10px;
        color: #909399;
        text-align: left;
        margin-left: -50%;
        padding-left: 0%;
        flex: 1;
      }
      .handler-name {
        font-size: 14px;
        font-weight: bold;
        color: #303133;
        text-align: left;
        flex: 1;
      }
    }
  }
}
.basic-info {
  margin-bottom: 20px;
}
.media-section {
  // margin-bottom: 20px;
  .el-row {
    display: flex;
    align-items: center;
  }
}
.leftBtn {
  width: 70px;
  height: 32px;
  background-color: #999;
  border-radius: 5px;
  text-align: center;
  line-height: 32px;
  color: #fff;
  cursor: pointer;
  opacity: 0.8;
}
.disableds {
  background: #999 !important;
  cursor: not-allowed !important;
  pointer-events: none;
  opacity: 0.3 !important;
}
.PopUpTableScrolls {
  max-height: 600px;
  overflow-y: scroll;
  overflow-x: hidden;
}
.media-box {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  background: #fff;
  box-sizing: border-box;
  .media-title {
    font-weight: bold;
    margin-bottom: 5px;
    display: flex;
    align-items: center;
    .QRCodeImg {
      width: 18px;
      height: 18px;
      cursor: pointer;
      padding-bottom: 1px;
    }
  }
  .media-content {
    position: relative;
    height: 500px;
    :deep(.el-image) {
      width: 100% !important;
      max-width: 100%;
      max-height: 100%;
      .el-image__inner {
        width: 100%;
        height: 100%;
        object-fit: cover !important;
      }
    }
  }
}
.image-placeholder,
.image-error,
.no-media {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.image-placeholder i,
.image-error i {
  font-size: 32px;
  margin-bottom: 8px;
}
.no-media {
  border: 1px dashed #d9d9d9;
}
.info-table {
  margin-bottom: 20px;
}
.info-item {
  display: flex;
  margin-bottom: 10px;
}
.info-label {
  font-weight: bold;
  width: 120px;
  color: #606266;
}
.info-value {
  flex: 1;
  color: #303133;
  word-break: break-word;
}
// 添加删除按钮样式
.danger-button {
  color: #f56c6c;
}
.danger-button:hover {
  color: #f78989;
}
.custom-steps-container {
  width: 100%;
  margin: 10px 0;
}
.steps-titles {
  display: flex;
  justify-content: space-between;
  margin-bottom: 14px;
  position: relative;
}
.step-title {
  text-align: center;
  flex: 1;
  font-size: 14px;
  color: #999;
  position: relative;
  padding-bottom: 5px;
}
.step-title.active {
  color: #409eff;
  font-weight: bold;
}
.event-title-center {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #333;
}
.custom-steps {
  margin-top: -20px;
  :deep(.el-step__description) {
    margin-top: 8px;
    padding: 0 20px;
  }
}
.step-description {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  display: block;
  text-align: center;
  &:first-child {
    font-weight: bold;
    margin-bottom: 4px;
  }
}
// 覆盖其他相关样式
.status-flow {
  .custom-steps {
    .el-step__description {
      position: relative;
      margin: 0;
      padding: 0;
    }
    // 移除之前的样式
    .init-step-info,
    .step-info {
      display: block;
      width: auto;
      text-align: center;
    }
  }
}
// 添加新的样式
.review-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
    background-color: #f5f7fa;
    border-top: 0.1rem solid #f0f0f0;
  }
}
.re-check-dialog {
  :deep(.el-dialog__body) {
    padding: 0;
    background-color: #f5f7fa;
    border-top: 0.1rem solid #f0f0f0;
  }
}
.review-container {
  position: relative;
  .review-image-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 600px;
    background-color: #f5f7fa;
  }
  .review-image-container {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    :deep(.el-image) {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      .el-image__inner {
        max-height: 100%;
        max-width: 100%;
        object-fit: contain;
      }
    }
  }
  .arrow-button {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width: 44px;
    height: 44px;
    background: rgba(0, 0, 0, 0.3);
    border-radius: 50%;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
    z-index: 100;
    &:hover {
      background: rgba(0, 0, 0, 0.6);
    }
    i {
      color: #fff;
      font-size: 24px;
    }
    &.left {
      left: 20px;
      color: #ffffff;
    }
    &.right {
      right: 20px;
      color: #ffffff;
    }
  }
  .preview-image {
    max-width: 100%;
    max-height: 100%;
  }
  .review-pagination {
    padding: 16px 0;
    display: flex;
    justify-content: center;
    background-color: #fff;
    :deep(.el-pagination) {
      .btn-prev,
      .btn-next {
        display: none;
      }
      .el-pager {
        .number {
          margin: 0 4px;
        }
      }
    }
  }
  .image-error {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #909399;
    i {
      font-size: 48px;
      margin-bottom: 16px;
    }
    span {
      font-size: 16px;
    }
  }
}
/* 新建工单和处理工单的上传组件样式 */
.create-upload,
.detail-upload {
  :deep(.el-upload--picture-card) {
    width: 120px;
    height: 100px;
    line-height: 100px;
  }
  /* 隐藏额外的上传按钮 */
  :deep(.el-upload.el-upload--picture-card) {
    display: none;
  }
  /* 当没有图片时显示上传按钮 */
  :deep(.el-upload.el-upload--picture-card:first-child) {
    display: flex;
  }
  /* 上传组件的预览图片样式 */
  :deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 120px;
    height: 100px;
  }
}
/* 原有图片预览的样式 */
.el-image-viewer__wrapper {
  :deep(.el-image-viewer__img) {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
  }
}
/* 必填项样式 */
.required-label {
  position: relative;
  display: inline-block;
  .required-star {
    color: #f56c6c;
    margin-right: 4px;
  }
}
/* 必填输入框样式 */
.required-input {
  width: 100%;
  :deep(.el-input__inner),
  :deep(.el-textarea__inner) {
    &:focus {
      border-color: #409eff;
    }
  }
}
</style>
src/views/tickets/ticket.vue
Diff too large
src/views/tickets/ticketComponent/CreateTicketDialog.vue
New file
@@ -0,0 +1,710 @@
<template>
  <el-dialog
    v-model="dialogVisible"
    title="新建工单"
    width="70%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="90px"
      class="create-ticket-form"
      @submit.prevent
    >
      <div class="form-section">
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="工单名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入工单名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工单类型" prop="type">
              <el-select
                @change="handleTypeChange"
                v-model="form.type"
                placeholder="请选择工单类型"
                class="full-width"
                clearable
              >
                <el-option
                  v-for="item in types"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="处理部门" prop="department">
              <el-select
                v-model="form.department"
                placeholder="请选择处理部门"
                @change="handleDepartmentChange"
                class="full-width"
                clearable
              >
                <el-option
                  v-for="dept in departments"
                  :key="dept.value"
                  :label="dept.label"
                  :value="dept.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理人员" prop="handler">
              <el-select
                v-model="form.handler"
                placeholder="请先选择处理人员"
                :disabled="!form.department"
                class="full-width"
                clearable
              >
                <el-option
                  v-for="user in availableHandlers"
                  :key="user.id"
                  :label="user.name"
                  :value="user.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="关联算法" prop="algorithm">
              <el-select
                v-model="form.algorithm"
                multiple
                placeholder="请选择关联算法"
                class="full-width"
                :disabled="!form.type"
                clearable
              >
                <el-option
                  v-for="item in availableAlgorithms"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事件位置" prop="location">
              <div class="location-wrapper">
                <avue-input-map
                  v-model="form.location"
                  :clearable="false"
                  :params="mapParams"
                  @change="handleLocationChange"
                  type="button"
                >
                  <el-button type="primary" plain class="map-button">
                    <i class="el-icon-map-location"></i> 地图选点
                  </el-button>
                </avue-input-map>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="工单内容" prop="content">
              <el-input
                type="textarea"
                v-model="form.content"
                :rows="4"
                placeholder="请输入工单内容描述"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事件图片" prop="photos" required class="upload-wrapper">
              <el-upload
                ref="uploadRef"
                :action="'#'"
                :auto-upload="false"
                list-type="picture-card"
                :on-change="handleFileChange"
                :on-remove="handleUploadRemove"
                :before-upload="beforeUpload"
                :file-list="form.photos"
                :limit="1"
                accept="image/*"
                class="create-upload"
              >
                <template v-if="form.photos.length < 1">
                  <div class="el-icon-plus">
                    <span>+</span>
                  </div>
                </template>
              </el-upload>
              <div class="upload-tip">需上传含有地址信息的照片(jpg、jpeg、png),且不超过5M</div>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <template #footer>
      <div class="dialog-footer-new">
        <el-button
          type="danger"
          :loading="submitLoading"
          @click="handleSubmit"
          icon="el-icon-position"
        >
          发布
        </el-button>
        <el-button @click="handleClose" icon="el-icon-circle-close">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script>
import { createTicket } from '@/api/tickets/ticket';
import { gcj02ToWgs84, wgs84ToGcj02 } from '@/utils/coordinateTransformation';
export default {
  name: 'CreateTicketDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    departments: {
      type: Array,
      default: () => []
    },
    departmentUsers: {
      type: Object,
      default: () => ({})
    },
    types: {
      type: Array,
      default: () => []
    },
    allAlgorithms: {
      type: Array,
      default: () => []
    },
    editData: {
      type: Object,
      default: null
    },
    mapCenter: {
      type: Array,
      default: () => [115.861365, 28.621311]
    }
  },
  emits: ['update:modelValue', 'create-success', 'draft-success', 'create-error'],
  data() {
    return {
      form: {
        name: '',
        type: '',
        department: '',
        handler: '',
        algorithm: [],
        location: [],
        address: '',
        content: '',
        photos: []
      },
      rules: {
        name: [{ required: true, message: '请输入工单名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择工单类型', trigger: 'change' }],
        department: [{ required: true, message: '请选择所属部门', trigger: 'change' }],
        handler: [{ required: true, message: '请选择处理人员', trigger: 'change' }],
        content: [{ required: true, message: '请输入工单内容', trigger: 'blur' }],
        algorithm: [{ required: true, message: '请选择关联算法', trigger: 'change' }],
        location: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (!value || value.length < 2) {
                callback(new Error('请选择位置信息'));
              } else if (!value[0] || !value[1]) {
                callback(new Error('请选择位置信息'));
              } else {
                callback();
              }
            },
            trigger: 'change',
          },
        ],
        photos: [
          {
            validator: (rule, value, callback) => {
              if (!this.form.photos || this.form.photos.length === 0) {
                callback(new Error('请上传工单图片'));
              } else {
                callback();
              }
            },
            trigger: 'change',
          },
        ],
      },
      availableAlgorithms: [],
      mapParams: {
        zoom: 15,
        center: null
      },
      submitLoading: false,
      draftLoading: false
    };
  },
  computed: {
    dialogVisible: {
      get() {
        return this.modelValue;
      },
      set(value) {
        this.$emit('update:modelValue', value);
      }
    },
    availableHandlers() {
      return this.form.department ? this.departmentUsers[this.form.department] || [] : [];
    },
    isEditMode() {
      return !!this.editData;
    }
  },
  watch: {
    modelValue(newVal) {
      if (newVal) {
        this.initForm();
        this.mapParams.center = [...this.mapCenter];
      }
    }
  },
  methods: {
    initForm() {
      if (this.isEditMode && this.editData) {
        // 编辑模式:填充表单数据
        this.loadEditData();
      } else {
        // 新建模式:重置表单
        this.resetForm();
      }
    },
    loadEditData() {
      const data = this.editData;
      // 获取部门ID
      let deptId = data.dept_id;
      if (!deptId) {
        const deptInfo = this.departments.find(
          dept => dept.label && dept.label.trim() === data.department.trim()
        );
        deptId = deptInfo?.value;
      }
      // 获取工单类型值
      const typeValue = this.types.find(t => t.value === data.type)?.value || data.work_order_type_dict_key;
      // 处理算法数组
      let algorithmArr = [];
      if (Array.isArray(data.aiType)) {
        algorithmArr = data.aiType;
      } else if (typeof data.aiType === 'string' && data.aiType) {
        algorithmArr = data.aiType.split(/[,、]/).map(item => item.trim());
      }
      // 确保算法值与选项匹配
      algorithmArr = algorithmArr
        .map(item => {
          if (typeof item === 'string') {
            const matchedAlgorithm = this.allAlgorithms.find(
              algo => algo.dict_value === item || algo.dict_key === item
            );
            return matchedAlgorithm ? matchedAlgorithm.dict_key : item;
          }
          return item;
        })
        .filter(Boolean);
      // 处理位置数据
      let curLocation = [];
      if (Array.isArray(data.location) && data.location.length >= 2) {
        let [lng, lat] = this.disposeLocation(false, data);
        curLocation = [lng, lat, data.location[2] || data.address || ''];
      }
      this.form = {
        id: data.id,
        name: data.orderName,
        type: typeValue,
        department: deptId,
        handler: data.handler,
        algorithm: algorithmArr,
        location: curLocation,
        address: curLocation[2] || '',
        content: data.content,
        photos: data.photo_url ? [{
          name: 'existing-photo.jpg',
          url: data.photo_url,
          status: 'success',
          raw: null,
          existingUrl: data.photo_url,
        }] : []
      };
      // 更新算法选项
      this.handleTypeChange(typeValue);
    },
    resetForm() {
      this.form = {
        name: '',
        type: '',
        department: '',
        handler: '',
        algorithm: [],
        location: [],
        address: '',
        content: '',
        photos: []
      };
      this.availableAlgorithms = [];
      if (this.$refs.formRef) {
        this.$refs.formRef.clearValidate();
      }
    },
    handleClose() {
      this.dialogVisible = false;
      this.resetForm();
    },
    handleTypeChange(typeValue) {
      this.form.algorithm = [];
      if (!typeValue) {
        this.availableAlgorithms = [];
        return;
      }
      const matchedCategory = this.allAlgorithms.find(category => category.dict_key === typeValue);
      if (!matchedCategory || !matchedCategory.algorithms || matchedCategory.algorithms.length === 0) {
        this.availableAlgorithms = [];
        this.$message.info('该工单类型暂无关联算法');
        return;
      }
      this.availableAlgorithms = matchedCategory.algorithms.map(algo => ({
        label: algo.dict_value,
        value: algo.dict_key,
        dict_key: algo.dict_key,
        dict_value: algo.dict_value,
      }));
    },
    handleDepartmentChange() {
      this.form.handler = '';
    },
    handleLocationChange(val) {
      let locationValue = val.value;
      if (locationValue && locationValue.length >= 2) {
        const [lng, lat] = gcj02ToWgs84(locationValue[0], locationValue[1]);
        this.form.location = [Number(lng), Number(lat), locationValue[2] || ''];
        this.form.address = locationValue[2] || '';
      } else {
        this.form.location = [];
        this.form.address = '';
      }
    },
    handleFileChange(file, fileList) {
      this.form.photos = fileList.map(item => ({
        ...item,
        existingUrl: item.url && !item.raw ? item.url : null,
      }));
    },
    handleUploadRemove(file, fileList) {
      this.form.photos = fileList;
    },
    beforeUpload(file) {
      const isImage = file.type.includes('image');
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('图片大小不能超过5MB!');
        return false;
      }
      return true;
    },
    async handleSubmit() {
      if (this.submitLoading) return;
      try {
        await this.$refs.formRef.validate();
        // 验证位置信息
        if (!this.form.location || this.form.location.length < 2) {
          this.$message.warning('请在地图上选择位置');
          return;
        }
        // 验证图片
        if (!this.form.photos || this.form.photos.length === 0) {
          this.$message.warning('请上传工单图片');
          return;
        }
        this.submitLoading = true;
        let [lng, lat] = this.disposeLocation(true, this.form);
        const submitData = {
          eventName: this.form.name,
          content: this.form.content,
          workType: '1',
          longitude: lng,
          latitude: lat,
          address: this.form.address,
          workOrderTypeDictKey: this.form.type,
          aiType: Array.isArray(this.form.algorithm) ? this.form.algorithm : [this.form.algorithm],
          updateUser: this.form.handler,
          createDept: this.form.department,
          isDraft: 0,
        };
        if (this.form.id) {
          submitData.id = this.form.id;
        }
        // 获取文件
        let file = null;
        const photoInfo = this.form.photos[0];
        if (photoInfo.raw) {
          file = photoInfo.raw;
        } else if (photoInfo.existingUrl) {
          submitData.photoUrl = photoInfo.existingUrl;
        } else {
          this.$message.warning('图片文件无效,请重新上传');
          return;
        }
        const response = await createTicket(submitData, file);
        if (response.data.code === 0) {
          this.$message.success(this.isEditMode ? '工单编辑成功' : '工单创建成功');
          this.$emit('create-success');
          this.handleClose();
        } else {
          throw new Error(response.data.msg || '操作失败');
        }
      } catch (error) {
        if (error.message.includes('验证未通过')) {
          this.$message.warning('请填写完整的工单信息');
        } else {
          this.$message.error(error.message || '操作失败,请稍后重试');
          this.$emit('create-error', error);
        }
      } finally {
        this.submitLoading = false;
      }
    },
    disposeLocation(goWgs84 = false, data) {
      let lng = '', lat = '';
      if (Array.isArray(data.location) && data.location.length > 0) {
        if (goWgs84) {
          lng = data.location?.[0] ? String(data.location[0]) : undefined;
          lat = data.location?.[1] ? String(data.location[1]) : undefined;
          if (lng && lat) {
            [lng, lat] = gcj02ToWgs84(Number(lng), Number(lat));
          }
        } else {
          lng = Number(data.location[0]);
          lat = Number(data.location[1]);
          if (lng && lat) {
            [lng, lat] = this.wgs84ToGcj02(Number(lng), Number(lat));
          }
        }
      }
      return [String(lng), String(lat)];
    },
  }
};
</script>
<style lang="scss" scoped>
.full-width {
  width: 100%;
}
.location-wrapper {
  width: 100%;
  height: auto;
}
.map-button {
  width: 100%;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.create-ticket-form {
  padding: 20px 10px;
  .form-section {
    background-color: #fff;
    border-radius: 4px;
    .el-row {
      margin-bottom: 16px;
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
  .location-wrapper {
    width: 100%; // 修改为100%以适应父容器
    height: auto; // 修改为auto以自适应内容
    .map-button {
      width: 100%; // 让按钮填满容器宽度
      height: 36px; // 与其他输入框保持一致的高度
      display: flex;
      align-items: center;
      justify-content: center;
      i {
        margin-right: 4px;
      }
    }
    .location-text {
      margin-top: 8px;
      padding: 8px 12px;
      background-color: #f5f7fa;
      border-radius: 4px;
      color: #606266;
      font-size: 13px;
      line-height: 1.4;
    }
  }
  .upload-wrapper {
    .uploader {
      :deep(.el-upload--picture-card) {
        width: 120px;
        height: 100px;
        line-height: 128px;
      }
      :deep(.el-upload-list__item) {
        width: 120px;
        height: 120px;
      }
    }
    .upload-tip {
      font-size: 12px;
      color: #909399;
      line-height: 1.4;
      margin-top: 8px;
    }
  }
  .el-form-item {
    margin-bottom: 18px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
  }
  // :deep(.el-input__inner) {
  //   height: 36px;
  //   line-height: 36px;
  // }
  :deep(.el-textarea__inner) {
    padding: 8px 12px;
  }
  // :deep(.el-input__inner),
  // :deep(.el-select),
  // :deep(.el-select .el-input) {
  //   width: 100%; // 确保所有输入框和选择框宽度一致
  // }
  .full-width {
    width: 100%;
  }
}
:deep(.el-dialog__body) {
  border-top: 0.1rem solid #f0f0f0;
}
/* 新建工单和处理工单的上传组件样式 */
.create-upload,
.detail-upload {
  :deep(.el-upload--picture-card) {
    width: 120px;
    height: 100px;
    line-height: 100px;
  }
  /* 隐藏额外的上传按钮 */
  :deep(.el-upload.el-upload--picture-card) {
    display: none;
  }
  /* 当没有图片时显示上传按钮 */
  :deep(.el-upload.el-upload--picture-card:first-child) {
    display: flex;
  }
  /* 上传组件的预览图片样式 */
  :deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 120px;
    height: 100px;
  }
}
</style>
src/views/tickets/ticketComponent/DispatchDialog.vue
New file
@@ -0,0 +1,244 @@
<template>
  <el-dialog
    v-model="dialogVisible"
    title="派发工单"
    width="40%"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="100px"
      @submit.prevent
    >
      <el-form-item label="选择部门" prop="department">
        <el-tree-select
          v-model="form.department"
          placeholder="请选择部门"
          :data="deptTreeData"
          :props="treeProps"
          :filterable="true"
          :allow-clear="true"
          :check-strictly="true"
          @change="handleDepartmentChange"
          class="full-width"
        />
      </el-form-item>
      <el-form-item label="选择处理人" prop="handler">
        <el-select
          filterable
          v-model="form.handler"
          placeholder="请选择处理人"
          :disabled="!form.department"
          class="full-width"
        >
          <el-option
            v-for="user in availableHandlers"
            :key="user.id"
            :label="user.name"
            :value="user.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose" icon="el-icon-circle-close">取消</el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="handleSubmit"
        icon="el-icon-check"
      >
        确认派发
      </el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { getDeptTree, getDeptLazyTree } from '@/api/system/dept'
import { ElMessage } from 'element-plus';
import { flowEvent } from '@/api/tickets/ticket';
import { onMounted } from 'vue';
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  currentDetail: {
    type: Object,
    default: () => ({})
  },
  departmentUsers: {
    type: Object,
    default: () => ({})
  },
  algorithms: {
    type: Array,
    default: () => []
  },
  types: {
    type: Array,
    default: () => []
  }
});
const emit = defineEmits(['update:modelValue', 'dispatch-success', 'dispatch-error']);
const formRef = ref(null); // 表单引用
const loading = ref(false);
const form = ref({
  department: '',
  handler: ''
});
const deptTreeData =ref([])
// 树形选择器配置
const treeProps = ref({
  value: 'id', // 对应部门数据的id字段(作为选中值)
  label: 'name', // 对应部门数据的name字段(作为显示文本)
  children: 'children' // 对应子部门字段
});
// 获取树形数据
    const getDepartmentTree=() =>{
    const tenantId = '000000'
    getDeptTree(tenantId).then(res => {
    deptTreeData.value = res.data.data
      })
}
// 表单校验规则
const rules = ref({
  department: [{ required: true, message: '请选择部门', trigger: 'change' }],
  handler: [{ required: true, message: '请选择处理人', trigger: 'change' }]
});
const dialogVisible = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit('update:modelValue', value);
  }
});
// 处理人列表
const availableHandlers = computed(() => {
  return form.value.department ? props.departmentUsers[form.value.department] || [] : [];
});
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      resetForm();
    }
  },
  { immediate: true }
);
// 重置表单
const resetForm = () => {
  form.value = {
    department: '',
    handler: ''
  };
  if (formRef.value) {
    formRef.value.clearValidate();
  }
};
// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  resetForm();
};
// 部门切换时清空处理人
const handleDepartmentChange = () => {
  form.value.handler = '';
};
// 验证必填字段(currentDetail 中的必填项)
const validateRequiredFields = () => {
  if (!props.currentDetail.orderName || !props.currentDetail.orderName.trim()) {
    ElMessage.warning('请填写工单名称');
    return false;
  }
  if (!props.currentDetail.type) {
    ElMessage.warning('请选择工单类型');
    return false;
  }
  if (!props.currentDetail.content || !props.currentDetail.content.trim()) {
    ElMessage.warning('请填写工单内容');
    return false;
  }
  return true;
};
// 获取算法值
const getAlgorithmValue = () => {
  const { aiType } = props.currentDetail;
  // 检查是否直接匹配 value
  const isValueMatch = props.algorithms.some(item => item.value === aiType);
  if (isValueMatch) {
    return aiType;
  }
  // 尝试匹配 dict_value 或 label
  const matched = props.algorithms.find(
    item => item.dict_value === aiType || item.label === aiType
  );
  return matched ? matched.value : null;
};
// 提交派发
const handleSubmit = async () => {
  try {
    const valid = await formRef.value.validate();
    if (!valid) return;
    if (!validateRequiredFields()) {
      return;
    }
    loading.value = true;
    const algorithmValue = getAlgorithmValue();
    const data = {
      id: props.currentDetail.id,
      status: props.currentDetail.status,
      isPass: 0, // 0 表示通过
      eventName: props.currentDetail.orderName,
      eventNum: props.currentDetail.orderNumber,
      workOrderTypeDictKey: props.currentDetail.type,
      content: props.currentDetail.content,
      createDept: form.value.department,
      updateUser: form.value.handler,
      aiType: algorithmValue,
    };
    // 发送请求
    const response = await flowEvent(data);
    if (response.data.code === 0) {
      ElMessage.success('工单已成功派发');
      emit('dispatch-success');
      handleClose();
    } else {
      throw new Error(response.data.msg || '派发失败');
    }
  } catch (error) {
    console.error('派发失败:', error);
    emit('dispatch-error', error);
    ElMessage.error(error.message || '派发失败,请稍后重试');
  } finally {
    loading.value = false;
  }
};
onMounted(()=>{
  getDepartmentTree()
})
</script>
<style scoped>
.full-width {
  width: 100%;
}
.el-form {
margin-top: 20px;}
</style>
src/views/tickets/ticketComponent/RecheckDialog.vue
New file
@@ -0,0 +1,117 @@
<template>
  <el-dialog
    v-model="dialogVisible"
    title="工单复核"
    width="30%"
    append-to-body
    class="ztzf-dialog-mange"
    @close="handleClose"
  >
    <div class="dialog-footer">
      <el-button type="primary" @click="handleConfirm(1)">人工复核</el-button>
      <el-button type="primary" @click="handleConfirm(2)">无人机复核</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { ElMessageBox, ElLoading } from 'element-plus';
import { getReviewById, getCreateEventJob } from '@/api/tickets/ticket';
export default {
  name: 'RecheckDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    recheckData: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:modelValue', 'recheck-success'],
  computed: {
    dialogVisible: {
      get() {
        return this.modelValue;
      },
      set(value) {
        this.$emit('update:modelValue', value);
      }
    }
  },
  methods: {
    handleClose() {
      this.dialogVisible = false;
    },
    handleConfirm(key) {
      if (key === 1) {
        this.handleManualRecheck();
      } else {
        this.handleUAVRecheck();
      }
    },
    async handleManualRecheck() {
      try {
        await getReviewById(this.recheckData.id);
        this.$message.success('人工复核成功');
        this.$emit('recheck-success');
        this.dialogVisible = false;
      } catch (error) {
        this.$message.error('人工复核失败');
        console.error('人工复核失败:', error);
      }
    },
    async handleUAVRecheck() {
      const loading = ElLoading.service({
        lock: true,
        text: '复核任务创建中……',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      try {
        const response = await getCreateEventJob(this.recheckData.id);
        const estimatedTime = response.data.data;
        loading.close();
        await ElMessageBox.confirm(
          `预计复核执行时间为${estimatedTime}`,
          '提示',
          {
            confirmButtonText: '确定',
            showCancelButton: false,
            closeOnClickModal: false,
            closeOnPressEscape: false,
            type: 'warning',
          }
        );
        this.$message.success('无人机复核任务创建成功');
        this.$emit('recheck-success');
        this.dialogVisible = false;
      } catch (error) {
        loading.close();
        if (error !== 'cancel') {
          this.$message.error('无人机复核任务创建失败');
          console.error('无人机复核失败:', error);
        }
        this.dialogVisible = false;
      }
    }
  }
};
</script>
<style scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
  padding: 20px 0;
}
</style>
src/views/tickets/ticketComponent/TicketDetailDialog.vue
New file
@@ -0,0 +1,1439 @@
<template>
  <el-dialog
    class="custom-dialog"
    align-center
    v-model="dialogVisible"
    :title="isEditMode ? '编辑工单' : '工单详情'"
    width="80%"
    append-to-body
    @close="handleClose"
  >
    <div class="detail-container">
      <div class="detail-top-title">
        <div class="event-title-center event-orderNumber">
          {{ currentDetail.orderNumber || '工单编号' }}
        </div>
        <div class="event-title-center">{{ currentDetail.orderName || '事件名称' }}</div>
      </div>
      <div v-if="totalTime" class="event-total-time">总耗时:{{ totalTime }}</div>
      <!-- 工单状态流程 -->
      <div class="custom-steps-container">
        <!-- 标题行 -->
        <div class="steps-titles">
          <div
            v-for="(status, index) in stepStatusList"
            :key="index"
            :class="{
              'step-title': true,
              active: index <= stepStatusList.indexOf(String(currentDetail.status)),
            }"
          >
            {{ mapStatus(status) }}
          </div>
        </div>
        <!-- Element Steps 组件 -->
        <el-steps :active="getActiveStep() - 1" align-center class="custom-steps">
          <el-step v-for="(status, index) in stepStatusList" :key="index">
            <template #description>
              <span class="step-description">
                {{ getStepHandler(status) }}
              </span>
              <div class="step-description" v-if="getStepTime(status)">
                <span class="step-timer"> 耗时:{{ getStepTime(status) }} </span>
              </div>
              <div class="step-description">
                {{ getStepCreateTime(status) }}
              </div>
            </template>
          </el-step>
        </el-steps>
      </div>
      <div class="PopUpTableScrolls">
        <!-- 基本信息表格 -->
        <el-table :show-header="false" :data="formattedDetailFields" border class="tableCss">
          <el-table-column prop="label1" label="基本信息" width="150">
            <template #default="{ row }">
              <span
                v-if="
                  currentDetail.status === 0 &&
                  (row.label1 === '关联算法' || row.label1 === '工单名称')
                "
                class="required-label"
              >
                <span class="required-star">*</span>{{ row.label1 }}
              </span>
              <span v-else>{{ row.label1 }}</span>
            </template>
          </el-table-column>
          <el-table-column>
            <template #default="{ row }">
              <template
                v-if="
                  currentDetail.status === 0 &&
                  row.label1 === '工单名称' &&
                  hasProcessingBtnPermission()
                "
              >
                <el-input
                  v-model="currentDetail.orderName"
                  placeholder="请输入工单名称"
                  class="required-input"
                />
              </template>
              <template
                v-else-if="
                  currentDetail.status === 0 &&
                  row.label1 === '关联算法' &&
                  hasProcessingBtnPermission()
                "
              >
                <el-select
                  v-model="currentDetail.aiType"
                  placeholder="请选择关联算法"
                  class="required-input"
                >
                  <el-option
                    v-for="item in algorithms"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
              <template v-else>{{ row.value1 }}</template>
            </template>
          </el-table-column>
          <el-table-column prop="label2" label="基本信息" width="150">
            <template #default="{ row }">
              <span
                v-if="currentDetail.status === 0 && row.label2 === '工单内容'"
                class="required-label"
              >
                <span class="required-star">*</span>{{ row.label2 }}
              </span>
              <span v-else>{{ row.label2 }}</span>
            </template>
          </el-table-column>
          <el-table-column>
            <template #default="{ row }">
              <template
                v-if="
                  currentDetail.status === 0 &&
                  row.label2 === '工单内容' &&
                  hasProcessingBtnPermission()
                "
              >
                <el-input
                  type="textarea"
                  :maxlength="200"
                  show-word-limit
                  v-model="currentDetail.content"
                  placeholder="请输入工单内容"
                  class="required-input"
                />
              </template>
              <template v-else>{{ row.value2 }}</template>
            </template>
          </el-table-column>
        </el-table>
        <!-- 事件处理详情 -->
        <div v-if="[3, 4].includes(currentDetail.status)" class="form-section">
          <div class="section-title">
            <template v-if="currentDetail.status === 3">
              <span class="required-label">
                <span class="required-star">*</span>事件处理详情
              </span>
            </template>
            <template v-else> 事件处理详情</template>
          </div>
          <!-- 处理中状态显示输入框 -->
          <template v-if="currentDetail.status === 3 && hasProcessedAndOverBtnPermission()">
            <el-input
              type="textarea"
              v-model="currentDetail.processingDetail"
              placeholder="请输入事件处理详情"
              :rows="4"
              :maxlength="200"
              show-word-limit
              style="width: 100%; margin-bottom: 10px"
              :disabled="!isCurrentUserAssigned"
            />
          </template>
          <!-- 已完成和已完结状态显示只读文本 -->
          <template v-else>
            <div class="readonly-processing-detail">
              {{ currentDetail.processingDetail }}
            </div>
          </template>
        </div>
        <!-- 上传图片 -->
        <div v-if="[3].includes(currentDetail.status)" class="form-section uploadImg">
          <div class="section-title" v-if="hasProcessedAndOverBtnPermission()">
            <template v-if="currentDetail.status === 3">
              <span class="required-label"> <span class="required-star">*</span>上传图片 </span>
            </template>
            <template v-else> 上传图片</template>
          </div>
          <el-upload
          :disabled="!isCurrentUserAssigned"
            v-if="hasProcessedAndOverBtnPermission()"
            ref="uploadRef"
            :action="'#'"
            :auto-upload="false"
            list-type="picture-card"
            :on-change="handleFileChange"
            :on-remove="handleUploadRemove"
            :before-upload="beforeUpload"
            :file-list="currentDetail.photos || []"
            :limit="1"
            accept="image/*"
            class="detail-upload"
          >
            <template v-if="!currentDetail.photos || currentDetail.photos.length < 1">
              <div class="el-icon-plus">
                <span>+</span>
              </div>
            </template>
          </el-upload>
          <div class="el-upload__tip" v-if="hasProcessedAndOverBtnPermission()">
            (上传照片即可完结工单,只能上传jpg、jpeg、png照片,且不超过5M)
          </div>
        </div>
        <!-- 图片和地图部分 -->
        <div class="media-section">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="media-box">
                <div class="media-title">事件图片</div>
                <div class="media-content">
                  <el-image
                    v-if="currentDetail.mediaUrl"
                    :src="getThumbUrl(currentDetail.mediaUrl)"
                    :preview-src-list="[getPreviewUrl(currentDetail.mediaUrl)]"
                    fit="contain"
                    style="cursor: pointer"
                  >
                    <template #placeholder>
                      <div class="image-placeholder">
                        <i class="el-icon-picture-outline"></i>
                        <span>加载中...</span>
                      </div>
                    </template>
                    <template #error>
                      <div class="image-error">
                        <i class="el-icon-picture-outline"></i>
                        <span>加载失败</span>
                      </div>
                    </template>
                  </el-image>
                  <div v-else class="no-media">暂无图片/视频</div>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="media-box">
                <template v-if="currentDetail.status === 4">
                  <div class="media-title">工单处理图片</div>
                  <div class="media-content">
                    <el-image
                      v-if="currentDetail.updatePhotoUrl"
                      :src="getThumbUrl(currentDetail.updatePhotoUrl)"
                      :preview-src-list="[getPreviewUrl(currentDetail.updatePhotoUrl)]"
                      fit="fill"
                    >
                      <template #placeholder>
                        <div class="image-placeholder">
                          <i class="el-icon-picture-outline"></i>
                          <span>加载中...</span>
                        </div>
                      </template>
                      <template #error>
                        <div class="image-error">
                          <i class="el-icon-picture-outline"></i>
                          <span>加载失败</span>
                        </div>
                      </template>
                    </el-image>
                    <div v-else class="no-media">暂无处理图片</div>
                  </div>
                </template>
                <template v-else>
                  <div class="media-title">
                    地图标记事件点
                    <el-popover
                      v-if="currentDetail.status === 3 || currentDetail.status === 0"
                      popper-class="custom-qrcode-popover"
                      :width="120"
                      :visible="currentDetail.showQR && dialogVisible"
                      placement="top"
                      title=""
                      trigger="click"
                    >
                      <template #reference>
                        <img
                          @click.stop="handleQRCode(currentDetail)"
                          class="QRCodeImg"
                          src="@/assets/images/dataCenter/qrCode.svg"
                          alt=""
                          title="事件导航"
                        />
                      </template>
                      <div class="qrcode-content">
                        <div class="close-btn" @click.stop="currentDetail.showQR = false">×</div>
                        <CreateQRcode
                          v-if="currentDetail.showQR && dialogVisible"
                          :lat-and-lon="currentDetail.location"
                        />
                      </div>
                    </el-popover>
                  </div>
                  <div class="media-content">
                    <map-container v-if="dialogVisible" ref="mapContainerRef" />
                  </div>
                </template>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
      <!-- 操作按钮 -->
      <div class="dialog-footer1-new">
        <div
          :class="currentIndex === 0 ? 'disableds' : ''"
          class="leftBtn"
          @click="handlePrev"
        >
          上一页
        </div>
        <div class="btngroups">
          <template v-if="currentDetail.status === 2">
            <!-- 待审核 -->
            <el-button
              v-if="hasReviewBtnPermission()"
              type="primary"
              :loading="approveLoading"
              @click="handleApprove"
              icon="el-icon-check"
            >
              通过
            </el-button>
            <el-button
              v-if="hasReviewBtnPermission()"
              type="danger"
              :loading="rejectLoading"
              @click="handleReject"
              icon="el-icon-close"
            >
              不通过
            </el-button>
            <el-button @click="handleClose" icon="el-icon-circle-close">取消</el-button>
          </template>
          <template v-else-if="currentDetail.status === 0">
            <el-button
              v-if="hasProcessingBtnPermission()"
              type="primary"
              :loading="dispatchLoading"
              @click="handleApproveAndDispatch"
              icon="el-icon-check"
            >
              受理
            </el-button>
            <el-button
              v-if="hasProcessingBtnPermission()"
              type="danger"
              :loading="rejectLoading"
              @click="handleReject"
              icon="el-icon-close"
            >
              不受理
            </el-button>
            <el-button @click="handleClose" icon="el-icon-circle-close">取消</el-button>
          </template>
          <template v-if="currentDetail.status === 3">
            <!-- 处理中 -->
            <el-button
              v-if="hasProcessedAndOverBtnPermission()"
              type="primary"
              :loading="completeLoading"
              @click="handleComplete"
              icon="el-icon-circle-check"
              :disabled="!isCurrentUserAssigned"
            >
              完成工单
            </el-button>
            <el-button @click="handleClose" icon="el-icon-circle-close">取消</el-button>
          </template>
          <template v-else-if="currentDetail.status === 4">
            <!-- 已完成 -->
            <el-button @click="handleClose" icon="el-icon-circle-close">取消</el-button>
          </template>
        </div>
        <div
          :class="currentIndex === totalItems - 1 ? 'disableds' : ''"
          class="leftBtn"
          @click="handleNext"
        >
          下一页
        </div>
      </div>
    </div>
  </el-dialog>
</template>
<script setup>
import { useStore } from 'vuex'
import { ref, computed, watch, nextTick } from 'vue';
import { flowEvent, getStepInfo } from '@/api/tickets/ticket';
import { getSmallImg, getShowImg } from '@/utils/util';
import CreateQRcode from '@/components/CreateQRcode/CreateQRcode.vue';
import { ElMessage} from 'element-plus';
const store = useStore()
const userInfo = computed(() => store.state.user.userInfo)
const isLoading = ref(false);
// console.log('userInfo',userInfo.value);
// 定义props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  currentDetail: {
    type: Object,
    default: () => ({})
  },
  currentIndex: {
    type: Number,
    default: 0
  },
  totalItems: {
    type: Number,
    default: 0
  },
  algorithms: {
    type: Array,
    default: () => []
  },
  types: {
    type: Array,
    default: () => []
  },
  permission: {
    type: Object,
    default: () => ({})
  },
  stepStatusList: {
    type: Array,
    default: () => []
  },
  workType: {
    type: Number,
    default: 0
  }
});
// 定义emits
const emit = defineEmits([
  'update:modelValue',
  'detail-success',
  'detail-error',
  'prev-item',
  'next-item',
  'update:currentDetail',
  'approve-and-dispatch'
]);
// 响应式数据
const stepInfos = ref([]);
const totalTime = ref('');
const approveLoading = ref(false);
const rejectLoading = ref(false);
const dispatchLoading = ref(false);
const completeLoading = ref(false);
const finalizeLoading = ref(false);
const uploadRef = ref(null);
const mapContainerRef = ref(null);
// 计算属性
const dialogVisible = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit('update:modelValue', value);
  }
});
const isEditMode = computed(() => {
  return props.currentDetail.status === -1;
});
// 是否有权限完成工单
const isCurrentUserAssigned  =computed(()=>{
  const handleUserId = props.currentDetail?.handle_user_id;
  const currentUserId = userInfo.value?.user_id;
   return !!handleUserId && !!currentUserId && String(handleUserId) === String(currentUserId);
})
const formattedDetailFields = computed(() => {
  const fields = [
    { label: '工单名称', value: props.currentDetail.orderName },
    {
      label: '工单类型',
      value: props.types.find(t => t.value === props.currentDetail.type)?.label || props.currentDetail.type,
    },
    { label: '关联任务', value: props.currentDetail.job_name || '/' },
    { label: '工单创建人', value: props.currentDetail.creator },
    { label: '当前状态', value: mapStatus(props.currentDetail.status) },
    { label: '事件地址', value: props.currentDetail.address || props.currentDetail.latAndLon },
    {
      label: '关联算法',
      value: props.algorithms.find(t => t.value === props.currentDetail.aiType)?.label || props.currentDetail.aiType,
    },
    { label: '发起单位', value: props.currentDetail.department },
    { label: '发起任务时间', value: props.currentDetail.startTime },
    { label: '工单内容', value: props.currentDetail.content },
  ];
  const filteredFields = fields.filter(field => field.value !== '/');
  const formattedFields = [];
  for (let i = 0; i < filteredFields.length; i += 2) {
    formattedFields.push({
      label1: filteredFields[i]?.label || '',
      value1: filteredFields[i]?.value || (filteredFields[i]?.label ? '暂无数据' : ''),
      label2: filteredFields[i + 1]?.label || '',
      value2: filteredFields[i + 1]?.value || (filteredFields[i + 1]?.label ? '暂无数据' : ''),
    });
  }
  return formattedFields;
});
// 监听
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal) {
      loadStepInfo();
      initMap();
    }
  }
);
watch(
  () => props.currentDetail,
  (newVal) => {
    if (newVal && dialogVisible.value) {
    isLoading.value = true;
     setTimeout(() => {
        loadStepInfo();
        initMap();
        isLoading.value = false;
      }, 50);
    }
  },
  { deep: true }
);
// 方法
const handleClose = () => {
  dialogVisible.value = false;
};
const handlePrev = () => {
  if (props.currentIndex > 0) {
    emit('prev-item');
  }
};
const handleNext = () => {
  if (props.currentIndex < props.totalItems - 1) {
    emit('next-item');
  }
};
const loadStepInfo = async () => {
  try {
    const stepResponse = await getStepInfo(props.currentDetail.orderNumber);
    const steps = Array.isArray(stepResponse.data.data)
      ? stepResponse.data.data
      : stepResponse.data.data?.steps || [];
    const finishedStep = steps.find(s => String(s.status) === '4');
    totalTime.value = finishedStep && finishedStep.total_time ? finishedStep.total_time : '';
    stepInfos.value = steps.map(step => ({
      status: String(step.status),
      name: step.name,
      time: step.time,
      create_time: step.create_time,
    }));
  } catch (error) {
    stepInfos.value = [];
  }
};
const initMap = () => {
  nextTick(() => {
    if (mapContainerRef.value && mapContainerRef.value.initAddEntity && props.currentDetail.location) {
      mapContainerRef.value.initAddEntity('point', props.currentDetail.location);
    }
  });
};
const mapStatus = (status) => {
  const statusTextMap = {
    2: '待审核',
    0: '待处理',
    3: '处理中',
    4: '已完成',
  };
  return statusTextMap[status] || '未知状态';
};
const getStepHandler = (status) => {
  const step = stepInfos.value.find(step => step.status === status);
  return step ? step.name : '';
};
const getStepTime = (status) => {
  const step = stepInfos.value.find(step => step.status === status);
  return step && step.time && step.time !== '0' ? step.time : false;
};
const getStepCreateTime = (status) => {
  const step = stepInfos.value.find(step => step.status === status);
  return step ? step.create_time : null;
};
const getActiveStep = () => {
  const arr = props.stepStatusList;
  const index = arr.indexOf(String(props.currentDetail.status));
  return index !== -1 ? index + 2 : 1;
};
const handleQRCode = (val) => {
  emit('update:currentDetail', {
    ...props.currentDetail,
    showQR: !val.showQR
  });
};
const getThumbUrl = (url) => {
  if (!url) return '';
  return getSmallImg(url);
};
const getPreviewUrl = (url) => {
  if (!url) return '';
  return getShowImg(url);
};
const hasProcessingBtnPermission = () => {
  return props.permission && props.permission.tickets_processing_btn === true;
};
const hasProcessedAndOverBtnPermission = () => {
  return props.permission && props.permission.tickets_view_processedAndOver === true;
};
// 通过不通过
const hasReviewBtnPermission = () => {
  return props.permission && props.permission.tickets_review_btn === true;
};
// 文件操作方法
const handleFileChange = (file, fileList) => {
  emit('update:currentDetail', {
    ...props.currentDetail,
    photos: fileList
  });
};
const handleUploadRemove = (file, fileList) => {
  emit('update:currentDetail', {
    ...props.currentDetail,
    photos: fileList
  });
};
const beforeUpload = (file) => {
  const isImage = file.type.includes('image');
  const isLt5M = file.size / 1024 / 1024 < 5;
  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!');
    return false;
  }
  return true;
};
// 工单操作方法
const handleApprove = async () => {
  if (approveLoading.value) return;
  approveLoading.value = true;
  try {
    const data = {
      id: props.currentDetail.id,
      status: props.currentDetail.status,
      isPass: 0,
      eventNum: props.currentDetail.orderNumber,
    };
    const response = await flowEvent(data);
    if (response.data.code === 0) {
      ElMessage.success('工单已通过');
      emit('detail-success');
      handleClose();
    } else {
      throw new Error(response.data.msg || '操作失败');
    }
  } catch (error) {
    ElMessage.error(error.message || '操作失败,请稍后重试');
    emit('detail-error', error);
  } finally {
    approveLoading.value = false;
  }
};
const handleReject = async () => {
  if (rejectLoading.value) return;
  rejectLoading.value = true;
  try {
    const data = {
      id: props.currentDetail.id,
      status: props.currentDetail.status,
      isPass: 1,
    };
    const response = await flowEvent(data);
    if (response.data.code === 0) {
      ElMessage.success('工单未通过');
      emit('detail-success');
      handleClose();
    } else {
      throw new Error(response.data.msg || '操作失败');
    }
  } catch (error) {
    ElMessage.error(error.message || '操作失败,请稍后重试');
    emit('detail-error', error);
  } finally {
    rejectLoading.value = false;
  }
};
const handleApproveAndDispatch = () => {
  // 触发派发工单操作,由父组件处理
  emit('approve-and-dispatch', props.currentDetail);
};
const handleComplete = async () => {
  if (completeLoading.value) return;
  completeLoading.value = true;
    if (!props.currentDetail.processingDetail) {
      ElMessage.warning('请先填写事件处理详情');
      completeLoading.value = false;
      return;
    }
    if (!props.currentDetail.photos || props.currentDetail.photos.length === 0) {
      ElMessage.warning('请选择上传图片');
      completeLoading.value = false;
      return;
    }
  try {
    const data = {
      id: props.currentDetail.id,
      status: props.currentDetail.status,
      processingDetails: props.currentDetail.processingDetail,
      eventNum: props.currentDetail.orderNumber,
    };
    const file = props.currentDetail.photos?.[0]?.raw || null;
    const response = await flowEvent(data, file);
    if (response.data.code === 0) {
      ElMessage.success('工单已完成');
      emit('detail-success');
      handleClose();
    } else {
      throw new Error(response.data.msg || '操作失败');
    }
      handleClose();
  } catch (error) {
    console.error('完成工单失败:', error);
    ElMessage.error(error.message || '操作失败,请稍后重试');
    emit('detail-error', error);
      handleClose();
  } finally {
    completeLoading.value = false;
      handleClose();
  }
};
</script>
<style lang="scss">
.custom-dialog {
  height: 96vh;
// min-height: 50vh;
  .el-dialog__body {
    border-top: 0.1rem solid #f0f0f0;
  }
}
.custom-qrcode-popover {
  min-width: 160px !important;
  min-height: 140px !important;
  position: relative;
  .qrcode-content {
    margin-top: 8px;
    .close-btn {
      position: absolute;
      top: 2px;
      right: 2px;
      width: 16px;
      height: 16px;
      line-height: 16px;
      text-align: center;
      cursor: pointer;
      color: #999;
      font-size: 16px;
      z-index: 10;
    }
  }
}
</style>
<style lang="scss" scoped>
.uploadImg {
  margin-bottom: 32px;
}
.tableCss {
  width: 100%;
  margin-bottom: 10px;
}
.step-timer {
  position: absolute;
  right: 92%;
  top: 50%;
  transform: translateY(-50%);
  width: 100px;
  margin-left: 4px;
  color: #666;
  font-size: 12px;
  white-space: nowrap;
}
.event-total-time {
  text-align: center;
  color: #666;
  font-size: 15px;
  margin-bottom: 12px;
}
.action-bar {
  margin-bottom: 16px;
}
.el-dialog {
  .el-form-item {
    margin-bottom: 20px;
  }
}
.el-upload {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  :deep(.el-upload-list__item) {
    transition: all 0.3s ease;
  }
  :deep(.el-upload-list__item:hover) {
    background-color: #f5f7fa;
  }
}
.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 12px;
}
.create-ticket-form {
  padding: 20px 10px;
  .form-section {
    background-color: #fff;
    border-radius: 4px;
    .el-row {
      margin-bottom: 16px;
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
  .location-wrapper {
    width: 100%; // 修改为100%以适应父容器
    height: auto; // 修改为auto以自适应内容
    .map-button {
      width: 100%; // 让按钮填满容器宽度
      height: 36px; // 与其他输入框保持一致的高度
      display: flex;
      align-items: center;
      justify-content: center;
      i {
        margin-right: 4px;
      }
    }
    .location-text {
      margin-top: 8px;
      padding: 8px 12px;
      background-color: #f5f7fa;
      border-radius: 4px;
      color: #606266;
      font-size: 13px;
      line-height: 1.4;
    }
  }
  .upload-wrapper {
    .uploader {
      :deep(.el-upload--picture-card) {
        width: 120px;
        height: 100px;
        line-height: 128px;
      }
      :deep(.el-upload-list__item) {
        width: 120px;
        height: 120px;
      }
    }
    .upload-tip {
      font-size: 12px;
      color: #909399;
      line-height: 1.4;
      margin-top: 8px;
    }
  }
  .el-form-item {
    margin-bottom: 18px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #606266;
  }
  :deep(.el-textarea__inner) {
    padding: 8px 12px;
  }
  .full-width {
    width: 100%;
  }
}
:deep(.el-dialog__body) {
  border-top: 0.1rem solid #f0f0f0;
}
.dialog-footer-new {
  text-align: right;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
  .el-button + .el-button {
    margin-left: 12px;
  }
  .el-button {
    padding: 9px 20px;
    &:last-child {
      margin-left: 12px;
    }
  }
}
.dialog-footer1-new {
  position: sticky;
  bottom: 28px;
  left: 0;
  right: 0;
  background: white;
  z-index: 10;
  padding: 16px 20px;
  border-top: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .el-button + .el-button {
    margin-left: 12px;
  }
  .btngroups {
    margin-left: 12px;
  }
  .el-button {
    padding: 9px 20px;
    &:last-child {
      margin-left: 12px;
      margin-right: 12px;
    }
  }
}
.map-container {
  width: 100%;
  height: 400px;
  margin-bottom: 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
  :deep(.el-input-map) {
    height: 100%;
  }
}
.location-info {
  margin-top: 10px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  p {
    margin: 5px 0;
    color: #606266;
    font-size: 14px;
  }
}
.map-select {
  display: flex;
  align-items: flex-start;
  gap: 15px;
  .selected-location {
    flex: 1;
    padding: 5px 10px;
    background-color: #f5f7fa;
    border-radius: 4px;
    p {
      margin: 5px 0;
      color: #606266;
      font-size: 14px;
    }
  }
}
.preview-image {
  border-radius: 4px;
  overflow: hidden;
  background-color: #f5f7fa;
}
.image-placeholder,
.image-error,
.no-media {
  height: 200px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  background-color: #f5f7fa;
  border-radius: 4px;
  i {
    font-size: 32px;
    margin-bottom: 8px;
  }
}
.no-media {
  border: 1px dashed #d9d9d9;
}
.detail-container {
  padding: 0 20px;
  .detail-top-title {
    display: flex;
    justify-content: center;
    align-items: center;
    .event-orderNumber {
      margin-right: 10px;
    }
  }
}
.status-flow {
  margin-bottom: 20px;
  .custom-steps {
    .el-step__description {
      position: relative;
      margin: 0;
      padding: 0;
    }
    // 添加发起任务步骤的特殊样式
    .init-step-info {
      display: flex;
      flex-direction: column;
      align-items: center;
      text-align: center;
      width: 130px;
      .creator-name {
        font-size: 14px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 4px;
      }
      .create-time {
        font-size: 10px;
        color: #909399;
      }
    }
    // 保持其他步骤的原有样式
    .step-info {
      display: flex;
      margin: 0;
      padding: 0;
      justify-content: space-between;
      align-items: center;
      width: 200px;
      .process-time {
        font-size: 10px;
        color: #909399;
        text-align: left;
        margin-left: -50%;
        padding-left: 0%;
        flex: 1;
      }
      .handler-name {
        font-size: 14px;
        font-weight: bold;
        color: #303133;
        text-align: left;
        flex: 1;
      }
    }
  }
}
.basic-info {
  margin-bottom: 20px;
}
.media-section {
  // margin-bottom: 20px;
  .el-row {
    display: flex;
    align-items: center;
  }
}
.leftBtn {
  width: 70px;
  height: 32px;
  background-color: #999;
  border-radius: 5px;
  text-align: center;
  line-height: 32px;
  color: #fff;
  cursor: pointer;
  opacity: 0.8;
}
.disableds {
  background: #999 !important;
  cursor: not-allowed !important;
  pointer-events: none;
  opacity: 0.3 !important;
}
.PopUpTableScrolls {
  max-height: 600px;
  overflow-y: scroll;
  overflow-x: hidden;
}
.media-box {
  width: 100%;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  background: #fff;
  box-sizing: border-box;
  .media-title {
    font-weight: bold;
    margin-bottom: 5px;
    display: flex;
    align-items: center;
    .QRCodeImg {
      width: 18px;
      height: 18px;
      cursor: pointer;
      padding-bottom: 1px;
    }
  }
  .media-content {
    position: relative;
    height: 500px;
    :deep(.el-image) {
      width: 100% !important;
      max-width: 100%;
      max-height: 100%;
      .el-image__inner {
        width: 100%;
        height: 100%;
        object-fit: cover !important;
      }
    }
  }
}
.image-placeholder,
.image-error,
.no-media {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.image-placeholder i,
.image-error i {
  font-size: 32px;
  margin-bottom: 8px;
}
.no-media {
  border: 1px dashed #d9d9d9;
}
.info-table {
  margin-bottom: 20px;
}
.info-item {
  display: flex;
  margin-bottom: 10px;
}
.info-label {
  font-weight: bold;
  width: 120px;
  color: #606266;
}
.info-value {
  flex: 1;
  color: #303133;
  word-break: break-word;
}
.readonly-processing-detail {
  background-color: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  min-height: 30px;
  color: #606266;
  line-height: 1.5;
  display: block;
  text-align: left;
  margin-bottom: 5px;
  &:first-child {
    font-weight: bold;
    margin-bottom: 4px;
  }
}
// 添加删除按钮样式
.danger-button {
  color: #f56c6c;
}
.danger-button:hover {
  color: #f78989;
}
.custom-steps-container {
  width: 100%;
  margin: 10px 0;
}
.steps-titles {
  display: flex;
  justify-content: space-between;
  margin-bottom: 14px;
  position: relative;
}
.step-title {
  text-align: center;
  flex: 1;
  font-size: 14px;
  color: #999;
  position: relative;
  padding-bottom: 5px;
}
.step-title.active {
  color: #409eff;
  font-weight: bold;
}
.event-title-center {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 5px;
  color: #333;
}
.custom-steps {
  margin-top: -20px;
  :deep(.el-step__description) {
    margin-top: 8px;
    padding: 0 20px;
  }
}
.step-description {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  display: block;
  text-align: center;
  &:first-child {
    font-weight: bold;
    margin-bottom: 4px;
  }
}
// 覆盖其他相关样式
.status-flow {
  .custom-steps {
    .el-step__description {
      position: relative;
      margin: 0;
      padding: 0;
    }
    // 移除之前的样式
    .init-step-info,
    .step-info {
      display: block;
      width: auto;
      text-align: center;
    }
  }
}
/* 新建工单和处理工单的上传组件样式 */
.create-upload,
.detail-upload {
  :deep(.el-upload--picture-card) {
    width: 120px;
    height: 100px;
    line-height: 100px;
  }
  /* 隐藏额外的上传按钮 */
  :deep(.el-upload.el-upload--picture-card) {
    display: none;
  }
  /* 当没有图片时显示上传按钮 */
  :deep(.el-upload.el-upload--picture-card:first-child) {
    display: flex;
  }
  /* 上传组件的预览图片样式 */
  :deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 120px;
    height: 100px;
  }
}
/* 原有图片预览的样式 */
.el-image-viewer__wrapper {
  :deep(.el-image-viewer__img) {
    max-width: 100%;
    max-height: 100%;
    object-fit: contain;
  }
}
/* 必填项样式 */
.required-label {
  position: relative;
  display: inline-block;
  .required-star {
    color: #f56c6c;
    margin-right: 4px;
  }
}
/* 必填输入框样式 */
.required-input {
  width: 100%;
  :deep(.el-input__inner),
  :deep(.el-textarea__inner) {
    &:focus {
      border-color: #409eff;
    }
  }
}
</style>