<template>
  <div :style="{ width: record.options.width }" :class="listClass" style="text-align: left;">
    <a-upload
      :disabled="record.options.disabled"
      v-if="!record.options.drag"
      name="file"
      :accept="accept"
      :multiple="record.options.multiple"
      :data="optionsData"
      :fileList="fileList"
      :action="uploadAction"
      :headers="headers"
      :listType="fileListType"
      @preview="handlePreview"
      @change="handleChange"
      :remove="remove"
      :beforeUpload="beforeUpload"
    >
      <a-button
        v-if="fileList.length < record.options.limit && !record.options.disabled"
      >
        <ych-icon type="upload"/>
        {{ LocleUtil.getLocale('m.common.button.upload') }} </a-button>
    </a-upload>
    <a-upload-dragger
      v-else-if="fileList.length < record.options.limit && !record.options.disabled"
      name="file"
      :accept="accept"
      :multiple="record.options.multiple"
      :fileList="fileList"
      :data="optionsData"
      :action="uploadAction"
      :headers="headers"
      :listType="fileListType"
      @preview="handlePreview"
      @change="handleChange"
      :remove="remove"
      :beforeUpload="beforeUpload"
    >
      <p class="ant-upload-drag-icon">
        <ych-icon type="cloud-upload"/>
      </p>
      <p class="ant-upload-text">{{ LocleUtil.getLocale('m.eform.formDesign.label.dan-ji-huo-tuo-dong-wen-jian-dao-ci-qu-yu') }}</p>
    </a-upload-dragger>
    <a-upload
      v-else
      name="file"
      :multiple="record.options.multiple"
      :data="optionsData"
      :fileList="fileList"
      :action="uploadAction"
      :headers="headers"
      :listType="fileListType"
      @preview="handlePreview"
      @change="handleChange"
      :remove="remove"
      :beforeUpload="beforeUpload"
    >
    </a-upload>
    <a-table
      ref="fileListTable"
      size="middle"
      bordered
      rowKey="uid"
      :columns="columns"
      :dataSource="fileList"
      :pagination="false"
      :loading="loading"
      :style="record.options.fileTableStyle || defaultTableStyle"
      v-if="listType=='table' && fileList && fileList.length>0"
    >
      <template slot="filename" slot-scope="text, record">
        <a @click="handlePreview(record)">
          {{text}}
        </a>
      </template>
      <template slot="action" slot-scope="text, record">
        <a @click="deleteFile(record)">
          {{LocleUtil.getLocale('m.common.button.delete')}}
        </a>
      </template>

    </a-table>
  </div>
</template>
<script>

  import { getFileAccessHttpUrl, deleteAction,encryptedDownload } from '../utils/manage'
  import YchConstant from "../utils/YchConstant";
  import TokenStorageUtil from "../utils/TokenStorageUtil";
  import LocleUtil from "../utils/LocleUtil";

  export default {
    name: 'UploadFile',
    data () {
      return {
        uploadAction: YchConstant.PREFIX_REQUEST + YchConstant.PREFIX_SYSTEM + '/common/upload',
        headers: {},
        userInfo: {},
        fileList: [],
        deleteUrl: YchConstant.PREFIX_SYSTEM + '/common/deleteFile',
        defaultTableStyle:'height:200px;overflow:auto;',
        loading:false
      }
    },
    props: {
      record: {
        type: Object,
        required: true,
      },
      value: {
        type: String,
      },
      accept:{
        type: String,
        default:''
      },
     fileSize:{
       type: Number,
       default:0
     },
      //支持 table、text、picture、picture-card，修改default值全局生效
      listType:{
        type: String,
        default:'table'
      },
    },
    watch: {
      value: {
        handler (val) {
          this.fileList = val ? JSON.parse(val) : []
        },
        immediate: true
      }
    },
    computed: {
      LocleUtil() {
        return LocleUtil
      },
      optionsData () {
        return {
          biz: this.record.options.bizPath || 'temp'
        }
      },
      listClass(){
        if(this.listType=='table'){
          return 'upload-fileList-table'
        }else{
          return ''
        }
      },
      fileListType(){
        if(!this.listType || this.listType=='table'){
          this.listType == 'text'
        }
      },
      columns(){
        if(this.record.options.disabled){
          return [
            {
              title: LocleUtil.getLocale('m.common.label.fileName'),
              dataIndex: 'name',
              align: 'left',
              scopedSlots: { customRender: 'filename' },
            },
            {
              title: LocleUtil.getLocale('m.common.label.upload_time'),
              dataIndex: 'uploadTime',
              width: 160,
              align: 'center',
            },
            {
              title: LocleUtil.getLocale('m.common.label.upload_user'),
              dataIndex: 'uploadUser',
              width: 160,
              align: 'center',
            },
          ]
        }else{
          return [
            {
              title: LocleUtil.getLocale('m.common.label.fileName'),
              dataIndex: 'name',
              align: 'left',
              scopedSlots: { customRender: 'filename' },
            },
            {
              title: LocleUtil.getLocale('m.common.label.upload_time'),
              dataIndex: 'uploadTime',
              width: 160,
              align: 'center',
            },
            {
              title: LocleUtil.getLocale('m.common.label.upload_user'),
              dataIndex: 'uploadUser',
              width: 160,
              align: 'center',
            },
            {
              title: LocleUtil.getLocale('m.common.label.operate'),
              dataIndex: 'action',
              align: "center",
              width: 100,
              scopedSlots: { customRender: 'action' },
            }
          ]
        }
      }
    },
    created () {
      const token = TokenStorageUtil.get()
      this.headers = { 'X-Access-Token': token };
      this.userInfo = localStorage.getItem('userInfo')
    },
    methods: {
      handleSelectChange () {
        setTimeout(() => {
          const arr = this.fileList.map(item => {
            if (typeof item.response !== 'undefined') {
              const res = item.response
              return {
                type: 'file',
                name: item.name,
                status: item.status,
                uid: item.uid,
                url: getFileAccessHttpUrl(res.message) || '',
                uploadTime:res.result || '',
                userId: this.userInfo.id || this.userInfo.userId,
                uploadUser: this.userInfo.nickname
              }
            } else {
              return {
                type: 'file',
                name: item.name,
                status: item.status,
                uid: item.uid,
                url: getFileAccessHttpUrl(item.url) || '',
                uploadTime:item.uploadTime,
                userId: this.userInfo.id || this.userInfo.userId,
                uploadUser: this.userInfo.nickname
              }
            }
          })

          const arrString = arr.length > 0 ? JSON.stringify(arr) : ''
          this.$emit('change', arrString)
          this.$emit('input', arrString)
        }, 10)
      },
      handlePreview(file) {
        //如不加密下载删除此段用下一段下载
        encryptedDownload(file)
        return;
        // 下载文件
        const x = new XMLHttpRequest();
        x.open("GET", getFileAccessHttpUrl(file.url || file.thumbUrl), true);
        x.responseType = 'blob';

        const token = TokenStorageUtil.get()
        x.setRequestHeader('X-Access-Token', token);

        x.onload = function (e) {
          const url = window.URL.createObjectURL(x.response);
          const a = document.createElement("a");
          a.href = url
          a.download = file.name
          a.click()
        }
        x.send();
      },
      remove (file) {
        return new Promise((resovle, reject) => {
          const that = this
          this.$confirm({
            title: LocleUtil.getLocale('m.common.title.delete'),
            okText: LocleUtil.getLocale('m.common.button.ok'),
            cancelText: LocleUtil.getLocale('m.common.button.cancel'),
            content: LocleUtil.getLocale('m.eform.formDesign.label.shi-fou-shan-chu-filename', [file.name]),
            onOk () {
              deleteAction(that.deleteUrl, { url: file.url }).then((res) => {
                if (res.success) {
                  resovle(true)
                  that.handleSelectChange()
                } else {
                  that.$message.error(LocleUtil.getLocale('m.common.tip.deleteFileFailed'))
                  resovle(false)
                }
              })
            },
            onCancel () {
              resovle(false)
            }
          })
        })
      },
      deleteFile(file){
        const that = this;
        this.$confirm({
          title: LocleUtil.getLocale('m.common.title.delete'),
          content: LocleUtil.getLocale('m.eform.formDesign.label.shi-fou-shan-chu-filename') + file.name,
          onOk() {
            that.loading = true
            deleteAction(that.deleteUrl, {url: file.url, id: file.uid}).then((res) => {
              if (res.success) {
                let matchKey = file.uid !== undefined ? 'uid' : 'name';
                that.fileList = that.fileList.filter(item=>item[matchKey] !== file[matchKey]);
                that.handleSelectChange();
              } else {
                that.$message.error(LocleUtil.getLocale('m.common.tip.deleteFileFailed'));
                let matchKey = file.uid !== undefined ? 'uid' : 'name';
                that.fileList = that.fileList.filter(item=>item[matchKey] !== file[matchKey]);
                that.handleSelectChange();
              }
            }).finally(() => {
              that.loading = false
            });
          },
          onCancel(){
          },
          okText: LocleUtil.getLocale('m.common.button.ok'),
          cancelText: LocleUtil.getLocale('m.common.button.cancel')
        });
      },
      handleChange (info) {
        // 上传数据改变时
        this.fileList = info.fileList
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            this.handleSelectChange()
          } else {
            this.fileList.pop()
            this.$message.error(`${info.file.name} `+info.file.response.message);
          }
          this.loading = false
        } else if (info.file.status === 'error') {
          this.fileList.pop()
          this.$message.error(LocleUtil.getLocale('m.eform.formDesign.label.infofilename-shang-chuan-shi-bai', [info.file.name]))
          this.loading = false
        }
      },
      beforeUpload (file, files) {
        if (files.length + this.fileList.length > this.record.options.limit) {
          this.$message.warning(LocleUtil.getLocale('m.eform.formDesign.label.zui-da-shang-chuan-shu-liang-wei-thisrecordoptionslimit', [this.record.options.limit]))
          files.splice(this.record.options.limit - this.fileList.length)
          return false
        }
        //fileSize值小于等于0时不限制
        if(this.fileSize>0){
          let fileSize = this.fileSize * 1024*1024
          if(file.size>fileSize){
            this.$message.warning(LocleUtil.getLocale('m.common.tip.checkFileSize',[file.name,this.fileSize]));
            files.pop();
            return false
          }
        }
        this.loading = true
      },
    }
  }
</script>
<style lang="less">
  .upload-fileList-table .ant-upload-list {
    display:none !important;
  }

  .upload-fileList-table .ant-table-placeholder{
    display:none;
  }
</style>
