<template>

  <div>
    <div class="aside">
      <div>
        <br>
        <br>
        <el-tree ref="tree"  :props="{children: 'children', label: 'label' }"
                 :data="caOptions"
                 default-expand-all
                 @node-click="handleNodeClick"
                 node-key="code"
                 :expand-on-click-node="false" >
                 <span slot-scope="{ node, data }">
                   <span>
                      <i class="el-icon-folder"></i>
                      {{ node.label }}
                   </span>
                 </span>
        </el-tree>
      </div>
    </div>
    <div style="float:left;width:83%;padding-top: 20px">
      <storage-time  @storageTime="getStorageTimeValue" @changeArchiveScopeValue="changeArchiveScopeValue"  :archiveScopeValue="code"></storage-time>
        <avue-crud ref="crud" style="padding-left:8px"
                   :page="page"
                   :data="tableData"
                   :table-loading="tableLoading"
                   @on-load="getPage"
                   @refresh-change="refreshChange"
                   :option="getOption"
                   v-model="form"
                   @row-update="handleUpdate"
                   @row-save="handleSave"
                   @row-del="handleDel"
                   @search-change="searchChange"
                   @selection-change="selectionChange" class="mainCrud"
        >
          <!--          左边按钮组-->
          <template slot="menuLeft">
            <el-button type="danger" size="small" icon="el-icon-refresh-left" @click="handleRecall()" :disabled="selectDate.length>0?false:true"> 撤回</el-button>
          </template>
          <!--          左边按钮组-->
          <template slot="menuLeft">
            <el-button type="primary" size="small" icon="el-icon-download" @click="exports" > 案卷导出</el-button>
          </template>
          <!--          左边按钮组-->
          <template slot="menuLeft">
            <el-button type="primary" size="small" icon="el-icon-download" @click="exportfile"  v-if="isval"> 卷内文件导出</el-button>
          </template>
<!--          行内按钮组-->
          <template slot="menu" slot-scope="scope">
            <el-dropdown ><span class="el-dropdown-link"><el-button type="text" size="small">操作列表<i class="el-icon-arrow-down el-icon--right"></i></el-button>
             </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item  ><span  @click="showFileList(scope.row,scope.index)"><i class="el-icon-document"></i> 卷内文件</span>
                </el-dropdown-item>
                <el-dropdown-item  ><span @click="view(scope.row)"><i class="el-icon-view"></i> 查看</span>
                </el-dropdown-item>
                <el-dropdown-item ><span @click="showFileUploadList(scope.row)"><i class="el-icon-tickets"></i>上传列表</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </avue-crud>


    </div>
<!--卷内文件-->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      v-if="dialogVisible"
      width="70%"
   >

    <archiveFileinfo  :arId="arId"  :archiveCategory="code" :status="status" ref="archiveFileinfo" :archiveCategoryName="archiveCategory" :archiveScope="archiveScope" :storageTime="storageTime"></archiveFileinfo>

    </el-dialog>
    <!--   文件列表组件-->
    <show-file-list ref="showFileUploadRef"></show-file-list>
  </div>
</template>

<script>
import {treeselect, treeselectAndYear} from '@/api/archives/categoryInfo.js'
import {exportModole} from '@/api/archives/fileInfo.js'
import {addInfo, deleteImportInfo, downLoadUtil} from '@/api/archives/archiveRecord.js'
import {delInfo, listInfoByRecordSearch, recall, transfer, updateInfo,exports} from "@/api/archives/archiveRecord";
import archiveFileinfo from '@/views/archives/archiveFileInfo';
import store  from "@/store";
import {getOptionUtils} from "@/utils/util";
import ShowFileList from "@/views/archives/showFileList/index";
import StorageTime from "@/views/archives/commonComponent/storageTime";
export default {
  components: {archiveFileinfo,ShowFileList,StorageTime},
  name:'recordSearch',
  data() {
    return {
      title:'',
      status:'',
      year:null,
      dialogVisible:false,
      tableLoading:false,
      storageTime:'',
      selectDate: [],
      arId:"",
      isval:false,
      authorizationheaders: {
        Authorization: 'Bearer ' + store.getters.token
      },
      form: {},
      tableData: [],
      code:'WS',
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 10, // 每页显示多少条
      },
      caOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      paramsSearch:{
        archiveCategory:'WS'
      },
      archiveCategory:'',
      archiveScope:'',
      storageTimeValue:null,
      archiveScopeValue:null,
    }
  },
  created() {
    this.getTreeselect();
    this.setVal();
  },
  watch:{
      'form.archiveCategory'(value){
        this.form.archiveCategory=this.code
      },
      getOption(value){
        value.column[1].hide=true
      }
  },
  computed: {
    getOption() {

        return getOptionUtils(this.code)

    }
  },
  mounted() {

    this.$refs.crud.option.column[1].hide=true
  },
  methods: {
    changeArchiveScopeValue(val){
      if (val!=null&&val!='-1'){
        this.archiveScopeValue=val;
      }else{
        this.archiveScopeValue=null;
      }
    },
    getStorageTimeValue(val){
      if (val!=null&&val!='0'){
        this.storageTimeValue=val;
      }else{
        this.storageTimeValue=null;
      }
    },
    showFileUploadList(row){
      this.$refs.showFileUploadRef.fileUpParamsSearch.fileId=row.id
      this.$refs.showFileUploadRef.fileUpParamsSearch.fileType='record'
      this.$refs.showFileUploadRef.fileUploadPage.currentPage=1
      this.$refs.showFileUploadRef.getUpPage(this.$refs.showFileUploadRef.fileUploadPage)
      this.$refs.showFileUploadRef.drawer=true
    },
    handleRecall(){
      let _this = this
      if(this.selectDate.length==0){
        _this.$message({
          showClose: true,
          message: '请先选择需要撤回的数据',
          type: 'warning'
        })
        return;
      }
      let ids = [];
      for (var i=0;i<this.selectDate.length;i++){
        let row = this.selectDate[i];
        ids.push(row.id);
      }
      this.$confirm('是否确认撤回', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return recall(ids)
      }).then(data => {
        _this.$notify({
          title:'成功',
          showClose: true,
          message: '撤回成功',
          type: 'success'
        })

        this.getPage(this.page)
      }).catch(function (err) {

      })
    },
    setVal(){
      if (this.code=='WS'||this.code=='JJ'||this.code=='ZXXM'||this.code=='ZX'){
        this.isval=true;
      }else {
        this.isval=false;
      }
    },
    view(row){
      this.$refs.crud.rowView(row)
    },
    downloadUtils(url){
      let  obj={
        fileName:url,
        delete:false
      }
      downLoadUtil(obj).then(res=>{
        let blob = res
        if (blob.size<=0){
          this.$notify.error("下载文件失败,或由于文件已不存在");
          return;
        }
        let downloadElement = document.createElement('a');
        let href = window.URL.createObjectURL(blob); // 创建下载的链接
        downloadElement.href = href;
       let fileName= url.substring(url.lastIndexOf("/")+1)
        downloadElement.download = fileName; // 下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); // 点击下载
        document.body.removeChild(downloadElement); // 下载完成移除元素
        window.URL.revokeObjectURL(href); // 释放掉blob对象
      }).catch(err=>{
        this.$notify.error(err)
      })
    },


    showFileList(row,index){
        this.title=row.boxName+"》卷内文件"
        this.arId=row.id
        this.status=row.status
        this.archiveCategory=row.$archiveCategory
        if (row.$archiveScope!=undefined&&row.$archiveScope!=null&&""!=row.$archiveScope){
          this.archiveScope=row.$archiveScope
        }else{
          this.archiveScope=null
        }
        this.storageTime=row.$storageTime
        this.dialogVisible=true
      setTimeout(()=>{
        let  page={
            currentPage: 1, // 当前页数
            pageSize: 10, // 每页显示多少条
          };
        this.$refs.archiveFileinfo.getPage(page)
      },)
    },
    getTreeselect() {
      let obj={
        parentId:1
      }
      treeselectAndYear(obj).then((response) => {
        this.caOptions = response.data;

      });
    },
    // 节点单击事件
    handleNodeClick(data) {
      //是否二级查询
      let isSecond = data.code.indexOf("-")!=-1;
      //节点单击选中的档案类目
      let code = isSecond?data.code.split("-")[0]:data.code;
      //如果选中的code不等于当前code则需要滞空查询条件;因为一定是选了其他类型的档案(二级查询不能滞空)
      this.year=null;
      if (code!=this.code){
        this.archiveScopeValue=null;
        this.storageTimeValue=null;
        this.paramsSearch={};
        this.$refs.crud.searchReset();
      }
      //如果二级查询
      if (isSecond){
        //如果是基建档案
        if (code=='JJ'){
          this.paramsSearch['fileNum']=data.label;
        }else{
          this.year=data.label;
        }
      }else{
        //一级查询如果是基建档案，则滞空fileNum;和右侧档号查询只取其一
        if (code=='JJ'){
          this.paramsSearch['fileNum']=null;
        }
      }
      //选中的档案类目赋给当前code
      this.code=code;
      this.$set(this.form,'archiveCategory',this.code);
      this.page.currentPage=1
      this.getPage(this.page)
      this.setVal();
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    searchChange(params, done) {
      if(params.searchDate &&　params.searchDate.length > 1){
        params.searchDate = params.searchDate[0]+","+params.searchDate[1];
      }else {
        delete(params.searchDate);
      }
      this.paramsSearch = params
      this.page.currentPage = 1
      this.getPage(this.page, params)
      done()
    },
    exports(){

      this.paramsSearch.status='6'
      this.paramsSearch.archiveCategory=this.code
      this.paramsSearch.year=this.year
      this.paramsSearch.storageTime=this.storageTimeValue;
      this.paramsSearch.archiveScope=this.archiveScopeValue;
      this.tableLoading = true
      var excel=[]
      exports(this.paramsSearch).then(response => {

        excel=response.data;
        excel.forEach(item=>{

           this.download(item)
        })
        // this.download(response.msg);
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      });

    },
    exportfile(){
      this.paramsSearch.status='6'
      this.paramsSearch.archiveCategory=this.code
      this.paramsSearch.year=this.year
      this.paramsSearch.storageTime=this.storageTimeValue;
      this.paramsSearch.archiveScope=this.archiveScopeValue;
      this.tableLoading = true
      exportModole(this.paramsSearch).then(rep=>{
        this.download(rep.msg);
      })

      this.tableLoading = false
    },
    getPage(page, params) {
      this.paramsSearch.status='6'
      this.paramsSearch.archiveCategory=this.code
      this.paramsSearch.year=this.year
      this.paramsSearch.storageTime=this.storageTimeValue;
      this.paramsSearch.archiveScope=this.archiveScopeValue;
      this.tableLoading = true
      listInfoByRecordSearch(Object.assign({
        pageNum: page.currentPage,
        pageSize: page.pageSize,
      }, params, this.paramsSearch)).then(response => {
        this.tableData = response.rows
        this.page.total = response.total.toString()
        this.page.currentPage=page.currentPage
        this.page.pageSize=page.pageSize
        this.tableLoading = false
      }).catch(() => {
        this.tableLoading = false
      })
    },
    /**
     * @title 数据删除
     * @param row 为当前的数据
     * @param index 为当前删除数据的行数
     *
     **/
    /**
     * @title 数据删除
     *
     **/
    handleDel: function () {
      if (this.selectDate.length == 0) {
        this.$notify({
          showClose: true,
          message: '请先选择需要删除的数据',
          type: 'warning'
        })
      } else {
        let ids = new Array();
        let length = this.selectDate.length;
        for (let i = 0; i < length; i++) {
          if (this.selectDate[i].status=='2'){
            this.$notify({
              showClose: true,
              message: '错误,不能删除待审核中的档案',
              type: 'warning'
            })
            return;
          }
          ids.push(this.selectDate[i].id)
        }
        this.$confirm('是否确认删除此数据', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          return delInfo(ids);
        }).then(data => {
          this.$notify({
            title: '成功',
            showClose: true,
            message: '删除成功',
            type: 'success'
          });
          this.getPage(this.page);
        }).catch(function (err) {
        })
      }
    },
    /**
     * @title 数据更新
     * @param row 为当前的数据
     * @param index 为当前更新数据的行数
     * @param done 为表单关闭函数
     *
     **/
    handleUpdate: function (row, index, done, loading) {
      updateInfo(row).then(response => {
        this.$notify({
          title: '成功',
          showClose: true,
          message: '修改成功',
          type: 'success'
        })
        done()
        this.getPage(this.page)
      }).catch(() => {
        loading()
      })
    },
    /**
     * @title 数据添加
     * @param row 为当前的数据
     * @param done 为表单关闭函数
     *
     **/
    handleSave: function (row, done, loading) {
      addInfo(row).then(response => {
        this.$notify({
          title: '成功',
          showClose: true,
          message: '添加成功',
          type: 'success'
        })
        done()
        this.getPage(this.page)
      }).catch(() => {
        loading()
      })
    },

    /**
     * 刷新回调
     */
    refreshChange(page) {
      this.getPage(this.page)
    },



    //多选
    selectionChange(list) {
      this.selectDate = list;
    },
  }
}
</script>

<style>
.aside {
  width: 17%;
  height: 100%;
  margin-bottom: 50px;
  text-align: center;
  float: left;
  padding-left: 35px;
  padding-right: 10px;
}
</style>
