<template>
  <view class="app">
    <view class="header">
      <view class="header_inner">
        <image src="../../static/order/clock.png"></image>
        <text class="txt1">配送剩余时间
          <text class="txt2">{{ preTime }}</text>
        </text>
      </view>
      <view class="tip">你需要在{{ sdTime === 'aN:aN' ? '' : sdTime }}前送达</view>
    </view>
    <view class="goods">
      <view class="goods_tit">商品信息</view>
      <view class="goods_details">
        <view class="detials_l">
          <scroll-view scroll-x="true">
            <image mode="aspectFit" v-for="(item,index) in details.riderItemVoList" :key="index"
                   :src="JSON.parse(item.url)[0].url" class="details_img"></image>
          </scroll-view>
        </view>
        <view class="detials_r">
          <view class="detials_r_inner">
            <text style="margin-left: 20rpx;">共{{ count }}件</text>
            <image @click="open()" src="../../static/order/dian.png"></image>
          </view>
        </view>
      </view>
    </view>
    <view class="count">
      <view class="count_item">
        <text class="txt3">配送费</text>
        <text class="txt4">{{ details.freightPrice }}元</text>
      </view>
      <view class="count_item nobor">
        <text class="txt3">商品费用</text>
        <text class="txt4 txt5">￥{{ details.totalPrice }}</text>
      </view>
      <view class="count_item nobor">
        <text class="txt3">合计</text>
        <text class="txt4 txt5">￥{{ (parseFloat(details.totalPrice) + parseFloat(details.freightPrice)).toFixed(2) }}
        </text>
      </view>
    </view>
    <view class="count">
      <view class="count_item">
        <text class="txt3">配送信息</text>
        <text class="txt4"></text>
      </view>
      <view class="count_item">
        <text class="txt3 txt6">收货人</text>
        <text class="txt4 txt5 txt7">{{ details.consignee }}</text>
      </view>
      <view class="count_item">
        <text class="txt3 txt6">联系电话</text>
        <text class="txt4 txt5 txt7">{{ details.phone }}</text>
      </view>
      <view class="count_item nobor">
        <text class="txt3 txt6">收货地址</text>
        <text class="txt4 txt5 txt7">{{ details.province }}{{ details.city }}{{ details.county }}{{ details.address }}
        </text>
      </view>
    </view>
    <view class="count">
      <view class="count_item">
        <text class="txt3">订单信息</text>
        <text class="txt4"></text>
      </view>
      <view class="count_item">
        <text class="txt3 txt6">订单编号</text>
        <text class="txt4 txt5 txt7">{{ details.orderNo }}
          <text style="padding-left: 20rpx;color: #3662DD;" @click="copy(details.orderNo)">复制</text>
        </text>
      </view>
      <view class="count_item">
        <text class="txt3 txt6">备注信息</text>
        <text class="txt4 txt5 txt7">{{ details.mono || '' }}</text>
      </view>
      <view class="count_item">
        <text class="txt3 txt6">支付方式</text>
        <text class="txt4 txt5 txt7">{{ details.payChannel }}</text>
      </view>
      <view class="count_item">
        <text class="txt3 txt6">下单时间</text>
        <text class="txt4 txt5 txt7">{{ orderCreateTime }}</text>
      </view>
      <view class="count_item nobor">
        <text class="txt3 txt6">支付时间</text>
        <text class="txt4 txt5 txt7">{{ payTime }}</text>
      </view>
    </view>
    
    <view class="count" >
      <view class="count_item">
        <text class="txt3">用户上传照片</text>
      </view>
      <view class="count_item nobor photo-upload-section">
        <view class="photo-upload-container">
          <view class="photo-list">
            <!-- 已上传的照片预览 -->
            <view
                v-for="(photo, index) in userOrderPhotos"
                :key="index"
                class="photo-item"
            >
              <image :src="photo" class="photo-preview" mode="aspectFill" @click="previewPhoto(index)"></image>
            </view>
          </view>
        </view>
      </view>
      
      <view class="count_item nobor"></view>
    </view>
    
    <!-- 照片上传区域 - 仅在订单状态为4时显示 -->
    <view class="count" >
      <view class="count_item">
        <text class="txt3">订单照片</text>
        <view class="photo-mode-btn" @click="togglePhotoMode" v-if="details.status === 4">
          <button class="mini-btn" @click="addScreenshot" :type="isEditMode ? 'primary' : 'default'" size="mini">
            {{ isEditMode ? '上传' : '编辑' }}
          </button>
        </view>
      </view>
      <view class="count_item nobor photo-upload-section">
        <view class="photo-upload-container">
          <view class="photo-list">
            <!-- 已上传的照片预览 -->
            <view
                v-for="(photo, index) in orderPhotos"
                :key="index"
                class="photo-item"
            >
              <image :src="photo" class="photo-preview" mode="aspectFill" @click="previewPhoto(index)"></image>
              <!-- 删除按钮仅在编辑模式下显示 -->
              <view v-if="isEditMode" class="photo-delete" @click="deletePhoto(index)">
                <text class="photo-delete-icon">×</text>
              </view>
            </view>
            
            <!-- 添加照片按钮仅在编辑模式下显示 -->
            <view
                v-if="isEditMode && orderPhotos.length < 6"
                class="photo-add-btn"
                @click="choosePhoto"
            >
              <text class="photo-add-icon">+</text>
              <text class="photo-add-text">添加照片</text>
            </view>
          </view>
          <view class="photo-tips" v-if="isEditMode">最多可上传6张照片</view>
        </view>
      </view>
    </view>
    <uni-popup ref="popup" type="bottom">
      <view class="popup_mask">
        <view class="popup_mask_tit">
          <text class="pop_t1">配送清单</text>
          <text class="pop_t2">共{{ count }}件</text>
          <image @click="closePop()" src="../../static/order/mask_close.png"></image>
        </view>
        <view class="pop_item" v-for="(item,index) in details.riderItemVoList" :key="'dt'+index">
          <view class="pop_item_l">
            <view class="item_l_l">
              <image mode="aspectFit" class="pil_img" :src="JSON.parse(item.url)[0].url"></image>
            </view>
            <view class="item_l_r">
              <view>{{ item.spuName }}</view>
              <view style="padding-top: 10rpx;">x{{ item.amount }}</view>
            </view>
            <!-- <image class="pil_img" src="../../static/login/logo.png"></image>
            <text>上海小白菜\n<text>x2</text> </text> -->
          </view>
          <view class="pop_item_r">
            ￥{{ item.unitPrice * item.amount }}
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import uniPopup from "@/components/uni-popup/uni-popup.vue";
import {
  mapState,
  mapMutations
} from 'vuex';

export default {
  components: {
    uniPopup
  },
  computed: {
    ...mapState(['token', 'userInfo'])
  },
  data() {
    return {
      goods: [1, 2, 3, 4, 5],
      id: '',
      details: '',
      preTime: '',
      count: 0,
      sdTime: '',
      orderCreateTime: '',
      payTime: '',
      interval: '',
      flag: false,
      orderPhotos: [], // 订单照片数组
      isEditMode: false, // 照片编辑模式标志
      userOrderPhotos: [],
    }
  },
  onLoad(e) {
    this.getDetails(e.id)
  },
  onHide() {
    clearInterval(this.interval)
  },
  methods: {
    closePop() {
      this.$refs.popup.close()
    },
    open() {
      this.$refs.popup.open()
    },
    copy(msg) {
      uni.setClipboardData({
        data: msg,
        success: function () {
          uni.showToast({
            title: '复制成功',
            icon: 'none',
            duration: 1500
          })
        }
      });
    },
    // 切换照片编辑模式
    togglePhotoMode() {
      this.isEditMode = !this.isEditMode
    },
    // 选择照片
    choosePhoto() {
      const remainingCount = 6 - this.orderPhotos.length
      uni.chooseImage({
        count: remainingCount,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePaths = res.tempFilePaths
          // 依次上传选中的照片
          tempFilePaths.forEach(filePath => {
            this.uploadPhoto(filePath)
          })
        },
        fail: (err) => {
          if (err.errMsg !== 'chooseImage:fail cancel') {
            console.error('选择照片失败:', err)
            uni.showToast({
              title: '选择照片失败',
              icon: 'none'
            })
          }
        }
      })
    },
    
    // 上传照片
    uploadPhoto(filePath) {
      const that = this
      that.$api.uploadImgByPath(filePath, that.token, (url) => {
        that.orderPhotos.push(url)
        uni.showToast({
          title: '上传成功',
          icon: 'success'
        })
      })
    },
    
    // 预览照片
    previewPhoto(index) {
      uni.previewImage({
        urls: this.orderPhotos,
        current: index
      })
    },
    
    // 删除照片
    deletePhoto(index) {
      const that = this
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这张照片吗？',
        success: (res) => {
          if (res.confirm) {
            that.orderPhotos.splice(index, 1)
          }
        }
      })
    },
    addScreenshot() {
      if (this.orderPhotos.length === 0) {
        return
      }
      const req = {
        orderId: this.details.orderId,
        screenshotType: 4,
        imageUrls: this.orderPhotos,
        userType: 2,
        uploadBy: this.userInfo.id
      }
      this.request('post', 'order/screenshot/add', this.token, req)
          .then(res => {
            if (res.code === 200) {
              uni.showToast({
                title: '添加成功',
                icon: 'success'
              })
            } else {
              uni.showToast({
                title: res.msg,
                icon: 'error'
              })
            }
          })
          .catch(err => {
            uni.showToast({
              title: '添加失败',
              icon: 'error'
            })
          })
          .catc
    },
    getDetails(id) {
      let that = this
      let params = {
        riderOrderId: id
      }
      that.request("get", "rider/task/detail", that.token, params).then(res => {
        if (res.code === 200) {
          let num = 0
          for (let i = 0; i < res.data.riderItemVoList.length; i++) {
            res.data.riderItemVoList[i].amount = parseInt(res.data.riderItemVoList[i].amount)
            num = num + parseInt(res.data.riderItemVoList[i].amount)
          }
          that.details = res.data
          if (res.data.imageUrls) {
            that.orderPhotos.push(...res.data.imageUrls)
          }
          if (res.data.userImageUrls) {
            that.userOrderPhotos.push(...res.data.userImageUrls)
          }
          // console.log(that.details)
          that.count = num
          that.orderCreateTime = that.dateFtt("yyyy-MM-dd hh:mm:ss", new Date(that.details.orderCreateTime))
          that.payTime = that.dateFtt("yyyy-MM-dd hh:mm:ss", new Date(that.details.payTime))
          that.sdTime = that.dateFtt("hh:mm", new Date(that.details.predictTime))
          // console.log(that.dateFtt("yyyy-MM-dd hh:mm:ss", new Date(that.details.predictTime)))
          that.preTime = new Date(that.details.predictTime).getTime() >= new Date().getTime() ? that.dateFtt("hh:mm:ss", new Date(that.details.predictTime)) : 0
          if (new Date(that.details.predictTime).getTime() >= new Date().getTime()) {
            that.preTime = true
          }
        }
      })
      
      that.interval = setInterval(function () {
        // console.log(new Date(that.details.predictTime).getTime()>=new Date().getTime())
        if (new Date(that.details.predictTime).getTime() > new Date().getTime()) {
          
          let d = new Date(that.details.predictTime).getTime() - new Date().getTime()
          // that.preTime = that.dateFtt("hh:mm:ss", d)
          //计算出相差天数
          var days = Math.floor(d / (24 * 3600 * 1000))
          
          //计算出小时数
          
          var leave1 = d % (24 * 3600 * 1000)    //计算天数后剩余的毫秒数
          var hours = Math.floor(leave1 / (3600 * 1000))
          //计算相差分钟数
          var leave2 = leave1 % (3600 * 1000)        //计算小时数后剩余的毫秒数
          var minutes = Math.floor(leave2 / (60 * 1000))
          
          
          //计算相差秒数
          var leave3 = leave2 % (60 * 1000)      //计算分钟数后剩余的毫秒数
          var seconds = Math.round(leave3 / 1000)
          that.preTime = days > 0 ? (days + ":" + hours + ":" + minutes + ":" + seconds) : (hours > 0 ? (hours + ":" + minutes + ":" + seconds) : (minutes + ":" + seconds))
          //alert(" 相差 "+days+"天 "+hours+"小时 "+minutes+" 分钟"+seconds+" 秒")
        } else {
          that.preTime = 0
          //console.log(that.flag)
          if (that.flag == true) {
            let nav_index = 2
            uni.redirectTo({
              url: '../task/task?nav_index=' + nav_index
            })
          }
          
          clearInterval(that.interval)
        }
      }, 1000)
    }
  }
}
</script>

<style scoped>
scroll-view {
  white-space: nowrap;
  height: 110rpx;
  width: 100%;
  margin-top: 42rpx;
  box-sizing: border-box;
}

.popup_mask {
  width: 690rpx;
  padding: 0 30rpx;
  height: 500rpx;
  background-color: #FFFFFF;
  border-top-left-radius: 24rpx;
  border-top-right-radius: 24rpx;
  padding-bottom: 6rpx;
}

.popup_mask_tit {
  height: 104rpx;
  line-height: 104rpx;
  position: relative;
}

.pop_t1 {
  font-size: 32rpx;
  color: #333333;
  font-weight: bold;
}

.pop_t2 {
  font-size: 28rpx;
  color: #1B1C33;
  margin-left: 40rpx;
}

.popup_mask_tit image {
  width: 30rpx;
  height: 30rpx;
  position: absolute;
  right: 20rpx;
  top: 38rpx;
}

.pop_item {
  height: 184rpx;
  border-bottom: 2rpx solid #F1F1F1;
  display: flex;
  flex-direction: row;
}

.pop_item_l {
  width: 520rpx;
  height: 184rpx;
  display: flex;
  flex-direction: row;
}

.item_l_l {
  width: 168rpx;
  height: 148rpx;
  padding-top: 36rpx;
}

.item_l_r {
  width: 452rpx;
  height: 148rpx;
  padding-top: 36rpx;
}

.pop_item_r {
  width: 150rpx;
  height: 148rpx;
  padding-top: 36rpx;
  font-size: 32rpx;
  color: #333333;
  font-weight: bold;
  text-align: right;
}

.pil_img {
  width: 118rpx;
  height: 110rpx;
}

.item_l_r view {
  font-size: 32rpx;
  color: #333333;
}

.test {
  width: 220upx;
  height: 220upx;
  display: inline-block;
  background-color: red;
}

.app {
  background-color: #F6F6F6;
}

.header {
  text-align: center;
  background-color: #FFFFFF;
}

.header_inner {
  display: inline-block;
  padding-top: 90rpx;
  
}

.header_inner image {
  width: 48rpx;
  height: 48rpx;
  position: relative;
  top: 8rpx;
}

.txt1 {
  font-size: 40rpx;
  color: #000000;
  font-weight: bold;
  margin-left: 24rpx;
}

.txt2 {
  color: #3662DD;
  padding-left: 20rpx;
}

.tip {
  text-align: center;
  font-size: 32rpx;
  color: #717171;
  padding-top: 24rpx;
  padding-bottom: 70rpx;
}

.goods {
  height: 282rpx;
  margin-top: 20rpx;
  background-color: #FFFFFF;
  padding: 0 30rpx;
}

.goods_tit {
  height: 86rpx;
  line-height: 86rpx;
  border-bottom: 2rpx solid #F1F1F1;
  font-size: 32rpx;
  color: #333333;
  font-weight: bold;
}

.goods_details {
  height: 194rpx;
  display: flex;
  flex-direction: row;
}

.detials_l {
  width: 496rpx;
  height: 194rpx;
}

.detials_r {
  width: 174rpx;
  height: 194rpx;
}

.details_img {
  display: inline-block;
  width: 118rpx;
  height: 110rpx;
  margin-right: 36rpx;
}

.detials_r_inner {
  height: 110rpx;
  margin-top: 42rpx;
  line-height: 110rpx;
  font-size: 28rpx;
  color: #1B1C33;
  position: relative;
}

.detials_r_inner image {
  width: 44rpx;
  height: 10rpx;
  position: absolute;
  right: 0;
  top: 48rpx;
}

.count {
  margin-top: 20rpx;
  padding: 0 30rpx;
  background-color: #FFFFFF;
}

.count_item {
  height: 99rpx;
  line-height: 99rpx;
  border-bottom: 2rpx solid #F1F1F1;
  font-size: 28rpx;
  
}

.txt3,
.txt5 {
  font-weight: bold;
  color: #333333;
}

.txt4 {
  
  color: #666666;
  float: right;
}

.nobor {
  border: none;
}

.txt6 {
  color: #999999;
  font-weight: normal;
}

.txt7 {
  font-weight: normal;
  color: #333333;
  word-wrap: break-word;
  word-break: break-all;
  white-space: normal;
}

/* 照片上传相关样式 */
.photo-upload-section {
  flex-direction: row !important; /* 改为横向布局 */
  align-items: flex-start !important;
  height: auto !important; /* 覆盖count_item的固定高度 */
  line-height: normal !important; /* 覆盖count_item的固定行高 */
  padding: 30rpx 0 !important; /* 添加上下内边距 */
  display: flex !important;
}

.distribution-text {
  width: 200upx;
  float: left;
  color: #333333;
  display: flex; /* 使用 flex 布局 */
  align-items: center; /* 垂直居中 */
}

.photo-upload-container {
  flex: 1; /* 占据剩余空间 */
  margin-top: 20rpx;
  margin-left: 20rpx; /* 与文案保持间距 */
  min-height: 200rpx; /* 确保至少有200rpx高度 */
}

.photo-list {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  align-content: flex-start;
  width: 100%;
}

.photo-item {
  position: relative;
  width: 200rpx; /* 固定正方形宽度 */
  height: 200rpx; /* 固定正方形高度 */
  margin-bottom: 20rpx; /* 行间距 */
}

.photo-preview {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
  border: 2rpx solid #e5e5e5;
}

.photo-delete {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: #ff4757;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.photo-delete-icon {
  color: #fff;
  font-size: 24rpx;
  font-weight: bold;
}

.photo-add-btn {
  width: 200rpx; /* 与photo-item保持一致 */
  height: 200rpx; /* 与photo-item保持一致 */
  margin-bottom: 20rpx; /* 与photo-item保持一致的行间距 */
  border: 2rpx dashed #ccc;
  border-radius: 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}

.photo-add-icon {
  font-size: 32rpx; /* 调小图标尺寸 */
  color: #999;
  margin-bottom: 4rpx; /* 减少间距 */
}

.photo-add-text {
  font-size: 20rpx; /* 调小文字尺寸 */
  color: #999;
}

.photo-tips {
  margin-top: 20rpx;
  font-size: 24rpx;
  color: #999;
}

/* 照片模式切换按钮样式 */
.photo-mode-btn {
  float: right;
  margin-top: 20rpx;
  margin-right: 10rpx;
}

.btn-text {
  color: #FFFFFF;
  font-size: 24rpx;
  font-weight: 500;
}

</style>
