<template>
  <div class="el-attachment-manage">
    <div class="attachment-manage-header">
      <div class="header-left">
        <el-button :type="!data.btnStyle ? '' : data.btnStyle" v-for="(btn, btnIndex) in buttons" :key="btnIndex" :disabled="btnDisabled(btn)" @click="!btnDisabled(btn)?btnClick(btn):null"
          v-if="!innerData.batch_prn?(innerData[btn.type] !== undefined ? innerData[btn.type] : true):btn.type != 'upload'?false:(innerData[btn.type] !== undefined ? innerData[btn.type] : true)">
          <img :src="!btnDisabled(btn)?btn.on:btn.off" />
          {{btn.text}}
        </el-button>
        <div v-if="data.inlineTips" class="attachment-tips">{{ data.inlineTips }}</div>
      </div>
      <div class="header-right" v-if="!innerData.batch_prn">
        <el-input :placeholder="t(`attachmentManage.message.content`)" v-model="search">
          <el-button slot="append" icon="el-icon-search"></el-button>
        </el-input>
        <el-button type="text" @click="switchView=!switchView">
          <img :src="switchView?require('../images/files-view.png'):require('../images/files-view-list.png')" alt="">
        </el-button>
      </div>
    </div>
    <!-- <div id="loglist">
            <div v-for="device in alldevices" :key="device.deviceId">{{ device.kind + '--@#@--' + device.label + '--@#@--' + device.deviceId }}</div>
        </div>
        <div>--------</div>
        <div id="exArray">
            <div v-for="device in exArray" :key="device">{{'deviceId::::'}}{{ device }}</div>
        </div> -->
    <div class="attachment-manage-content" v-if="!innerData.batch_prn">
      <Capture :data="innerData" :interfaceUrl="interfaceUrl" :typeData="typeData" v-if="buttons_type=='capture'" />
      <file-list ref="child" :data="innerData" :switchView="switchView" :search="search" :interfaceUrl="interfaceUrl" :typeData="typeData" :tagData="tagData" :deleteFile="deleteFile"
        v-on:headCallBack="headCallBack" v-else />
    </div>

    <!-- 附件上传 -->
    <el-dialog class="attachment-manage-dialog" :title="t(`attachmentManage.title`)" width="545px" :visible.sync="uploadVisible" :close-on-click-modal="false" @close="uploadClose" append-to-body>
      <table>
        <tr>
          <td>{{ t(`attachmentManage.uploadFile`) }}</td>
          <td>
            <div class="upload-box">
              <!-- {
                bus_type: upload_info.type,
                fileSizeLimit: innerData.fileSizeLimit||'20M',
                JID: innerData.JID
              } -->
              <!-- 循环接口--批量上传（每个接口一个文件） -->
              <el-upload v-if="!innerData.isBatchSave" multiple ref="upload" class="upload_xy" :action="innerData.uploadUrl" :data="uploadParams" :before-upload="beforeUpload"
                :on-success="uploadSuccess" :on-error="uploadError" :on-remove="uploadRemove" :accept="accept" :auto-upload="false">
                <el-button type="primary">{{ t(`attachmentManage.selectFile`) }}</el-button>
                <div slot="tip" class="el-upload__tip" style="word-break: break-word;">
                  {{ t(`attachmentManage.message.fileLimit`, { accept: accept.replace(/\./g, ''), limit: innerData.fileSizeLimit||'20M' }) }}
                </div>
              </el-upload>
              <!-- 一次接口--批量上传，任务21448支持多任务上传 -->
              <el-upload class="upload_xy" v-else multiple ref="upload" :data="uploadParams" :on-remove="uploadRemove" :accept="accept" :auto-upload="false" :on-error="uploadError"
                :action="innerData.batch_prn?'/ks-prj/pic/fileBatchUpload':innerData.batchUploadUrl" :before-upload="beforeUpload" :limit="innerData.batchUploadMaxLimit" :on-exceed="batchUploadExceed" :http-request="httpRequest">
                <el-button type="primary">{{ t(`attachmentManage.selectFile`) }}</el-button>
                <div slot="tip" class="el-upload__tip" style="word-break: break-word;">
                  {{ t(`attachmentManage.message.fileLimit`, { accept: accept.replace(/\./g, ''), limit: innerData.fileSizeLimit||'20M' }) }}
                </div>
              </el-upload>
            </div>
          </td>
        </tr>
        <tr v-if="innerData.secret">
          <td width="100">{{ t(`attachmentManage.secretId`) }}</td>
          <td>
            <el-select v-model="upload_info.secret_mark">
              <el-option v-for="(opt, optIndex) in secretData" :key="optIndex" :label="opt.label" :value="opt.value"></el-option>
            </el-select>
          </td>
        </tr>
        <tr height="50" v-if="innerData.selectType===undefined?true:innerData.selectType">
          <td width="100">{{ t(`attachmentManage.selectType`) }}</td>
          <td>
            <el-select v-model="upload_info.type">
              <el-option
                v-for="(opt, optIndex) in typeData.filter(v => v.disabled != true)"
                :key="optIndex"
                :label="opt.label"
                :value="opt.value"
                :disabled="opt.disabled == true"
              ></el-option>
            </el-select>
          </td>
        </tr>
        <tr v-if="innerData.appendix">
          <td width="100">{{ t(`attachmentManage.appendix`) }}</td>
          <td>
            <el-select v-model="upload_info.attatch_tag">
              <el-option v-for="(opt, optIndex) in tagData" :key="optIndex" :label="opt.label" :value="opt.value"></el-option>
            </el-select>
          </td>
        </tr>
        <tr>
          <td width="100">{{ t(`attachmentManage.remark`) }}</td>
          <td>
            <el-input type="textarea" v-model="upload_info.remark" :maxlength="100" :autosize="{ minRows: 2, maxRows: 4}" :placeholder="t(`attachmentManage.message.content`)"></el-input>
          </td>
        </tr>
      </table>
      <template slot="footer">
        <el-button @click="uploadClose">{{ t(`toolbar.cancel`) }}</el-button>
        <el-button type="primary" @click="uploadSubmit" :disabled="uploadStatus" :loading="uploadStatus">{{ t(`toolbar.confirm`) }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import vueResource from 'vue-resource';
import Vue from 'vue';
Vue.use(vueResource);

import Locale from 'element-ui-qz/src/mixins/locale';
import ElInput from 'element-ui-qz/packages/input';
import ElButton from 'element-ui-qz/packages/button';
import ElUpload from 'element-ui-qz/packages/upload';
import ElDialog from 'element-ui-qz/packages/dialog';

import Capture from './capture';
import FileList from './attachment-list';
import { osUserAgent } from 'element-ui-qz/src/utils/util';

function getCurrentTime() {
  var date = new Date();
  var year = date.getFullYear(); //  返回的是年份
  var month = date.getMonth() + 1; //  返回的月份上个月的月份，记得+1才是当月
  var dates = date.getDate(); //  返回的是几号
  // var day = date.getDay();          //  周一返回的是1，周六是6，但是周日是0
  // var arr = [ "星期日","星期一","星期二","星期三","星期四","星期五","星期六",];
  return `${year}${month}${dates}`;
}

export default {
  name: 'ElAttachmentManage',
  mixins: [Locale],
  components: {
    ElInput,
    ElButton,
    ElUpload,
    ElDialog,
    Capture,
    FileList
  },
  props: {
    data: {
      type: Object,
      default: () => {
        return {
          uploadUrl: '',
          prn: '',
          capture: false,
          scan: true,
          edit: true,
          showAttachments: false,
          delete: true,
          upload: true,
          allButtonDisabled: false,
          JID: '',
        //   showIcon: 'delete',
        //   btnStyle: 'primary',
        //   inlineTips: '我是测试文本提示我是测试文本提示我是测试文本提示！！！' // 行内文本提示
        };
      }
    },
    params: Array
  },
  data: function() {
    return {
      buttons: [
        {
          on: require('../images/capture-icon.png'),
          off: '',
          text: '拍照',
          type: 'capture'
        },
        {
          on: require('../images/upload-icon.png'),
          off: require('../images/icon-upload-gray.png'),
          text: '上传',
          type: 'upload'
        },
        {
          on: require('../images/delete-icon.png'),
          off: require('../images/icon-delete-gray.png'),
          text: '删除',
          type: 'delete'
        }
      ].map(v => ({
        ...v,
        text: this.t(`attachmentManage.toolbar.${v.type}`)
      })),
      innerData: {},
      buttons_type: '',
      search: '',
      switchView: true,
      uploadVisible: false,
      tagData: [
        { label: '图片1', value: '1' },
        { label: '图片2', value: '2' },
        { label: '图片3', value: '3' },
        { label: '图片4', value: '4' },
        { label: '图片5', value: '5' },
        { label: '图片6', value: '6' },
        { label: '图片7', value: '7' },
        { label: '图片8', value: '8' },
        { label: '图片9', value: '9' },
        { label: '图片10', value: '10' }
      ].map(v => ({
        ...v,
        label: this.t(`attachmentManage.picture`, { value: v.value })
      })),
      secretData: [
        { 'label': '非密', 'value': '0' },
        { 'label': '秘密', 'value': '1' }
      ].map(v => ({
        ...v,
        label: this.t(`attachmentManage.secret.${v.value}`)
      })),
      upload_info: {},
      uploadStatus: false,
      encryptData: [
        { label: '高', value: '1' },
        { label: '中', value: '2' },
        { label: '低', value: '3' }
      ].map(v => ({
        ...v,
        label: this.t(`attachmentManage.encrypt.${v.value}`)
      })),
      selectedData: [],
      exArray: [],
      navigatorStream: undefined,
      batchUploadArr: [],
      backCamera: '',
      isfront: true,
      alldevices: [],
      os: osUserAgent()
    };
  },
  computed: {
    accept() {
      return this.innerData.accept || this.innerData.uploadAccept || '.jpg,.jpeg,.png,.doc,.docx,.xls,.xlsx,.xlsm,.pdf,.raq,.rpg,.rpx,.prg,.dfx,.olap,.rar,.zip';
    },
    typeData() {
      const data = this.innerData.uploadType ? this.innerData.uploadType.items : [
        { label: '客户文件', value: 'KHWJ' },
        { label: '样品文件', value: 'YPWJ' },
        { label: '设备文件', value: 'SBWJ' },
        { label: '其它文件', value: 'QTWJ' },
        { label: '报告组成', value: 'BGZC' },
        { label: '嵌入报告', value: 'QRBG' }
      ];
      return data.map(v => {
        const options = this.t(`attachmentManage.uploadType`) || {}
        const label = options[v.value] || v.label
        // const label = this.t(`attachmentManage.uploadType.${v.value}`) || v.label
        return {
          ...v,
          label: label
        }
      })
    },
    interfaceUrl() {
      let url = this.innerData.uploadUrl;
      let result = '';
      if (url !== undefined) {
        let arr = url.split('/');
        for (let i = 0; i < arr.length - 1; i++) {
          result += arr[i] + '/';
        }
      }
      console.log('interfaceUrl', result);
      return result;
    },
    uploadParams() {
      let { fileSizeLimit, JID, m_code, isUploadLocal, secret, uploadCompressPic, fileNameGenerator, isBatchSave, prn, isOrNoOriginal, isOrNoCheckFile = {}, comp_code,batch_prn } = this.innerData;
      let obj = {
        bus_type: this.upload_info.type,
        fileSizeLimit: fileSizeLimit || '20M',
        JID: JID,
        fileTypes: this.accept,
        remark:this.upload_info.remark,
        isOrNoCheckFile: isOrNoCheckFile.value || '',
        comp_code: comp_code
      };
      //   获取大列表每一行的prn
      obj.typePrn = prn;
      if (isUploadLocal !== undefined) {
        obj.isUploadLocal = isUploadLocal;
      }
      // 判断图片压缩上传
      if (uploadCompressPic !== undefined) {
        obj.uploadCompressPic = uploadCompressPic;
      }
      if (secret) {
        obj.secret_mark = this.upload_info.secret_mark;
      }
      if (fileNameGenerator) {
        const selected = this.upload_info.type;
        let item = this.typeData.find(item=>item.value === selected);
        const customItems = (fileNameGenerator.items || []).filter(v => v.itemType === 'custom-type')
        if (customItems.length) {
            obj.build_rule = customItems.reduce((pre, cur) => {
                const { para_val } = cur
                switch (cur.value) {
                    case '17':
                        const arr = this.$store.state.basic_table_map_mcode_selected.get(m_code)
                        const [checked] = arr
                        if (para_val && checked) {
                            pre += checked[`${para_val}`.replace('.', '$')]
                        }
                        break;
                    case 'compField':
                        if (para_val === 'type') {
                            pre += (item && item.label || '')
                        } else if (para_val === 'remark') {
                            pre += (obj.remark || '')
                        }
                        break;
                    case '2':
                        pre += (para_val || '')
                        break;
                
                }
                return pre
            }, '')
        } else {
            if (selected && fileNameGenerator.value) {
                obj.build_rule = `${item.label || ''}${getCurrentTime()}`;
            }
        }
        
      }
      if (isBatchSave && !batch_prn) {
        obj.prn = prn;
      }
      if(isBatchSave && batch_prn){
        obj.batch_prn = batch_prn;
        obj.isSavePic = 1;
      }
      // 是否保存原图
      obj.isOrNoOriginal = isOrNoOriginal == undefined ? true : isOrNoOriginal;
      return obj;
    }
  },
  watch: {
    innerData() {
      console.log('附件上传入参', this.innerData);
      this.$emit('loaded');
      this.upload_info = {
        type: this.innerData.uploadType ? this.innerData.uploadType.value : 'KHWJ',
        remark: '',
        attatch_tag: '',
        secret_mark: '0'
      };
      this.switchView = this.innerData.listView === undefined ? true : this.innerData.listView;
    },
    params: {
      handler: function(n, v) {
        this.handlerData();
      },
      deep: true
    },
    data(n, o) {
      this.innerData = n;
    }
  },
  created() {
    this.innerData = this.data;
  },
  mounted() {
    // this.innerData = this.data;
    this.$nextTick(function() {
      setTimeout(() => {
        this.$emit('loaded');
      });
    });
  },
  beforeDestroy() {
    if (this.srcObjectUrl) {
      window.URL.revokeObjectURL(this.srcObjectUrl);
      this.srcObjectUrl = null;
    }
  },
  methods: {
    handlerData() {
      let parentIns = this.$parent;
      if (parentIns) {
        let item = parentIns.formItem && parentIns.formItem.find(v=>v.compConfVO && v.compConfVO.comp_code === this.$attrs.id);
        if (item && typeof parentIns.getProps === 'function') {
          this.innerData = this.$parent.getProps(this.params, item);
        }
      }
    },
    btnDisabled(btn) {
      let result = this.innerData.allButtonDisabled;
      if (this.innerData.disabled) {
        let value = this.innerData[btn.type];
        if (this.innerData.disabled.includes(btn.type) && value !== undefined) {
          result = !value;
        }
      };
      return result;
    },
    btnShow(btn) {
      let result = true;
      if (this.innerData[btn.type] !== undefined) {
        result = this.innerData[btn.type];
      }
      return result;
    },
    btnClick(btn) {
      this.buttons_type = btn.type;
      switch (btn.type) {
        case 'capture':
          this.$nextTick(() => {
            this.startVideo();
          });
          break;
        case 'upload':
          this.uploadVisible = true;
          break;
        case 'delete':
          let ids = this.rowSelected();
          if (ids === '') {
            this.$message.warning(this.t(`attachmentManage.message.deleteFile`));
            return;
          }
          this.deleteFile(ids);
          break;
      }
    },
    startVideo() {
      let video = this.$el.querySelector('#video');
      let video_bak = this.$el.querySelector('#video_bak');
      try {
        if ('srcObject' in video) {
          if (video_bak) {
            video.srcObject = video_bak.srcObject = null;
          }
        } else {
          if (video_bak) {
            if (this.srcObjectUrl) {
              window.URL.revokeObjectURL(this.srcObjectUrl);
              this.srcObjectUrl = null;
            }
            video.src = video_bak.src = '';
          }
        }
      } catch (error) {
      }
      let capture;
      if (navigator.webkitGetUserMedia) {
        // webkit核心浏览器
        capture = navigator.webkitGetUserMedia;
      } else if (navigator.mozGetUserMedia) {
        // firfox浏览器
        capture = navigator.mozGetUserMedia;
      } else if (navigator.getUserMedia) {
        // 旧版API
        capture = navigator.getUserMedia;
      }

      const opt = {
        audio: false,
        video: {
          width: this.os.isPc ? 3703 : 2560,
          height: this.os.isPc ? 2614 : 1920
        }
      };
      if (this.navigatorStream && this.navigatorStream.getTracks) {
        const tracks = this.navigatorStream.getTracks() || [];
        tracks.forEach(track => {
          track && track.stop();
        });
      }

      //   this.navigatorStream = null

      let self = this;
      if (capture || (navigator.mediaDevices && navigator.mediaDevices.getUserMedia)) {
        const open = () => {
          if (this.os.isPc) {
            if (this.isfront) {
              if (self.exArray[0]) {
                opt.video.deviceId = {
                  exact: self.exArray[0]
                };
              }
            } else {
              opt.video.deviceId = {
                exact: this.backCamera || self.exArray[0]
              };
            }
          } else {
            opt.video = this.isfront ? { facingMode: 'user' } : { facingMode: { exact: 'environment' } };
          }

          if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            navigator.mediaDevices.getUserMedia(opt).then(stream=>{
              let video = this.$el.querySelector('#video');
              let video_bak = this.$el.querySelector('#video_bak');
              if ('srcObject' in video) {
                video.srcObject = video_bak.srcObject = stream;
              } else {
                // 防止在新的浏览器里使用它，应为它已经不再支持了
                this.srcObjectUrl = window.URL.createObjectURL(stream);
                video.src = video_bak.src = this.srcObjectUrl;
              }
              //   video.srcObject = video_bak.srcObject = stream;
              this.$el.querySelector('#non-video').style.display = 'none';
              self.navigatorStream = stream;
            }).catch(err=>{
              console.log('The following error occurred: ' + err.name);
            });
          } else {
            capture(opt,
              (stream) => {
                let video = this.$el.querySelector('#video');
                let video_bak = this.$el.querySelector('#video_bak');
                if ('srcObject' in video) {
                  video.srcObject = video_bak.srcObject = stream;
                } else {
                  // 防止在新的浏览器里使用它，应为它已经不再支持了
                  this.srcObjectUrl = window.URL.createObjectURL(stream);
                  video.src = video_bak.src = this.srcObjectUrl;
                }
                // video.srcObject = video_bak.srcObject = stream;
                this.$el.querySelector('#non-video').style.display = 'none';
                self.navigatorStream = stream;
              },
              function(err) {
                console.log('The following error occurred: ' + err.name);
              });
          }
        };
        self.exArray.length === 0 ? navigator.mediaDevices.enumerateDevices()
          .then(function(devices) {
            self.alldevices = devices;
            devices.forEach(function(device) {
              if (device.label && `${device.label}`.toLowerCase().indexOf('back') >= 0) { // 某些平板device.kind 不存在或不为 videoinput
                self.backCamera = device.deviceId;
              }
              if (device.kind === 'videoinput') {
                self.exArray.push(device.deviceId);
              }
            });
            open();
          }) : open();
      } else {
        console.log('getUserMedia not supported');
      }
    },
    deleteFile(ids) {
      if (this.data.logic_code) {
        let idArr = ids.split(','),
          filesList = this.$refs.child.filesList;
        for (var i = 0;i < idArr.length;i++) {
          for (var ii = 0;ii < filesList.length;ii++) {
            if (filesList[ii].id == idArr[i] && !filesList[ii].delete) {
              this.$message.warning(this.t(`attachmentManage.message.noAuthDelete`, {
                value: filesList[ii].file_name
              }));
              return;
            }
          }
        }
      }
      this.$confirm(this.t(`attachmentManage.message.deletePermanent`), this.t(`confirm.title`), {
        confirmButtonText: this.t(`toolbar.confirm`),
        cancelButtonText: this.t(`toolbar.cancel`),
        type: 'warning'
      }).then(() => {
        const params = Object.assign({ ids }, this.innerData);
        // this.$http.post(`${this.interfaceUrl}deleteAll`, params, {
        this.$http.post(`${this.interfaceUrl}deleteFiles?JID=${this.innerData.JID}`, {
          fileDatasStr: JSON.stringify(params)
        }, {
          emulateJSON: true
        }).then((res) => {
          if (res.body.status) {
            const prns = this.selectedData.map(v => v.file_prn).join(',');
            sessionStorage.setItem('cache__filePrn', prns);
            this.$message.success(this.t(`message.delSuccess`));
            this.$refs.child.getTableData();
            this.$emit('deleteSuccess');
          } else {
            this.$message.error(res.body.error);
          }
        }, (error) => {
          console.log(error);
        });
      }).catch(() => {
        this.$message.info(this.t(`attachmentManage.message.cancel`));
      });
    },
    batchUploadExceed(files, fileList) {
      this.$message.warning(this.t(`attachmentManage.message.uploadLimit`, {
        limit: this.innerData.batchUploadMaxLimit,
        current: files.length,
        count: files.length + fileList.length
      }));
    },
    beforeUpload(file) {
      let fileName = file.name.lastIndexOf('.');
      let fileType = file.name.substr(fileName);
      let accept = this.accept.split(',');
      let maximum = this.innerData.maximum || 100;
      let result = true;
      let callback = (msg) => {
        this.$message.warning(msg);
        this.uploadStatus = false;
        result = false;
      };
      if (!accept.includes(fileType.toLowerCase())) {
        callback(this.t(`attachmentManage.message.noAuthUpload`));
      } else if (fileName > maximum) {
        callback(this.t(`attachmentManage.message.fileNameLength`, {
          value: maximum
        }));
      }
      return result;
    },
    // 批量上传
    httpRequest(file) {
      this.batchUploadArr.push(file);
    },
    batchUploadFunc() {
      let formData = new FormData(),
        params = this.batchUploadArr[0].data;
      for (let key in params) {
        formData.append(key, params[key]);
      }
      this.batchUploadArr.forEach(v=>{
        formData.append('files', v.file);
      });
      this.$http.post(this.innerData.batch_prn?'/ks-prj/pic/fileBatchUpload':this.innerData.batchUploadUrl, formData, {
        _timeout: 15 * 60 * 1000, // 超时时间15min
        onTimeout: () =>{
          this.uploadStatus = false;
          this.uploadVisible = false;
          this.$message.error(this.t(`message.timeout`));
        }
      }).then((res) => {
        this.uploadStatus = false;
        if (res.body.status) {
          this.$message.success(this.t(`message.submitSuccess`));
          this.batchUploadArr = [];
          sessionStorage.setItem('cache__filePrn', res.body.list.map(v=>v.obj.prn).join(','));
          this.uploadVisible = false;
          !(this.innerData.batch_prn) && this.$refs.child.getTableData();
          this.$emit('uploadSuccess');
        } else {
          this.$message.error(res.body.error);
        }
      }, (error) => {
        this.uploadStatus = false;
        if (error.body.obj) {
          this.$message.error(this.t(`message.submitFail`));
          this.uploadVisible = false;
        }
      });
    },
    uploadSuccess(response, file, fileList) {
      let arr = [];
      let prns = [];
      fileList.forEach(v => {
        if (!v.response.obj.status || !v.response.status) {
          this.$message.error(v.response.error || `${v.name}${this.t(`message.submitFail`)}`);
          this.$refs.upload.clearFiles();
          this.uploadStatus = false;
        } else {
          arr.push(v);
          prns.push((v.response.obj.obj || {}).prn);
        }
      });
      sessionStorage.setItem('cache__filePrn', prns.join(',')); // 存储文件prn 方便外部调用
      this.$refs.upload.clearFiles();
      // 上传成功
      const { type, remark, attatch_tag, secret_mark } = this.upload_info || {};
      arr.forEach(v => {
        const obj = v.response.obj.obj || {};
        const params = Object.assign({
          file_name: obj.name,
          file_prn: obj.prn,
          file_size: obj.file_size,
          file_uri: obj.file_uri,
          bus_type: type,
          remark,
          attatch_tag: this.innerData.appendix ? attatch_tag : '',
          secret_mark: this.innerData.secret ? secret_mark : '',
          source: '上传',
          busin_co: '',
          encr_lev: ''
        }, this.innerData);
        // this.$http.post(`${this.interfaceUrl}/add`, params, {
        this.$http.post(`${this.interfaceUrl}saveFileDatas?JID=${this.innerData.JID}`, {
          fileDatasStr: JSON.stringify(params)
        }, {
          emulateJSON: true
        }).then((res) => {
          this.uploadStatus = false;
          if (res.body.status) {
            this.uploadVisible = false;
            this.$refs.child.getTableData();
            this.$emit('uploadSuccess');
          } else {
            this.$message.error(res.body.error);
          }
        }, (error) => {
          this.uploadStatus = false;
          if (error.body.obj) {
            this.$message.error(this.t(`message.submitFail`));
            this.uploadVisible = false;
          }
        });
      });
    },
    uploadError(error, file, filelist) {
      console.log(error);
      this.$refs.upload.clearFiles();
      this.uploadStatus = false;
    },
    uploadRemove(file, fileList) {
      console.log(file, fileList);
      if (fileList.length === 0) {
        this.uploadStatus = false;
      }
    },
    uploadClose() {
      this.uploadStatus = false;
      this.upload_info = {
        // type: 'KHWJ',
        type: this.innerData.uploadType ? this.innerData.uploadType.value : 'KHWJ',
        remark: '',
        attatch_tag: '',
        secret_mark: '0'
      };
      this.uploadVisible = false;
      this.$refs.upload.clearFiles();
    },
    uploadSubmit() {
      const uploadList = this.$refs.upload && this.$refs.upload.uploadFiles;
      if (uploadList && uploadList.length === 0) {
        this.$message.warning(this.t(`attachmentManage.message.selectFile`));
        return;
      }
      this.uploadStatus = true;
      this.$refs.upload.submit();
      if (this.innerData.isBatchSave) {
        // 批量上传
        this.batchUploadFunc();
      }
    },
    headCallBack(ids) {

      this.selectedData = ids;
    },
    rowSelected() {
      let result = null;
      if (this.switchView) {
        result = this.selectedData.map(v => v.id).join(',');
      } else {
        let checkbox = document.getElementsByName('checkbox');
        let temp = [];
        for (let key in checkbox) {
          if (checkbox[key].checked) {
            temp.push(checkbox[key].value);
          }
        }
        result = temp.join(',');
      }
      return result;
    }
  }
};
</script>

<style lang="scss" scoped>
/deep/.upload_xy ul.el-upload-list{
  max-height: 303px;
  overflow: auto;
}
.attachment-tips{
    padding: 6px 0 0;
    color: #f5222d;
}
</style>

