<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="70px">
        <div class="search">
          <div class="sl">
            <el-form-item label="文档编号" prop="docCode">
              <el-input
                v-model="queryParams.docCode"
                placeholder="请输入文档名称"
                clearable
                @clear="handleQuery"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="文档名称" prop="docName">
              <el-input
                v-model="queryParams.docName"
                placeholder="请输入文档名称"
                clearable
                @clear="handleQuery"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="文档类别" prop="docType">
              <el-select v-model="queryParams.docType" placeholder="请选择" @change="handleQuery">
                <el-option
                  v-for="dict in dict.type.doc_class"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="文档来源" prop="docSource">
              <el-select v-model="queryParams.docSource" placeholder="请选择" @change="handleQuery">
                <el-option
                  v-for="dict in dict.type.doc_source"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="dateRange"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                @change="handleQuery"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="负责人" prop="docPrincipalsName">
              <el-input
                v-model="queryParams.docPrincipalsName"
                placeholder="请输入负责人名称"
                clearable
                @clear="handleQuery"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
<!--            <el-form-item label="归属单位" prop="docRespDept">
              <treeselect v-model="queryParams.docRespDept" :options="deptOptions"
                          placeholder="请选择归属单位"
                          :show-count="true" style="width: 150px"/>
            </el-form-item>-->

            <el-form-item label="状态" prop="docStatus">
              <el-select v-model="queryParams.docStatus" placeholder="请选择" @change="handleQuery">
                <el-option
                  v-for="dict in dict.type.doc_upload_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>

          </div>
          <div class="sr">
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </div>
        </div>
      </el-form>
    </el-card>
    <el-card class="lrtt">
      <div class="lt">
        <el-input
          v-model="categoryNameParam"
          placeholder="请输入文档分类名称"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="margin-bottom: 20px"
        />
<!--        <el-input placeholder="请输入..." prefix-icon="el-icon-search"
                  clearable size="small" style="margin-bottom: 20px"
                  v-model="categoryNameParam"></el-input>-->
        <div class="divide"></div><!--divide 分隔-->
        <el-tree :data="docCategory" :props="docCategoryProps"
                 ref="tree" :expand-on-click-node="false"
                 :filter-node-method="filterNode"
                 node-key="id"
                 default-expand-all
                 highlight-current
                 @node-click="handleNodeClick">
					<span class="custom-tree-node" slot-scope="{ node, data }">
					    <span>{{ node.label }}</span>
                <el-dropdown>
                  <span class="el-dropdown-link"><i class="el-icon-more"></i></span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item  @click.native="handleDocCategoryAdd(data)"><i class="el-icon-plus"></i>添加</el-dropdown-item>
                    <el-dropdown-item v-if="data.types != 'system'" @click.native="handleDocCategoryUpdate(data)"><i class="el-icon-edit"></i>编辑</el-dropdown-item>
                    <el-dropdown-item v-if="data.types != 'system'" @click.native="handleDocCategoryDelete(data)"><i class="el-icon-delete"></i>删除</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
          </span>
        </el-tree>
      </div><!--lt 左-->
      <div class="rt">
        <div class="operate">
          <el-button
            type="primary"
            plain
            icon="el-icon-upload2"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['document:add']"
          >上传文档</el-button>
          <el-button type="primary" icon="el-icon-position" @click="handlePush" v-hasPermi="['document:push']">发布</el-button>
          <el-button type="primary" icon="el-icon-download" @click="handleOpenExport()" v-hasPermi="['document:export']">全量导出</el-button>
          <el-button type="primary" icon="el-icon-download" @click="handleOpenBatchExport()" v-hasPermi="['document:batch:export']">批量导出</el-button>
          <el-button icon="el-icon-delete" @click="handleDelete" v-hasPermi="['document:batch:remove']">批量删除</el-button>


        </div><!--operate 操作按钮-->

        <el-table v-loading="loading" :data="docList" ref="tableRef" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="文档编号"  prop="docCode" width="120" />
          <el-table-column label="文档名称"  prop="docName" :show-overflow-tooltip="true" />
          <el-table-column label="文档类别"  prop="docType" :show-overflow-tooltip="true" width="80">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.doc_class" :value="scope.row.docType"/>
            </template>
          </el-table-column>·
          <el-table-column label="负责人"   prop="docPrincipalsName" :show-overflow-tooltip="true" width="100" />
          <el-table-column label="归属单位" prop="docRespDeptName" :show-overflow-tooltip="true" width="80" />
          <el-table-column label="文档来源" prop="docSource" width="100">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.doc_source" :value="scope.row.docSource"/>
            </template>
          </el-table-column>
<!--          <el-table-column label="关联工具" align="center" prop="toolName" width="100" />-->
          <el-table-column label="文档状态" align="center" prop="docStatus" width="100" >
            <template slot-scope="scope">
              <dict-tag :options="dict.type.doc_upload_status" :value="scope.row.docStatus"/>
            </template>
<!--
            <template slot-scope="scope">
              <el-tag type="info" v-if="scope.row.docStatus == 'ysc'">已上传</el-tag>
              <el-tag type="success" v-else-if="scope.row.docStatus == 'yfb'">已发布</el-tag>
              <el-tag type="warning" v-else-if="scope.row.docStatus == 'shz'">审核中</el-tag>
            </template>-->

          </el-table-column>
          <el-table-column label="创建时间" align="center" prop="createTime" width="180" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="160px" fixed="right">
            <template slot-scope="scope">
<!--              <el-button
                size="mini"
                type="text"
                icon="el-icon-view"
                v-if="previewAuth(scope.row)"
                @click="handlePreview(scope.row)"
                v-hasPermi="['document:preview']"
              >预览</el-button>-->
              <el-button type="text" icon="el-icon-download" @click="handleDownload(scope.row)"
                         v-if="scope.row.downloadStatus"
                         v-loading="loadingDownload">下载</el-button>
<!--              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                v-if="scope.row.docStatus != 'yfb' && scope.row.docStatus != 'shz'"
                @click="handleEdit(scope.row)"
                v-hasPermi="['document:edit']"
              >编辑</el-button>
              <el-button type="text" icon="el-icon-info" @click="handleDetail(scope.row)">详情</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                v-if="scope.row.docStatus != 'yfb' && scope.row.docStatus != 'shz'"
                @click="handleDelete(scope.row)"
                v-hasPermi="['document:remove']"
              >删除</el-button>-->

              <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
                <el-button size="mini" type="text" icon="el-icon-d-arrow-right" >更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="handleDetail" icon="el-icon-info" >详情</el-dropdown-item>
                  <el-dropdown-item command="handleEdit" icon="el-icon-edit"  v-if="scope.row.docStatus != 'yfb' && scope.row.docStatus != 'shz'">编辑</el-dropdown-item>
                  <el-dropdown-item command="handleDelete" icon="el-icon-delete" v-if="scope.row.docStatus != 'yfb' && scope.row.docStatus != 'shz'">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </el-card>



    <el-dialog :title="docCategoryTitle" :visible.sync="docCategoryOpen"  width="50%"
               :close-on-press-escape="false" :close-on-click-modal="false" :destroy-on-close="true"
               :show-close="false" :wrapperClosable="false"
               append-to-body>
      <el-form ref="docCategoryFormRefs" :model="docCategoryForm" :rules="docCategoryRules" label-width="80px">
        <el-form-item label="父分类" prop="parentId">
          <treeselect v-if="docCategoryOpen" v-model="docCategoryForm.parentId" :options="docCategory" :show-count="true" placeholder="如果不选择，默认为一级分类" />
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="docCategoryForm.categoryName" placeholder="请输入分类名称" maxlength="50" show-word-limit/>
        </el-form-item>
        <el-form-item label="分类描述" prop="categoryDescription">
          <el-input v-model="docCategoryForm.categoryDescription"
                    type="textarea" :rows="3" maxlength="500" show-word-limit
                    placeholder="请输入分类描述" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="docCategorySubmitForm">确 定</el-button>
        <el-button @click="docCategoryCancel">取 消</el-button>
      </span>
    </el-dialog>

    <!--文档修改-->
    <el-drawer :visible.sync="open"
               :wrapperClosable="false"
               :modal-append-to-body="false" :show-close="false" :close-on-press-escape="false"
               size="75%">
      <template #title>
        <span class="title">{{docTitle}}</span>
        <div class="drawer-head-btn" v-if="docDetailDisable">
          <el-button icon="el-icon-check" type="primary" @click="docConfrim()">保 存</el-button>
          <el-button icon="el-icon-close"  @click="docCancel()">关 闭</el-button>
        </div><!--drawer-head-btn 抽屉顶部按钮区域-->
        <div class="drawer-head-btn" v-else>
          <el-button icon="el-icon-close" @click="docCancel()">关 闭</el-button>
        </div><!--drawer-head-btn 抽屉顶部按钮区域-->
      </template>
      <edit-document v-if="open" ref="editDocumentRef" @submit="editDocumentSubmit"/>
    </el-drawer>


    <!--文档详情-->
    <el-drawer :visible.sync="detailDocOpen"
               :wrapperClosable="false"
               :modal-append-to-body="false" :show-close="false" :close-on-press-escape="false"
               size="75%">
      <template #title>
        <span class="title">{{docTitle}}</span>
        <div class="drawer-head-btn">
          <el-button icon="el-icon-close" @click="docDetailCancel()">关 闭</el-button>
        </div><!--drawer-head-btn 抽屉顶部按钮区域-->
      </template>
      <template v-if="detailOpen">
        <doc-detail ref="docDetailRef" @submit="docDetailFormSubmit"/>
      </template>
    </el-drawer>


    <!-- 文档导出对话框 -->
    <el-dialog :title="exportTitle" :visible.sync="exportDrawerOpen"
               :wrapperClosable="false"
               :modal-append-to-body="false" :show-close="false" :close-on-press-escape="false"
               v-loading="wordLoading"  element-loading-text="正在下载数据，请稍候"
               width="980px" append-to-body>
      <div class="el-form-border">
          <el-form ref="exportFrom" label-width="180px">
            <el-row>
              <el-col :span="24">
                <el-form-item label="导出格式">
                  <el-radio-group v-model="statevalue">
                    <el-radio v-for="item in stateoptions"  :key="item.value"  :label="item.value" >{{item.label}}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
      </div><!--el-form-border 表单-->
      <div class="el-form-border">
        <el-form ref="form" label-width="180px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="导出字段">
                <el-checkbox-group v-model="checkList">
                  <el-checkbox label="docCode">文档编号</el-checkbox>
                  <el-checkbox label="docName">文档名称</el-checkbox>
                  <el-checkbox label="docType">文档类别</el-checkbox>
                  <el-checkbox label="docPrincipalsName">负责人</el-checkbox>
                  <el-checkbox label="docRespDeptName">归属单位</el-checkbox>
                  <el-checkbox label="docSource">文档来源</el-checkbox>
                  <el-checkbox label="docStatus">文档状态</el-checkbox>
                  <el-checkbox label="createTime">创建时间</el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form><!--el-form-->
      </div><!--el-form-border 表单-->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleExport">确 定</el-button>
        <el-button @click="exportDrawerOpen=false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 文档下载对话框 -->
    <el-drawer :visible.sync="fileDetailDrawerOpen"
               :wrapperClosable="false"
               :modal-append-to-body="false" :show-close="false" :close-on-press-escape="false"
               size="80%" class="no-padding" @close="handleFileCloseDetail()">
      <template #title>
        <span>文档附件下载</span>
        <div class="drawer-head-btn">
          <el-button icon="el-icon-close" @click="fileDetailDrawerOpen = false">关 闭</el-button>
        </div><!--drawer-head-btn 抽屉顶部按钮区域-->
      </template>
      <template v-if="fileDetailOpen">
        <download-file-detail ref="downloadFileDetailRef" :docDetail="docDetail"/>
      </template>
    </el-drawer><!--el-drawer 详情-抽屉-->


  </div>
</template>

<script>
import { listDocument, getDocument, delDocument, addDocument, updateDocument,pushDoc, getExportWordList} from "@/api/document/document";
import { deptTreeSelect } from "@/api/system/user";
import { documentTree,addCategory,updateCategory,delCategory,getCategory } from "@/api/documentCategory/documentCategory.js";
import { Base64 } from 'js-base64';
import editDocument from "./editDocument";
import uploadProgress from "./uploadProgress";
import Treeselect from "@riophae/vue-treeselect";
import { exportDocx } from '@/utils/docUtil/docutil.js';
import downloadFileDetail from "./downloadFileDetail.vue";
import docDetail from "@/views/document/detail";
import store from "@/store";

export default {
  name: "Document",
  components: { editDocument, uploadProgress, Treeselect, downloadFileDetail, docDetail},
  dicts:['doc_class','doc_source','doc_upload_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 部门名称
      deptName: undefined,
      // 部门树选项
      deptOptions: undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 文档树
      docCategory: undefined,
      docCategoryProps: {
        children: "children",
        label: "label"
      },
      // 总条数
      total: 0,
      // 表格数据
      docList: [],
      // 弹出层标题
      title: "",
      viewDialogTitle: "",
      viewDialogOpen: false,
      open: false,
      // 日期范围
      dateRange: [],
      previewUrl: '',
      progress: 0,
      fileList: [],
      websocket: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        docName: '',
        docCode: '',
        docType: '',
        docPrincipalsName: '',
        docSource: '',
        docStatus: '',
        createById: this.$store.getters.userId,
        permissionCheck: true,
        downloadCheck:true
      },
      // 文件夹查询
      queryCategoryParams: {
        pageNum: 1,
        pageSize: 10,
        docCategoryId: '',
        categoryName: '',
      },
      // 表单参数
      form: {
        docName: '',
        docType: '',
        docPrincipals: '',
        docRespDept: '',
        docSource: ''
      },
      // 表单校验
      rules: {
        docType: [
          { required: true, message: "类别不能为空", trigger: "blur" }
        ],
        docSource: [
          { required: true, message: "文档来源不能为空", trigger: "blur" }
        ]
      },
      docCategoryRules: {
        categoryName: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "创建人名称不能为空", trigger: "blur" }
        ],
        createById: [
          { required: true, message: "创建人id不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      },
      docCategoryTitle: "",
      docCategoryOpen: false,
      // 文档资源参数
      docCategoryForm: {
        categoryName: null,
        categoryDescription: null,
        parentId: null
      },
      loadingDownload: false,
      acceptType: "zip,rar,7z",
      //导出属性
      columnList: ['docCode', 'docName', 'docType', 'docPrincipalsName', 'docRespDeptName', 'docSource', 'docStatus', 'createTime'],
      checkList: [],
      exportDrawerOpen: false,
      docTitle: '',
      //文件详情标识
      docDetailDisable: true,
      //导出类型
      statevalue: 1,
      stateoptions: [
        {
          value: 1,
          label: 'excel'
        },
        {
          value: 2,
          label: 'word'
        }
      ],
      docTipAddOrEdit: null,
      //详情
      fileDetailDrawerOpen: false,
      fileDetailOpen: false,
      toolDetail: {},
      //导出
      exportTitle:'',
      batchExportFlag: false,
      //查询
      selection: undefined,
      docDetail: {},
      detailDocOpen: false,
      detailOpen: false,
      categoryNameParam: undefined,
      wordLoading: false,
    };
  },
  watch: {
    // 根据名称筛选部门树
    categoryNameParam(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getDeptTree();
    this.getDocumentTree();
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 查询树形下拉树结构 */
    getDocumentTree() {
      documentTree().then(response => {
        this.docCategory = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.docCategoryId = data.id;
      this.handleQuery();
    },
    /** 查询列表 */
    getList() {
      let self = this
      self.loading = true;
      listDocument(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        self.docList = response.rows;
        self.total = response.total;
        self.loading = false;
        }
      ).catch(err=>{
        console.error("getList=======", err)
        self.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.queryParams.docCategoryId = '';
      this.resetForm("queryForm");
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.docTitle="新增文档资源"
      this.docTipAddOrEdit = 'add'
      this.docDetailDisable=true
      this.open = true
      this.$nextTick(()=>{
        this.$refs.editDocumentRef.resetForm();
      })
    },
    handleEdit(row){
      this.docTitle="编辑文档资源"
      this.docTipAddOrEdit = 'edit'
      this.docDetailDisable=true
      this.open = true
      this.$nextTick(()=>{
        this.$refs.editDocumentRef.editInit(row.docId, "edit");
      })
    },
    handleDetail(row){
      this.docTitle="文档详情"
      this.docTipAddOrEdit = 'detail'
      this.docDetailDisable=false
      this.detailDocOpen = true
      this.detailOpen = true
      this.$nextTick(()=>{
        this.$refs.docDetailRef.editInit(row.docId, "detail");
      })
    },
    handlePreview(row){
      this.viewDialogOpen = true;
      let protocol = window.location.protocol
      let hostname = window.location.hostname;
      let getDocUrl = protocol + '//' + hostname + ':8080' + process.env.VUE_APP_BASE_API
      this.previewUrl = process.env.VUE_APP_TOOL_TECH_FILE_VIEW_API + '/onlinePreview?url=' + encodeURIComponent(Base64.encode(getDocUrl + row.docUrl));
      this.viewDialogTitle = '文档在线预览'
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selection=selection
      this.ids = selection.map(item => item.docId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    editDocumentSubmit: function() {
      this.open = false;
      this.getList();
    },
    docDetailFormSubmit: function() {
      this.detailDocOpen = false;
      this.detailOpen = false;
      this.getList();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let self = this
      const docIds = row.docId || this.ids;
      if(docIds == null || docIds == undefined || docIds =='' || docIds.length < 0){
        this.$modal.msgWarning(`最少选择一条数据`);
        return;
      }
      //只能删除已上传数据
      let delFlag = false;
      if(self.selection){
        for(let item of self.selection){
          if(!(item.docStatus == 'ysc')){
            delFlag = true;
          }
        }
      }
      if(row.docStatus && row.docStatus != 'ysc'){
        delFlag = true;
      }
      if(delFlag){
        this.$modal.msgError(`只能删除文档状态为[已上传]数据,请重新选择`);
        return
      }

      this.$modal.confirm('是否确认删除？').then(function() {
        return delDocument(docIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch((err) => {console.error(err)});
    },
    /** 新增按钮操作 */
    handleDocCategoryAdd(data) {
      this.docCategoryOpen = true;
      // this.docCategoryForm.parentId = data.id;
      this.$nextTick(() => {
        this.resetDocCategoryForm();
        this.docCategoryForm.parentId = data.id;
      })
      this.docCategoryTitle = "添加文档资源分类";
    },
    /** 删除按钮操作 */
    handleDocCategoryDelete(row) {
      this.$modal.confirm('是否删除该项数据？').then(function() {
        return delCategory(row.id);
      }).then(() => {
        this.getDocumentTree();
        this.$modal.msgSuccess("删除成功");
      }).catch((err) => {
        console.error("err============", err)
      });
    },
    /** 修改按钮操作 */
    handleDocCategoryUpdate(row) {
      let self = this
      self.docCategoryOpen = true;
      self.$nextTick(() => {
        self.resetDocCategoryForm();
      })
      const id = row.id;
      getCategory(id).then(response => {
        self.docCategoryForm = response.data;
        self.docCategoryTitle = "修改文档资源分类";
      });
    },
    /** 提交按钮 */
    docCategorySubmitForm() {
      this.$refs["docCategoryFormRefs"].validate(valid => {
        if (valid) {
          if (this.docCategoryForm.id != null) {
            updateCategory(this.docCategoryForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.docCategoryOpen = false;
              this.getDocumentTree();
            });
          } else {
            this.$set(this.docCategoryForm, "types", "user")
            addCategory(this.docCategoryForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.docCategoryOpen = false;
              this.getDocumentTree();
            });
          }
        }
      });
    },
    // 取消按钮
    docCategoryCancel() {
      this.docCategoryOpen = false;
      this.resetDocCategoryForm();
    },
    /** 重置 **/
    resetDocCategoryForm(){
      this.docCategoryForm = {
          categoryName: null,
          categoryDescription: null,
          parentId: null
      },
      this.$refs.docCategoryFormRefs.resetFields();
    },
    /**
     * 处理下载
     * **/
    handleDownload(row){
      this.fileDetailDrawerOpen = true
      this.fileDetailOpen = true
      this.docDetail = row
    },
    /** 发布操作 */
    handlePush(row) {
      let self = this
      const docIds = row.docId || this.ids;
      if(docIds == null || docIds == undefined || docIds =='' || docIds.length < 0){
        this.$modal.msgWarning(`最少选择一条数据`);
        return;
      }
      //只能删除已上传数据
      let delFlag = false;
      for(let item of self.selection){
        if(!(item.docStatus == 'ysc')){
          delFlag = true;
        }
      }
      if(delFlag){
        this.$modal.msgError(`只能发布文档状态为[已上传]数据,请重新选择`);
        return
      }

      this.$modal.confirm('是否确认发布？').then(function() {
        return pushDoc(docIds);
      }).then(() => {
        self.getList();
        store.commit('SET_UNREAD_MSG_NUMBER', this.$store.state.user.unreadMsgNumber+1);
        self.$modal.msgSuccess("发布成功");
      }).catch((err) => {
        console.error(err)
      });
    },
    /**
     * 确认
     */
    docConfrim(){
      this.$refs.editDocumentRef.submitForm();
    },
    docCancel(){
      this.$refs.editDocumentRef.resetForm();
      this.open = false
    },
    docDetailCancel(){
      this.$refs.docDetailRef.resetForm();
      this.detailDocOpen = false
      this.detailOpen = false
    },
    previewAuth(row){
      if(row.docUrl == null || row.docUrl == '' || row.docUrl == undefined){
        return false
      }
      let extension = this.getExtension(row.docUrl);
      const acceptedExtensions = this.acceptType.toLowerCase().split(',');
      if(acceptedExtensions.includes(extension)){
        return false
      }
      return true
    },
    getExtension(filePath) {
      // 分割字符串，以 '.' 为分隔符
      const parts = filePath.split('.');
      // 取最后一个部分作为后缀名
      const extension = parts.pop();
      return extension;
    },
    isSelectable(row) {
      return row.docStatus !== 'yfb' && row.docStatus !== 'shz';
    },
    /** 批量导出 */
    handleOpenBatchExport() {
      let self = this
      if(self.selection == null || self.selection == '' || self.selection == undefined || self.selection.length <= 0){
        this.$modal.msgWarning(`最少选择一条数据`);
        return;
      }
      if (this.checkList.length<1) {
        this.checkList = JSON.parse(JSON.stringify(this.columnList))
      }
      this.exportTitle = '批量导出'
      this.batchExportFlag = true
      this.exportDrawerOpen = true
    },
    /** 导出按钮操作 */
    handleOpenExport() {
      if (this.checkList.length<1) {
        this.checkList = JSON.parse(JSON.stringify(this.columnList))
      }
      this.exportTitle = '全量导出'
      this.exportDrawerOpen = true
      this.batchExportFlag = false
    },
    /** 导出按钮操作 */
    handleExport() {
      let self = this
      if(this.checkList.length == 0){
        this.$modal.msgWarning(`最少选择一个字段`);
        return
      }
      if (this.statevalue == 1) {
        let excludeFields = this.columnList.filter(item=>!this.checkList.includes(item))

        let params = {
          ...this.queryParams,
          downloadCheck:false,
          excludeFields:excludeFields,
        }
        if(this.batchExportFlag){
          params = {
            downloadCheck:false,
            docIdList: self.selection.map(item=>item.docId),
            excludeFields:excludeFields,
          }
        }
        this.download('/document/export', params , `document_${new Date().getTime()}.xlsx`)
      }
      if (this.statevalue == 2) {
        let params = {
          ...this.queryParams
        }
        if(this.batchExportFlag){
          params = {
            docIdList: self.selection.map(item=>item.docId)
          }
        }
        self.wordLoading = true
        getExportWordList(params).then(r => {
          if (r.data.length != 0) {
            const data = {
              form: null,
              list: r.data
            }
            exportDocx('document.docx', data, `document_${new Date().getTime()}.docx`)
            setTimeout(() => {
              if(self.batchExportFlag){
                self.clearSelected()
              }
              self.wordLoading = false
              self.exoportDrawerOpen = false;
            }, 1000);
          } else {
            self.wordLoading = false
            self.exportDrawerOpen = false
            this.$message.error('没有数据');
          }
        }).catch((err) => {
          console.error("err=============", err)
          self.wordLoading = false
          self.exportDrawerOpen = false
        })
      }

    },
    handleBeforeClose() {
      this.viewDialogOpen = false
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleEdit":
          this.handleEdit(row);
          break;
        case "handleUpdate":
          this.handleUpdate(row);
          break;
        case "handleDelete":
          this.handleDelete(row);
          break;
        case "handleDetail":
          this.handleDetail(row);
          break;
        default:
          break;
      }
    },
    clearSelected() {
      // 清空选中的tab
      this.$refs.tableRef.clearSelection();
    },
    /** 关闭详情 **/
    handleFileCloseDetail(){
      this.fileDetailDrawerOpen = false;
      this.fileDetailOpen = false;
      this.$refs.downloadFileDetailRef.$destroy(); // 销毁组件
      this.$nextTick(() => {
        this.$refs.downloadFileDetailRef = null; // 清空引用
      });
    },

  }
};
</script>

