<template>
  <div class="el-attachment-manage">
    <div class="attachment-manage-header">
      <div class="header-left">
        <el-button
          v-for="(btn, btnIndex) in buttons"
          :key="btnIndex"
          :disabled="btnDisabled(btn)"
          @click="!btnDisabled(btn)?btnClick(btn):null"
          v-if="innerData[btn.type] !== undefined ? innerData[btn.type] : true"
        >
          <img :src="!btnDisabled(btn)?btn.on:btn.off"/>
          {{btn.text}}
        </el-button>
      </div>
      <div class="header-right">
        <el-input placeholder="请输入内容" v-model="search">
          <el-button slot="append" icon="el-icon-search" @click="searchFile"></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 class="attachment-manage-content">
      <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="附件上传"
      width="545px"
      :visible.sync="uploadVisible"
      :close-on-click-modal="false"
      @close="uploadClose"
      append-to-body
    >
      <table>
        <tr>
          <td>上传附件</td>
          <td>
            <div class="upload-box">
              <!-- {
                bus_type: upload_info.type,
                fileSizeLimit: innerData.fileSizeLimit||'20M',
                JID: innerData.JID
              } -->
              <el-upload
                multiple
                ref="upload"
                :action="innerData.uploadUrl"
                :data="uploadParams"
                :on-exceed="uploadExceed"
                :before-upload="beforeUpload"
                :on-success="uploadSuccess"
                :on-error="uploadError"
                :on-remove="uploadRemove"
                :accept="accept"
                :auto-upload="false"
              >
                <el-button type="primary">选择文件</el-button>
                <div slot="tip" class="el-upload__tip">支持格式 {{accept.replace(/\./g, '')}} 文件不超过{{innerData.fileSizeLimit||'20M'}}</div>
              </el-upload>
            </div>
          </td>
        </tr>
        <tr v-if="innerData.secret">
          <td width="80">密级标识</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="80">选择类型</td>
          <td>
            <el-select v-model="upload_info.type">
                <el-option
                  v-for="(opt, optIndex) in typeData"
                  :key="optIndex"
                  :label="opt.label"
                  :value="opt.value"
                ></el-option>
            </el-select>
          </td>
        </tr>
        <tr v-if="innerData.appendix">
          <td width="80">附页标记</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="80">备注</td>
          <td>
            <el-input
              type="textarea"
              v-model="upload_info.remark"
              :maxlength="100"
              :autosize="{ minRows: 2, maxRows: 4}"
              placeholder="请输入内容"
            ></el-input>
          </td>
        </tr>
      </table>
      <template slot="footer">
          <el-button @click="uploadClose">取 消</el-button>
          <el-button type="primary" @click="uploadSubmit" :disabled="uploadStatus" :loading="uploadStatus">确 定</el-button>
      </template>
    </el-dialog>
    
  </div>
</template>

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

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';

export default {
  name: 'ElAttachmentManage',
  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: ''
        };
      }
    },
    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'
        }
      ],
      innerData: {},
      buttons_type: '',
      search: '',
      switchView: true,
      uploadVisible: false,
      // accept: this.innerData.uploadAccept ? this.innerData.uploadAccept : '.jpg,.jpeg,.png,.doc,.docx,.xls,.xlsx,.xlsm,.pdf,.raq,.rpg,.rpx,.prg,.dfx,.olap,.rar,.zip',
      // typeData: [
      //   { label: '客户文件', value: 'KHWJ' },
      //   { label: '样品文件', value: 'YPWJ' },
      //   { label: '设备文件', value: 'SBWJ' },
      //   { label: '其它文件', value: 'QTWJ' },
      //   { label: '报告组成', value: 'BGZC' },
      //   { label: '嵌入报告', value: 'QRBG' }
      // ],
      // typeData: 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' }
      // ],
      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' }
      ],
      secretData: [
        { 'label': '非密', 'value': '0' },
        { 'label': '秘密', 'value': '1' }
      ],
      // upload_info: {
      //   // type: 'KHWJ',
      //   type: this.innerData.uploadType ? this.innerData.uploadType.value : 'KHWJ',
      //   remark: '',
      //   attatch_tag: '',
      //   secret_mark: '0'
      // },
      upload_info: {},
      uploadStatus: false,
      encryptData: [
        { label: '高', value: '1' },
        { label: '中', value: '2' },
        { label: '低', value: '3' }
      ],
      selectedData: [],
      exArray: [],
      navigatorStream: undefined
    };
  },
  computed: {
    accept() {
      return this.innerData.uploadAccept ? this.innerData.uploadAccept : '.jpg,.jpeg,.png,.doc,.docx,.xls,.xlsx,.xlsm,.pdf,.raq,.rpg,.rpx,.prg,.dfx,.olap,.rar,.zip';
    },
    /* upload_info() {
      return {
        type: this.innerData.uploadType ? this.innerData.uploadType.value : 'KHWJ',
        remark: '',
        attatch_tag: '',
        secret_mark: '0'
      };
    }, */
    typeData() {
      return 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' }
      ];
    },
    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, isUploadLocal, secret } = this.innerData;
      let obj = {
        bus_type: this.upload_info.type,
        fileSizeLimit: fileSizeLimit || '20M',
        JID: JID,
        fileTypes: this.accept
      };
      if (isUploadLocal !== undefined) {
        obj.isUploadLocal = isUploadLocal;
      }
      if (secret) {
        obj.secret_mark = this.upload_info.secret_mark;
      }
      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');
      });
    });
  },
  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.startVideo();
          break;
        case 'upload':
          this.uploadVisible = true;
          break;
        case 'delete':
          let ids = this.rowSelected();
          if (ids === '') {
            this.$message.warning('请选择需要删除附件');
            return;
          }
          this.deleteFile(ids);
          break;
      }
    },
    startVideo() {
      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;
      }
      // = navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
      const opt = {
        audio: false,
        video: {
          width: 3703,
          height: 2614
        }
      };
      let self = this;
      if (capture) {
        const open = () => {
          if (self.exArray[0]) {
            opt.video.deviceId = {
              exact: self.exArray[0]
            };
          }

          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');
              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,
              function(stream) {
                let video = this.$el.querySelector('#video');
                let video_bak = this.$el.querySelector('#video_bak');
                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) {
            devices.forEach(function(device) {
              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(`您没有权限删除文件【${filesList[ii].file_name}】`);
              return;
            }
          }
        }
      }
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        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) {
            this.$message.success('删除成功');
            this.$refs.child.getTableData();
            this.$emit('deleteSuccess');
          } else {
            this.$message.error(res.body.error);
          }
        }, (error) => {
          console.log(error);
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    searchFile() {
    },
    uploadExceed(files, fileList) {
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeUpload(file) {
      /* let type = file.name.substr(file.name.lastIndexOf('.'));
      let arr = this.accept.split(',');
      if (!arr.includes(type.toLowerCase())) {
        this.$message.warning('文件格式不支持上传');
        this.uploadStatus = false;
        return false;
      } */
      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('文件格式不支持上传');
      } else if (fileName > maximum) {
        callback(`文件名过长，最多${maximum}个字符`);
      }
      return result;
    },
    uploadSuccess(response, file, fileList) {
      let arr = [];
      fileList.forEach(v => {
        if (!v.response.status) {
          this.$message.error(v.response.error || `${v.name}提交失败`);
          this.$refs.upload.clearFiles();
          this.uploadStatus = false;
        } else {
          arr.push(v);
        }
      });
      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: v.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.$message.success('提交成功');
            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.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 = document.getElementsByClassName('el-upload-list')[0];
      // if (uploadList.children.length === 0) {
      const uploadList = this.$refs.upload && this.$refs.upload.uploadFiles;
      if (uploadList && uploadList.length === 0) {
        this.$message.warning('请选择文件');
        return;
      }
      this.uploadStatus = true;
      this.$refs.upload.submit();
    },
    headCallBack(ids) {
      this.selectedData = ids;
    },
    rowSelected() {
      let result = null;
      if (this.switchView) {
        result = this.selectedData.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>

</style>

