<template>
  <view>
    <view
      class="as-gravity-center"
      style="
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        position: relative;
      "
      :style="
        'justify-content:' +
        (imageList.length === 0 ? 'flex-start' : 'space-between')
      "
    >
      <!-- 嵌套这层就over了  -->
      <view
        :style="
          'margin-left: ' +
          (retract + 10) +
          'rpx;margin-right: ' +
          retract +
          'rpx'
        "
        style="
          justify-content: flex-start;
          align-items: center;
          display: flex;
          flex-direction: row;
          flex-wrap: wrap;
        "
      >
        <block v-for="(image, indexs) in imageList" :key="indexs">
          <view
            :style="
              'width:' + innerWidth + 'px;' + 'height:' + innerWidth + 'px'
            "
            style="
              display: block;
              margin-left: 5px;
              margin-top: 5px;
              opacity: 0.7;
            "
          >
            <view
              class="as-gravity-center"
              @tap="previewImage(indexs, imageList)"
              :style="
                'width:' +
                (isDelete ? innerWidth / 2 : innerWidth / 2) +
                'px;' +
                'height:' +
                innerWidth +
                'px'
              "
              style="position: absolute; z-index: 3; opacity: 1"
            >
              <image
                v-show="isDelete"
                :src="`${$imgUrl}common/big.png`"
                style="width: 40rpx; height: 40rpx"
              >
              </image>
            </view>
            <view
              v-show="isDelete"
              class="as-gravity-center"
              @tap="removeImg(indexs, imageList)"
              :style="
                'width:' +
                innerWidth / 2 +
                'px;' +
                'height:' +
                innerWidth +
                'px;' +
                'margin-left: ' +
                innerWidth / 2 +
                'px;'
              "
              style="position: absolute; z-index: 3; opacity: 1"
            >
              <image
                :src="`${$imgUrl}common/remove.png`"
                style="width: 40rpx; height: 40rpx"
              >
              </image>
            </view>

            <view
              :style="
                'width:' + innerWidth + 'px;' + 'height:' + innerWidth + 'px'
              "
              style="
                position: absolute;
                z-index: 2;
                background-color: #b2b2b2;
                opacity: 0.5;
              "
            ></view>
            <image
              :style="
                'width:' + innerWidth + 'px;' + 'height:' + innerWidth + 'px'
              "
              class="as-radius-8px"
              style="position: relative; display: block"
              :src="isUrl ? urls + image : image"
              :data-src="isUrl ? urls + image : image"
            >
            </image>
          </view>
        </block>

        <view
          v-if="canChoose"
          class="layout4 as-gravity-center"
          @tap="chooseImage(item)"
          :style="'width:' + innerWidth + 'px;height:' + innerWidth + 'px'"
          style="
            display: flex;
            flex-direction: column;
            margin-top: 8px;
            margin-left: 5px;
          "
        >
          <image
            :src="`${$imgUrl}common/photo.png`"
            style="height: 56rpx; width: 56rpx"
          ></image>
          <view v-if="showTxt" class="text8" style="margin-top: 8px"
            >上传图片</view
          >
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { pathToBase64 } from "@/utils/util/imageTool.js";
import { request } from "@/utils/network/request";
import { fileUpload } from "@/utils/network/api";
import { stringToJson } from "@/utils/network/encryption";
export default {
  name: "form-image",
  props: {
    showImageList: {
      /* 图片数组*/
      type: Array,
      default: function () {
        return [];
      },
    },
    imgWidth: {
      /*获取屏幕宽度*/
      type: Number,
      default: 0,
      required: false,
    },
    retract: {
      /*缩进*/
      type: Number,
      default: 0,
    },
    isChoose: {
      /*是否选择图片*/
      type: Boolean,
      default: true,
    },
    isDelete: {
      /* 是否具备删除*/
      type: Boolean,
      default: true,
    },
    isUrl: {
      /* 是否拼接图片地址*/
      type: Boolean,
      default: false,
    },
    count: {
      /* 图片上传数量*/
      type: Number,
      default: 9,
    },
    showTxt: {
      /* 是否显示上传图片文字*/
      type: Boolean,
      default: true,
    },
  },
  created() {
    let { showImageList } = this;
    if (showImageList.length > 0) {
      this.imageList = showImageList;
    }
    let _this = this;

    //console.log('输出内容', this.imgWidth)
    if (isNaN(this.imgWidth) || this.imgWidth === 0) {
      //判断是否不是数字
      uni.getSystemInfo({
        success: function (res) {
          _this.innerWidth = res.windowWidth / 4 - 18;
        },
      });
    } else {
      _this.innerWidth = this.imgWidth - 18;
    }
  },
  mounted() {
    //当视图运行完后执行
  },
  data() {
    return {
      sourceTypeIndex: 2,
      innerWidth: 0,
      imageList: [],
      item: {},
      urls: "",
      update: true,
      canChoose: this.isChoose,
    };
  },
  watch: {
    //计算属性
    imageList(val) {
      //console.log('图片数据改变了', this.imageList.length);
    },
  },
  methods: {
    previewImage(e, item) {
      //放大图片
      // var current = this.isUrl ? this.urls + item[e] : item[e]
      if (this.isUrl) {
        for (var i = 0; i < item.length; i++) {
          if (item[i].indexOf("http") == -1) {
            item[i] = this.urls + item[i];
          }
        }
      }
      var current = item[e];
      console.log("输出内容", current);
      uni.previewImage({
        current: current,
        urls: item,
      });
    },
    removeImg(e, item) {
      //删除图片
      this.$emit("removeImg", item, e);
      item.splice(e, 1);
      this.canChoose = this.imageList.length === this.count ? false : true;
    },
    chooseImage: function (item) {
      //选择相机或相册时
      let _this = this;
      if (_this.imageList === undefined) {
        _this.imageList = [];
      }
      if (_this.imageList.length === this.count) {
        uni.showToast({
          icon: "none",
          title: "最多只能选择" + _this.count + "张图片",
        });
        return;
      }
      /* 图片选择 */
      uni.chooseImage({
        count: _this.count,
        success: (res) => {
          //选择成功
          // _this.imageList = _this.imageList.concat(res.tempFilePaths);
          const tempFilePaths = res.tempFilePaths;
          const imgUrl = "";
          //_this.$emit('backImg', _this.imageList) //测试环境下(正式环境请切换至接口返回地址)
          this.canChoose = _this.imageList.length === this.count ? false : true;
          for (var i = 0; i < tempFilePaths.length; i++) {
            pathToBase64(tempFilePaths[i])
              .then((path) => {
                var data = { fileBase64: path };
                const options = {
                  type: 2,
                  data: data,
                  method: "POST",
                  showLoading: true,
                };
                request(fileUpload, options).then((res) => {
                  const data = stringToJson(res.bizContent);
                  _this.imageList.push(data.data.url);
                  _this.$emit("backImg", _this.imageList); //测试环境下(正式环境请切换至接口返回地址)
                });
              })
              .catch((error) => {console.log(error)});

            /* 图片上传 */
            // uni.uploadFile({
            // 	url: 'https://www.example.com/upload', //仅为示例，非真实的接口地址
            // 	filePath: tempFilePaths[i],
            // 	name: 'file',
            // 	header: {
            // 		'X-Access-Token': uni.getStorageSync('token')
            // 	},
            // 	formData: {
            // 		biz: 'app'
            // 	},
            // 	success: (uploadFileRes) => {
            // 		let imgData = JSON.parse(uploadFileRes.data)
            // 		/* 数据拼接 */
            // 		if (imgUrl === undefined || imgUrl === '') {
            // 			imgUrl = imgData.message
            // 		} else {
            // 			imgUrl += ',' + imgData.message
            // 		}
            // 		_this.$emit('backImg', _this.imageList) //正式环境下
            // 	},
            // 	fail: (res) => {
            // 		console.log(res);
            // 	}
            // });
          }
        },
        fail: (err) => {
          if (err.errMsg.indexOf("cancel") !== "-1") {
            return;
          }
          uni.getSetting({
            success: (res) => {
              let authStatus = false;
              switch (this.sourceTypeIndex) {
                case 0:
                  authStatus = res.authSetting["scope.camera"];
                  break;
                case 1:
                  authStatus = res.authSetting["scope.album"];
                  break;
                case 2:
                  authStatus =
                    res.authSetting["scope.album"] &&
                    res.authSetting["scope.camera"];
                  break;
                default:
                  break;
              }
              if (!authStatus) {
                uni.showModal({
                  title: "授权失败",
                  content:
                    "需要从您的相机或相册获取图片，请在设置界面打开相关权限",
                  success: (res) => {
                    if (res.confirm) {
                      uni.openSetting();
                    }
                  },
                });
              }
            },
          });
        },
      });
    },
  },
};
</script>

<style>
.text8 {
  font-size: 26rpx;
  font-family: PingFang SC;
  color: #333333;
  opacity: 1;
}

.layout4 {
  background: #f3f3f3;
  opacity: 1;
  border-radius: 8px;
  border: 1px solid #dcdcdc;
}
</style>
