无人机管理后台前端(已迁走)
张含笑
2025-11-21 ecfec8fe862440c703ae64e1a5b23dffe41d8fa8
feat:vue3
1 files modified
2293 ■■■■■ changed files
src/views/tickets/ticket.vue 2293 ●●●●● patch | view | raw | blame | history
src/views/tickets/ticket.vue
@@ -110,7 +110,6 @@
            </el-form>
          </div>
          <!-- 表格部分 -->
            <!-- 表格操作按钮 -->
          <div class="table-operations">
            <div class="left-operations">
              <el-button
@@ -398,7 +397,10 @@
  </basic-container>
</template>
<script >
<script setup>
import { ElMessage} from 'element-plus';
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { pxToRem, pxToRemNum } from '@/utils/rem';
import { getSmallImg, getShowImg } from '@/utils/util';
import { calculateDefaultRange } from '@/utils/util';
@@ -424,781 +426,630 @@
import CreateTicketDialog from '@/views/tickets/ticketComponent/CreateTicketDialog.vue';
import TicketDetailDialog from '@/views/tickets/ticketComponent/TicketDetailDialog.vue';
const { envName } = getBaseConfig();
const route = useRoute()
const router = useRouter()
const store = useStore()
const currentIndex = ref(null)
const finalizeLoading = ref(false)
const activeTab = ref('all')
const tabs = ref([
  { label: '我的工单', name: 'myTickets', value: null, count: 0 },
  { 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 },
])
const filters = reactive({
  keyword: '',
  department: '',
  type: '',
  dateRange: [],
  status: '',
  algorithm: '',
  isReview: '',
})
const departments = ref([])
const types = ref([])
const allAlgorithms = ref([])
const handlers = ref([
  { label: '处理人A', value: 'handlerA' },
  { label: '处理人B', value: 'handlerB' },
])
const algorithms = ref([])
const algorithms2 = ref([])
const statuses = ref([
  { label: '待审核', value: '2' },
  { label: '待处理', value: '0' },
  { label: '处理中', value: '3' },
  { label: '已完成', value: '4' },
])
const reviewStatuses = ref([
  { label: '否', value: 0 },
  { label: '是', value: 1 },
])
const tableData = ref([])
const option = reactive({
  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: '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 },
  ],
})
const page = reactive({
  pageSize: 10,
  currentPage: 1,
  total: 0,
})
const dialogVisible = ref(false)
const editFormData = ref(null)
const detailVisible = ref(false)
const currentDetail = ref({})
const departmentUsers = ref({})
const loading = ref(false)
const globalCounts = ref({})
const mapLoaded = ref(false)
const isFetching = ref(false)
const mapParams = reactive({
  zoom: 15,
  center: null,
})
const dispatchDialogVisible = ref(false)
const stepInfos = ref([])
const fixedStatuses = ref(['2', '0', '3', '4'])
const userNameToIdMap = ref({})
const workType = ref(0)
const selections = ref([])
const reviewDialogVisible = ref(false)
const currentReviewImage = ref('')
const currentImageIndex = ref(1)
const totalTime = ref('')
const isShowInfo = ref(false)
const datePickerDefaultVal = ref(calculateDefaultRange())
const reCheckDialog = ref(false)
const reCheckData = ref({})
const treePropsSF = reactive({
  label: 'dictValue',
  value: 'id',
  children: 'children',
})
const dictKey = ref('')
const dataList = ref([])
const checkedKeys = ref([])
const inputMapShowDefaultCenter = ref(null)
const userInfo = computed(() => store.state.user.userInfo)
console.log('userInfo',userInfo);
const permission = computed(() => store.state.user.permission);
// 计算属性
const firstRowData = computed(() => {
  return tableData.value.length > 0 ? tableData.value[0] : null
})
 // 动态过滤tabs,保证isShow为true/false
 const filteredTabs = computed(() => {
  const tabStatus = permission.value?.tickets_tab_status === true
  const tabPending = permission.value?.tickets_tab_pending === true
  const tabMyTickets = permission.value?.tickets_tab_mytickets === true
  return tabs.value
    .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)
})
 // 可根据实际后端权限key调整
const permissionList = computed(() => {
  return {
    addBtn: validData(permission.value.tickets_add, false),
    delBtn: validData(permission.value.tickets_delete, false),
    exportBtn: validData(permission.value.tickets_export, false),
    reviewBtn: validData(permission.value.tickets_review, false),
  }
})
const stepStatusList = computed(() => {
// “我发起的工单”tab用默认流程,其它tab用接口返回的stepInfos
  if (activeTab.value === 'myTickets') {
    if (workType.value === 1) {
      return ['3', '4']
    }
    return fixedStatuses.value
  }
   // 其它tab直接用接口返回的stepInfos
  return stepInfos.value.map(step => String(step.status))
})
const showIsReviewText = computed(() => (row) => {
  if (['4'].includes(String(row.status))) return row.isReview === 1 ? '是' : '否'
  return '/'
})
const popupShowImage = computed(() => (list) => {
  return list.map(item => ({
    ...item,
    url: getShowImg(item.url),
  }))
})
// 方法
function regExp(label, name) {
  var reg = new RegExp(label + '=([^&]*)(&|$)', 'g');
  return name.match(reg)[0].split('=')[1];
  const reg = new RegExp(label + '=([^&]*)(&|$)', 'g')
  return name.match(reg)[0].split('=')[1]
}
export default {
  components: { elTooltipCopy, RecheckDialog,DispatchDialog,CreateTicketDialog,TicketDetailDialog, },
  name: 'TicketPage',
  data() {
    return {
      currentIndex: null, // 当前显示的数据索引
      finalizeLoading: false,
      activeTab: 'all',
      // tabs 只保留静态结构,不做权限判断
      tabs: [
        { label: '我的工单', name: 'myTickets', value: null, count: 0 },
        { 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 },
      ,
      ],
      filters: {
        keyword: '',
        department: '',
        type: '',
        dateRange: [],
        status: '',
        algorithm: '', // 新增算法筛选字段
        isReview: '', // 添加复核状态筛选字段
      },
      departments: [],
      types: [],
      allAlgorithms: [],
      handlers: [
        { label: '处理人A', value: 'handlerA' },
        { label: '处理人B', value: 'handlerB' },
      ],
      algorithms: [],
      algorithms2: [],
      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: '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, // 专门用于存储编辑数据的对象
      detailVisible: false,
      currentDetail: {},
      departmentUsers: {},
      loading: false,
      globalCounts: {},
      mapLoaded: false,
      isFetching: false,
      mapParams: {
        zoom: 15,
        center: null, // 初始设为 null,等待动态设置
      },
      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 = {};
    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: {
    firstRowData() {
      return this.tableData.length > 0 ? this.tableData[0] : null;
    },
    ...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 => ({
function validData(value, defaultValue) {
  return value !== undefined ? value : defaultValue
}
function findObject(array, prop) {
  return array.find(item => item.prop === prop)
}
// 获取工单类型标签
function getTypeLabel(typeValue) {
  const typeObj = types.value.find(item => item.value === typeValue)
  return typeObj ? typeObj.label : typeValue
}
function handleCheck(data, { checkedKeys: keys, checkedNodes }) {
  checkedKeys.value = keys
  const selectedDictKeys = checkedNodes.map(node => node.dictKey).filter(Boolean)
  filters.type = selectedDictKeys
  fetchTableData()
}
// 算法
function 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,
          url: getShowImg(item.url),
        }));
      };
    },
  },
  methods: {
  // 获取工单类型标签
  getTypeLabel(typeValue) {
    const typeObj = this.types.find(item => item.value === typeValue);
    return typeObj ? typeObj.label : typeValue;
  },
    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;
          children: children || [],
        }
      });
    },
      })
      dataList.value = filteredData
    }
  })
}
function handleSFNodeClick(data) {
  filters.type = ''
  filters.algorithm = ''
  filters.type = data.dictKey
  fetchTableData()
}
function handleClear() {
  dictKey.value = ''
  filters.algorithm = ''
  filters.type = ''
  fetchTableData()
}
// 上一项
function handlePrevItem() {
  currentIndex.value = Math.max(0, currentIndex.value - 1)
  updateCurrentDetail()
}
    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();
    },
     // 上一项
    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.processing_details;
      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;
    },
// 下一项
function handleNextItem() {
  currentIndex.value = Math.min(tableData.value.length - 1, currentIndex.value + 1)
  updateCurrentDetail()
}
    // 受理并派发
    handleApproveAndDispatch(detail) {
      this.currentDetail = detail;
      this.dispatchDialogVisible = true;
    },
// 更新当前详情
function updateCurrentDetail() {
  currentDetail.value = tableData.value[currentIndex.value]
  currentDetail.value.mediaUrl = currentDetail.value.photo_url
  currentDetail.value.updatePhotoUrl = currentDetail.value.update_photo_url
  currentDetail.value.processingDetail = currentDetail.value.processing_details
  currentDetail.value.showQR = false
  currentDetail.value.latAndLon = _.round(currentDetail.value.location[0], 6) + ',' + _.round(currentDetail.value.location[1], 6)
  getStepInfoData(currentDetail.value.orderNumber)
}
    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 = [];
        return;
      }
      const matchedCategory = this.allAlgorithms.find(category => category.dict_key === typeValue);
      if (
        !matchedCategory ||
        !matchedCategory.algorithms ||
        matchedCategory.algorithms.length === 0
      ) {
        // 无匹配的算法时清空
        this.algorithms2 = [];
        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,
      }));
    },
    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(val) {
  console.log('1111', val);
  const params = {
    "status_list": val
  }
// 更新当前详情数据
function handleCurrentDetailUpdate(updatedDetail) {
  currentDetail.value = updatedDetail
}
// 受理并派发
function handleApproveAndDispatch(detail) {
  currentDetail.value = detail
  dispatchDialogVisible.value = true
}
async function loadAMapScripts() {
  try {
    const response = await getstatusCount(params);
    console.log('response', response.data.data);
    const statusCount = response.data.data || {}; // 确保statusCount是对象
    // 先计算总工单数(所有状态之和)
    const totalCount = Object.values(statusCount).reduce((sum, count) => sum + (count || 0), 0);
    this.tabs.forEach(tab => {
      if (tab.name === 'all') {
        tab.count = totalCount;
      } else if (tab.name === 'myTickets') {
    const areaCode = userInfo.value.detail.areaCode
    const subAreaCode = areaCode ? areaCode.substring(0, 6) : ''
    const adcodeObj = getAdcodeObj(geoJson, 'adcode', subAreaCode)
        tab.count = 0;
    const center = adcodeObj?.payload?.objects?.collection?.geometries?.[0]?.properties?.center
    if (Array.isArray(center) && center.length === 2) {
      inputMapShowDefaultCenter.value = center
    } else {
      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
        inputMapShowDefaultCenter.value = [centerX, centerY]
      } else {
        // 根据tab的value匹配statusCount中的key
        tab.count = statusCount[String(tab.value)] || 0;
        inputMapShowDefaultCenter.value = [115.861365, 28.621311]
      }
    });
    }
    mapParams.center = [...inputMapShowDefaultCenter.value]
    mapLoaded.value = true
  } catch (error) {
    this.tabs.forEach(tab => {
      tab.count = 0;
    });
    console.error('地图加载失败:', error)
  }
},
handleTabChange(tab) {
  console.log('tab', tab);
  this.activeTab = tab.props?.name || tab.name;
  console.log('this.activeTab', this.activeTab);
  // 传递所有需要统计的状态列表
  const statusList = ['0', '2', '3', '4'];
  this.fetchTabCounts(statusList);
  this.handleReset();
  this.page.currentPage = 1;
  this.fetchTableData();
},
    //新增 跳转后触发的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;
    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) {
}
async function fetchDropdownData() {
  try {
  const orderNum = val
    const stepResponse = await getStepInfo(orderNum);
    const response = await getTicketInfo()
    const { dept_data, event_type, ai_type, info } = response.data.data
    departments.value = dept_data.map(item => ({
      label: item.dept_name,
      value: item.id,
    }))
    departmentUsers.value = dept_data.reduce((acc, dept) => {
      acc[dept.id] = dept.user_data || []
      return acc
    }, {})
    types.value = Object.entries(event_type).map(([key, value]) => ({
      label: value,
      value: key,
    }))
    const columnType = findObject(option.column, 'type')
    columnType.dicData = types.value
    allAlgorithms.value = info
    algorithms.value = ai_type?.map(item => ({
      dict_key: item.dict_key,
      dict_value: item.dict_value,
      label: item.dict_value,
      value: item.dict_key,
    })) || []
    algorithms2.value = _.cloneDeep(algorithms.value)
    userNameToIdMap.value = {}
    dept_data.forEach(dept => {
      (dept.user_data || []).forEach(user => {
        userNameToIdMap.value[user.name] = user.id
      })
    })
  } catch (error) {
    console.error('加载下拉框数据失败:', error)
  }
}
// 获取表格数据
async function fetchTableData() {
  if (isFetching.value) return
  isFetching.value = true
  loading.value = true
  try {
    const currentTab = tabs.value.find(tab => tab.name === activeTab.value)
    const params = {
      ai_types: filters.type || undefined,
      status: currentTab?.name === 'myTickets'
        ? undefined
        : filters.status !== ''
        ? Number(filters.status)
        : currentTab?.value,
      event_name: filters.keyword || undefined,
      dept_id: filters.department || undefined,
      start_date: filters.dateRange?.[0]
        ? formatDate(filters.dateRange[0])
        : undefined,
      end_date: filters.dateRange?.[1]
        ? formatDate(filters.dateRange[1]).replace('00:00:00', '23:59:59')
        : undefined,
      current: Number(page.currentPage),
      size: Number(page.pageSize),
      ai_type: filters.algorithm || undefined,
      is_draft: currentTab?.name === 'myTickets' ? 1 : undefined,
      user_id: currentTab?.name === 'myTickets' ? userInfo.value.user_id : undefined,
      is_review: filters.isReview === '' ? undefined : 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
    tableData.value = filteredRecords.map(item => {
      const longitude = Number(item.longitude) || 0
      const latitude = Number(item.latitude) || 0
      return {
        id: item.id,
        orderNumber: item.event_num,
        orderName: item.event_name,
        department: departments.value.find(d => d.value === item.dept_id)?.label || item.dept_name,
        startTime: item.job_create_time || '/',
        aiType: item.ai_types,
        content: item.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 || '',
        video_url: item.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,
        job_name: item.job_name || '',
        job_create_time: item.job_create_time || '',
        isReview: item.is_review,
      }
    })
    page.total = total || 0
    if (isShowInfo.value) {
      handleViewDetail(firstRowData.value)
      isShowInfo.value = false
    }
    await fetchTabCounts()
  } catch (error) {
    console.error('获取数据失败:', error)
    tableData.value = []
    page.total = 0
  } finally {
    loading.value = false
    isFetching.value = false
  }
}
function handleTypeChange(typeValue) {
  if (!typeValue) {
    algorithms2.value = []
    return
  }
  const matchedCategory = allAlgorithms.value.find(category => category.dict_key === typeValue)
  if (!matchedCategory || !matchedCategory.algorithms || matchedCategory.algorithms.length === 0) {
    algorithms2.value = []
    return
  }
  algorithms2.value = matchedCategory.algorithms.map(algo => ({
    label: algo.dict_value,
    value: algo.dict_key,
    dict_key: algo.dict_key,
    dict_value: algo.dict_value,
  }))
}
function 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`
}
function mapStatus(status) {
  const statusTextMap = {
    '-1': '草稿',
    2: '待审核',
    0: '待处理',
    3: '处理中',
    4: '已完成',
  }
  return statusTextMap[status] || '未知状态'
}
function getStatusTagType(status) {
  if (status === -1 || status === '-1') return ''
  const colorMap = {
    0: '#FF7411',
    3: '#FFC300',
    2: '#FF472F',
    4: '#0291A1',
  }
  return colorMap[String(status)] || ''
}
async function fetchTabCounts(val) {
  const params = {
    status_list: val
  }
  try {
    const response = await getstatusCount(params)
    const statusCount = response.data.data || {}
    const totalCount = Object.values(statusCount).reduce((sum, count) => sum + (count || 0), 0)
    tabs.value.forEach(tab => {
      if (tab.name === 'all') {
        tab.count = totalCount
      } else if (tab.name === 'myTickets') {
        tab.count = 0
      } else {
        tab.count = statusCount[String(tab.value)] || 0
      }
    })
  } catch (error) {
    console.error('获取标签页计数失败:', error)
    tabs.value.forEach(tab => {
      tab.count = 0
    })
  }
}
function handleTabChange(tab) {
  activeTab.value = tab.props?.name || tab.name
  const statusList = ['0', '2', '3', '4']
  fetchTabCounts(statusList)
  handleReset()
  page.currentPage = 1
  fetchTableData()
}
// 跳转后触发的Tab切换
function handleTabChangeAfterJump() {
  const isReview = findObject(option.column, 'isReview')
  isReview.hide = !['all', 'completed', 'myTickets'].includes(activeTab.value)
  handleReset()
  page.currentPage = 1
  fetchTableData()
  fetchTabCounts()
}
function handleSearch() {
  page.currentPage = 1
  fetchTableData()
  fetchTabCounts()
}
function handleReset() {
  dictKey.value = ''
  Object.assign(filters, {
    keyword: '',
    department: '',
    type: '',
    dateRange: [],
    status: '',
    algorithm: '',
    isReview: '',
  })
  page.currentPage = 1
  router.replace({})
  fetchTableData()
}
function handleKeyWords() {
  router.replace({})
}
// 分页
async function handleCurrentChange(val) {
  page.currentPage = val
  await nextTick()
  await fetchTableData()
}
async function sizeChange(val) {
  page.pageSize = val
  page.currentPage = 1
  await nextTick()
  await fetchTableData()
}
function handleAdd() {
  editFormData.value = null
  dialogVisible.value = true
}
async function 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 || [];
      : stepResponse.data.data?.steps || []
    
    const finishedStep = steps.find(s => String(s.status) === '4');
    this.totalTime = finishedStep && finishedStep.total_time ? finishedStep.total_time : '';
    const finishedStep = steps.find(s => String(s.status) === '4')
    totalTime.value = finishedStep && finishedStep.total_time ? finishedStep.total_time : ''
    
    if (this.activeTab !== 'myTickets') {
      this.stepInfos = steps.map(step => ({
    if (activeTab.value !== 'myTickets') {
      stepInfos.value = 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));
      const statusArr = workType.value === 1 ? ['3', '4'] : fixedStatuses.value
      stepInfos.value = 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; // 表示成功获取数据
    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 => ({
    console.error('获取步骤信息失败:', error)
    if (activeTab.value === 'myTickets') {
      const statusArr = workType.value === 1 ? ['3', '4'] : fixedStatuses.value
      stepInfos.value = statusArr.map(status => ({
        status,
        name: status === row.status ? row.handler || '未分配' : '未处理',
        time: status === row.status ? row.startTime || '未知时间' : null,
      }));
      }))
    } else {
      this.stepInfos = [];
      stepInfos.value = []
    }
    return false; // 表示获取数据失败
    return false
  }
},
   async handleViewDetail(row) {
   console.log('row',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;
}
async function handleViewDetail(row) {
  currentIndex.value = tableData.value.findIndex(item => item.id === row.id)
  workType.value = row.work_type !== undefined ? Number(row.work_type) : 0
  const detailData = {
    ...row,
@@ -1207,521 +1058,464 @@
    updatePhotoUrl: row.update_photo_url || '',
    photos: [],
    job_name: row.job_name || '',
  };
  }
  // 获取步骤信息
  await this.getStepInfoData(row.orderNumber);
  this.currentDetail.status = row.status;
  await getStepInfoData(row.orderNumber)
  currentDetail.value.status = row.status
 
  this.currentDetail = {
  currentDetail.value = {
    ...detailData,
    showQR: false,
    latAndLon: _.round(detailData.location[0], 6) + ',' + _.round(detailData.location[1], 6),
  };
  }
  console.log('this.currentDetail', this.currentDetail);
  detailVisible.value = true
  handleTypeChange(currentDetail.value.type)
}
  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);
// 详情成功回调
function handleDetailSuccess() {
  fetchTableData()
}
// 详情错误回调
function handleDetailError(error) {
  console.error('工单操作失败:', error)
}
function refreshChange() {
  if (isFetching.value) return
  fetchTableData()
}
function onLoad() {
  if (isFetching.value) return
  fetchTableData()
}
async function exportData() {
  try {
    loading.value = true
    let exportData = []
    if (selections.value.length > 0) {
      exportData = selections.value.map(item => formatExportItem(item))
    } else {
      exportData = tableData.value.map(item => formatExportItem(item))
    }
  });
},
 // 详情成功回调
    handleDetailSuccess() {
      this.fetchTableData();
    },
    // 详情错误回调
    handleDetailError(error) {
      console.error('工单操作失败:', error);
    },
    if (exportData.length === 0) {
      console.warn('没有数据可供导出')
      return
    }
    const headers = [
      '工单编号',
      '工单名称',
      '所属部门',
      '发起时间',
      '关联算法',
      '工单内容',
      '工单类型',
      '经纬度',
      '创建人',
      '处理人',
      '工单状态',
    ]
   refreshChange() {
    if (this.isFetching) return;
    this.fetchTableData();
  },
    export_json_to_excel(headers, exportData, '工单数据')
    console.log('数据导出成功')
  } catch (error) {
    console.error('导出失败:', error)
  } finally {
    loading.value = false
  }
}
    onLoad() {
      if (this.isFetching) return;
      this.fetchTableData();
    },
function formatExportItem(item) {
  const longitude = Number(item.longitude) || Number(item.location?.[0]) || 0
  const latitude = Number(item.latitude) || Number(item.location?.[1]) || 0
    async exportData() {
      try {
        this.loading = true;
        let exportData = [];
  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 || '',
    工单类型: types.value.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 || '',
    工单状态: mapStatus(Number(item.status || 0)),
  }
}
// 派发成功回调
function handleDispatchSuccess() {
  detailVisible.value = false
  fetchTableData()
}
// 派发错误回调
function handleDispatchError(error) {
  console.error('派发失败:', error)
}
// 编辑工单
function handleEdit(row) {
  editFormData.value = row
  dialogVisible.value = true
}
        // 如果有选中的数据,则导出选中的数据
        if (this.selections.length > 0) {
          exportData = this.selections.map(item => this.formatExportItem(item));
        } else {
          // 没有选中数据时,导出当前页面的数据
          exportData = this.tableData.map(item => this.formatExportItem(item));
// 创建成功回调
function handleCreateSuccess() {
  fetchTableData()
}
// 草稿保存成功回调
function handleDraftSuccess() {
  fetchTableData()
}
// 创建失败回调
function handleCreateError(error) {
  console.error('工单操作失败:', error)
}
// 删除方法
function handleDelete(row) {
  console.log('删除工单:', row)
}
// 添加选择变化处理方法
function handleSelectionChange(selection) {
  selections.value = selection
}
// 打开审核对话框
function openReviewDialog() {
  if (selections.value.length === 0) {
       ElMessage.warning('请先选择要审核的工单');
    return
  }
  currentImageIndex.value = 1
  updateCurrentReviewImage()
  reviewDialogVisible.value = true
}
// 更新当前审核图片
function updateCurrentReviewImage() {
  if (!selections.value || selections.value.length === 0) {
    currentReviewImage.value = ''
    currentImageIndex.value = 1
    return
  }
  if (currentImageIndex.value > selections.value.length) {
    currentImageIndex.value = selections.value.length
  }
  if (currentImageIndex.value < 1) {
    currentImageIndex.value = 1
  }
  const index = currentImageIndex.value - 1
  if (index >= 0 && index < selections.value.length) {
    const currentItem = selections.value[index]
    currentReviewImage.value = currentItem.photo_url || ''
  } else {
    currentReviewImage.value = ''
  }
}
// 处理图片分页变化
function handleImagePageChange(page) {
  if (page > 0 && page <= selections.value.length) {
    currentImageIndex.value = page
    updateCurrentReviewImage()
  }
}
// 批量审核通过
async function handleBatchApprove() {
  try {
    if (selections.value.length === 0) {
      console.warn('没有选中的工单')
      return
    }
    const currentItem = selections.value[currentImageIndex.value - 1]
    if (!currentItem) {
      console.warn('当前工单数据无效')
      return
    }
    // 在Vue 3中需要使用ElMessageBox.confirm
    const data = {
      id: currentItem.id,
      status: currentItem.status,
      isPass: 0,
      eventNum: currentItem.orderNumber,
    }
    const response = await flowEvent(data)
    if (response.data.code === 0) {
      console.log('工单审核通过')
      const newSelections = [...selections.value]
      newSelections.splice(currentImageIndex.value - 1, 1)
      if (newSelections.length > 0) {
        if (currentImageIndex.value > selections.value.length) {
          currentImageIndex.value = selections.value.length
        }
        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.elTable.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 || '';
        updateCurrentReviewImage()
      } 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));
          }
        }
        reviewDialogVisible.value = false
        currentImageIndex.value = 1
        currentReviewImage.value = ''
        fetchTableData()
      }
      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('数据导出成功');
      selections.value = newSelections
    } else {
      throw new Error(response.data.msg || '审核失败')
    }
  },
  activated() {
    this.handleReset();
  },
};
  } catch (error) {
    console.error('审核失败:', error)
  }
}
function cancleBatchReject() {
  reviewDialogVisible.value = false
  selections.value = []
  currentImageIndex.value = 1
  currentReviewImage.value = ''
  fetchTableData()
}
// 批量审核不通过
async function handleBatchReject() {
  try {
    if (selections.value.length === 0) {
      console.warn('没有选中的工单')
      return
    }
    const currentItem = selections.value[currentImageIndex.value - 1]
    if (!currentItem) {
      console.warn('当前工单数据无效')
      return
    }
    // 在Vue 3中需要使用ElMessageBox.confirm
    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) {
      console.log('工单审核不通过')
      const newSelections = [...selections.value]
      newSelections.splice(currentImageIndex.value - 1, 1)
      selections.value = newSelections
      if (selections.value.length > 0) {
        if (currentImageIndex.value > selections.value.length) {
          currentImageIndex.value = selections.value.length
        }
        updateCurrentReviewImage()
      } else {
        reviewDialogVisible.value = false
        currentImageIndex.value = 1
        currentReviewImage.value = ''
        fetchTableData()
      }
    } else {
      throw new Error(response.data.msg || '驳回失败')
    }
  } catch (error) {
    console.error('驳回失败:', error)
  }
}
// 获取所有图片列表用于预览
function getImageList() {
  return selections.value.map(item => getPreviewUrl(item.photo_url)).filter(url => url)
}
// 处理上一张图片
function handlePrevImage() {
  if (currentImageIndex.value > 1) {
    currentImageIndex.value--
    updateCurrentReviewImage()
  }
}
// 处理下一张图片
function handleNextImage() {
  if (currentImageIndex.value < selections.value.length) {
    currentImageIndex.value++
    updateCurrentReviewImage()
  }
}
/**
 * 获取缩略图地址
 */
function getThumbUrl(url) {
  if (!url) return ''
  const lastDot = url.lastIndexOf('.')
  if (lastDot === -1) return url
  return url.slice(0, lastDot) + '_small' + url.slice(lastDot)
}
// 获取预览图地址
function getPreviewUrl(url) {
  if (!url) return ''
  const lastDot = url.lastIndexOf('.')
  if (lastDot === -1) return url
  return url.slice(0, lastDot) + '_show' + url.slice(lastDot)
}
/**
 * 坐标转换方法处理
 */
function disposeLocation(goWgs84 = false, data) {
  let lng = ''
  let 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)]
}
// 复核按钮
function reCheck(row) {
  reCheckData.value = row
  reCheckDialog.value = true
}
// 复核成功回调
function handleRecheckSuccess() {
  page.currentPage = 1
  fetchTableData()
  fetchTabCounts()
}
// 导出工单报表
function 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)
  })
  console.log('数据导出成功')
}
// 生命周期
onMounted(() => {
  inputMapShowDefaultCenter.value = null
  loadAMapScripts()
  fetchDropdownData()
 const href = window.location.href;
  if (route?.query?.status !== undefined && route?.query?.status !== null) {
    filters.status = route?.query?.status + ''
    router.replace({})
  }
  let curQueryParams = {}
  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)
      filters.dateRange = proxyArray
    }
    if (orderNumber) {
      filters.keyword = orderNumber
      nextTick(() => {
        isShowInfo.value = true
        const find = store.state.tags.bsTagList.find(i => i.path === '/tickets/ticket')
        if (find) {
          find.query = {}
        }
      })
    }
    if (tab) {
      const isTabValid = filteredTabs.value.some(t => t.name === tab)
      if (isTabValid) {
        activeTab.value = tab
        handleTabChangeAfterJump()
        const find = store.state.tags.bsTagList.find(i => i.path === '/tickets/ticket')
        if (find) {
          find.query = {}
        }
      }
    }
  }
  fetchTabCounts()
  fetchTableData()
})
onActivated(() => {
  handleReset()
})
</script>
<style lang="scss" scoped>
@@ -2513,31 +2307,6 @@
  }
}
/* 新建工单和处理工单的上传组件样式 */
.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 {
@@ -2547,6 +2316,4 @@
    object-fit: contain;
  }
}
</style>