add-order.vue 27.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
<template>
  <view class="page-container">
    <view class="work-order-form-content commonPageLRpadding">
      <up-form
          label-position="left"
          :model="baseForm"
          ref="workOrderFormRef"
          labelWidth="200rpx"
      >
        <!-- 1. 工单位置(地图选择)【公共项】 -->
        <up-form-item
            label="工单位置"
            prop="workLocation"
            border-bottom
            required
            @click="chooseWorkLocation(); hideKeyboard()"
        >
          <up-input
              v-model="baseForm.workLocation"
              border="none"
              readonly
              suffix-icon="map-fill"
              placeholder="点击选择工单位置"
          ></up-input>
        </up-form-item>

        <!-- 2. 情况描述【公共项】 -->
        <up-form-item
            label="情况描述"
            prop="problemDesc"
            required
            border-bottom
        >
          <up-textarea
              placeholder="请输入情况描述(最多200字)"
              v-model.trim="baseForm.problemDesc"
              count
              maxlength="200"
              rows="4"
              @blur="() => workOrderFormRef.validateField('problemDesc')"
          ></up-textarea>
        </up-form-item>

        <!-- 3. 问题照片【公共项】 -->
        <up-form-item label="问题照片" prop="problemImgs" required >
          <up-upload
              :file-list="problemImgs.imgList.value || []"
              @after-read="problemImgs.uploadImgs"
              @delete="problemImgs.deleteImg"
              multiple
              :width="70"
              :height="70"
              :max-count="problemImgs.uploadConfig.maxCount"
              :upload-text="problemImgs.uploadText"
              :size-type="problemImgs.uploadConfig.sizeType"
          ></up-upload>
        </up-form-item>

        <!-- 多组派单区域 -->
        <view class="dispatch-list-wrap">
          <view class="dispatch-title">派单情况</view>

          <!-- 循环渲染每组派单 -->
          <view class="dispatch-item" v-for="(item, idx) in dispatchList" :key="idx">
            <view class="item-head">
              <text>派单{{ idx + 1 }}</text>
              <!-- 数量大于1才显示红色关闭X -->
              <up-icon
                  v-if="dispatchList.length > 1"
                  name="close"
                  color="#f53f3f"
                  size="26"
                  class="close-icon"
                  @click="delDispatchItem(idx)"
              ></up-icon>
            </view>

            <!-- 业务线 -->
            <up-form-item
                label="业务线"
                prop="busiLineCn"
                border-bottom
                required
                @click="handleActionSheetOpen('busiLine', idx); hideKeyboard()"
            >
              <up-input
                  v-model="item.busiLineCn"
                  disabled
                  disabled-color="#ffffff"
                  placeholder="请选择业务线"
                  border="none"
              ></up-input>
              <template #right>
                <up-icon name="arrow-right" size="16"></up-icon>
              </template>
            </up-form-item>

            <!-- 问题类型 -->
            <up-form-item
                label="问题类型"
                prop="orderName"
                border-bottom
                required
                @click="openCascader(idx); hideKeyboard()"
            >
              <up-input
                  v-model="item.orderName"
                  disabled
                  disabled-color="#ffffff"
                  placeholder="请选择问题类型"
                  border="none"
              ></up-input>
              <template #right>
                <up-icon name="arrow-right" size="16"></up-icon>
              </template>
            </up-form-item>

            <!-- 道路名称 -->
            <up-form-item
                label="道路名称"
                prop="roadName"
                border-bottom
                required
                @click="handleActionSheetOpen('roadName', idx); hideKeyboard()"
            >
              <up-input
                  v-model="item.roadName"
                  readonly
                  disabled-color="#ffffff"
                  placeholder="请先选择工单位置"
                  border="none"
              ></up-input>
              <template #right>
                <up-icon name="arrow-right" size="16"></up-icon>
              </template>
            </up-form-item>

            <!-- 紧急程度 -->
            <up-form-item
                label="紧急程度"
                prop="pressingTypeName"
                border-bottom
                required
                @click="handleActionSheetOpen('pressingType', idx); hideKeyboard()"
            >
              <up-input
                  v-model="item.pressingTypeName"
                  disabled
                  disabled-color="#ffffff"
                  placeholder="请选择紧急程度"
                  border="none"
              ></up-input>
              <template #right>
                <up-icon name="arrow-right" size="16"></up-icon>
              </template>
            </up-form-item>

            <!-- 每组派单独立:希望完成时间 -->
            <up-form-item
                label="希望完成时间"
               
                @click="openItemDatePicker(idx); hideKeyboard()"
            >
              <up-input
                  v-model="item.expectedFinishDate"
                  border="none"
                  readonly
                  placeholder="点击选择时间"
              ></up-input>
              <template #right>
                <view v-if="item.expectedFinishDate" @click.stop>
                  <up-icon name="close" size="16" @click.stop="clearItemDate(idx)"></up-icon>
                </view>
                <up-icon name="arrow-right" size="16" v-else></up-icon>
              </template>
            </up-form-item>
          </view>
        </view>

        <!-- 新增派单按钮 -->
        <view class="add-dispatch-btn-wrap" v-if="!isRenew">
          <up-button
              type="primary"
              plain
              text="新增派单"
              :disabled="dispatchList.length >= 3"
              @click="addDispatchItem"
          ></up-button>
        </view>
      </up-form>
    </view>

    <!-- 底部提交按钮 -->
    <view class="fixed-bottom-btn-wrap">
      <up-button type="primary" text="提交工单" @click="submitWorkOrder"></up-button>
    </view>

    <!-- 通用下拉弹窗:业务线 / 道路 / 紧急程度 共用 -->
    <up-action-sheet
        :show="showActionSheet"
        :actions="currentActionSheetData.list"
        :title="currentActionSheetData.title"
        @close="handleActionSheetClose"
        @select="handleActionSheetSelect"
    ></up-action-sheet>

    <!-- 问题类型 级联选择器 -->
    <up-cascader
        v-model="cascaderValue"
        :data="cascaderOptions"
        v-model:show="showCascader"
        title="问题类型"
        :auto-close="false"
        @confirm="cascaderConfirm"
    ></up-cascader>

    <!-- 单独时间选择器(给每组派单用) -->
    <up-datetime-picker
        :show="showItemDatePicker"
        v-model="tempDateValue"
        mode="datetime"
        :min-date="Date.now()"
        @cancel="closeItemDatePicker"
        @confirm="itemDateConfirm"
    ></up-datetime-picker>
  </view>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import { onReady, onShow, onLoad, onBackPress } from '@dcloudio/uni-app';
import { useUploadImgs } from '@/common/utils/useUploadImgs'
import { getRoadListByLatLng, getProblemListByType } from '@/api/common'
import {
  daquUniversalApproval, qyUniversalApproval, qyWorkorderCreate,dycCreateBatchNew,
  dcyUniversalApproval, daquWorkorderCreate, dcyWorkorderCreate
} from '@/api/regional-order-manage/regional-order-manage'
import { timeFormat } from '@/uni_modules/uview-plus'
import { nextStepMap } from '@/common/utils/common'
import { useUserStore } from '@/pinia/user';

// ========== 常量配置区 ==========
const CONST = {
  DICT_PRESSING_TYPE: 'workorder_pressing_type',
  UPLOAD_CONFIG: { maxCount: 3, uploadText: '选择问题照片', sizeType: ['compressed'] },
  PAGE_ORDER_LIST: '/pages-sub/problem/regional-order-manage/index',
  BUSI_LINE_MAP: {
    yl: '园林', sz: '市政', wy: '物业', '园林': 'yl', '市政': 'sz', '物业': 'wy',
    'zx': '秩序管理', 'hj': '环境卫生', '秩序管理': 'zx', '环境卫生': 'hj'
  },
  ROLE: { MANAGER: 'regional_manager', INSPECTOR: 'Inspector_global', PATROL: 'patrol_global' , LEADER: 'Inspector_global_leader'}
}

// ========== 全局实例 & 基础状态 ==========
const userStore = useUserStore();
const USER_ROLES = userStore.userInfo?.roles || [];
const workOrderFormRef = ref(null);
const showActionSheet = ref(false);
const isRenew = ref(false);
const renewOrderData = ref(null);

// 当前操作的派单项下标
const currentDispatchIndex = ref(0);

// 三级级联选择器
const showCascader = ref(false);
const cascaderValue = ref([]);
const cascaderOptions = ref([]);

// 下拉弹窗数据
const currentActionSheetData = reactive({ type: '', list: [], title: '', index: 0 });
const roadNameList = ref([]);
const pressingTypeList = ref([]);
const busiLineOptions = ref([]);
const currentBusiLineCode = ref('');

// 每组派单独立时间选择器
const showItemDatePicker = ref(false);
const tempDateValue = ref(Date.now());
const curSelectDateIndex = ref(-1);

// 图片上传
const problemImgs = useUploadImgs({
  ...CONST.UPLOAD_CONFIG,
  formRef: workOrderFormRef,
  fieldName: 'problemImgs'
})
if (!Array.isArray(problemImgs.rawImgList.value)) problemImgs.rawImgList.value = [];

// ========== 公共表单(所有派单共用) ==========
const baseForm = reactive({
  workLocation: '',
  problemDesc: '',
  lat: 0,
  lon: 0
})

// ========== 派单列表(多组派单核心数组) ==========
const createDispatchItem = (defaultBusiLine = null) => {
  return {
    busiLineCn: defaultBusiLine?.name || '',
    busiLineCode: defaultBusiLine?.value || '',
    roadId: 0,
    roadName: '',
    orderName: '',
    orderCode: '',
    pressingType: '',
    pressingTypeName: '',
    expectedFinishDate: '' // 每组独立完成时间
  }
}
// 初始化默认 1 组派单
const dispatchList = ref([createDispatchItem()])

// ========== 表单校验规则 ==========
const workOrderFormRules = reactive({
  workLocation: [{ type: 'string', required: true, message: '请选择工单位置', trigger: ['change', 'blur'] }],
  problemDesc: [
    { type: 'string', required: true, message: '请输入情况描述', trigger: ['change', 'blur'] },
    { type: 'string', min: 3, max: 200, message: '情况描述需3-200字', trigger: ['change', 'blur'] }
  ],
  problemImgs: [problemImgs.imgValidateRule]
})

// ========== 工具方法 ==========
const busiLineCnToEn = (cn) => CONST.BUSI_LINE_MAP[cn] || '';
const busiLineEnToCn = (en) => CONST.BUSI_LINE_MAP[en] || '';
const toOrderListPage = () => uni.reLaunch({ url: CONST.PAGE_ORDER_LIST });
const formatDate = (dateVal, fmt = 'yyyy-mm-dd hh:MM:ss') => dateVal ? timeFormat(dateVal, fmt) : '';
const dateToTimestamp = (dateStr) => dateStr ? new Date(dateStr).getTime() : '';

/**
 * 加载三级问题类型级联数据
 */
const loadProblemCascader = async (parentCode) => {
  if (!parentCode) {
    cascaderOptions.value = [];
    return;
  }
  try {
    uni.showLoading({ title: '加载类型中...' });
    const res = await getProblemListByType({ parentCode });
    cascaderOptions.value = res|| [];
  } catch (err) {
    console.error('加载问题类型失败', err);
    uni.showToast({ title: '问题类型加载失败', icon: 'none' });
    cascaderOptions.value = [];
  } finally {
    uni.hideLoading();
  }
};

/** 打开级联选择器 */
const openCascader = (idx) => {
  currentDispatchIndex.value = idx;
  const item = dispatchList.value[idx];
  if (!item.busiLineCode) {
    uni.showToast({ title: '请先选择业务线', icon: 'none' });
    return;
  }
  if (!cascaderOptions.value || cascaderOptions.value.length === 0) {
    uni.showToast({ title: '正在加载问题类型,请稍等', icon: 'none' });
    loadProblemCascader(item.busiLineCode);
    return;
  }
  cascaderValue.value = [];
  showCascader.value = true;
};

/** 级联选择确认回调 */
const cascaderConfirm = (selectedArr) => {
  const idx = currentDispatchIndex.value;
  const item = dispatchList.value[idx];
  console.log('最终选中值数组:', selectedArr);

  const getLabelByValueList = (list, valList) => {
    const labelArr = [];
    let currentList = list;
    for (const val of valList) {
      const target = currentList.find(item => item.value === val);
      if (!target) break;
      labelArr.push(target.label);
      currentList = target.children || [];
    }
    return labelArr.join('/');
  };

  const fullLabel = getLabelByValueList(cascaderOptions.value, selectedArr);
  item.orderName = fullLabel;
  item.orderCode = selectedArr.at(-1);
  cascaderValue.value = selectedArr;
  workOrderFormRef.value?.validateField('orderName');
};

// ========== 每组派单 时间选择相关 ==========
const openItemDatePicker = (idx) => {
  curSelectDateIndex.value = idx;
  tempDateValue.value = Date.now();
  showItemDatePicker.value = true;
};
const closeItemDatePicker = () => {
  showItemDatePicker.value = false;
  curSelectDateIndex.value = -1;
};
const itemDateConfirm = (e) => {
  const idx = curSelectDateIndex.value;
  if (idx > -1 && dispatchList.value[idx]) {
    dispatchList.value[idx].expectedFinishDate = formatDate(e.value);
  }
  closeItemDatePicker();
};
const clearItemDate = (idx) => {
  dispatchList.value[idx].expectedFinishDate = '';
};

// ========== 新增 / 删除 派单项 ==========
/** 新增派单 */
const addDispatchItem = () => {
  if (dispatchList.value.length >= 3) return;
  // 新项:业务线默认第一个,其余置空
  const firstBusi = busiLineOptions.value[0] || null;
  dispatchList.value.push(createDispatchItem(firstBusi));
  if(firstBusi) {
    currentBusiLineCode.value = firstBusi.value;
    loadProblemCascader(firstBusi.value);
  }
};

/** 删除派单项 */
const delDispatchItem = (idx) => {
  if (dispatchList.value.length <= 1) return;
  dispatchList.value.splice(idx, 1);
};


// 生命周期
onLoad(async (options) => {
  initBusiLineOptions();
  // 初始化第一组派单默认业务线
  if (busiLineOptions.value.length) {
    const firstLine = busiLineOptions.value[0];
    dispatchList.value[0].busiLineCn = firstLine.name;
    dispatchList.value[0].busiLineCode = firstLine.value;
    currentBusiLineCode.value = firstLine.value;
    // 非重新提交才默认加载级联
    if (!(options.isRenew == 1 && options.tempKey)) {
      loadProblemCascader(firstLine.value);
    }
  }
  // 重新提交场景:等待回显完成
  if (options.isRenew == 1 && options.tempKey) {
    await handleRenewOptions(options.tempKey);
  }
});

onReady(() => {
  nextTick(() => {
    workOrderFormRef.value?.setRules(workOrderFormRules);
  });
});

onShow(() => {
  pressingTypeList.value = uni.$dict.transformLabelValueToNameValue(uni.$dict.getDictSimpleList(CONST.DICT_PRESSING_TYPE));
});

// 物理返回拦截
onBackPress(() => {
  uni.redirectTo({ url: CONST.PAGE_ORDER_LIST });
  return true;
});

// ========== 业务线相关 ==========
const initBusiLineOptions = () => {
  const rawBusiLines = userStore.userInfo?.user?.busiLine?.split(',') || [];
  busiLineOptions.value = rawBusiLines.map(item => ({
    name: busiLineEnToCn(item.trim()),
    value: item.trim()
  }));
};

/** 业务线切换联动清空数据并重新加载级联 */
const handleBusiLineChange = (code, idx) => {
  const item = dispatchList.value[idx];
  item.roadName = '';
  item.roadId = 0;
  item.orderName = '';
  item.orderCode = '';
  cascaderValue.value = [];
  roadNameList.value = [];

  currentBusiLineCode.value = code;
  loadProblemCascader(code);

  if(baseForm.workLocation) getRoadListByBusiLine();
};

/** 根据经纬度+业务线获取道路列表 */
const getRoadListByBusiLine = async () => {
  if (!baseForm.lat || !baseForm.lon) return;
  const busiLineEn = busiLineCnToEn(dispatchList.value[0].busiLineCn);
  if (!busiLineEn) return uni.showToast({ title: '业务线选择异常', icon: 'none' });

  try {
    uni.showLoading({ title: '获取道路名称中...' });
    const roadRes = await getRoadListByLatLng({
      busiLine: busiLineEn,
      latitude: baseForm.lat,
      longitude: baseForm.lon
    });
    roadNameList.value = Array.isArray(roadRes)
      ? roadRes.map(item => ({ name: item.roadName || '', code: item.roadCode || '', id: item.roadId || 0 }))
      : [{ name: '未查询到道路名称', code: '', id: 0 }];
    !Array.isArray(roadRes) && uni.showToast({ title: '未查询到该位置的道路信息', icon: 'none' });
  } catch (err) {
    console.error('获取道路名称失败:', err);
    roadNameList.value = [{ name: '获取失败,请重新选择位置', code: '', id: 0 }];
    uni.showToast({ title: '获取道路名称失败,请重试', icon: 'none' });
  } finally {
    uni.hideLoading();
  }
};

// ========== 通用下拉弹窗方法(支持下标) ==========
const handleActionSheetOpen = (type, idx) => {
  currentDispatchIndex.value = idx;
  if (type === 'roadName' && !baseForm.workLocation) {
    return uni.showToast({ title: '请先选择工单位置', icon: 'none' });
  }
  const configMap = {
    busiLine: { title: '请选择业务线', list: busiLineOptions.value },
    roadName: { title: '请选择道路名称', list: roadNameList.value },
    pressingType: { title: '请选择紧急程度', list: pressingTypeList.value }
  };
  Object.assign(currentActionSheetData, configMap[type], { type, index: idx });
  showActionSheet.value = true;
};

const handleActionSheetClose = () => {
  showActionSheet.value = false;
  Object.assign(currentActionSheetData, { type: '', list: [], title: '', index: 0 });
};

const handleActionSheetSelect = (e) => {
  const { type, index } = currentActionSheetData;
  const item = dispatchList.value[index];
  switch (type) {
    case 'busiLine':
      item.busiLineCn = e.name;
      item.busiLineCode = e.value;
      handleBusiLineChange(e.value, index);
      break;
    case 'roadName':
      item.roadName = e.name;
      item.roadId = e.code;
       console.log('选中道路对象e:', e)
      console.log('赋值后 roadId:', item.roadName, '类型:', typeof item.roadId)
      break;
    case 'pressingType':
      item.pressingType = e.value;
      item.pressingTypeName = e.name;
      break;
  }
  handleActionSheetClose();
};

// ========== 页面交互方法 ==========
const hideKeyboard = () => uni.hideKeyboard();

/** 选择地图位置 */
const chooseWorkLocation = () => {
  uni.chooseLocation({
    success: async (res) => {
      baseForm.workLocation = res.name;
      baseForm.lat = res.latitude;
      baseForm.lon = res.longitude;
      // 清空所有组道路
      dispatchList.value.forEach(item => {
        item.roadName = '';
        item.roadId = 0;
      })
      workOrderFormRef.value?.validateField(['workLocation']);
      await getRoadListByBusiLine();
    },
    fail: (err) => {
      console.error('选择位置失败:', err);
      const errMsg = err.errMsg.includes('auth deny') ? '请开启位置权限后重试' : '选择位置失败,请重试';
      uni.showToast({ title: errMsg, icon: 'none' });
    }
  })
};

/** 重新提交数据回显 */
const handleRenewOptions = async (tempKey) => {
  isRenew.value = true;
  try {
    const orderData = uni.getStorageSync(tempKey);
    if (orderData && typeof orderData === 'object') {
      renewOrderData.value = orderData;
      await echoOrderData(orderData); // 等待回显执行完毕
    } else {
      uni.showToast({ title: '工单数据不存在,无法重新提交', icon: 'none' });
      setTimeout(toOrderListPage, 1000);
    }
  } catch (error) {
    console.error('读取工单数据失败:', error);
    uni.showToast({ title: '数据读取异常,无法重新提交', icon: 'none' });
    setTimeout(toOrderListPage, 1000);
  } finally {
    uni.removeStorageSync(tempKey);
  }
};


/** 工单数据回显 */
const echoOrderData = async (orderItem) => {
  const busiCode = orderItem.busiLine || '';
  // 回显公共字段
  baseForm.workLocation = orderItem.lonLatAddress || orderItem.roadName || '';
  baseForm.problemDesc = orderItem.remark || '';
  baseForm.lat = orderItem.lat || 0;
  baseForm.lon = orderItem.lon || 0;
  console.log(orderItem)
    console.log(orderItem.orderCode)
  
  // 回显第一组派单
  if(dispatchList.value[0]){
    const firstItem = dispatchList.value[0]
    firstItem.busiLineCn = busiLineEnToCn(busiCode);
    firstItem.busiLineCode = busiCode;
    firstItem.roadId = orderItem.roadId || 0;
    
    firstItem.roadName = orderItem.roadName || '';
    firstItem.orderName = orderItem.orderName || '';
    firstItem.orderCode = orderItem.orderCode || ''; // 回显编码
    firstItem.pressingType = orderItem.pressingType || '';
    firstItem.pressingTypeName = uni.$dict.getDictLabel(CONST.DICT_PRESSING_TYPE, orderItem.pressingType) || '';
    firstItem.expectedFinishDate = orderItem.expectedFinishDate ? formatDate(orderItem.expectedFinishDate) : '';
  }

  // 图片回显
  if (Array.isArray(orderItem.problemsImgs) && orderItem.problemsImgs.length) {
    const imgList = orderItem.problemsImgs.map((url, idx) => ({ url, name: `renew_img_${idx}`, status: 'success' }));
    problemImgs.imgList.value = imgList;
    problemImgs.rawImgList.value = imgList;
  }

  // ========== 关键修复:业务线加载完级联数据后,回填 cascaderValue ==========
  if (busiCode) {
    // 先加载级联选项
    await loadProblemCascader(busiCode);
    // 根据回显的 orderCode 反向匹配级联路径,赋值给 cascaderValue
    const targetCode = orderItem.orderCode
    if (targetCode && cascaderOptions.value.length) {
      // 递归查找级联选中路径
      const findCascaderPath = (list, targetVal, path = []) => {
        for (const node of list) {
          const newPath = [...path, node.value]
          if (node.value === targetVal) {
            return newPath
          }
          if (node.children && node.children.length) {
            const res = findCascaderPath(node.children, targetVal, newPath)
            if (res) return res
          }
        }
        return null
      }
      const selectPath = findCascaderPath(cascaderOptions.value, targetCode)
      if (selectPath) {
        cascaderValue.value = selectPath
      }
    }
  }

  if (orderItem.lat && orderItem.lon) getRoadListByBusiLine();
};

// ========== 接口分发(按角色) ==========
const callApiByRole = async (params, isRenewFlag) => {
  if (isRenewFlag) {
    if (USER_ROLES.includes(CONST.ROLE.MANAGER)) return await daquUniversalApproval(params);
    if (USER_ROLES.includes(CONST.ROLE.INSPECTOR)) return await dcyUniversalApproval(params);
    if (USER_ROLES.includes(CONST.ROLE.LEADER)) return await dcyUniversalApproval(params);
    if (USER_ROLES.includes(CONST.ROLE.PATROL)) return await qyUniversalApproval(params);
  } else {
    console.log('dasda')
    console.log(CONST.ROLE.INSPECTOR)
    if (USER_ROLES.includes(CONST.ROLE.MANAGER)) return await daquWorkorderCreate(params);
    // if (USER_ROLES.includes(CONST.ROLE.INSPECTOR)) return await dcyWorkorderCreate(params);
     if (USER_ROLES.includes(CONST.ROLE.INSPECTOR)) return await dycCreateBatchNew(params);
      if (USER_ROLES.includes(CONST.ROLE.LEADER)) return await dycCreateBatchNew(params);
    if (USER_ROLES.includes(CONST.ROLE.PATROL)) return await qyWorkorderCreate(params);
    
    
  }
};

// ========== 提交工单(纯数组提交,无 dispatchList,校验 roadId 非0) ==========
const submitWorkOrder = async () => {
  try {
    // 校验公共表单
    await workOrderFormRef.value.validate();

    // 校验:同一业务线 + 同一问题类型 不允许重复
const list = dispatchList.value;
const keySet = new Set();
let hasRepeat = false;

for (const item of list) {
  const busi = (item.busiLineCn || '').trim();
  const type = (item.orderName || '').trim();
  // 拼接唯一标识
  const uniqueKey = `${busi}_${type}`;
  if (keySet.has(uniqueKey)) {
    hasRepeat = true;
    break;
  }
  keySet.add(uniqueKey);
}

if (hasRepeat) {
  uni.showToast({
    title: '存在同业务同问题类型,请修改后再提交',
    icon: 'none'
  });
  return;
}
    // ==============================================

    // 组装纯数组,不再包裹 dispatchList
    const submitArr = dispatchList.value.map(item => {
      return {
        roadId: item.roadId,
        roadName: item.roadName,
        orderName: item.orderName,
        orderCode: item.orderCode,
        pressingType: item.pressingType,
        busiLine: busiLineCnToEn(item.busiLineCn),
        busiType: busiLineCnToEn(item.busiLineCn),
        expectedFinishDate: dateToTimestamp(item.expectedFinishDate),
        problemsImgs: problemImgs.getSuccessImgUrls(),
        remark: baseForm.problemDesc.trim(),
        latLonType: 2,
        lat: baseForm.lat,
        lon: baseForm.lon,
        lonLatAddress: baseForm.workLocation,
        sourceId: 1,
        sourceName: item.busiLineCn
      }
    });

    // 逐项校验:保证 roadId 不为 0,以及其他必填项
    for (let i = 0; i < submitArr.length; i++) {
      const row = submitArr[i];
      const num = i + 1;
      if (!row.roadId || row.roadId === 0) {
        uni.showToast({ title: `第${num}条派单请选择道路名称`, icon: 'none' });
        return;
      }
      if (!row.busiLine) {
        uni.showToast({ title: `第${num}条派单请选择业务线`, icon: 'none' });
        return;
      }
      if (!row.orderCode) {
        uni.showToast({ title: `第${num}条派单请选择问题类型`, icon: 'none' });
        return;
      }
      if (!row.pressingType) {
        uni.showToast({ title: `第${num}条派单请选择紧急程度`, icon: 'none' });
        return;
      }
    }

    uni.showLoading({ title: '提交中...', mask: true });

    let submitParams;
    if (isRenew.value) {
      // 重新提交:外层对象 + list 承载数组
      submitParams = {
        workerDataId: renewOrderData.value.id,
        taskKey: renewOrderData.value.taskKey,
        taskId: renewOrderData.value.taskId,
        operateType: nextStepMap[renewOrderData.value.taskKey]?.operateTypeRenew || '',
        agree: 0,
        reason: baseForm.problemDesc.trim(),
        ...submitArr[0]
      };
    } else {
      // 新建工单:根节点直接为纯数组
      submitParams = submitArr;
    }

    console.log(submitParams)

    await callApiByRole(submitParams, isRenew.value);

    uni.showToast({
      title: isRenew.value ? '重新提交成功' : '工单提交成功',
      icon: 'success',
      duration: 1000
    });
    setTimeout(toOrderListPage, 1000);
  } catch (error) {
    uni.hideLoading();
    if (!Array.isArray(error)) {
      console.error(isRenew.value ? '工单重新提交失败:' : '工单提交失败:', error);
      uni.showToast({
        title: error.msg || '提交失败,请重试',
        icon: 'none',
        duration: 2000
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  padding-bottom: 100rpx;
  background: #fafafa;
}

.work-order-form-content {
  background: #fff;
}

.dispatch-list-wrap {
  padding-top: 24rpx;
  margin-top: 8rpx;
  border-top: 1px solid #f5f5f5;
}

.dispatch-title {
  font-size: 32rpx;
  font-weight: 600;
  color: $u-primary;
  margin-bottom: 20rpx;
  padding-left: 10rpx;
}

.dispatch-item {
  position: relative;
  border: 1px solid #eee;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  background: #fdfdfd;

  .item-head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16rpx;
    font-size: 28rpx;
    font-weight: 500;
  }

  .close-icon {
    position: absolute;
    top: 20rpx;
    right: 20rpx;
  }
}

.add-dispatch-btn-wrap {
  margin: 20rpx 0;
}
</style>