<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>