<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> -->
      <button class="margin-left-xs" type="primary" size="mini" @click="getCourierNumber()"
              style="float: right;margin-top: 10rpx">
        {{ $t('生成单号') }}
      </button>
      <button class="margin-left-xs" type="primary" size="mini" @tap="customerModal=true"
              style="float: right;margin-top: 10rpx">
        {{ $t('选择客户') }}
      </button>
    </view>
    <!-- 自定义表单校验 -->
    <uni-forms ref="form" :rules="rules" :modelValue="form" label-width="100" class="padding-xs">

      <uni-row class="padding-xs">
        <uni-col :span="9">
          <uni-forms-item label="客户编号" class="align-center">
            {{ form.customerNumber }}
          </uni-forms-item>
        </uni-col>
        <uni-col :span="10">
          <uni-forms-item label="电话" class="align-center">
            {{ form.phoneNew }}
          </uni-forms-item>
        </uni-col>
        <uni-col :span="5">
          <uni-forms-item label="姓名" class="align-center">
            {{ form.customerName }}
          </uni-forms-item>
        </uni-col>
      </uni-row>
      <uni-forms-item label="快递单号" name="expressNo">
        <uni-easyinput v-model="form.expressNo" disabled/>
      </uni-forms-item>
      <uni-forms-item :label="$t('集运仓库')" required name="wareId">
        <uni-data-checkbox v-model="form.wareId" :localdata="warehouseList" mode="tag"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item label="货运方式" class="align-center">
        <uni-data-checkbox v-model="form.transportId" :localdata="transportList"></uni-data-checkbox>
      </uni-forms-item>

      <uni-forms-item :label="$t('商品信息')" required/>
      <uni-row class="padding-xs" v-for="(item,index) in form.consItemVOList">
        <uni-col :span="3">
          <uni-forms-item :label="'商品'+(index + 1)" class="align-center"/>
        </uni-col>
        <uni-col :span="8">
          <view @click="tagIndex(index)" :class="newTag?'':'dis'">
            <select-combox
                :productListToBeDetermined="productListToBeDetermined"
                :candidates="productListZh"
                @getValue="getValue"
                @input="handleInputZh"
                :modelValue="item.prodName"
                v-model="item.prodName"
            ></select-combox>
          </view>
        </uni-col>
        <uni-col :span="3">
          <uni-forms-item :label="'数量'+(index + 1)" class="align-center margin-left-xs"/>
        </uni-col>
        <uni-col :span="5">
          <uni-easyinput type="number" v-model="item.quantity" :clearable="false" :class="newTag?'':'dis'"/>
        </uni-col>
        <uni-col :span="5">
          <button class="margin-left-xs" type="warn" size="mini" @click="delProduct(index)" v-if="newTag">{{
              $t('删除')
            }}
          </button>
        </uni-col>
      </uni-row>
      <button class="margin-left-xs" type="primary" size="mini" @click="addProduct()" v-if="newTag">
        {{ $t('添加一行') }}
      </button>
      <uni-forms-item label="填单数据" class="align-center">
        {{ sum }}个
      </uni-forms-item>
      <uni-forms-item label="订单总货值（元）" class="align-center" type="number">
        <uni-easyinput v-model="form.worth"/>
      </uni-forms-item>
      <uni-forms-item label="包裹备注" class="align-center">
        <uni-easyinput type="textarea" v-model="form.remarks"/>
      </uni-forms-item>
      <uni-forms-item label="签收人" class="align-center">
        {{ userInfo.nickname }}
      </uni-forms-item>
      <uni-forms-item label="签收时间" class="align-center">
        <uni-datetime-picker type="datetime" return-type="timestamp" v-model="form.signedTime" style="width: 400rpx"/>
      </uni-forms-item>
      <uni-forms-item label="签收备注" class="align-center" name="signedRemarks">
        <uni-easyinput type="textarea" v-model="form.signedRemarks"/>
      </uni-forms-item>
      <uni-forms-item label="签收影像"></uni-forms-item>
      <view class="img-wrap">
        <uni-grid :column="4" :highlight="true" :show-border="false">
          <uni-grid-item v-for="(image, index) in form.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(form.mediaUrl)">
                <uni-icons type="plusempty" size="30" color="#eae8eb"></uni-icons>
                <!-- <text>添加视频或图片</text> -->
              </view>
            </view>
          </uni-grid-item>
        </uni-grid>
      </view>
    </uni-forms>

    <uni-row class="padding-xl text-center">
      <uni-col :span="12">
        <button type="primary" size="mini" @click="submit('form')" v-if="!newTag">
          {{ $t('签收完成') }}
        </button>
      </uni-col>
      <uni-col :span="12">
        <button size="mini" @click="goList">{{ $t('取消') }}</button>
      </uni-col>
      <uni-col :span="12">
        <button type="primary" size="mini" @click="submitModel('form')" v-if="newTag">
          {{ $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">
          快递单号：{{ form.expressNo }}签收成功
        </view>
        <view class="cu-bar bg-white justify-end">
          <view class="action">
            <button class="cu-btn bg-blue margin-left" @tap="refresh()">继续签收</button>
            <button class="cu-btn bg-grey margin-left" @click="goList">关闭</button>
          </view>
        </view>
      </view>
    </view>

    <view class="cu-modal" :class="customerModal?'show':''">
      <view class="cu-dialog">
        <view class="cu-bar bg-white">
          <view class="action text-blue" @tap="customerModal=false">取消</view>
        </view>
        <view class="padding-xl text-left">
          <uni-easyinput class="uni-mt-5" suffixIcon="search" v-model="searchKey"
                         @iconClick="queryCustomer"></uni-easyinput>
          <view class="scroll">
            <view class="list-row list-header">
              <view class="">{{ $t('客户编号') }}</view>
              <view class="">{{ $t('姓名') }}</view>
              <view class="">{{ $t('电话') }}</view>
            </view>
            <view>
              <view v-for="(v, key) in listCustomerData" :class="{'list-row': true, 'row-bg' : key % 2 === 0}"
                    :key="key"
                    @tap="selectCustomer(v)">
                <view class="">{{ v.customerNumber }}</view>
                <view class="">{{ v.contactsName }}</view>
                <view class="">{{ v.phoneNew }}</view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

  </view>
</template>

<script>

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

export default {
  name: "batch-sign-cons",
  components: {selectCombox},
  computed: {
    DICT_TYPE() {
      return DICT_TYPE
    },
    sum() {
      let sum = 0
      for (let i in this.form.consItemVOList) {
        sum = sum + this.form.consItemVOList[i].quantity * 1
      }
      return sum
    }
  },
  data() {
    return {
      iconPath,
      // 自定义表单数据
      form: {},
      // 自定义表单校验规则
      rules: {
        expressNo: {
          rules: [{
            required: true,
            errorMessage: '快递单号不能为空'
          }]
        },
        wareId: {
          rules: [{
            required: true,
            errorMessage: '集运仓库不能为空'
          }]
        },
        signedRemarks: {
          rules: [{
            maxLength: 100,
            errorMessage: '备注长度不能超{maxLength}个字符',
          }]
        }
      },
      warehouseList: [],
      transportList: [],
      expressList: [],
      productListZh: [],
      productListZhObj: [],
      productListEn: [],
      // 是否待确定
      productListToBeDetermined: [],
      listCustomerData: [],
      productIndex: null,
      keyword: '',
      searchKey: '',
      userInfo: this.$store.getters.userInfo(),
      newTag: false,
      autoRefresh: false,
      customerModal: false,
      consModel: false
    };
  },
  onLoad: function (option) {
    const that = this
    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)

    getConsWarehouseApp().then(row => {
      this.warehouseList = row
      if (row) {
        this.form.wareId = row[0].value
      }
    })
    getExpressApp().then(row => {
      this.expressList = row
    })
    this.getProductList();
  },
  methods: {
    getCourierNumber() {
      getCourierNumber().then(row => {
        this.keyword = row
        this.getList()
      })
    },
    goList() {
      uni.navigateBack({
        delta: 1
      })
    },
    queryCustomer() {
      selectPda({searchKey: this.searchKey, pageSize: 30, page: 1}).then(row => {
        this.listCustomerData = row.list
      })
    },
    selectCustomer(row) {
      this.form.customerId = row.customerId
      this.form.customerNumber = row.customerNumber
      this.form.phoneNew = row.areaCode + row.phoneNew
      this.form.customerName = row.customerName
      this.customerModal = false
      console.log(row)
    },
    getList() {
      if (this.keyword !== '') {
        getConsById({expressNo: this.keyword}).then(row => {
          if (row !== null) {
            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.newTag = false
            this.form = row
          } else {
            // 获取当前时间精确至[年、月、日、时、分、秒]
            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}`
            this.form = {
              consItemVOList: [],
              expressNo: this.keyword,
              mediaUrl: [],
              signedTime: defaultDate,
              wareId: JSON.parse(JSON.stringify(this.warehouseList[0].value))
            }
            this.newTag = true
          }
        })
      } else {
        this.form = {
          consItemVOList: [],
          mediaUrl: []
        }
      }
    },
    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.form.mediaUrl.splice(index, 1)
    },
    search() {
      this.getList()
      // this.page = 1
      // setTimeout(() => {
      //   this.getData(this.keyword)
      // }, 100)
    },
    scanCode() {
      uni.scanCode({
        success: (res) => {
          this.keyword = res.result
          this.goList()
        }
      })
    },
    tagIndex(index) {
      this.productIndex = index
    },
    getValue(e) {
      if (e) {
        var sindex = 0
        const that = this
        that.productListZhObj.forEach((item, index) => {
          if (item.titleZh == e) {
            sindex = index
          }
        })
        this.form.consItemVOList[this.productIndex].prodId = that.productListZhObj[sindex].id
      }
    },
    getProductList(prodName = '') {
      // 注意：由于接口特性，中英文均都必须使用titleZh字段搜索
      return getProductList({
        filter: false,
        pageSize: 30,
        titleZh: prodName
      }).then(data => {
        this.productListZh = data.list.map(v => v.titleZh)
        this.productListZhObj = data.list
        this.productListEn = data.list.map(v => v.titleEn)
        this.productListToBeDetermined = data.list.map(v => v.auditStatus !== 2)
      })
    },
    handleInputZh(e) {
      this.getProductList(e)
    },
    submit(ref) {
      const that = this
      this.$refs[ref].validate().then(res => {
        for (let i in this.form.consItemVOList) {
          if (this.form.consItemVOList[i].prodId === 0) {
            uni.showToast({
              title: `请选择第${1 * i + 1}个商品`,
              icon: 'none'
            })
            return
          }
        }
        if (this.form.worth === undefined || this.form.worth === '') {
          uni.showToast({
            title: `货值不能为空`,
            icon: 'none'
          })
          return;
        }
        var form = {
          ...this.form,
          mediaUrl: this.form.mediaUrl.map(e => e.url).join(',')
        }
        if (form.needInspect === 0) {
          form.status = 1
          form.signer = this.$store.getters.userInfo().id
          form.signed = 1
        }
        if (form.mediaUrl === "") {
          uni.showToast({
            title: `请拍照`,
            icon: 'none'
          })
          return
        }
        signedPda(form).then(() => {
          this.consModel = true
          this.autoRefresh = true
          setTimeout(function () {
            if (that.autoRefresh) {
              that.refresh()
            }
          }, 2000)
        })
      }).catch(err => {
        console.log('err', err);
      })
    },
    refresh() {
      this.autoRefresh = false
      this.consModel = false
      this.keyword = ''
      this.getList()
    },
    submitModel(ref) {
      this.consModel = false
      this.$refs[ref].validate().then(res => {
        for (let i in this.form.consItemVOList) {
          if (this.form.consItemVOList[i].prodId === 0) {
            uni.showToast({
              title: `请选择第${1 * i + 1}个商品`,
              icon: 'none'
            })
            return
          }
        }
        var form = {
          ...this.form,
          mediaUrl: this.form.mediaUrl.map(e => e.url).join(','),
          status: 1,
          signer: this.$store.getters.userInfo().id,
          signed: 1
        }
        if (form.mediaUrl === "") {
          uni.showToast({
            title: `请拍照`,
            icon: 'none'
          })
          return
        }
        const that = this
        createCons(form).then(() => {
          this.consModel = true
          this.autoRefresh = true
          setTimeout(function () {
            if (that.autoRefresh) {
              that.refresh()
            }
          }, 2000)
        })
      }).catch(err => {
        console.log('err', err);
      })
    },
    delProduct(index) {
      this.form.consItemVOList.splice(index, 1)
    },
    addProduct() {
      this.form.consItemVOList.push({prodId: 0, prodName: "", 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>
