<template>
  <div :style="{ width: record.options.width }" :class="listClass"  style="text-align: left;">
    <a-upload
      :disabled="record.options.disabled || !record.dataId"
      v-if="!record.options.drag"
      name="file"
      :accept="accept"
      :multiple="record.options.multiple"
      :data="optionsData"
      :fileList="validFileList"
      :action="uploadAction"
      :headers="headers"
      :listType="fileListType"
      @preview="handlePreview"
      @change="handleChange"
      :remove="remove"
      :beforeUpload="beforeUpload"
    >
      <a-button
        v-if="validFileList.length < record.options.limit && !(record.options.disabled || !record.dataId)"
      >
        <ych-icon type="upload"/>
        {{LocleUtil.getLocale('m.common.button.selectFile')}}
      </a-button>
    </a-upload>
    <a-upload-dragger
      v-else-if="validFileList.length < record.options.limit && !(record.options.disabled || !record.dataId)"
      :disabled="record.options.disabled || !record.dataId"
      name="file"
      :accept="accept"
      :multiple="record.options.multiple"
      :fileList="validFileList"
      :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="validFileList"
      :action="uploadAction"
      :headers="headers"
      :listType="fileListType"
      @preview="handlePreview"
      @change="handleChange"
      :remove="remove"
      :beforeUpload="beforeUpload"
    >
    </a-upload>
    <a-table
      ref="fileListTable"
      size="small"
      bordered
      rowKey="uid"
      :columns="columns"
      :dataSource="validFileList"
      :pagination="false"
      :style="record.options.fileTableStyle || defaultTableStyle"
      v-if="listType=='table' && validFileList && validFileList.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 {getAction, deleteAction,uploadAction,getFileAccessHttpUrl} from '../utils/manage';
  import YchConstant from "../utils/YchConstant";
  import TokenStorageUtil from "../utils/TokenStorageUtil";
  import LocleUtil from "../utils/LocleUtil";

  export default {
    name: "uploadFileNoModel",
    data() {
      return {
        uploadAction: YchConstant.PREFIX_REQUEST + YchConstant.PREFIX_SYSTEM + '/common/upload',
        headers: {},
        fileList: [],
        deleteUrl: YchConstant.PREFIX_SYSTEM + "/common/deleteFile",
        getFileList: YchConstant.PREFIX_SYSTEM + "/common/getFileList",
        defaultTableStyle:'height:200px;overflow:auto;',
        userInfo: {}
      };
    },
    props: {
      record: {
        type: Object,
        required: true,
      },
      formId: {
        type: String,
      },
      accept:{
        type: String,
        default:''
      },
     fileSize:{
       type: Number,
       default:0
     },
      //支持 table、text、picture、picture-card，修改default值全局生效
      listType:{
        type: String,
        default:'table'
      },
      //文件上传成功后触发刷新文件列表
      uploadTimestamp:{
        type:String
      },
    },
    watch: {
      compId: {
        handler() {
          if(this.formId && this.record.dataId){
            getAction(this.getFileList, {formId: this.formId, dataId: this.record.dataId}).then((res) => {
              if (res.success) {
                let files = res.result;
                files.map(item=>{
                  item.uploaded = true
                  item.delete = false
                })
                this.fileList = files
                this.$emit("change", this.fileList);
                this.$emit("input", this.fileList);
              }
            })
          }
        },
        immediate: true
      },
    },
    computed: {
      LocleUtil() {
        return LocleUtil
      },
      optionsData() {
        return {
          biz: this.record.options.bizPath || 'temp',
          formId: this.formId,
          dataId: this.record.dataId
        }
      },
      listClass(){
        if(this.listType=='table'){
          return 'upload-fileList-table'
        }else{
          return ''
        }
      },
      fileListType(){
        if(!this.listType || this.listType=='table'){
          this.listType == 'text'
        }
      },
      compId(){
        return (this.formId || '') + (this.record.dataId || '')+(this.uploadTimestamp || '');
      },
      validFileList(){
        return this.fileList.filter(item=>!item.delete)
      },
      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() {
          const arr = this.fileList.map(item => {
            return {
              name: item.name,
              status: item.status,
              uid: item.uid,
              url: getFileAccessHttpUrl(item.url) || '',
              dataId:this.optionsData.dataId,
              uploadTime:item.uploadTime,
              uploaded : item.uploaded,
              delete : item.delete,
              originFileObj:item.originFileObj,
              biz:this.optionsData.biz,
              userId: this.userInfo.id || this.userInfo.userId,
              uploadUser: this.userInfo.nickname
            };
          });
          this.fileList = arr;
        console.log(this.fileList,'this.fileList')
          this.$emit("change", this.fileList);
          this.$emit("input", this.fileList);
      },
      handlePreview(file) {
        // 下载文件
        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() {
              let matchKey = file.uid !== undefined ? 'uid' : 'name';
              that.fileList.map(item=>{
                if(item[matchKey] == file[matchKey]){
                  item.delete = true
                }
              })
              that.handleSelectChange();
            },
            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]),
          okText: LocleUtil.getLocale('m.common.button.ok'),
          cancelText: LocleUtil.getLocale('m.common.button.cancel'),
          onOk() {
            let matchKey = file.uid !== undefined ? 'uid' : 'name';
            that.fileList.map(item=>{
              if(item[matchKey] == file[matchKey]){
                item.delete = true
              }
            })
            that.handleSelectChange();
          },
          onCancel(){
          }
        });
      },
      handleChange(info) {
        let files = info.fileList.filter(item=>item.uid==info.file.uid)
        this.fileList = [...this.fileList,...files]
        this.handleSelectChange();
      },
      beforeUpload(file, files) {
        if (files.length + this.validFileList.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.validFileList.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
          }
        }
        return false
      },
    }
  };
</script>
<style lang="less">
  .upload-fileList-table .ant-upload-list {
    display:none !important;
  }
  .upload-fileList-table .ant-table-placeholder{
    display:none;
  }
</style>
