<template>
  <view style="background: #fff; min-height: calc(100vh - 44px)">
    <view class="search-header">
      <!-- <uni-search-bar class="uni-mt-10" @confirm="search" placeholder="请输入订单号" radius="100" v-model="keyword" cancelButton="none" clearButton="none" ></uni-search-bar> -->
      <scanlistener
          v-if="showScanlistener"
          suffixIcon="scan"
          v-model="keyword"
          :placeholder="$t('请扫描快递单号')"
          @iconClick="scanCode"
          @confirm="search"
          @submit="keyword=$event;search()"
      ></scanlistener>
      <!-- <text class="cuIcon-scan" style="font-size: 21px;" @click="scanCode"></text> -->
    </view>
    <!-- 自定义表单校验 -->
    <uni-forms ref="form" :rules="rules" :modelValue="cons" label-width="100" class="padding-xs">
      <view class="cu-form-group">
        <view class="title">{{ $t('包裹号') }}</view>
        <view class="content">{{ cons.consNum }}</view>
      </view>
      <view class="cu-form-group">
        <view class="title">{{ $t('发件人') }}</view>
        <view class="content">({{ cons.customerId }}){{ cons.customerName }}</view>
      </view>
      <view class="cu-form-group">
        <view class="title">{{ $t('发件人电话') }}</view>
        <view class="content">{{ cons.phoneNew }}</view>
      </view>
      <view class="cu-form-group">
        <view class="title">{{ $t('快递单号') }}</view>
        <view class="content" style="width: 400rpx">
          <uni-forms-item name="expressNo" style="margin-bottom: 0;">
            <uni-easyinput placeholder="请输入快递单号" v-model="cons.expressNo"/>
          </uni-forms-item>
        </view>
      </view>
      <view class="cu-form-group">
        <view class="title">{{ $t('快递公司') }}</view>
        <view class="content" style="width: 220rpx">
          <uni-data-select v-model="cons.expressId" :localdata="expressList" :clear="false"/>
        </view>
      </view>
      <view class="cu-form-group">
        <view class="title">{{ $t('货运方式') }}</view>
        <view class="content" style="width: 220rpx">
          <uni-data-select v-model="cons.transportId" :localdata="transportList" :clear="false"/>
        </view>
      </view>
      <view class="cu-form-group">
        <view class="title">{{ $t('包裹状态') }}</view>
        <view class="content">
          <dict-tag :type="DICT_TYPE.CONS_STATUS" :value="cons.status"/>
        </view>
      </view>
      <uni-row class="padding-xs" v-for="(item,index) in cons.consItemVOList">
        <uni-col :span="4">
          <uni-forms-item :label="'商品'+(index + 1)" class="align-center"/>
        </uni-col>
        <uni-col :span="8">
          <uni-easyinput class="dis" v-model="item.prodName" :clearable="false"/>
        </uni-col>
        <uni-col :span="4">
          <uni-forms-item :label="'数量'+(index + 1)" class="align-center margin-left-xs"/>
        </uni-col>
        <uni-col :span="8">
          <uni-easyinput class="dis" v-model="item.quantity" :clearable="false"/>
        </uni-col>
      </uni-row>
      <view class="cu-form-group">
        <view class="title">{{ $t('包裹备注') }}</view>
        <view class="content">
          {{ cons.remarks }}
        </view>
      </view>
      <view class="cu-form-group" @tap="toLocation()">
        <view class="title">{{ $t('货位') }}</view>
        <view class="content">
          {{
            this.cons.consLocationBackList && this.cons.consLocationBackList.length ? this.cons.consLocationBackList.map(v => v.code || v.areaName + (v.locationName || '')).join(',') : ''
          }}
          <uni-icons type="right" size="16"></uni-icons>
        </view>
      </view>
      <view class="cu-form-group">
        <view class="title">{{ $t('签收人') }}</view>
        <view class="content">
          {{ userInfo.nickname }}
        </view>
      </view>
      <view class="cu-form-group">
        <view class="title">{{ $t('签收时间') }}</view>
        <view class="content">
          <uni-datetime-picker type="datetime" return-type="timestamp" v-model="cons.signedTime" style="width: 400rpx"/>
        </view>
      </view>
      <view class="cu-form-group">
        <view class="title">{{ $t('签收影像') }}</view>
      </view>
      <view class="img-wrap">
        <uni-grid :column="4" :highlight="true" :show-border="false">
          <uni-grid-item v-for="(image, index) in cons.mediaUrl" :index="index" :key="index">
            <view class="grid-item-box" style="height: 100%;position: relative;">
              <image :src="iconPath" style="position: absolute;top:4px;right:4px;width:24px;height:24px;z-index:9"
                     @tap="delImage(index)" mode="widthFix"></image>
              <image v-if="image.type === 'image'" :src="image.url" mode="scaleToFill" style="height: 100%"
                     @tap="previewImage(image.url)"/>
              <video v-else-if="image.type === 'video'" :id="`video_${index}`" style="width: 100%;height: 100%"
                     :src="image.url" @play="playVideo(index)" @tap="playVideo(index)"
                     @fullscreenchange="fullscreenchange"></video>
            </view>
          </uni-grid-item>
          <uni-grid-item>
            <view class="grid-item-box" style="height: 100%">
              <view class="grid-item-box-add" @tap="chooseVideoImage(cons.mediaUrl)">
                <uni-icons type="plusempty" size="30" color="#eae8eb"></uni-icons>
                <!-- <text>添加视频或图片</text> -->
              </view>
            </view>
          </uni-grid-item>
        </uni-grid>
      </view>
      <view class="cu-form-group">
        <view class="title">{{ $t('签收备注') }}</view>
        <view class="content">
          <uni-forms-item name="signedRemarks" style="width: 400rpx">
            <uni-easyinput type="textarea" v-model="cons.signedRemarks"/>
          </uni-forms-item>
        </view>
      </view>
    </uni-forms>

    <uni-row class="padding-xl text-center">
      <uni-col :span="12">
        <button type="primary" size="mini" @click="submit('form')" v-if="cons.signed ===false">
          {{ $t('签收完成') }}
        </button>
      </uni-col>
      <uni-col :span="12">
        <button type="primary" size="mini" v-if="cons.status===2" @click="consModel='show'">
          {{ $t('保存') }}
        </button>
      </uni-col>
      <uni-col :span="12">
        <button class="cu-btn bg-grey" size="mini" @click="goList">{{ $t('取消') }}</button>
      </uni-col>
    </uni-row>

    <view class="cu-modal" :class="consModel ? 'show' : ''" style="z-index: 999;">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end">
          <view class="content">提示</view>
        </view>
        <view class="padding-xl">
          包裹已签收，是否更新信息
        </view>
        <view class="cu-bar bg-white justify-end">
          <view class="action">
            <button class="cu-btn bg-blue margin-left" @tap="submitModel('form')">提交</button>
            <button class="cu-btn bg-grey margin-left" @tap="consModel=!consModel">取消</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>

import {getConsById, getExpressApp, signedPda} from "@/api/cons";
import {DICT_TYPE, getDictDatas} from "@/util/dict";
import selectCombox from "@/components/select-combox/select-combox.vue";
import iconPath from "@/static/images/close.png"
import {updateImg} from "@/api/system";

export default {
  name: "sign-cons",
  components: {selectCombox},
  computed: {
    DICT_TYPE() {
      return DICT_TYPE
    },
    sum() {
      let sum = 0
      for (let i in this.consItemVOList) {
        sum = sum + this.consItemVOList[i].quantity * 1
      }
      return sum
    }
  },
  data() {
    return {
      iconPath,
      // 自定义表单校验规则
      rules: {
        expressNo: {
          rules: [{
            required: true,
            errorMessage: '快递单号不能为空'
          }]
        },
        signedRemarks: {
          rules: [{
            maxLength: 100,
            errorMessage: '备注长度不能超{maxLength}个字符',
          }]
        }
      },
      consItemVOList: [],
      warehouseList: [],
      transportList: [],
      expressList: [],
      productIndex: null,
      consModel: false,
      cons: {},
      id: null,
      keyword: '',
      userInfo: this.$store.getters.userInfo()
    };
  },
  onLoad: function (option) {
    const that = this
    this.id = option.consId
    this.getList()
    setTimeout(function () {
      var transportList = getDictDatas(DICT_TYPE.ECW_TRANSPORT_TYPE)
      for (let i in transportList) {
        that.transportList.push({value: transportList[i].value * 1, text: transportList[i].label})
      }
    }, 300)
    getExpressApp().then(row => {
      this.expressList = row
    })
  },
  methods: {
    // 选择储位回调
    setAddFormLocation(locationList, extra) {
      this.cons.consLocationBackList = locationList
      console.log('locationList', locationList)
    },
    toLocation() {
      const warehouseId = this.cons.wareId
      // let url = './location?warehouseId=' + warehouseId;
      let url = `/pages/cons/components/location?warehouseId=${warehouseId}&consId=${this.id}&locationList=${JSON.stringify(this.cons.consLocationBackList || [])}&callback=setAddFormLocation`
      uni.navigateTo({
        url: url
      });
    },
    scanCode() {
      uni.scanCode({
        success: (res) => {
          this.keyword = res.result
          this.cons.expressNo = JSON.parse(JSON.stringify(this.keyword))
        }
      })
    },
    search() {
      this.cons.expressNo = JSON.parse(JSON.stringify(this.keyword))
    },
    getList() {
      getConsById({id: this.id}).then(row => {
        console.log(row.signedTime)
        if (row.signedTime === null) {
          // 获取当前时间精确至[年、月、日、时、分、秒]
          var now = new Date()
          var year = now.getFullYear()
          var month = now.getMonth()
          var date = now.getDate()
          var hours = now.getHours()
          var minutes = now.getMinutes()
          var seconds = now.getSeconds()
          month = month + 1
          month = month.toString().padStart(2, '0')
          date = date.toString().padStart(2, '0')
          hours = hours.toString().padStart(2, '0')
          minutes = minutes.toString().padStart(2, '0')
          seconds = seconds.toString().padStart(2, '0')
          var defaultDate = `${year}-${month}-${date} ${hours}:${minutes}:${seconds}`
          row['signedTime'] = defaultDate
        }
        row.mediaUrl = (row.mediaUrl === null || row.mediaUrl === '') ? [] : row.mediaUrl.split(',').map(e => {
          return {
            url: e,
            type: ['jpg', 'png', 'jpeg', 'heic'].includes(e.split('.')?.reverse()[0]) ? 'image' : 'video'
          }
        })
        this.cons = row
      })
    },
    fullscreenchange(event) {
      // if (uni.getSystemInfoSync().platform == "ios") { return }
      if (!event.detail.fullScreen) {
        // this.videoContext.pause()
      }
    },
    chooseImages(flag, mediaUrl) {
      console.log(flag, '---------flag-----');
      uni.chooseImage({
        count: 9, //默认是9张
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], //从相册选择
        success: res => {
          console.log(res, 'ddddsss')
          // let imgFile = res.tempFilePaths;
          res.tempFilePaths.forEach((item, index) => {
            updateImg(item).then(data => {
              console.log(data, flag, '--------res--------');
              if (flag) {
                uni.showToast({
                  title: this.$t('影像上传成功'),
                  icon: 'success'
                })
                mediaUrl.push({type: 'image', url: data.data})
              } else {
                // this.exceptionList.push({ url: data.data })
                this.$set(this.exceptionList, this.exceptionList.length, {url: data.data})
              }
            })
          })
        }
      })
    },
    //上传视频
    chooseVideo(mediaUrl) {
      uni.chooseVideo({
        maxDuration: 60, //拍摄视频最长拍摄时间，单位秒。最长支持 60 秒
        count: 9,
        success: res => {
          let videoFile = res.tempFilePath;
          updateImg(videoFile).then(data => {
            mediaUrl.push({type: 'video', url: data.data})
          })
        },
        fail: (error) => {
          uni.hideLoading();
          uni.showToast({
            title: error,
            icon: 'none'
          })
        }
      })
    },
    chooseVideoImage(mediaUrl) {
      uni.showActionSheet({
        title: this.$t('选择上传类型'),
        itemList: [this.$t('图片'), this.$t('视频')],
        success: res => {
          console.log(res);
          if (res.tapIndex == 0) {
            this.chooseImages(true, mediaUrl);
          } else {
            this.chooseVideo(mediaUrl);
          }
        }
      });
    },
    playVideo(index) {
      setTimeout(() => {
        this.videoContext = uni.createVideoContext(`video_${index}`)
        // this.videoContext.play()
        // this.videoContext.requestFullScreen()
      }, 500)
    },
    previewImage(url) {
      uni.previewImage({
        current: 0, //预览图片的下标
        urls: [url] //预览图片的地址，必须要数组形式，如果不是数组形式就转换成数组形式就可以
      })
    },
    delImage(index) {
      this.cons.mediaUrl.splice(index, 1)
    },
    tagIndex(index) {
      this.productIndex = index
    },
    submit(ref) {
      this.$refs[ref].validate().then(res => {
        var form = {
          ...this.cons,
          mediaUrl: this.cons.mediaUrl.map(e => e.url).join(',')
        }
        if (form.mediaUrl === "") {
          uni.showToast({
            title: `请拍照`,
            icon: 'none'
          })
          return
        }
        if (form.needInspect === null || form.needInspect === 0) {
          form.status = 1
          form.signer = this.$store.getters.userInfo().id
          form.signed = 1
        }
        signedPda(form).then(() => {
          uni.showToast({
            title: `签收成功`
          })
          this.getList()
        })
        console.log(form)
      }).catch(err => {
        console.log('err', err);
      })
    },
    submitModel(ref) {
      this.consModel = false
      this.$refs[ref].validate().then(res => {
        var form = {
          ...this.cons,
          mediaUrl: this.cons.mediaUrl.map(e => e.url).join(',')
        }
        console.log(form.mediaUrl)
        if (form.mediaUrl === "") {
          uni.showToast({
            title: `请拍照`,
            icon: 'none'
          })
          return
        }
        signedPda(form).then(() => {
          uni.showToast({
            title: `保存成功`
          })
          this.getList()
        })
        console.log(form)
      }).catch(err => {
        console.log('err', err);
      })
    },
    goList() {
      uni.navigateBack({
        delta: 1
      })
    },
    delProduct(index) {
      this.consItemVOList.splice(index, 1)
    },
    addProduct() {
      this.consItemVOList.push({prodId: 0, titleZh: "", quantity: 1})
    }
  }
}
;
</script>

<style lang="scss" scoped>
.search-header {
  ::v-deep .uni-easyinput__content {
    border-radius: 20px;
    padding-right: 10px;
    background: rgba($color: #fff, $alpha: 0.5) !important;
    border: none;
    // opacity: 0.5;
  }

  ::v-deep .uni-input-placeholder {
    padding-left: 8px;
    color: #b2c9f3;
  }

  ::v-deep .uni-input-input {
    padding-left: 8px;
  }
}

.scroll {
  margin-top: -8px;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  padding: 8px;
  background: #fff;

  .list-row {
    display: flex;
    align-items: center;
    // line-height: 24px;
    padding: 8px 0;

    view {
      flex: 1;
      text-align: center;
    }
  }

  .list-header {
    font-weight: bold;
  }

  .row-bg {
    background: #ebebed;
  }

  // .red-badge-wrap{
  //   position: absolute;
  //   right: -34upx;
  //   top: -26upx;
  // }
  .red-badge {
    display: inline-block;
    // background-color: #dd514c;
    color: #d9001c;
    // font-size: 24upx;
    // width: 30upx;
    // height: 30upx;
    // line-height: 30upx;
    // vertical-align: middle;
    // border-radius: 30upx;
    // margin-left: 2upx;
    /* transform: scale(0.9); */
  }
}

.img-wrap {
  ::v-deep .uni-grid-item {
    background: #fbf8fb;
  }

  .grid-item-box-add {
    height: 100%;
    display: flex;
    flex-flow: column;
    font-size: 10px;
    padding: 16px 0;
    text-align: center;
    justify-content: center;
  }
}

.dis {
  pointer-events: none
}
</style>
