wlzboy
2025-11-27 668e570bd1db6bd00e4293b6977e6d3d051053ce
app/pages/task/detail.vue
@@ -135,7 +135,7 @@
        </view>
        <view class="info-item" v-if="taskDetail.emergencyInfo.patientCondition">
          <view class="label">病情描述</view>
          <view class="value">{{ taskDetail.emergencyInfo.patientCondition }}</view>
          <view class="value" style="white-space: pre-line;">{{ taskDetail.emergencyInfo.patientCondition }}</view>
        </view>
      </view>
      
@@ -189,10 +189,69 @@
          <view class="value">{{ taskDetail.emergencyInfo.transferDistance }}公里</view>
        </view>
        <view class="info-item" v-if="taskDetail.emergencyInfo.transferPrice">
          <view class="label">转运费用</view>
          <view class="label">基础费用</view>
          <view class="value">¥{{ taskDetail.emergencyInfo.transferPrice }}</view>
        </view>
        <view class="info-item" v-if="paymentInfo">
          <view class="label">附加费用</view>
          <view class="value">¥{{ paymentInfo.additionalAmount || 0 }}</view>
        </view>
        <view class="info-item" v-if="paymentInfo">
          <view class="label">总费用</view>
          <view class="value" style="color: #e54d42; font-weight: bold;">¥{{ paymentInfo.totalAmount || 0 }}</view>
        </view>
        <view class="info-item" v-if="paymentInfo && paymentInfo.paidAmount > 0">
          <view class="label">已支付</view>
          <view class="value" style="color: #34C759;">¥{{ paymentInfo.paidAmount }}</view>
        </view>
        <view class="info-item" v-if="paymentInfo && paymentInfo.paidAmount > 0">
          <view class="label">剩余未付</view>
          <view class="value" style="color: #ff9900; font-weight: bold;">¥{{ getRemainingAmount() }}</view>
        </view>
      </view>
      <!-- 支付记录明细 -->
      <view class="detail-section" v-if="paymentInfo && paymentInfo.paidPayments && paymentInfo.paidPayments.length > 0">
        <view class="section-title">支付记录</view>
        <view
          class="payment-record-item"
          v-for="payment in paymentInfo.paidPayments"
          :key="payment.id"
        >
          <view class="payment-header">
            <view
              class="payment-method-tag"
              :class="[
                payment.paymentMethod === '1' ? 'method-cash' : '',
                payment.paymentMethod === '2' ? 'method-bank' : '',
                payment.paymentMethod === '3' ? 'method-wechat' : '',
                payment.paymentMethod === '4' ? 'method-alipay' : '',
                payment.paymentMethod === '5' ? 'method-pos' : '',
                payment.paymentMethod === '6' ? 'method-account' : '',
                payment.paymentMethod === '7' ? 'method-yyt' : ''
              ]"
            >
              {{ getPaymentMethodLabel(payment.paymentMethod) }}
            </view>
            <view class="payment-amount">¥{{ payment.settlementAmount }}</view>
          </view>
          <view class="payment-time" v-if="payment.payTime">
            {{ formatPaymentTime(payment.payTime) }}
          </view>
          <view class="payment-remark" v-if="payment.remark">
            备注:{{ payment.remark }}
          </view>
        </view>
      </view>
      <!-- 附件信息 -->
      <AttachmentUpload
        :taskId="taskId"
        title="任务附件"
        :readonly="isTaskFinished"
        @uploaded="onAttachmentUploaded"
        @deleted="onAttachmentDeleted"
      />
      
      <!-- 福祉车任务特有信息 -->
      <view class="detail-section" v-if="taskDetail.taskType === 'WELFARE' && taskDetail.welfareInfo">
@@ -260,8 +319,14 @@
    
    <!-- 操作按钮区域 -->
    <view class="action-buttons" v-if="taskDetail">
      <!-- 待处理状态: 显示出发、取消 -->
      <!-- 待处理状态: 显示编辑、出发、取消 -->
      <template v-if="taskDetail.taskStatus === 'PENDING'">
        <button
          class="action-btn edit"
          @click="handleEdit"
        >
          修改
        </button>
        <button 
          class="action-btn primary" 
          @click="handleTaskAction('depart')"
@@ -276,8 +341,14 @@
        </button>
      </template>
      
      <!-- 出发中状态: 显示已到达、强制结束 -->
      <!-- 出发中状态: 显示编辑、已到达、强制结束 -->
      <template v-else-if="taskDetail.taskStatus === 'DEPARTING'">
        <button
          class="action-btn edit"
          @click="handleEdit"
        >
          修改
        </button>
        <button 
          class="action-btn primary" 
          @click="handleTaskAction('arrive')"
@@ -292,8 +363,14 @@
        </button>
      </template>
      
      <!-- 已到达状态: 显示已返程 -->
      <!-- 已到达状态: 显示编辑、已返程 -->
      <template v-else-if="taskDetail.taskStatus === 'ARRIVED'">
        <button
          class="action-btn edit"
          @click="handleEdit"
        >
          修改
        </button>
        <button 
          class="action-btn primary" 
          @click="handleTaskAction('return')"
@@ -302,8 +379,14 @@
        </button>
      </template>
      
      <!-- 返程中状态: 显示已完成 -->
      <!-- 返程中状态: 显示编辑、已完成 -->
      <template v-else-if="taskDetail.taskStatus === 'RETURNING'">
        <button
          class="action-btn edit"
          @click="handleEdit"
        >
          修改
        </button>
        <button 
          class="action-btn primary" 
          @click="handleTaskAction('complete')"
@@ -312,23 +395,46 @@
        </button>
      </template>
      
      <!-- 已完成/已取消: 不显示按钮 -->
      <!-- 已完成/已取消: 不显示按钮,但如果是转运任务则显示结算按钮 -->
      <!-- 转运任务的结算按钮:仅完成/取消状态不显示 -->
      <button
        v-if="taskDetail.taskType === 'EMERGENCY_TRANSFER' && !isTaskFinished"
        class="action-btn settlement"
        @click="handleSettlement"
      >
        结算
      </button>
    </view>
  </view>
</template>
<script>
  import { getTask, changeTaskStatus } from '@/api/task'
  import { checkVehicleActiveTasks } from '@/api/task'
  import { getPaymentInfo } from '@/api/payment'
  import { formatDateTime } from '@/utils/common'
  import AttachmentUpload from '@/components/AttachmentUpload.vue'
  
  export default {
    components: {
      AttachmentUpload
    },
    data() {
      return {
        taskDetail: null,
        taskId: null
        taskId: null,
        paymentInfo: null // 支付信息
      }
    },
    computed: {
      // 判断任务是否已结束(已完成或已取消)
      isTaskFinished() {
        if (!this.taskDetail || !this.taskDetail.taskStatus) {
          return false
        }
        return ['COMPLETED', 'CANCELLED'].includes(this.taskDetail.taskStatus)
      },
      // 显示任务类型
      displayTaskType() {
        if (!this.taskDetail || !this.taskDetail.taskType) {
@@ -388,6 +494,12 @@
      this.taskId = options.id
      this.loadTaskDetail()
    },
    onShow() {
      // 每次页面显示时重新加载数据,确保从编辑页面返回后能看到最新数据
      if (this.taskId) {
        this.loadTaskDetail()
      }
    },
    methods: {
      // 加载任务详情
      loadTaskDetail() {
@@ -404,10 +516,68 @@
          console.log('任务状态字段值:', this.taskDetail.taskStatus)
          console.log('出发地址:', this.taskDetail.departureAddress)
          console.log('目的地址:', this.taskDetail.destinationAddress)
          console.log('转运任务信息 (emergencyInfo):', this.taskDetail.emergencyInfo)
          // 如果是转运任务,加载支付信息
          if (this.taskDetail.taskType === 'EMERGENCY_TRANSFER') {
            this.loadPaymentInfo()
          }
        }).catch(error => {
          console.error('加载任务详情失败:', error)
          this.$modal.showToast('加载任务详情失败')
        })
      },
      // 加载支付信息
      loadPaymentInfo() {
        getPaymentInfo(this.taskId).then(res => {
          this.paymentInfo = res.data
          console.log('支付信息:', this.paymentInfo)
        }).catch(err => {
          console.error('加载支付信息失败', err)
        })
      },
      // 根据支付方式字典值获取显示标签
      getPaymentMethodLabel(dictValue) {
        const methodMap = {
          '1': '现金',
          '2': '银行转账',
          '3': '微信支付',
          '4': '支付宝',
          '5': 'POS收款',
          '6': '挂账',
          '7': '易医通挂账',
          '8': '退款',
          '9': '积分'
        }
        return methodMap[dictValue] || dictValue
      },
      // 格式化支付时间
      formatPaymentTime(time) {
        if (!time) return '未知'
        const date = new Date(time)
        const year = date.getFullYear()
        const month = String(date.getMonth() + 1).padStart(2, '0')
        const day = String(date.getDate()).padStart(2, '0')
        const hour = String(date.getHours()).padStart(2, '0')
        const minute = String(date.getMinutes()).padStart(2, '0')
        return `${year}-${month}-${day} ${hour}:${minute}`
      },
      // 计算剩余未付金额
      getRemainingAmount() {
        if (!this.paymentInfo) {
          return '0.00'
        }
        const total = parseFloat(this.paymentInfo.totalAmount || 0)
        const paid = parseFloat(this.paymentInfo.paidAmount || 0)
        const remaining = total - paid
        console.log('总金额:', total.toFixed(2))
        console.log('已付金额:', paid.toFixed(2))
        console.log('剩余未付金额:', remaining.toFixed(2))
        return remaining > 0 ? remaining.toFixed(2) : '0.00'
      },
      
      // 获取车辆信息
@@ -454,6 +624,41 @@
        uni.navigateBack()
      },
      
      // 处理编辑按钮
      handleEdit() {
        if (!this.taskDetail) {
          this.$modal.showToast('任务信息不存在')
          return
        }
        // 检查任务状态,已完成或已取消的任务不能编辑
        if (this.isTaskFinished) {
          this.$modal.showToast('已完成或已取消的任务不能编辑')
          return
        }
        const taskType = this.taskDetail.taskType
        const taskId = this.taskDetail.taskId
        // 根据任务类型跳转到不同的编辑页面
        if (taskType === 'EMERGENCY_TRANSFER') {
          // 转运任务:跳转到转运任务编辑页面
          uni.navigateTo({
            url: `/pages/task/edit-emergency?id=${taskId}`
          })
        } else if (taskType === 'WELFARE') {
          // 福祗车任务:跳转到福祗车编辑页面
          uni.navigateTo({
            url: `/pages/task/edit-welfare?id=${taskId}`
          })
        } else {
          // 其他任务:跳转到通用任务编辑页面
          uni.navigateTo({
            url: `/pages/task/edit?id=${taskId}`
          })
        }
      },
      // 获取状态文本
      getStatusText(status) {
        const statusMap = {
@@ -480,14 +685,19 @@
        return typeMap[type] || '未知类型'
      },
      
      // 处理结算
      handleSettlement() {
        uni.navigateTo({
          url: '/pages/task/settlement?taskId=' + this.taskId
        })
      },
      // 处理任务操作
      handleTaskAction(action) {
        switch (action) {
          case 'depart':
            // 出发 -> 状态变为出发中
            this.$modal.confirm('确定要出发吗?').then(() => {
              this.updateTaskStatus('DEPARTING', '任务已出发')
            }).catch(() => {});
            // 出发 -> 检查车辆是否有其他正在进行中的任务
            this.checkVehicleAndDepart();
            break;
            
          case 'cancel':
@@ -525,6 +735,82 @@
            }).catch(() => {});
            break;
        }
      },
      // 检查车辆状态并出发
      checkVehicleAndDepart() {
        // 获取任务车辆ID
        const vehicleId = this.getVehicleId();
        if (!vehicleId) {
          this.$modal.showToast('未找到任务车辆信息');
          return;
        }
        // 显示加载提示
        uni.showLoading({
          title: '检查车辆状态...'
        });
        checkVehicleActiveTasks(vehicleId).then(response => {
          uni.hideLoading();
          const activeTasks = response.data || [];
          // 过滤掉当前任务本身
          const otherActiveTasks = activeTasks.filter(task => task.taskId !== this.taskId);
          if (otherActiveTasks.length > 0) {
            // 车辆有其他正在进行中的任务
            const task = otherActiveTasks[0];
            const taskStatus = this.getStatusText(task.taskStatus);
            const message = `该车辆已有正在转运中的任务!
任务单号:${task.taskCode}
任务状态:${taskStatus}
请先完成当前任务后再出发新任务。`;
            uni.showModal({
              title: '提示',
              content: message,
              showCancel: false,
              confirmText: '我知道了'
            });
            return;
          }
          // 车辆没有其他正在进行中的任务,可以出发
          this.$modal.confirm('确定要出发吗?').then(() => {
            this.updateTaskStatus('DEPARTING', '任务已出发')
          }).catch(() => {});
        }).catch(error => {
          uni.hideLoading();
          console.error('检查车辆状态失败:', error);
          // 检查失败时,仍然允许出发
          this.$modal.confirm('检查车辆状态失败,是否继续出发?').then(() => {
            this.updateTaskStatus('DEPARTING', '任务已出发')
          }).catch(() => {});
        });
      },
      // 获取任务车辆ID
      getVehicleId() {
        if (!this.taskDetail) {
          return null;
        }
        console.log("taskDetail assignedVehicles",this.taskDetail.assignedVehicles);
        // 从车辆列表中获取第一个车辆的ID(后端返回的字段名是assignedVehicles)
        if (this.taskDetail.assignedVehicles && this.taskDetail.assignedVehicles.length > 0) {
          return this.taskDetail.assignedVehicles[0].vehicleId;
        }
        // 或者从单个车辆对象获取
        if (this.taskDetail.vehicleId) {
          return this.taskDetail.vehicleId;
        }
        return null;
      },
      
      // 更新任务状态
@@ -592,6 +878,264 @@
            })
          }
        })
      },
      // 加载附件列表
      loadAttachmentList() {
        if (!this.taskId) {
          return
        }
        getAttachmentList(this.taskId).then(response => {
          this.attachmentList = response.data || response || []
        }).catch(error => {
          console.error('加载附件列表失败:', error)
        })
      },
      // 显示上传对话框
      showUploadDialog() {
        this.selectedCategoryIndex = 0
        this.tempImagePath = null
        this.$refs.uploadPopup.open()
      },
      // 关闭上传对话框
      closeUploadDialog() {
        this.$refs.uploadPopup.close()
      },
      // 分类选择变化
      onCategoryChange(e) {
        this.selectedCategoryIndex = e.detail.value
      },
      // 选择图片
      chooseImage() {
        const that = this
        uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera'],
          success: function(res) {
            that.tempImagePath = res.tempFilePaths[0]
          },
          fail: function(err) {
            console.error('选择图片失败:', err)
            that.$modal.showToast('选择图片失败')
          }
        })
      },
      // 确认上传
      confirmUpload() {
        if (!this.tempImagePath) {
          this.$modal.showToast('请先选择图片')
          return
        }
        const that = this
        const category = this.categoryList[this.selectedCategoryIndex].value
        // 微信小程序环境:先获取AccessToken,再上传到微信服务器,最后提交mediaId到后端
        // #ifdef MP-WEIXIN
        if (this.isWechatMiniProgram) {
          uni.showLoading({
            title: '上传中...'
          })
          // 第一步:从后端获取AccessToken
          getWechatAccessToken().then(tokenResponse => {
            // 接口返回格式:{"msg":"token值","code":200}
            console.log('获取AccessToken成功:', tokenResponse)
            const accessToken = tokenResponse.msg || tokenResponse.data || tokenResponse
            if (!accessToken) {
              uni.hideLoading()
              that.$modal.showToast('获取AccessToken失败')
              console.error('获取AccessToken失败,响应数据:', tokenResponse)
              return
            }
            console.log('获取到AccessToken:', accessToken)
            // 第二步:上传到微信服务器
            const uploadUrl = `https://api.weixin.qq.com/cgi-bin/media/upload?access_token=${accessToken}&type=image`
            uni.uploadFile({
              url: uploadUrl,
              filePath: that.tempImagePath,
              name: 'media',
              success: function(res) {
                console.log('微信上传响应:', res)
                try {
                  const data = JSON.parse(res.data)
                  if (data.media_id) {
                    // 第三步:提交mediaId到后端
                    uploadAttachmentFromWechat(that.taskId, data.media_id, category).then(response => {
                      uni.hideLoading()
                      that.$modal.showToast('上传成功')
                      that.closeUploadDialog()
                      that.loadAttachmentList()
                    }).catch(error => {
                      uni.hideLoading()
                      console.error('提交mediaId失败:', error)
                      that.$modal.showToast('上传失败:' + (error.msg || '请重试'))
                    })
                  } else {
                    uni.hideLoading()
                    const errMsg = data.errmsg || '未知错误'
                    console.error('微信返回错误:', data)
                    that.$modal.showToast('微信上传失败:' + errMsg)
                  }
                } catch (e) {
                  uni.hideLoading()
                  console.error('解析微信响应失败:', e, res.data)
                  that.$modal.showToast('上传失败:响应解析错误')
                }
              },
              fail: function(err) {
                uni.hideLoading()
                console.error('上传到微信失败:', err)
                that.$modal.showToast('上传失败:' + (err.errMsg || '请检查网络'))
              }
            })
          }).catch(error => {
            uni.hideLoading()
            console.error('获取AccessToken失败:', error)
            that.$modal.showToast('获取AccessToken失败')
          })
          return
        }
        // #endif
        // 非微信小程序环境:直接上传到后端服务器
        uni.showLoading({
          title: '上传中...'
        })
        uni.uploadFile({
          url: that.$baseUrl + '/task/attachment/upload/' + that.taskId,
          filePath: that.tempImagePath,
          name: 'file',
          formData: {
            'category': category
          },
          header: {
            'Authorization': 'Bearer ' + uni.getStorageSync('token')
          },
          success: function(uploadRes) {
            uni.hideLoading()
            if (uploadRes.statusCode === 200) {
              const result = JSON.parse(uploadRes.data)
              if (result.code === 200) {
                that.$modal.showToast('上传成功')
                that.closeUploadDialog()
                that.loadAttachmentList()
              } else {
                that.$modal.showToast(result.msg || '上传失败')
              }
            } else {
              that.$modal.showToast('上传失败')
            }
          },
          fail: function(err) {
            uni.hideLoading()
            console.error('上传失败:', err)
            that.$modal.showToast('上传失败')
          }
        })
      },
      // 查看附件
      viewAttachment(item) {
        // 如果是图片,使用图片预览
        const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp']
        const fileExt = item.fileName.split('.').pop().toLowerCase()
        if (imageTypes.includes(fileExt)) {
          // 构建图片访问地址
          // 如果是filePath是完整路径,需要通过下载接口访问
          const imageUrl = this.$baseUrl + '/task/attachment/download/' + item.attachmentId
          // 微信小程序中预览图片
          // #ifdef MP-WEIXIN
          // 微信小程序需要先下载到本地再预览
          uni.showLoading({ title: '加载中...' })
          uni.downloadFile({
            url: imageUrl,
            success: function(res) {
              uni.hideLoading()
              if (res.statusCode === 200) {
                uni.previewImage({
                  urls: [res.tempFilePath],
                  current: res.tempFilePath
                })
              } else {
                uni.showToast({ title: '加载图片失败', icon: 'none' })
              }
            },
            fail: function() {
              uni.hideLoading()
              uni.showToast({ title: '下载失败', icon: 'none' })
            }
          })
          // #endif
          // 非微信小程序环境,直接预览
          // #ifndef MP-WEIXIN
          uni.previewImage({
            urls: [imageUrl],
            current: imageUrl
          })
          // #endif
        } else {
          this.$modal.showToast('仅支持预览图片')
        }
      },
      // 删除附件
      deleteAttachment(attachmentId, index) {
        const that = this
        this.$modal.confirm('确定要删除该附件吗?').then(() => {
          deleteAttachment(attachmentId).then(response => {
            that.$modal.showToast('删除成功')
            that.attachmentList.splice(index, 1)
          }).catch(error => {
            console.error('删除附件失败:', error)
            that.$modal.showToast('删除失败')
          })
        }).catch(() => {})
      },
      // 获取分类名称
      getCategoryName(category) {
        const item = this.categoryList.find(c => c.value === category)
        return item ? item.label : '未分类'
      },
      // 格式化时间
      formatTime(time) {
        if (!time) return ''
        return formatDateTime(time, 'YYYY-MM-DD HH:mm')
      },
      // 格式化文件大小
      formatFileSize(size) {
        if (!size) return '0B'
        if (size < 1024) return size + 'B'
        if (size < 1024 * 1024) return (size / 1024).toFixed(2) + 'KB'
        return (size / 1024 / 1024).toFixed(2) + 'MB'
      },
      // 附件上传成功回调
      onAttachmentUploaded(response) {
        console.log('附件上传成功:', response)
      },
      // 附件删除成功回调
      onAttachmentDeleted(attachmentId) {
        console.log('附件删除成功:', attachmentId)
      }
    }
  }
@@ -647,6 +1191,18 @@
        color: #333;
        border-bottom: 1rpx solid #f0f0f0;
        padding-bottom: 10rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .upload-btn {
          font-size: 24rpx;
          padding: 8rpx 20rpx;
          background-color: #007AFF;
          color: white;
          border-radius: 8rpx;
          border: none;
        }
      }
      
      .info-item {
@@ -697,6 +1253,80 @@
      }
    }
    
    // 支付记录样式
    .payment-record-item {
      background-color: #f9f9f9;
      border-radius: 10rpx;
      padding: 20rpx;
      margin-bottom: 20rpx;
      &:last-child {
        margin-bottom: 0;
      }
      .payment-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15rpx;
        .payment-method-tag {
          display: inline-block;
          padding: 6rpx 16rpx;
          border-radius: 6rpx;
          font-size: 24rpx;
          color: white;
          font-weight: 500;
          &.method-cash {
            background-color: #34C759;
          }
          &.method-bank {
            background-color: #5AC8FA;
          }
          &.method-wechat {
            background-color: #09BB07;
          }
          &.method-alipay {
            background-color: #1677FF;
          }
          &.method-pos {
            background-color: #FF9500;
          }
          &.method-account {
            background-color: #FF9500;
          }
          &.method-yyt {
            background-color: #AF52DE;
          }
        }
        .payment-amount {
          font-size: 32rpx;
          font-weight: bold;
          color: #34C759;
        }
      }
      .payment-time {
        font-size: 24rpx;
        color: #999;
        margin-bottom: 10rpx;
      }
      .payment-remark {
        font-size: 24rpx;
        color: #666;
        line-height: 1.5;
      }
    }
    .loading {
      display: flex;
      flex-direction: column;
@@ -730,6 +1360,11 @@
        background-color: #f0f0f0;
        color: #333;
        
        &.edit {
          background-color: #ff9500;
          color: white;
        }
        &.primary {
          background-color: #007AFF;
          color: white;
@@ -740,6 +1375,11 @@
          color: white;
        }
        
        &.settlement {
          background-color: #34C759;
          color: white;
        }
        &:first-child {
          margin-left: 0;
        }