add-patrol-record.vue 21.2 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
<template>
  <view class="u-page">
    <!-- 原有模板内容不变,仅调整表单校验相关配置 -->
    <view class="inspect-form-content">
      <up-form label-position="left" :model="inspectForm" ref="inspectFormRef" labelWidth="200rpx">
        <!-- 巡查信息 -->
        <view class="form-card form-card--field">
          <view class="sec-head">
            <view class="sec-bar"></view>
            <view class="sec-title">巡查信息</view>
          </view>
          <!-- 1. 巡查描述 -->
          <up-form-item label="巡查描述" prop="content" class="form-item" required>
            <up-textarea v-model.trim="inspectForm.content" placeholder="请输入巡查描述" maxlength="200" count></up-textarea>
          </up-form-item>
        </view>

        <!-- 作业信息 -->
        <view class="form-card">
          <view class="sec-head">
            <view class="sec-bar"></view>
            <view class="sec-title">作业信息</view>
          </view>
          <!-- 3. 转为工单 -->
          <up-form-item label="转为工单" prop="isWorkOrder" required border-bottom class="form-item">
            <up-radio-group v-model="inspectForm.isWorkOrder" active-color="#2563EB" direction="row" class="radio-group"
              @change="handleWorkOrderChange">
              <up-radio :custom-style="{ marginRight: '40rpx' }" v-for="(item, index) in radioList" :key="index"
                :label="item.label" :name="item.value">
                {{ item.label }}
              </up-radio>
            </up-radio-group>
          </up-form-item>
          <!-- ========== 【新增】业务线(单选框,对齐参考页面) ========== -->
          <up-form-item v-if="inspectForm.isWorkOrder === '2'" label="业务线" prop="busiLineCn" border-bottom required
            class="form-item">
            <up-radio-group v-model="inspectForm.busiLineCn" placement="row" @change="handleBusiLineChange">
              <up-radio v-for="item in busiLineOptions" :key="item.name" :label="item.name" :name="item.name"></up-radio>
            </up-radio-group>
          </up-form-item>
          <!-- ========== 【新增】问题类型(级联选择器,对齐参考页面) ========== -->
          <up-form-item v-if="inspectForm.isWorkOrder === '2'" label="问题类型" prop="orderName" border-bottom required
            class="form-item" @click="openCascader(); uni.hideKeyboard()">
            <up-input v-model="inspectForm.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 v-if="inspectForm.isWorkOrder === '2'" label="紧急程度" prop="pressingTypeName" border-bottom required
            class="form-item" @click="handleActionSheetOpen('pressingType')">
            <up-input v-model="inspectForm.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>
          <!-- 希望完成时间(移除 required 属性,改为非必填) -->
          <up-form-item v-if="inspectForm.isWorkOrder === '2'" label="希望完成时间" prop="expectedFinishDate" class="form-item"
            @click="show = true; uni.hideKeyboard()">
            <up-input v-model="inspectForm.expectedFinishDate" border="none" readonly placeholder="点击选择时间">
            </up-input>
            <template #right>
              <!-- 核心修复:用view包裹图标,添加双重@click.stop -->
              <view v-if="inspectForm.expectedFinishDate" @click.stop>
                <up-icon name="close" size="16" @click.stop="clearExpectedFinishDate"></up-icon>
              </view>
              <up-icon name="arrow-right" size="16" v-else></up-icon>
            </template>
          </up-form-item>
        </view>

        <!-- 上传图片 -->
        <view class="form-card form-card--field">
          <view class="sec-head">
            <view class="sec-bar"></view>
            <view class="sec-title">上传图片</view>
          </view>
          <!-- 2. 上传图片 -->
          <up-form-item label="上传图片" prop="images" required class="form-item">
            <up-upload :file-list="imagesList" @after-read="(event) => uploadImgs(event)"
              @delete="(event) => deleteImg(event)" @on-exceed="handleExceed" multiple :max-count="3" upload-text="选择图片"
              del-color="#ff4d4f" class="upload-wrap" width="70" height="70"></up-upload>
            <view class="upload-hint">最少 1 张 · 最多 3 张</view>
          </up-form-item>
        </view>
      </up-form>
    </view>
    <!-- 底部提交按钮 -->
    <view class="fixed-bottom-btn-wrap">
      <up-button type="primary" text="提交" @click="submitInspect"></up-button>
    </view>
    <!-- 紧急程度下拉弹窗 -->
    <up-action-sheet :show="showActionSheet" :actions="pressingTypeList" title="请选择紧急程度" @close="handleActionSheetClose"
      @select="handlePressingTypeSelect"></up-action-sheet>
    <!-- ========== 新增级联选择器组件 ========== -->
    <up-cascader v-model:show="showCascader" v-model="cascaderValue" :data="cascaderOptions" title="选择问题类型"
      :auto-close="false" @confirm="cascaderConfirm"></up-cascader>
    <!-- 完成时间选择器 -->
    <up-datetime-picker :show="show" v-model="datetimeValue" mode="datetime" :min-date="new Date()"
      @cancel="show = false" @confirm="expectedFinishDateConfirm"></up-datetime-picker>
  </view>
</template>
<script setup lang="ts">
import { ref, getCurrentInstance } from 'vue'
import type { UniFormRef } from '@/uni_modules/uview-plus/types'
import { useUserStore } from '@/pinia/user';
import { getDictLabel, getDictValue } from '@/common/utils/dict';
import { getProblemListByType } from '@/api/common'
const { proxy } = getCurrentInstance()!
const inspectFormRef = ref<UniFormRef>(null)
const userStore = useUserStore();
const BUSI_LINE_DICT_TYPE = 'business_line';
const CJK_RE = /[一-龥]/;

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

// 打开级联弹窗
const openCascader = () => {
  const busiLineEn = getBusiLineEnByCn(proxy.$data.inspectForm.busiLineCn)
  if (!busiLineEn) {
    uni.showToast({ title: '请先选择业务线', icon: 'none' })
    return
  }
  if (!cascaderOptions.value || cascaderOptions.value.length === 0) {
    uni.showToast({ title: '正在加载问题类型,请稍等', icon: 'none' });
    loadProblemCascader(busiLineEn);
    return;
  }
  cascaderValue.value = [];
  showCascader.value = true;
};

// 级联确认回调
const cascaderConfirm = (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);
  proxy.$data.inspectForm.orderName = fullLabel;
  proxy.$data.inspectForm.orderCode = selectedArr.at(-1);
  cascaderValue.value = selectedArr;
  inspectFormRef.value?.validateField('orderName');
};

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

const getBusiLineCnByEn = (busiLineEn) => {
  if (!busiLineEn) return '';
  return getDictLabel(BUSI_LINE_DICT_TYPE, busiLineEn) || busiLineEn;
};
const getBusiLineEnByCn = (cnName) => {
  if (!cnName) return '';
  const code = getDictValue(BUSI_LINE_DICT_TYPE, cnName);
  if (code) return code;
  return CJK_RE.test(cnName) ? '' : cnName;
};

// 暴露给选项式访问
proxy.$setupCtx = {
  loadProblemCascader,
  getBusiLineEnByCn,
  cascaderOptions,
  cascaderValue
}
</script>
<script lang="ts">
import { uploadImages } from '@/common/utils/upload';
import { inspectionCreate } from "@/api/patrol-manage/patrol-plan";
import { timeFormat } from '@/uni_modules/uview-plus'
import { useUserStore } from '@/pinia/user';
import { getDictLabel } from '@/common/utils/dict';
export default {
  data() {
    return {
      imagesList: [],
      radioList: [
        { label: '否', value: '1' },
        { label: '是', value: '2' }
      ],
      pressingTypeList: [],
      busiLineOptions: [], // 业务线移到data,不再放在setup
      inspectForm: {
        content: '',
        isWorkOrder: '1',
        pressingTypeName: '',
        pressingType: '',
        busiLineCn: '',
        orderName: '',
        orderCode: '',
        expectedFinishDate: '' // 非必填,可空
      },
      paramsOptins: {},
      showActionSheet: false,
      show: false,
      datetimeValue: Date.now(),
      inspectFormRules: {
        images: [
          {
            required: true,
            message: '请上传图片',
            trigger: 'change',
            validator: (rule, value, callback) => {
              const hasSuccessImg = this.imagesList.some(item => item.status === 'success')
              const imgCount = this.imagesList.filter(item => item.status === 'success').length
              if (!hasSuccessImg || imgCount < 1) {
                callback(new Error('最少需要上传1张图片'))
              } else if (imgCount > 3) {
                callback(new Error('最多只能上传3张图片'))
              } else {
                callback()
              }
            }
          }
        ],
        content: [
          { type: 'string', required: true, message: '请输入巡查描述', trigger: ['change'] }
        ],
        isWorkOrder: [
          { type: 'string', required: true, message: '请选择是否转为工单', trigger: ['change'] }
        ],
        pressingTypeName: [
          {
            required: true,
            message: '请选择紧急程度',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.inspectForm.isWorkOrder === '2' && !value) {
                callback(new Error('请选择紧急程度'))
              } else {
                callback()
              }
            }
          }
        ],
        busiLineCn: [
          {
            required: true,
            message: '请选择业务线',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.inspectForm.isWorkOrder === '2' && !value) {
                callback(new Error('请选择业务线'))
              } else {
                callback()
              }
            }
          }
        ],
        orderName: [
          {
            required: true,
            message: '请选择问题类型',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (this.inspectForm.isWorkOrder === '2' && !value) {
                callback(new Error('请选择问题类型'))
              } else {
                callback()
              }
            }
          }
        ],
        expectedFinishDate: [
          {
            message: '请选择有效的希望完成时间',
            trigger: 'change',
            validator: (rule, value, callback) => {
              if (value && !/^\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}$/.test(value)) {
                callback(new Error('请选择有效的希望完成时间'))
              } else {
                callback()
              }
            }
          }
        ]
      }
    }
  },
  onLoad(option) {
    this.paramsOptins = option
    // 初始化业务线选项
    const userStore = useUserStore();
    if (userStore.userInfo?.user?.busiLine) {
      const rawBusiLines = userStore.userInfo.user.busiLine.split(',');
      this.busiLineOptions = rawBusiLines.map(item => ({
        name: getDictLabel('business_line', item.trim()) || item.trim()
      }));
    }
  },
  onReady() {
    this.$refs.inspectFormRef.setRules(this.inspectFormRules)
  },
  onShow() {
    this.pressingTypeList = uni.$dict.transformLabelValueToNameValue(uni.$dict.getDictSimpleList('workorder_pressing_type'))
  },
  methods: {
    handleWorkOrderChange() {
      if (this.inspectForm.isWorkOrder === '1') {
        this.inspectForm.pressingTypeName = ''
        this.inspectForm.pressingType = ''
        this.inspectForm.busiLineCn = ''
        this.inspectForm.orderName = ''
        this.inspectForm.orderCode = ''
        this.$setupCtx.cascaderOptions.value = []
        this.$setupCtx.cascaderValue.value = []
        this.inspectForm.expectedFinishDate = ''
        this.$refs.inspectFormRef.validateField(['pressingTypeName', 'busiLineCn', 'orderName', 'expectedFinishDate'])
      } else {
        // 修复点:直接读取data中的 busiLineOptions,不再访问setup
        const busiOpts = this.busiLineOptions
        if (busiOpts.length > 0) {
          this.inspectForm.busiLineCn = busiOpts[0].name
          this.handleBusiLineChange()
        }
      }
    },
    handleBusiLineChange() {
      this.inspectForm.orderName = ''
      this.inspectForm.orderCode = ''
      this.$setupCtx.cascaderValue.value = []
      this.$setupCtx.cascaderOptions.value = []
      const busiLineEn = this.$setupCtx.getBusiLineEnByCn(this.inspectForm.busiLineCn)
      this.$setupCtx.loadProblemCascader(busiLineEn)
      this.$refs.inspectFormRef.validateField('busiLineCn')
    },
    handleActionSheetOpen(type) {
      uni.hideKeyboard()
      if (type === 'pressingType') {
        this.showActionSheet = true
      }
    },
    handleActionSheetClose() {
      this.showActionSheet = false
    },
    handlePressingTypeSelect(e) {
      this.inspectForm.pressingTypeName = e.name
      this.inspectForm.pressingType = e.value
      this.showActionSheet = false
      this.$refs.inspectFormRef.validateField('pressingTypeName')
    },
    expectedFinishDateConfirm(e) {
      this.inspectForm.expectedFinishDate = timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss')
      this.show = false
      this.$refs.inspectFormRef.validateField('expectedFinishDate')
    },
    clearExpectedFinishDate() {
      this.inspectForm.expectedFinishDate = ''
      this.$refs.inspectFormRef.validateField('expectedFinishDate')
    },
    deleteImg(event) {
      this.imagesList.splice(event.index, 1)
      this.$refs.inspectFormRef.validateField('images')
      uni.showToast({ title: '图片删除成功', icon: 'success' })
    },
    async uploadImgs(event) {
      const fileList = Array.isArray(event.file) ? event.file : [event.file]
      const targetImgList = this.imagesList
      const filePaths = fileList.map(item => item.url)
      const tempItems = fileList.map(item => ({
        ...item,
        status: 'uploading',
        message: '上传中'
      }))
      const startIndex = targetImgList.length
      targetImgList.push(...tempItems)
      try {
        const uploadResultUrls = await uploadImages({
          filePaths: filePaths,
          ignoreError: true
        })
        uploadResultUrls.forEach((url, index) => {
          if (targetImgList[startIndex + index]) {
            targetImgList.splice(startIndex + index, 1, {
              ...fileList[index],
              status: 'success',
              message: '',
              url: url
            })
          }
        })
        if (uploadResultUrls.length < fileList.length) {
          const failCount = fileList.length - uploadResultUrls.length
          uni.showToast({ title: `成功上传${uploadResultUrls.length}张,失败${failCount}张`, icon: 'none' })
        } else {
          uni.showToast({ title: `成功上传${fileList.length}张图片`, icon: 'success' })
        }
        this.$refs.inspectFormRef.validateField('images')
      } catch (err) {
        console.error('图片上传失败:', err)
        for (let i = 0; i < fileList.length; i++) {
          if (targetImgList[startIndex + i]) {
            targetImgList.splice(startIndex + i, 1, {
              ...fileList[i],
              status: 'failed',
              message: '上传失败'
            })
          }
        }
        uni.showToast({ title: '图片上传失败,请重试', icon: 'none' })
        this.$refs.inspectFormRef.validateField('images')
      }
    },
    handleExceed() {
      uni.showToast({ title: '最多只能上传3张图片', icon: 'none' })
    },
    getImgUrlList(imgList) {
      return imgList.filter(item => item.status === 'success').map(item => item.url)
    },
    async submitInspect() {
      console.log('当前选择是否转为工单:', this.inspectForm.isWorkOrder)
      try {
        await this.$refs.inspectFormRef.validate()
        console.log(this.imagesList)
        const baseSubmitData = {
          "batchNo": this.paramsOptins.batchNo,
          "planNo": this.paramsOptins.planNo,
          "imgHost": "1",
          "imgList": this.getImgUrlList(this.imagesList),
          "inspectionState": this.inspectForm.isWorkOrder,
          "transState": this.inspectForm.isWorkOrder === '1' ? '1' : '2',
          "transWorkNo": "default'",
          "remark": this.inspectForm.content.trim()
        }
        let submitData = { ...baseSubmitData }
        if (this.inspectForm.isWorkOrder === '2') {
          submitData.pressingType = this.inspectForm.pressingType
          const busiLineEn = this.$setupCtx.getBusiLineEnByCn(this.inspectForm.busiLineCn)
          submitData.busiLine = busiLineEn
          submitData.orderName = this.inspectForm.orderName
          submitData.orderCode = this.inspectForm.orderCode
          if (this.inspectForm.expectedFinishDate) {
            submitData.expectedFinishDate = new Date(this.inspectForm.expectedFinishDate).getTime()
          }
        }
        uni.showLoading({ title: '提交中...' })
        await inspectionCreate(submitData)
        uni.hideLoading()
        uni.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 1000
        })
        setTimeout(() => {
          uni.reLaunch({
            url: '/pages-sub/daily/patrol-manage/index'
          })
        }, 1000)
      } catch (error) {
        uni.hideLoading()
        if (!Array.isArray(error)) {
          console.error('巡查表单提交失败:', error)
          uni.showToast({
            title: error.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.u-page {
  min-height: 100vh;
  padding-bottom: 200rpx;
  background-color: #F4F6FA;
  box-sizing: border-box;
}

.inspect-form-content {
  padding: 0 24rpx;
  background: transparent;
}

.form-item {
  margin-bottom: 20rpx;
}

// 白色卡片:8px 圆角 + 卡片阴影(设计稿 .card)
.form-card {
  margin-top: 24rpx;
  padding: 8rpx 24rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(17, 24, 39, 0.06);
}

// 区块标题:蓝色竖条 + 标题文字
.sec-head {
  display: flex;
  align-items: center;
  gap: 12rpx;
  padding: 20rpx 0 8rpx;
}
.sec-bar {
  width: 6rpx;
  height: 28rpx;
  background-color: #2563EB;
  border-radius: 3rpx;
}
.sec-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #1F2937;
}

// 表单行:上下 24rpx(左右由卡片内边距控制)
.form-card .form-item {
  margin-bottom: 0;
}
.form-card :deep(.u-form-item__body) {
  padding: 24rpx 0 !important;
}
.form-card :deep(.u-form-item__body__left__content__label) {
  font-size: 28rpx;
  color: #333333;
}
.form-card :deep(.u-line) {
  background-color: #EEF1F6;
}
/* 卡片内最后一行不画分隔线 */
.form-card :deep(.u-form-item:last-child .u-line) {
  display: none;
}

/* 巡查描述 / 上传图片:分区标题已说明字段,隐藏左侧标签、内容整行铺满 */
.form-card--field :deep(.u-form-item__body__left) {
  display: none;
}
.form-card--field :deep(.u-form-item__body__right) {
  flex: 1;
}
.form-card--field :deep(.u-form-item__body) {
  padding: 16rpx 0 24rpx;
}
/* 文本域:浅灰圆角输入区 */
.form-card--field :deep(.u-textarea) {
  padding: 20rpx 20rpx 4rpx;
  background-color: #F5F7FA;
  border-radius: 12rpx;
}
.form-card--field :deep(.u-textarea__count) {
  color: #9CA3AF;
}
/* 上传:虚线框 */
.form-card--field :deep(.u-upload__button) {
  background-color: #FAFBFC;
  border: 1rpx dashed #C8D2E0;
  border-radius: 12rpx;
}
.upload-hint {
  margin-top: 16rpx;
  font-size: 24rpx;
  color: #9CA3AF;
}

/* 底部提交栏 */
.fixed-bottom-btn-wrap {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  padding: 16rpx 24rpx;
  padding-bottom: calc(16rpx + env(safe-area-inset-bottom));
  background-color: #ffffff;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.06);
  box-sizing: border-box;
}
.fixed-bottom-btn-wrap :deep(.u-button) {
  height: 88rpx !important;
  border-radius: 16rpx !important;
  font-size: 30rpx !important;
}
</style>