<template>
  <div class="attachment-list">
    <div class="list-header">
      <div class="title">全部文件</div>
      <div class="desc">已全部加载，共{{filesList ? filesList.length : 0}}个</div>
    </div>
    <div class="list-content">
      <el-table
        ref="multipleTable"
        tooltip-effect="dark"
        :data="filesList"
        @selection-change="selectionChange"
        v-if="switchView"
      >
        <el-table-column type="selection" width="55" value="1"></el-table-column>
        <el-table-column label="文件名">
          <template slot-scope="scope">
            <img :src="getFileInfo(scope.row.file_name).icon" v-if="getFileInfo(scope.row.file_name).icon">
            <i class="el-icon-tickets" v-else></i>
            <span :title="scope.row.file_name">{{getFileInfo(scope.row.file_name).name}}</span>
          </template>
        </el-table-column>
        <el-table-column label="选择类型" prop="bus_type" show-overflow-tooltip>
          <template slot-scope="scope">
            {{typeData.filter(v=>v.value==scope.row.bus_type)[0]&&typeData.filter(v=>v.value==scope.row.bus_type)[0].label}}
          </template>
        </el-table-column>
        <el-table-column label="修改时间" prop="upload_tm" show-overflow-tooltip></el-table-column>
        <el-table-column label="上传人" prop="op_na" show-overflow-tooltip></el-table-column>
        <el-table-column label="备注" prop="remark" show-overflow-tooltip></el-table-column>
        <el-table-column
          label="状态"
          prop="active_st"
          width="80px"
          v-if="data.invalid"
        >
          <template slot-scope="{ row, column }">
            <span>{{invalidData.find(v => v.value === row[column.property]) && invalidData.find(v => v.value === row[column.property]).label || row[column.property]}}</span>
          </template>
        </el-table-column>
        <el-table-column width="140px" label="操作" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button
              type="text"
              v-for="(btn, btnIndex) in getOperate(scope.row)"
              :key="btnIndex"
              :icon="btn.icon"
              :title="btn.title"
              :disabled="btnDisabled(scope.row, btn)"
              @click="btnClick(scope.row, btn)"
              v-if="btnShow(scope.row, btn)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="list-view" v-else>
        <div class="checkbox-all">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkValue" @change="checkboxAll">全选</el-checkbox>
        </div>
        <ul>
          <li
            v-for="(item, itemIndex) in filesList"
            :key="itemIndex"
            :title="item.file_name"
            @dblclick="downloadFile(item)"
          >
            <input
              type="checkbox"
              name="checkbox"
              :id="item.id"
              :value="item.id"
              @click="checkbox(item.id, $event)"
            >
            <img :src="getFileInfo(item.file_name).pic" v-if="getFileInfo(item.file_name).pic">
            <i class="el-icon-tickets" v-else></i>
            <span>{{getFileInfo(item.file_name).name}}</span>
          </li>
        </ul>
      </div>
    </div>

    <!-- 修改 -->
    <el-dialog
      class="attachment-manage-dialog"
      title="修改附件信息"
      width="400px"
      :visible.sync="updateVisible"
      :close-on-click-modal="false"
      @close="updateClose"
      append-to-body
    >
      <table>
        <tr height="50" v-if="data.selectType===undefined?true:data.selectType">
          <td>选择类型</td>
          <td>
            <el-select v-model="updateInfo.bus_type">
                <el-option
                  v-for="(opt, optIndex) in typeData"
                  :key="optIndex"
                  :label="opt.label"
                  :value="opt.value"
                ></el-option>
            </el-select>
          </td>
        </tr>
        <tr>
          <td>文件名</td>
          <td>
            <el-input v-model="updateInfo.file_name" placeholder="请输入文件名"></el-input>
          </td>
        </tr>
        <tr>
          <td>备注</td>
          <td>
            <el-input v-model="updateInfo.remark" placeholder="请输入备注"></el-input>
          </td>
        </tr>
        <tr v-if="data.appendix">
          <td>附页标记</td>
          <td>
            <el-select v-model="updateInfo.attatch_tag">
                <el-option
                  v-for="(opt, optIndex) in tagData"
                  :key="optIndex"
                  :label="opt.label"
                  :value="opt.value"
                ></el-option>
            </el-select>
          </td>
        </tr>
      </table>
      <template slot="footer">
        <el-button @click="updateClose">取 消</el-button>
        <el-button type="primary" @click="updateSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import ElTable from 'element-ui-qz/packages/table';
import ElTableColumn from 'element-ui-qz/packages/table-column';
import ElButton from 'element-ui-qz/packages/button';
import ElInput from 'element-ui-qz/packages/input';
import ElDialog from 'element-ui-qz/packages/dialog';
import ElCheckbox from 'element-ui-qz/packages/checkbox';

export default {
  components: {
    ElTable,
    ElTableColumn,
    ElButton,
    ElInput,
    ElDialog,
    ElCheckbox
  },
  props: {
    switchView: Boolean,
    search: String,
    interfaceUrl: String,
    data: Object,
    typeData: Array,
    tagData: Array,
    deleteFile: { type: Function, default: () => {} }
  },
  watch: {
    data() {
      this.getTableData();
    },
    search(value) {
      let data = this.filesListSearch;
      this.filesList = data && data.filter(v => v.file_name.search(value) !== -1) || [];
    },
    switchView(value) {
      this.checkValue = false;
      this.isIndeterminate = false;
      // this.$refs.multipleTable && this.$refs.multipleTable.clearSelection();
      this.$nextTick(function() {
        this.checkedData.forEach(v => {
          const row = this.filesList.find(item => item.id === v.id) || {};
          if (this.$refs.multipleTable) {
            this.$refs.multipleTable.toggleRowSelection(row, true);
          } else {
            this.checkbox(row.id);
          }
        });
      });
    },
    filesList(value) {
      if (value.length === 0) {
        this.checkValue = false;
        this.isIndeterminate = false;
        this.checkedData = [];
      }
    }
  },
  data() {
    return {
      filesList: [],
      filesListSearch: [],
      updateVisible: false,
      updateInfo: {},
      checkValue: false,
      checkedData: [],
      isIndeterminate: false,
      invalidData: [
        { label: '激活', value: 'JH' },
        { label: '作废', value: 'ZF' }
      ]
    };
  },
  methods: {
    getOperate (row) {
      let data = [
        {
          icon: 'el-icon-edit-outline',
          title: '修改',
          type: 'edit'
        },
        {
          icon: 'el-icon-download',
          title: '下载',
          type: 'download'
        },
        // {
        //   icon: 'el-icon-delete',
        //   title: '删除',
        //   type: 'delete'
        // }
        {
          icon: 'el-icon-view',
          title: '预览',
          type: 'preview'
        },
        {
          icon: 'el-icon-setting',
          // title: `${row.active_st === 'ZF' ? '激活' : '作废'}`,
          title: '设置状态',
          type: 'invalid'
        }
      ]
      return data || []
    },
    btnDisabled(row, btn) {
      let result = this.data.allButtonDisabled;
      if (this.data.disabled) {
        let value = this.data[btn.type];
        if (this.data.disabled.includes(btn.type) && value !== undefined) {
          result = !value;
        }
      };
      // 作废
      if (this.data.invalid) {
        if (['download', 'preview'].includes(btn.type)) {
          if (row.active_st === 'ZF') {
            result = this.data.allButtonDisabled;
          }
        }
      }
      return result;
    },
    btnShow(row, btn) {
      let result = true;
      if (this.data[btn.type] !== undefined) {
        result = this.data[btn.type];
      }
      // 作废
      if (this.data.invalid) {
        if (['download', 'preview'].includes(btn.type)) {
          if (row.active_st === 'ZF') {
            result = true;
          }
        }
      }
      return result;
    },
    btnClick(row, btn) {
      if(this.data.logic_code && btn.type!='invalid' && !row[btn.type]){
        this.$message.warning('您没有此功能的操作权限！');
        return
      }
      switch (btn.type) {
        case 'edit':
          this.updateShow(row);
          break;
        case 'download':
          this.downloadFile(row);
          break;
        // case 'delete':
        //   this.deleteFile(row.id);
        //   break;
        case 'preview':
          this.previewFile(row);
          break;
        case 'invalid':
          this.invalidFile(row)
          break
      }
    },
    invalidFile (row) {
      this.$confirm(`是否${row.active_st === 'ZF' ? '激活' : '作废'}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http.post(`${this.interfaceUrl}updateStatus`, {
          ids: row.id,
          status: row.active_st === 'ZF' ? 'JH' : 'ZF',
        }, {
          emulateJSON: true,
          headers: {
            JID: this.data.JID
          }
        }).then((res) => {
          if (res.body.status) {
            this.$message.success('操作成功');
            this.getTableData();
            this.$parent && this.$parent.$emit('invalidEvent');
          } else {
            this.$message.error(res.body.error);
          }
        }, (error) => {
          console.log(error);
        });
      }).catch(() => {});
    },
    previewFile(row) {
      this.$http.get(`${this.interfaceUrl}previewFile`, {
        params: {
          filePrn: row.file_prn,
          JID: this.data.JID,
          waterMark: this.data.watermark || ''
        }
      }).then((res) => {
        if (res.body.obj) {
          // window.open(`${window.location.origin}${res.body.obj}`, '_blank');
          // window.open(res.body.obj, '_blank');
          let pdfUrl = res.body.obj;
          let type = pdfUrl && row.file_name && row.file_name.split('.').pop();
          if (type === 'pdf' && window.pdfviewer) {
            const baseUrl = `${window.pdfviewer}/web/viewer.html`;
            // pdfUrl = `${baseUrl}?file=${window.configs.api.url}:${window.configs.api.port}${window.configs.fileProxy}${row.file_uri}&download=${this.data.download}`;
            const newUrl = this.data.watermark ? pdfUrl : `${window.configs.api.url}:${window.configs.api.port}${window.configs.fileProxy}${row.file_uri}`;
            pdfUrl = `${baseUrl}?file=${newUrl}&download=${this.data.download}`;
          }
          window.open(this.syncUrl ? this.syncUrl(pdfUrl) : pdfUrl, '_blank');
          this.$parent && this.$parent.$emit('previewEvent');
        }
      }, (error) => {
        console.log(error);
      });
    },
    getTableData() {
      const { prn, JID } = this.data || {};
      if (!this.interfaceUrl || !prn || !JID) {
        this.filesList = [];
        this.filesListSearch = [];
        return;
      }
      this.$http.get(`${this.interfaceUrl}getListByPrn`, {
        params: Object.assign({}, this.data)
      }).then((res) => {
        this.filesList = res.body.list || [];
        this.filesListSearch = res.body.list || [];
        if(this.data.logic_code && this.filesList.length>0){
          let ids = this.filesList.map((v)=>{
            return v.id
          })
          this.getBtnDis(ids);
        }
      }, (error) => {
        console.log(error);
      });
    },
    getBtnDis(ids){
      this.$http.post("/ks-prj/logicOpt/doOpt", {
        sourceDataJsonStr:JSON.stringify({lgObj:{file_ids: ids}}),
        logic_code: this.data.logic_code
      },{
        emulateJSON: true,
        headers: {
          JID: this.data.JID
        }
      }).then((res) => {
        if(!res.data.status){
          this.$message.error(res.data.error);
          return
        }
        let resList = res.data.obj.data;
        this.filesList.forEach(v => {
          resList.forEach(vv => {
            for(var key in vv){
              if(v.id == key){
                v = Object.assign(v,vv[key])
              }
            }
          })
        });
      }, (error) => {
        console.log(error);
      });
    },
    getFileInfo(fileName) {
      let arr = fileName.split('.');
      // let name = arr[0] || '';
      let format = arr[arr.length - 1];
      let index = fileName.indexOf(format);
      let name = fileName.substring(0, index - 1);
      let pic = null;
      let icon = null;
      // switch (arr[1]) {
      switch (format) {
        case 'png':
          pic = require('../images/png-file-icon.png');
          icon = require('../images/png-icon-small.png');
          break;
        case 'jpg':
          pic = require('../images/jpg_file_icon.png');
          icon = require('../images/jpg_icon_small.png');
          break;
        case 'doc':
        case 'docx':
          pic = require('../images/doc-file-icon.png');
          icon = require('../images/doc-icon.png');
          break;
        case 'pdf':
          pic = require('../images/pdf-file-icon.png');
          icon = require('../images/pdf-icon.png');
          break;
        case 'xls':
        case 'xlsx':
        case 'xlsm':
          pic = require('../images/png-file-icon.png');
          icon = require('../images/xsl-icon.png');
          break;
      }
      return { name, pic, icon };
    },
    selectionChange(selection) {
      this.checkedData = selection;
      let arr = selection.map(v => {
        return v.id;
      });
      this.$emit('headCallBack', arr);
    },
    checkbox(id, event) {
      let el = document.getElementById(id);
      if (!el) {
        return;
      }
      let parent = el.parentNode;
      /* if (el.checked) {
        parent.setAttribute('class', 'selected');
      } else {
        parent.setAttribute('class', '');
      } */
      el.checked = event ? event.target.checked : true;
      parent.setAttribute('class', el.checked ? 'selected' : '');
      //
      const row = this.filesList.find(v => v.id == id);
      const rowIndex = this.checkedData.findIndex(v => v.id == id);
      if (el.checked) {
        rowIndex === -1 && this.checkedData.push(row);
      } else {
        this.checkedData.splice(rowIndex, 1);
      }
      this.isIndeterminate = this.checkedData.length > 0 && this.checkedData.length < this.filesList.length;
      this.checkValue = this.checkedData.length === this.filesList.length;
    },
    checkboxAll(val) {
      let checkbox = document.getElementsByName('checkbox');
      /* if (this.checkValue) {
        for (let key in checkbox) {
          checkbox[key].checked = 'checked';
          checkbox[key].parentNode.setAttribute('class', 'selected');
        }
      } else {
        for (let key in checkbox) {
          checkbox[key].checked = '';
          checkbox[key].parentNode.setAttribute('class', '');
        }
      } */
      for (let key in checkbox) {
        if (typeof checkbox[key] === 'object') {
          checkbox[key].checked = val ? 'checked' : '';
          checkbox[key].parentNode.setAttribute('class', val ? 'selected' : '');
        }
      }
      this.checkedData = val ? JSON.parse(JSON.stringify(this.filesList)) : [];
    },
    downloadFile(row) {
      if(this.data.logic_code && !row.download){
        this.$message.warning('您沒有权限下载此文件！');
        return
      }
      const { file_prn, file_name } = row;
      // const url = `${this.interfaceUrl}downloadFile?filePrn=${file_prn}&fileName=${file_name}&JID=${this.data.JID}`;
      const convertObj = (data) => {
        let _result = [];
        for (let key in data) {
          // let value = data[key] || {};
          let value = typeof data[key] === 'string' ? data[key] : data[key] || {};
          if (value.constructor === Array) {
            value.forEach(function(_value) {
              _result.push(key + '=' + _value);
            });
          } else {
            _result.push(key + '=' + value);
          }
        }
        return _result.join('&');
      };
      let { JID, isUploadLocal, watermark } = this.data;
      let obj = {
        filePrn: file_prn,
        // fileName: file_name,
        JID,
        waterMark: watermark || ''
      };
      if (isUploadLocal !== undefined) {
        obj.isUploadLocal = isUploadLocal;
      }
      const url = `${this.interfaceUrl}downloadFile?${convertObj(obj)}`;
      console.log('download', row, url);
      //
      if (this.downloadUrl) {
        this.downloadUrl(url, file_name);
      } else {
        let eleLink = document.createElement('a');
        eleLink.download = file_name;
        eleLink.style.display = 'none';
        eleLink.href = url;
        document.body.appendChild(eleLink);
        eleLink.click();
      };
      this.$parent && this.$parent.$emit('downloadEvent');
    },
    updateShow(row) {
      this.updateInfo = JSON.parse(JSON.stringify(row));
      this.updateVisible = true;
    },
    updateClose() {
      this.updateVisible = false;
      this.updateInfo = {};
    },
    updateSubmit() {
      const { id, bus_type, file_name, file_prn, file_size, file_uri, remark, source, upload_tm, up_ver, attatch_tag } = this.updateInfo || {};
      let params = {
        id,
        bus_type,
        file_name,
        file_prn,
        file_size,
        file_uri,
        remark,
        source,
        upload_tm,
        up_ver,
        attatch_tag,
        busin_co: '',
        encr_lev: ''
      };
      this.$http.post(`${this.interfaceUrl}update`, Object.assign(params, this.data), {
        emulateJSON: true,
        headers: {
          JID: this.data.JID
        }
      }).then((res) => {
        this.$message.success('修改成功');
        this.updateVisible = false;
        this.getTableData();
      }, (error) => {
        console.log(error);
      });
    }
  },
  created() {
    this.getTableData();
  }
};
</script>

<style lang="scss" scoped>

</style>
