<template>
  <div
    ref="box"
    :id="elId"
  >
    <!-- <div @click="dialogVisible=true">
      附件📎

    </div> -->
    <!-- <el-link el-icon-view @click="dialogVisible=true"> 附件📎</el-link> -->
    <el-link @click="dialogVisible=true">
      <div class="showTxt">
        <p class="showFiletxt" v-show="fileName">{{fileName}}</p>
        <div>{{configData.label}}
          <i class="el-icon-s-operation el-icon--right"></i>
        </div>
      </div>
    </el-link>
    <el-dialog
      title="附件上传预览"
      :visible.sync="dialogVisible"
      width="80%"
      center
      :before-close="handleClose"
      :fullscreen='isfullscreen'
      :append-to-body='true'
      @open='openDialog'
    >
      <div class="file_imags">
        <div class="header_box">
          <div
            v-show="!hideInput"
            class="file"
          >
            选择文件
            <input
              type="file"
              id="avatar"
              name="avatar"
              :accept="configData.accept"
              :multiple='configData.multiple'
              @change='handleFileChange'
            />
          </div>
          <div v-show="hideInput">
            仅支持单文件上传,若需继续,请删除已有文件~
          </div>
          <div>
            <el-button
              size="mini"
              type="danger"
              @click="upload"
            >上传到服务器</el-button>
            <!-- <div  @click="isfullscreen=!isfullscreen">全屏</div> -->
            <i
              @click="isfullscreen=!isfullscreen"
              class="el-icon-full-screen fullScreen"
            ></i>
          </div>
        </div>
        <div class="imgBox">
          <div class="fileTypeItem">
            <div class="title_type">
              <i class="el-icon-house"></i>待上传文件:
            </div>
            <div class="allbox">
              <div
                class="file_item"
                v-for="(item,index) in  fileList"
                :key='index'
              >
                <div class="indexTitle">
                  <label class="indexText">{{index+1}}</label>
                  <div class="fileName">{{item.NewFileName}}</div>
                </div>
                <div class="image_tool">
                  <el-image
                    v-if="item.file"
                    style="width: 100px; height: 100px"
                    :src='item.file'
                    :preview-src-list="item.previewList"
                  >
                  </el-image>
                  <div class="tool">
                    <el-button
                      v-show="false"
                      size="mini"
                      @click="preview(item,index)"
                    >预览</el-button>
                    <el-button
                      type="danger"
                      size="mini"
                      slot="reference"
                      @click="deleteCurrImage(index)"
                      icon="el-icon-delete"
                      circle
                    ></el-button>
                  </div>
                </div>

              </div>
            </div>
          </div>
          <div class="fileTypeItem">
            <div class="title_type"><i class="el-icon-thumb"></i>服务器文件:</div>
            <div class="allbox">
              <div
                class="file_item"
                v-for="(item,index) in  newFileList"
                :key='index'
              >
                <div class="indexTitle">
                  <label class="indexText">{{index+1}}</label>
                  <div class="fileName">{{item.OldFileName}}</div>
                </div>
                <div class="image_tool">
                  <el-image
                    v-if="item.file"
                    style="width: 100px; height: 100px"
                    :src='item.file'
                    :preview-src-list="item.fileListImage"
                  >
                  </el-image>
                  <div class="tool">
                    <el-button
                      v-show="false"
                      size="mini"
                      @click="preview(item,index)"
                    >预览</el-button>
                    <el-button
                      type="danger"
                      size="mini"
                      slot="reference"
                      @click="deleteExitFile(index)"
                      icon="el-icon-delete"
                      circle
                    ></el-button>
                  </div>
                </div>

              </div>
            </div>
          </div>

        </div>
      </div>
    </el-dialog>
    <jsoneditor
      v-model='jsoneditorVisible'
      :elInfo='elInfo'
      :layout='layout'
      :jsoneditorCloseAfter='jsoneditorCloseAfter'
      :jsoneditorOpenAfter='jsoneditorOpenAfter'
    >
    </jsoneditor>
  </div>
</template>

<script>
import ucComponent from '../ucClass/uc_component'
import jsoneditor from '../common/jsoneditor'
import commonUtility from '../funTools/commonUtility'
import _ from 'lodash'
export default {
  mixins: [ucComponent],
  components: {
    jsoneditor
  },
  name: 'hsFile',
  props: {
    allSourceData: {
      type: Object,
      default() {
        return {}
      }
    },
    elInfo: {
      type: Object,
      default() {
        return {}
      }
    },
    value: '',
    layout: {},
    jsoneditorCloseAfter: {
      type: Function
    },
    jsoneditorOpenAfter: {
      type: Function
    }
  },
  watch: {
    allSourceData: {
      handler: function(newVal, oldVal) {
        const { config } = newVal
        this.initConfig(config)
      },
      deep: true
    },
    value(val) {
      this.value_inner = val
      this.initData()
    },
    value_inner(val) {
      this.$emit('input', val)
    },
    fileList: {
      handler: function(newVal, oldVal) {
        this.changeBtnStatus(newVal)
      },
      deep: true
    },
    newFileList: {
      handler: function(newVal, oldVal) {
        const data = _.cloneDeep(newVal)
        data.forEach(item => {
          delete item.fileListImage
          delete item.file
          delete item.name
        })
        this.value_inner = JSON.stringify(data)
        // this.changeBtnStatus(data)
      },
      deep: true
    }
  },
  data() {
    return {
      elId: '',
      value_inner: '',
      jsoneditorVisible: false,
      sourceData: [],
      visible_popover: false,
      fileList: [],
      fileListImage: [],
      fileListNoImage: [],
      dialogVisible: false,
      newFileList: [],
      files: [],
      isfullscreen: false,
      multiple: true,
      configData: {
        multiple: true,
        accept: '*',
        appCode: '',
        label: '查看附件'
      },
      appCode: '',
      hideInput: false,
      fileName: ''
    }
  },
  mounted() {
    this.$nextTick(() => {
      const { config } = this.allSourceData
      this.initConfig(config)
    })
    // const exitImage = localStorage['exitImage']
    // if(this.value){
    //   const data=JSON.parse(this.value)
    // }
    // console.log(this.value, 'append-to-body')
    // this.initData()
  },

  methods: {
    changeBtnStatus(data) {
      if (data.length >= 1) {
        this.hideInput = true
      } else {
        this.hideInput = false
      }
    },
    openDialog() {
      this.initData()
    },
    initData() {
      if (this.value) {
        this.newFileList = JSON.parse(this.value)
        const { config } = this.allSourceData
        this.initConfig(config)
        const appCode_ = this.configData.appCode
        const { appCode } = commonUtility.parseUrlQueryBIDyncAppcodePageName()
        const appCode__ = appCode_ || appCode
        this.appCode = appCode__
        this.newFileList.forEach(item => {
          const { NewFileName } = item
          this.$set(
            item,
            'file',
            `fileresourceAPI/file/${appCode__}/${NewFileName}/`
          )
          this.$set(item, 'fileListImage', [
            `fileresourceAPI/file/${appCode__}/${NewFileName}/`
          ])
        })
        // this.changeBtnStatus(this.newFileList)
      }
    },
    initConfig(config = {}) {
      this.configData = Object.assign(this.configData, config)
      const { multiple } = this.configData
      if (!multiple && this.newFileList.length) {
        this.fileName = this.newFileList[0].OldFileName
      }
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    imgPreview(file) {
      const self = this
      // 看支持不支持FileReader
      if (!file || !window.FileReader) return
      // 创建一个reader
      const reader = new FileReader()
      // 将图片将转成 base64 格式
      reader.readAsDataURL(file)
      // 读取成功后的回调
      reader.onloadend = function() {
        const type = file.type
        if (/^image/.test(type)) {
          self.fileListImage.push(this.result)
        } else {
          self.fileListNoImage.push({
            name: file.name
          })
        }
        self.fileList.push({
          type: file.type,
          NewFileName: file.name,
          OldFileName: file.name,
          file: this.result,
          fileBrod: file,
          previewList: [this.result]
        })
      }
    },
    handleFileChange(e) {
      const inputDOM = document.getElementById('avatar')
      this.file = inputDOM.files[0]
      this.files = Array.from(inputDOM.files)
      // 在获取到文件对象进行预览就行了！
      this.files.forEach(item => {
        this.imgPreview(item)
      })
      // 清除当前input 值
      e.target.value = ''
    },
    deleteCurrImage(image, index) {
      this.fileList.splice(index, 1)
    },
    preview(item, index) {
      const { name } = item
      this.$set(item, 'file', `fileresourceAPI/file/${this.appCode}/${name}/`)
      this.$set(item, 'fileListImage', [
        `fileresourceAPI/file/${this.appCode}/${name}/`
      ])
    },
    deleteFile(item, index) {
      this.fileList.splice(index, 1)
    },
    deleteExitFile(item, index) {
      this.newFileList.splice(index, 1)
    },
    async upload() {
      const formData = new FormData()
      if (!this.fileList.length) {
        this.$message.error('请选择文件!')
        return
      }
      const { multiple } = this.configData
      if (!multiple) {
        if (this.newFileList.length >= 1) {
          this.$message.error('仅支持单文件上传,请手动删除服务器文件后再试!')
          return
        }
      }
      this.fileList.forEach(element => {
        const { NewFileName, fileBrod } = element
        formData.append(NewFileName, fileBrod)
      })
      const newFileList = []
      const res = await this.$API.uploadFile(formData)
      const resData = (res.data || []).filter(item => {
        return item.Sucess
      })
      const resDataError = (res.data || []).filter(item => {
        return !item.Sucess
      })
      let errorStr = ''
      resDataError.forEach(jtem => {
        const { Error, OldFileName } = jtem
        errorStr += `${OldFileName}:${Error}`
      })
      if (errorStr) {
        this.$message.error(errorStr)
      }
      resData.forEach(item => {
        newFileList.push({
          OldFileName: item.OldFileName,
          NewFileName: item.NewFileName,
          file: `fileresourceAPI/file/${this.appCode}/${item.NewFileName}/`,
          fileListImage: [
            `fileresourceAPI/file/${this.appCode}/${item.NewFileName}/`
          ]
        })
        const targetIndex = this.fileList.findIndex(
          item_ => item_.NewFileName === item.OldFileName
        )
        this.fileList.splice(targetIndex, 1)
      })
      this.newFileList.push(...newFileList)
      if (!multiple && this.newFileList.length) {
        this.fileName = this.newFileList[0].OldFileName
      }
      localStorage['exitImage'] = JSON.stringify(this.newFileList)
    }
  }
}
</script>
<style scoped>
.file {
  position: relative;
  display: inline-block;
  background: #d0eeff;
  border: 1px solid #99d3f5;
  border-radius: 4px;
  padding: 4px 12px;
  overflow: hidden;
  color: #1e88c7;
  text-decoration: none;
  text-indent: 0;
  line-height: 20px;
  height: 20px;
}
.file input {
  position: absolute;
  font-size: 100px;
  right: 0;
  top: 0;
  opacity: 0;
}
.file:hover {
  background: #aadffd;
  border-color: #78c3f3;
  color: #004974;
  text-decoration: none;
}
.innerImageBox {
  position: relative;
  margin: 5px;
  border: 1px solid #9e9e9e;
}
.delete_icon {
  position: absolute;
  right: -8px;
  top: -7px;
  color: red;
}
.fileTypeItem {
  margin: 10px;
}
.otherFileBox {
  margin: 5px;
  border: 1px solid #9e9e9e;
  position: relative;
}
.otherFileOutBox {
  display: flex;
}
.imgOutBox {
  display: flex;
  flex-wrap: wrap;
}
.allbox {
  display: flex;
  flex-wrap: wrap;
}
.file_item {
  margin: 10px;
  padding: 5px;
  border: 1px solid gainsboro;
  box-shadow: 1px 4px 5px #888888;
}
.image_tool {
  display: flex;
  justify-content: space-around;
}
.tool {
  display: flex;
  align-items: flex-end;
}
.header_box {
  display: flex;
  justify-content: space-between;
}
.title_type {
  border-bottom: 1px solid #ddd;
}
.title_type > i {
  color: red;
}
.indexTitle {
  display: flex;
}
.fileName {
  width: 140px;
  white-space: nowrap;
  overflow-x: scroll;
}
.fileName::-webkit-scrollbar {
  width: 0px;
  height: 0px;
  /**/
}
.fileName::-webkit-scrollbar-track {
  background: rgb(239, 239, 239);
  border-radius: 2px;
}
.fileName::-webkit-scrollbar-thumb {
  background: #bfbfbf;
  border-radius: 10px;
}
.fileName::-webkit-scrollbar-thumb:hover {
  background: #333;
}
.fileName::-webkit-scrollbar-corner {
  background: #179a16;
}
.fullScreen {
  position: absolute;
  right: 50px;
  top: 25px;
}
.indexText {
  color: red;
  margin-right: 5px;
}
.showFiletxt{
height: 18px;
}
</style>
