<template>
  <view>
    <view class="cu-form-group" style="border-bottom: none; padding-bottom: 0;">
      <view class="title">
        <text v-if="required" class="lr-required">*</text>
        {{ title || '' }}
      </view>
    </view>

    <view class="cu-form-group" style="border-top: none;">
      <view class="grid col-4 grid-square flex-sub">
        <view v-for="(file, index) in value" :key="index" class="bg-img" style="position: relative;">
			 <!-- :style="{borderColor:file.noUpdated?'#EEE8AA':'#fff'}" -->
		  <view v-if="file.noUpdated" class="mask"></view>
          <image
            v-if="isImgFile(file)"
            @click="fileClick(index)"
            :src="file.path?file.path:file"
            :webp="file.type === 'webp'"
            mode="aspectFill"
          ></image>
          <view v-else-if="isDocFile(file)" @click="fileClick(index)" class="file-icon solids">
            <l-icon type="text" />
          </view>
          <view v-else class="file-icon solids" @click="fileClick(index)">
			  <l-icon type="text" />
		  </view>

          <view v-if="!readonly" @click.stop="delFile(index)" class="cu-tag bg-red" style="height: 24px; width: 24px;">
            <l-icon type="close" color="white" style="width: 18px; height: 24px; font-size: 24px;" />
          </view>
		  
		  <view class="fileName">
			  <text>{{file.name}}</text>
		  </view>
        </view>

        <view v-if="!readonly && value.length < Number(number)" @click="chooseFile" class="solids">
          <l-icon type="file" />
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// import uniCopy from '@/common/js/uni-copy.js'
export default {
  name: 'l-upload-file',

  props: {
    number: { default: 1 },
    readonly: {},
    value: { default: () => [] },
    title: {},
    required: {}
  },

  methods: {
    getFileExt(path) {
      return /\.(\w{2,5})$/.exec(path)[1] || null
    },
	
    isImgFile(file) {
      const typeString = (file.type || '').toLowerCase()
      return ['jpg','image/jpg','jpeg','image/jpeg', 'png', 'image/png','gif', 'image/gif','bmp', 'image/bmp','webp', 'image/webp','image'].includes(typeString)
    },

    isDocFile(file) {
      const typeString = (file.type || '').toLowerCase()
      return ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf'].includes(typeString)
	  return true
    },

    async delFile(index) {
	  if (!(await this.CONFIRM('删除文件', '确定要删除该文件吗？', true))) {
	    return
	  }
      const newList = JSON.parse(JSON.stringify(this.value))
      newList.splice(index, 1)
      this.$emit('input', newList)
      this.$emit('change')
      this.$emit('del')
    },

    chooseFile() {
      // #ifdef MP-DINGTALK
      // dd.chooseImage({
      //   count: Number(this.number),
      //   success: ({ filePaths }) => {
      //     if (filePaths) {
      //       const newList = JSON.parse(JSON.stringify(this.value || [])).concat(
      //         filePaths.map(t => ({ path: t, type: this.getFileExt(t) }))
      //       )
      //       this.$emit('input', newList)
      //       this.$emit('change', newList)
      //       this.$emit('add')
      //     }
      //   }
      // })
      // #endif

      // #ifndef MP-DINGTALK
      uni.chooseFile({
        count: Number(this.number),
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: ({ tempFilePaths,tempFiles }) => {
          const newList = JSON.parse(JSON.stringify(this.value || [])).concat(
            // tempFilePaths//.map(t => ({ path: t, type: this.getFileExt(t) }))
			tempFilePaths.map((t,i) => ({ path: t, type: tempFiles[i].type, size:tempFiles[i].size, name:tempFiles[i].name, noUpdated:true} ))
          )
          this.$emit('input', newList)
          this.$emit('change', newList)
          this.$emit('add')
        }
      })
      // #endif
    },

    async fileClick(index) {
      const { path, type, uid, size = 0 } = this.value[index]
	  if (this.isImgFile(this.value[index])) {
	    uni.previewImage({ urls: [path], current: path })
	  }else{
		  uni.openDocument({ filePath: this.value[index].path, fileType: type })
		  	// uniCopy({
		  	// 	content:this.value[index].path,
		  	// 	success:(res)=>{
		  	// 		uni.showToast({
		  	// 			title: "复制链接成功！请在浏览器进行打开~",
		  	// 			icon: 'none',
					// 	duration:3000,
		  	// 		})
		  	// 	},
		  	// 	error:(e)=>{
		  	// 		uni.showToast({
		  	// 			title: e,
		  	// 			icon: 'none',
		  	// 			duration:3000,
		  	// 		})
		  	// 	}
		  	// })
	  }
      // if (this.isImgFile(this.value[index])) {
      //   uni.previewImage({ urls: [path], current: path })
      // } else if (this.isDocFile(this.value[index])) {
      //   // #ifndef H5 || MP-DINGTALK
      //   if (size >= 50 * 1024 * 1024) {
      //     this.TOAST('小程序端无法下载超过50MB的文件，此文件大小为${size}KB，超过限制')
      //     return
      //   }
      //   // #endif

      //   // #ifndef MP-DINGTALK
      //   const tempFilePath = await this.HTTP_DOWNLOAD(uid)
      //   uni.openDocument({ filePath: tempFilePath, fileType: type })
      //   // #endif

      //   // #ifdef MP-DINGTALK
      //   this.TOAST('钉钉小程序只支持查看图片文件')
      //   // #endif
      // } else {
      //   // #ifndef MP-DINGTALK
      //   this.TOAST('小程序端只支持打开图片和文档(word、pdf等)文件')
      //   // #endif

      //   // #ifdef MP-DINGTALK
      //   this.TOAST('钉钉小程序只支持查看图片文件')
      //   // #endif

      //   // #ifdef APP-VUE
      //   const tempFilePath = await this.HTTP_DOWNLOAD(uid)
      //   uni.openDocument({ filePath: tempFilePath, fileType: type })
      //   // #endif

      //   // #ifdef H5
      //   await this.HTTP_DOWNLOAD(uid)
      //   // #endif
      // }
    },
	// ClickDownload(url) {
	//     var src = url;
	//     var iframe = document.createElement('iframe');
	//     iframe.style.display = 'none';
	//     iframe.src = "javascript: '<script>location.href=\"" + src + "\"<\/script>'";
	//     document.getElementsByTagName('body')[0].appendChild(iframe);
	// }
  }
}
</script>

<style lang="less" scoped>
.file-icon {
  line-height: 100%;
  position: static;
}
.fileName{
	padding: 2px 2px;
	margin-bottom: 2px;
	text-align: center;
	position: absolute;
	bottom: 0px;
	width: 100%;
	background: rgba(0,0,0,0.2);
	color: #fff;
	font-size: 12px;
	
	text-overflow: ellipsis;
	overflow: hidden;
	white-space: nowrap;
}
.mask{
	position: absolute;
	top: 0;left: 0;
	width: 100%;
	height: 100%;
	// background: rgba(255,252,153,0.2);
	background: rgba(0,0,0,0.7);
	z-index: 100;
	pointer-events: none;
}
</style>
