<template>
  <div
    :style="{ width: record.options.width }"
    class="upload-img-box-9136076486841527"
  >
    <a-upload
      name="file"
      :multiple="record.options.multiple"
      :listType="record.options.listType"
      :disabled="record.options.disabled || !record.dataId"
      :data="optionsData"
      :fileList="validFileList"
      :action="uploadAction"
      :headers="headers"
      accept="image/gif, image/jpeg, image/png"
      @change="handleChange"
      @preview="handlePreview"
      :remove="remove"
      :beforeUpload="beforeUpload"
    >
      <a-button
        v-if="record.options.listType !== 'picture-card' && validFileList.length < record.options.limit && !(record.options.disabled || !record.dataId)"
      >
        <ych-icon type="upload"/>
        {{LocleUtil.getLocale('m.common.button.selectPicture')}}
      </a-button>
      <div
        v-if="record.options.listType === 'picture-card' && validFileList.length < record.options.limit && !(record.options.disabled || !record.dataId)"
      >
        <ych-icon type="plus"/>
        <div class="ant-upload-text">{{LocleUtil.getLocale('m.common.button.selectPicture')}}</div>
      </div>
    </a-upload>
    <a-modal
      :maskClosable="false"
      :keyboard="false"
      :visible="previewVisible"
      :footer="null"
      @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImageUrl"/>
    </a-modal>
  </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: "uploadImgNoModel",
    data() {
      return {
        uploadAction: YchConstant.PREFIX_REQUEST + YchConstant.PREFIX_SYSTEM + '/common/upload',
        headers: {},
        fileList: [],
        previewImageUrl: "",
        previewVisible: false,
        deleteUrl: YchConstant.PREFIX_SYSTEM + "/common/deleteFile",
        getFileList: YchConstant.PREFIX_SYSTEM + "/common/getFileList"
      }
    },
    props: {
      record: {
        type: Object,
        required: true,
      },
      formId: {
        type: String,
      },
      //文件上传成功后触发刷新文件列表
      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
        }
      },
      compId(){
        return (this.formId || '') + (this.record.dataId || '')+(this.uploadTimestamp || '');
      },
      validFileList() {
        return this.fileList.filter(item => !item.delete).map(item => {
          item.url = getFileAccessHttpUrl(item.url) || ''
          return item
        })
      },
    },
    created() {
      const token = TokenStorageUtil.get();
      this.headers = {"X-Access-Token": token}
    },
    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
            };
          });
          this.fileList = arr;
          this.$emit("change", this.fileList);
          this.$emit("input", this.fileList);
      },
      // 预览
      handlePreview(file) {
        this.previewImageUrl = getFileAccessHttpUrl(file.url || file.thumbUrl)
        this.previewVisible = true
      },
      handleCancel() {
        this.previewVisible = false;
      },
      remove(file) {
        return new Promise((resovle, reject) => {
          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(){
              resovle(false);
            }
          });
        });
      },
      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
        }
        return false
      },
    },
  }
</script>
<style lang="less">
  .upload-img-box-9136076486841527 {
    /* you can make up upload button and sample style by using stylesheets */

    .ant-upload-select-picture-card i {
      font-size: 32px;
      color: #999;
    }

    .ant-upload-select-picture-card .ant-upload-text {
      margin-top: 8px;
      color: #666;
    }
  }
</style>
