<template>
  <view>
    <form>
      <view class="cu-form-group margin-top">
        <view class="title">{{$t('发货人员')}}</view>
        {{ getUserName }}
      </view>
      <view class="cu-form-group">
        <view class="title">{{$t('装柜日期')}}</view>
        <uni-datetime-picker type="datetime" :border=false :value="date" @change="selectDate" :placeholder="$t('请选择')"></uni-datetime-picker>
      </view>
    </form>

    <!-- 装柜影像 -->
    <view class="confirm-img">
      <view class="detail-title">
        <uni-title type="h3" :title="$t('装柜影像')"></uni-title>
      </view>
      <view class="img-wrap">
        <uni-grid :column="4" :highlight="true" :show-border="false">
          <uni-grid-item v-for="(item, index) in imageList" :index="index" :key="index">
            <view class="grid-item-box" style="height: 100%;position: relative;">
              <image :src="iconpath" style="position: absolute;top:4px;right:4px;height:24px;width:24px;z-index:9" @tap="delimage(index)" mode="widthFix"></image>
              <image v-if="item.type === 'image'" :src="item.url" mode="scaleToFill" style="height: 100%" @tap="previewImage(item.url)" />
              <video v-else-if="item.type === 'video'" :id="`video_${index}`" style="width: 100%;height: 100%" :src="item.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">
                <uni-icons type="plusempty" size="30" color="#eae8eb"></uni-icons>
                <!-- <text>添加视频或图片</text> -->
              </view>
            </view>
          </uni-grid-item>
        </uni-grid>
      </view>
    </view>

    <view class="padding-xl">
      <view class="item">
        <button class="cu-btn block bg-green margin-tb-sm lg" @click="apply">{{$t('申请封柜')}}</button>
      </view>
    </view>
  </view>
</template>

<script>
import * as types from "../../store/mutations-types.js";
import {boxCabinetUpdate, closureApply, getCabinet} from "./api";
import { updateImg } from "@/api/system";
import dayjs from "dayjs";
import iconpath from "../../static/images/close.png";

export default {
  name: "loading-confirm",
  data() {
    return {
      imageList: [],
      iconpath: iconpath,
      date: dayjs(new Date()).format("YYYY-MM-DD hh:mm:ss"),
      shipmentStatus: null,
      shipmentId: null,

      ignoreCheckNum: false,
      closingIgnoreCheckNum: false,
      cabinetInfo: {}
    };
  },
  computed: {
    getUserName() {
      return this.$store.getters.userInfo().nickname;
    },
  },
  methods: {
    boxCabinetUpdate() {
      boxCabinetUpdate({
        ...this.cabinetInfo,
        ldPictures: JSON.stringify(this.imageList),
        ldBoxTime: this.date,
        operator: this.getUserName,
        operateType: 1
      }).then(r => {
        console.log(r)
      })
    },
    /* 视频/图片 */
    chooseVideoImage() {
      uni.showActionSheet({
        title: this.$t("选择上传类型"),
        itemList: [this.$t("图片")/* , this.$t("视频") */],
        success: (res) => {
          if (res.tapIndex == 0) {
            this.chooseImages();
          } else {
            this.chooseVideo();
          }
        },
      });
    },
    /* 视频/图片 */
    chooseImages() {
      uni.chooseImage({
        count: 9, // 默认是9张
        sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album", "camera"], //从相册选择
        success: (res) => {
          res.tempFilePaths.forEach((item, index) => {
            updateImg(item).then((data) => {
              this.imageList.push({ type: "image", url: data.data });
              this.boxCabinetUpdate()
            });
          });
        },
      });
    },
    /* 视频/图片 */
    chooseVideo(index) {
      uni.chooseVideo({
        maxDuration: 60, //拍摄视频最长拍摄时间，单位秒。最长支持 60 秒
        count: 9,
        // camera: this.cameraList[this.cameraIndex].value, //'front'、'back'，默认'back'
        // sourceType: sourceType[this.sourceTypeIndex],
        success: (res) => {
          let videoFile = res.tempFilePath;
          // res.tempFilePaths.forEach((item, index) => {
          updateImg(videoFile).then((data) => {
            this.imageList.push({ type: "video", url: data.data });
            this.boxCabinetUpdate()
          });
          // })
        },
        fail: (error) => {
          uni.hideLoading();
          uni.showToast({
            title: error,
            icon: "none",
          });
        },
      });
    },
    delimage(index) {
      this.imageList.splice(index, 1);
      this.boxCabinetUpdate()
    },
    /* 视频/图片 */
    previewImage(url) {
      //uniapp预览轮播图
      uni.previewImage({
        current: 0, //预览图片的下标
        urls: [url], //预览图片的地址，必须要数组形式，如果不是数组形式就转换成数组形式就可以
      });
    },
    /* 视频/图片 */
    playVideo(index) {
      setTimeout(() => {
        this.videoContext = uni.createVideoContext(`video_${index}`);
        this.videoContext.play();
        this.videoContext.requestFullScreen();
      }, 500);
    },
    /* 视频/图片 */
    fullscreenchange(event) {
      if (!event.detail.fullScreen) {
        this.videoContext.pause();
      }
    },
    /* 装柜日期 */
    selectDate(e) {
      this.date = e.detail.value;
    },
    /* 封柜 */
    apply() {
      if (this.shipmentId) {
        uni.showModal({
          cancelText:this.$t('取消'),
          confirmText:this.$t('确定'),
          content: this.$t("确认要封柜吗？"),
          success: (e) => {
            if (e.confirm) {
              this.doApply();
            }
          },
        });
      }
    },
    /* 确定封柜 */
    doApply() {
      closureApply({
        ldBoxTime: dayjs(this.date).format("YYYY-MM-DD 00:00:00"),
        ldPictures: JSON.stringify(this.imageList),
        shipmentId: this.shipmentId,
      })
        .then((data) => {
          this.$store.dispatch(types.SHOW_TOAST, {
            msg: this.$t("封柜成功"),
          });

          setTimeout(() => {
            uni.redirectTo({
              url: "./list",
            });
          }, 1500);
        })
        .catch((data) => {
          this.$store.dispatch(types.SHOW_TOAST, {
            msg: data.msg,
          });
        });
    },
  },
  onLoad: function (option) {
	  uni.setNavigationBarTitle({
	  	title:this.$t('装柜完成')
	  })
    if ("id" in option) {
      this.shipmentId = option.id;
      getCabinet(this.shipmentId).then(r => {
        if (r.cabinetInfo) {
          this.cabinetInfo = r.cabinetInfo
          if (this.cabinetInfo.ldPictures) {
            this.imageList = JSON.parse(this.cabinetInfo.ldPictures)
          }
          if (this.cabinetInfo.ldBoxTime) {
            this.date = dayjs(this.cabinetInfo.ldBoxTime).format("YYYY-MM-DD HH:mm:ss")
          }
        }
      })
    }
    if ("status" in option) {
      this.shipmentStatus = option.status;
    }
  },
};
</script>

<style lang="scss" scoped>
.confirm-img {
  background: #ffffff;
  padding: 0px 15px;
  .img-wrap {
    padding-bottom: 10px;
    width: calc(100% - 68px);
    ::v-deep .uni-grid-item {
      background: #ffffff;
    }
    .grid-item-box-add {
      height: 100%;
      display: flex;
      flex-flow: column;
      font-size: 10px;
      padding: 16px 0;
      text-align: center;
      justify-content: center;
    }
  }
}
.cu-form-group {
  .inpur-userName {
    padding: 0 12px;
  }
}
</style>
