<template>
  <div>
    <!-- 数据表格 -->
    <ele-pro-table
      ref="table"
      :columns="columns"
      :datasource="datasource"
      height="calc(45vh)"
      tool-class="ele-toolbar-form"
      :initLoad="false"
      row-key="id"
      :current.sync="current"
      :selection.sync="selection"
      highlight-current-row
      @row-click="rowClick"
      @selection-change="selectionClick"
      @done="done"
      :toolbar="!isPop"
    >
      <!-- 表头工具栏 -->
      <template v-slot:toolbar>
        <!-- <div style="display: contents;"> -->
        <el-dropdown trigger="click" v-if="lcyStatus == 1">
          <el-button type="primary">
            新建<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              @click.native="
                parenOpen('add', {
                  power: 'add',
                  dataKey: 'parentData',
                  isArr: false
                })
              "
              >新建文件夹</el-dropdown-item
            >
            <el-dropdown-item
              @click.native="
                openEdit('add', '', {
                  power: 'add',
                  dataKey: 'parentData',
                  isArr: false
                })
              "
              >新建文档</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
        <el-dropdown trigger="click" v-if="lcyStatus == 1">
          <el-button type="primary">
            编辑<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              @click.native="
                parenOpen('edit', {
                  power: 'revise',
                  dataKey: 'parentData',
                  isArr: false
                })
              "
              >修改</el-dropdown-item
            >
            <el-dropdown-item
              @click.native="
                parenOpen('del', {
                  power: 'del',
                  dataKey: 'parentData',
                  isArr: false
                })
              "
              >删除</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
        <el-button
          v-if="lcyStatus == 1"
          type="primary"
          @click.native="
            openEditAll({
              power: 'add',
              dataKey: 'parentData',
              isArr: false
            })
          "
        >
          批量上传
        </el-button>

        <el-button
          type="primary"
          @click.native="
            checkEnter({
              power: 'checkEnter',
              dataKey: 'current',
              isArr: true
            })
          "
          :disabled="selection.length > 1 || selection[0]?.checkOutStatus == 0"
          v-if="lcyStatus == 1"
        >
          检入
        </el-button>
        <el-button
          type="primary"
          @click.native="
            checkOut({
              power: 'checkOut',
              dataKey: 'current',
              isArr: true
            })
          "
          :disabled="selection.length > 1 || selection[0]?.checkOutStatus == 1"
          v-if="lcyStatus == 1"
        >
          检出
        </el-button>

        <el-popconfirm
          class="ele-action"
          v-if="lcyStatus == 1 && fileType === 0"
          title="归档后文档无法修改，是否确认归档"
          @confirm="
            updateLcyStatus({
              power: 'archive',
              dataKey: 'current',
              isArr: true
            })
          "
        >
          <template v-slot:reference>
            <el-button type="primary"> 归档 </el-button>
          </template>
        </el-popconfirm>
        <el-button
          type="primary"
          v-if="lcyStatus == 2"
          @click="
            noUpdateLcyStatus({
              power: 'cancelArchive',
              dataKey: 'current',
              isArr: true
            })
          "
        >
          <!-- {
              power: 'cancelArchive',
              dataKey: 'current',
              isArr: true
            } -->
          取消归档
        </el-button>

        <el-button
          type="primary"
          v-if="
            (lcyStatus == 1 || lcyStatus == 2) &&
            (fileType == 0 || fileType == 1)
          "
          @click="
            openSendEdit({
              power: 'release',
              dataKey: 'current',
              isArr: true
            })
          "
        >
          发布
        </el-button>
        <el-button
          v-if="fileType == 2"
          type="primary"
          @click="processSubmit_template"
        >
          发布
        </el-button>

        <el-button
          v-if="fileType === 0 && lcyStatus != 4"
          type="primary"
          :disabled="selection.length > 1"
          @click="
            processSubmit({
              power: 'abolish',
              dataKey: 'current',
              isArr: true
            })
          "
        >
          废止
        </el-button>
        <el-button
          v-if="fileType === 0 && lcyStatus != 4"
          type="primary"
          @click="powerOpen"
        >
          批量设置权限
        </el-button>
        <el-button
          type="primary"
          @click.native="
            getFile({
              power: 'download',
              dataKey: 'current',
              isArr: true
            })
          "
        >
          下载
        </el-button>
        <el-button
          :disabled="selection.length > 1"
          type="primary"
          v-if="fileType == 1"
          @click.native="move"
        >
          移动
        </el-button>
        <fileSearch @search="reload" style="margin-left: 20px"></fileSearch>
        <!-- </div> -->
      </template>

      <!-- 操作列 -->
      <template v-slot:action="{ row }">
        <el-dropdown
          trigger="click"
          v-if="
            lcyStatus == 1 &&
            (row.reviewStatus == 0 || row.reviewStatus == 3) &&
            row.status == 0
          "
        >
          <el-link type="primary" :underline="false" icon="el-icon-edit">
            编辑
          </el-link>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              @click.native="
                openEdit('edit', row, {
                  power: 'revise',
                  dataKey: 'current',
                  isArr: false
                })
              "
              >修改</el-dropdown-item
            >
            <el-dropdown-item>
              <el-popconfirm
                class="ele-action"
                title="确定要删除此文档吗？"
                @confirm="
                  remove(row, {
                    power: 'del',
                    dataKey: 'current',
                    isArr: false
                  })
                "
              >
                <template v-slot:reference>
                  <el-link type="danger" :underline="false"> 删除 </el-link>
                </template>
              </el-popconfirm>
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </template>
    </ele-pro-table>
    <el-tabs
      type="border-card"
      v-show="!current?.id && parentData?.id"
      style="height: calc(55vh - 260px)"
    >
      <el-tab-pane label="常规">
        <folderInfo :parentId="parentData?.id" :folderList="folderList" />
      </el-tab-pane>

      <el-tab-pane label="操作日志"></el-tab-pane>
    </el-tabs>
    <el-tabs
      v-model="activeName"
      type="border-card"
      v-show="current.id && isPower(current, 'check')"
      style="height: calc(55vh - 260px)"
      @tab-click="tabClick"
    >
      <el-tab-pane label="常规" name="常规">
        <Info :parentId="current.id" :folderList="folderList" />
      </el-tab-pane>
      <el-tab-pane
        label="浏览"
        name="浏览"
        :disabled="!isPower(current, 'browse')"
      >
        <browse ref="browseRef"></browse>
      </el-tab-pane>
      <el-tab-pane label="历史版本" name="VersionRef">
        <Version :parentId="current.id" ref="VersionRef" />
      </el-tab-pane>

      <el-tab-pane label="发布记录" name="IssueRef">
        <Issue :parentId="current.id" ref="IssueRef" />
      </el-tab-pane>
      <el-tab-pane label="回收记录" name="ReceiveRef"
        ><Receive :parentId="current.id" ref="ReceiveRef"></Receive
      ></el-tab-pane>
      <el-tab-pane label="变更记录" name="变更记录" v-if="fileType === 0"
        ><Change :parentId="current.id"
      /></el-tab-pane>
      <!-- <el-tab-pane label="打印记录" name="打印记录"
        ><print></print
      ></el-tab-pane> -->
      <el-tab-pane label="工作流" name="bpmRef"
        ><bpm :parentId="current.id" ref="bpmRef"></bpm
      ></el-tab-pane>

      <el-tab-pane
        label="权限"
        name="权限"
        v-if="isCreateUserId(current) && !isCheckOut(current) && fileType === 0"
      >
        <Power style="" @powerSave="powerSave" ref="PowerRef" />
      </el-tab-pane>
      <el-tab-pane label="操作日志" name="ActionRef"
        ><Action :parentId="current.id" ref="ActionRef"
      /></el-tab-pane>
    </el-tabs>
    <!-- 编辑弹窗 -->
    <file-edit
      ref="fileEditRef"
      :parentId="parentData?.id"
      @done="reload"
      :lcyStatus="lcyStatus"
      :fileType="fileType"
    />
    <move ref="moveRef" @done="reload" />

    <file-editAll
      ref="fileEditAllRef"
      :parentId="parentData?.id"
      @done="reload"
      :fileType="fileType"
      :lcyStatus="lcyStatus"
    />
    <sendEdit ref="sendEditRef" @done="reload" :isAdd="false"></sendEdit>
    <process-submit-dialog
      :processSubmitDialogFlag.sync="processSubmitDialogFlag"
      v-if="processSubmitDialogFlag"
      ref="processSubmitDialogRef"
      @reload="reload"
    ></process-submit-dialog>
    <ele-modal
      width="70vw"
      :visible.sync="powerOpenShow"
      :close-on-click-modal="false"
      custom-class="ele-dialog-form"
      :maxable="true"
      append-to-body
    >
      <Power style="" @powerSave="powerSave" ref="PowerRefAll" />
    </ele-modal>
  </div>
</template>

<script>
  import fileSearch from './file-search.vue';
  import fileEdit from './file-edit.vue';
  import fileEditAll from './file-editAll.vue';
  import move from './move.vue';

  import Info from './info.vue';
  import folderInfo from './folderInfo.vue';
  import processSubmitDialog from '@/components/processSubmitDialog/processSubmitDialog.vue';
  import Version from './version.vue';
  import Power from './power/index.vue';
  import Issue from './issue.vue';
  import Action from './action.vue';
  import Change from './change.vue';
  import Receive from './receive.vue';
  import print from './print.vue';
  import bpm from './bpm.vue';
  import browse from './browse.vue';
  import sendEdit from '@/views/doc/issue_doc/components/edit.vue';

  import { isPower, isCheckOut, fileStatus, isCreateUserId } from '../util.js';
  import { getFile } from '@/api/system/file/index.js';
  import {
    fileDeleteAPI,
    filePageAPI,
    checkEnter,
    checkOut,
    fileUpdateAPI,
    updateLcyStatus,
    noUpdateLcyStatus,
    fileUpdateAllAPI
  } from '@/api/doc-manage';
  export default {
    components: {
      fileSearch,
      fileEdit,
      Info,
      Version,
      Power,
      Issue,
      Action,
      Change,
      folderInfo,
      processSubmitDialog,
      Receive,
      print,
      fileEditAll,
      bpm,
      sendEdit,
      browse,
      move
    },
    props: {
      // 上级
      parentData: {
        type: Object,
        default: () => {}
      },
      // 文件夹数据
      folderList: {
        type: Array,
        default: () => []
      },
      lcyStatus: {
        default: 1
      },
      fileType: '', //0：公共文档 1：个人文档 2：文档模板

      isPop: '',
      disabledTableList: {
        //已选择列表
        default: () => []
      }
    },
    //add:新建 fileEdit:修改  filePigeonhole:归档 fileUnPigeonhole:取消归档  fileIssue:发布 fileChange:变更 fileDel:删除

    data() {
      return {
        isPower,
        isCheckOut,
        isCreateUserId,
        powerOpenShow: false,
        selection: [],
        processSubmitDialogFlag: false,
        current: {},
        fileUrl: '',
        activeName: '常规',
        // 表格列配置
        columns: [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            selectable: (row, index) => {
              return (
                !this.disabledTableList
                  .map((item) => item.id)
                  .includes(row.id) &&
                row.reviewStatus != 1 &&
                row.status != 1
              );
            }
          },
          {label: '分类',
            prop: 'typeName',
            width: 180,
            align: 'center',
            fixed: 'left',
            showOverflowTooltip: true,
            formatter: () => {
              // 优先使用fullPath，如果没有则回退到name
              return this.parentData?.fullPath || this.parentData?.name || '';
            }
          },
          {
            label: '编码',
            prop: 'code',
            width: 180,
            align: 'center',
            fixed: 'left',
            showOverflowTooltip: true
          },
          {
            prop: 'name',
            label: '文档名称',
            align: 'center',
            slot: 'name',
            showOverflowTooltip: true,
            minWidth: 200
          },
          {
            prop: 'storagePath',
            label: '文件名称',
            align: 'center',

            showOverflowTooltip: true,
            minWidth: 200,
            formatter: (_row, _column, cellValue) => {
              return cellValue[0]?.name;
            }
          },
          {
            prop: 'version',
            label: '版本',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100
          },
          {
            prop: 'checkOutUserName',
            label: '检出人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100
          },
          {
            prop: 'checkOutStatus',
            label: '检出状态',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100,
            formatter: (_row, _column, cellValue) => {
              return cellValue == 1 ? '已检出' : '';
            }
          },
          {
            prop: 'checkOutTime',
            label: '检出时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 160
          },
          {
            prop: 'createUserName',
            label: '创建人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100
          },
          {
            prop: 'createTime',
            label: '创建时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 160
          },
          {
            prop: 'updateUserName',
            label: '修改人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100
          },
          {
            prop: 'updateTime',
            label: '修改时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 160
          },
          {
            prop: 'sizeUnit',
            label: '文档大小',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100
          },
          {
            prop: 'status',
            label: '状态',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100,
            formatter: (_row, _column, cellValue) => {
              return fileStatus(cellValue);
            }
          },
          {
            align: 'center',
            label: '审核状态',
            prop: 'reviewStatus',
            width: 100,
            formatter: (_row, _column, cellValue) => {
              return cellValue == 0
                ? '未提交'
                : cellValue == 1
                ? '审核中'
                : cellValue == 2
                ? '已审核'
                : '审核不通过';
            }
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 200,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true,
            fixed: 'right'
          }
        ],
        // 是否显示编辑弹窗
        showEditFlag: false
      };
    },
    created() {},

    methods: {
      /* 表格数据源 */
      datasource({ page, limit, where, order }) {
        if (this.lcyStatus) {
          this.current = {};
          return filePageAPI({
            ...where,
            ...order,
            pageNum: page,
            size: limit,
            directoryId: this.parentData?.id,
            lcyStatus: this.lcyStatus,
            fileType: this.fileType,
            isQueryAll: this.$hasPermission('fm:doc:viewAll') ? 1 : ''
          });
        }
      },
      /* 刷新表格 */
      reload(where) {
        this.$refs.table &&
          this.$refs.table.reload({ pageNum: 1, where: where });
      },

      processSubmit(powerData) {
        if (this.selection.length == 0 || this.selection.length > 1) {
          this.$message.warning('请选择一条数据');
          return;
        }
        if (this.selection[0].checkOutUserName) {
          this.$message.warning(
            this.selection[0].name +
              '已被' +
              this.selection[0].checkOutUserName +
              '检出 无法废止'
          );
          return;
        }
        if (this.powerFn(powerData)) {
          return;
        }
        if (isCheckOut(this.selection[0])) {
          this.$message.warning(
            this.selection[0].name +
              '已被' +
              this.selection[0].checkOutUserName +
              '检出 无法发起流程'
          );
          return;
        }
        this.processSubmitDialogFlag = true;
        this.$nextTick(() => {
          this.selection[0]['businessKey'] = 'fm_file_repeal_approve';
          this.$refs.processSubmitDialogRef.init(this.selection[0]);
        });
      },
      //发布模板
      processSubmit_template() {
        if (this.selection.length == 0 || this.selection.length > 1) {
          this.$message.warning('请选择一条数据');
          return;
        }
        if (this.selection[0].checkOutUserName) {
          this.$message.warning(
            this.selection[0].name +
              '已被' +
              this.selection[0].checkOutUserName +
              '检出 无法发布'
          );
          return;
        }
        if (this.selection[0].status == 2) {
          this.$message.warning('模板已发布');
          return;
        }
        this.processSubmitDialogFlag = true;
        this.$nextTick(() => {
          this.selection[0]['businessKey'] = 'fm_file_template_approve';
          this.$refs.processSubmitDialogRef.init(this.selection[0]);
        });
      },
      selectionClick(data) {
        this.current = data.reverse()[0] || {};
        this.rowClick(this.current);
        this.$refs.table.setCurrentRow(this.current);
      },
      rowClick(row) {
        this.$nextTick(() => {
          this.$refs.browseRef && this.$refs.browseRef.setFileUrl(row);
          this.$refs.PowerRef &&
            this.$refs.PowerRef.setTableList(row.userAuthority);
        });
      },
      /* 显示编辑 */
      openEdit(type, row = '', powerData) {
        if (type != 'add') {
          if (!row.checkOutUserName) {
            this.$message.warning('请先检出在修改');
            return;
          }
          if (isCheckOut(this.current)) {
            this.$message.warning(
              this.current.name +
                '已被' +
                this.current.checkOutUserName +
                '检出 无法修改'
            );
            return;
          }
        }
        if (this.powerFn(powerData, row)) {
          return;
        }

        this.$refs.fileEditRef.open(type, row, this.folderList);
      },
      /* 显示编辑 */
      openEditAll(powerData) {
        if (this.powerFn(powerData)) {
          return;
        }
        this.$refs.fileEditAllRef.open(this.folderList);
      },
      tabClick(data) {
        if (this.$refs[data.name] && this.$refs[data.name].init) {
          this.$refs[data.name].init();
        }
      },
      parenOpen(type, powerData) {
        if (this.powerFn(powerData)) {
          return;
        }
        this.$emit('parenOpen', type);
      },
      // async success(current) {
      //   await this.reload();
      //   this.current = current;
      //   this.$nextTick(() => {
      //     this.$refs.PowerRef &&
      //       this.$refs.PowerRef.setTableList(this.current.userAuthority);
      //   });
      // },
      //权限判断
      powerFn({ power, dataKey, isArr }, row) {
        let arr = isArr ? this.selection : [];
        if (!isPower(row || this[dataKey], power, arr)) {
          this.$message.warning('抱歉，您没有操作权限！');
          return true;
        }
      },
      powerOpen() {
        if (!this.selection?.length) {
          this.$message.warning('请选择一条数据！');
          return;
        }

        let createUserS=[],checkOutS=[]
        this.selection.forEach(item=>{
          if(!isCreateUserId(item)){
            createUserS.push(item.name)
          }
          if(isCreateUserId(item)){
            checkOutS.push(item.name)
          }
        })
        if(createUserS.toString()){
          this.$message.warning(createUserS+'您不是创建人，无权限修改！');
          return;
        }
        if(!checkOutS.toString()){
          this.$message.warning(checkOutS+'已被检出 无法修改！');
          return;
        }
        this.powerOpenShow = true;
        this.$nextTick(()=>{
          this.$refs.PowerRefAll.setTableList([])
        })
                
      },
      //权限保存
      powerSave(tableList) {
        if (this.powerOpenShow) {
          let data = this.selection.map((item) => {
            return {
              id: item.id,
              userAuthority: tableList,
              authority: 1
            };
          });
          fileUpdateAllAPI(data).then((msg) => {
            this.reload();
          });
          this.powerOpenShow = false;
        } else {
          fileUpdateAPI({
            id: this.current.id,
            userAuthority: tableList,
            authority: 1
          }).then((msg) => {
            this.reload();
          });
        }
      },
      //检出
      checkOut(powerData) {
        if (this.selection.length == 0) {
          this.$message.warning('请选择一条数据');
          return;
        }
        if (this.powerFn(powerData)) {
          return;
        }
        checkOut({
          id: this.selection[0].id,
          checkOutStatus: 1
        }).then((msg) => {
          this.reload();
        });
      },
      //检入
      checkEnter(powerData) {
        if (this.selection.length == 0) {
          this.$message.warning('请选择一条数据');
          return;
        }
        if (this.powerFn(powerData)) {
          return;
        }
        checkEnter({
          id: this.selection[0].id,
          checkOutStatus: 0
        }).then((msg) => {
          this.reload();
        });
      },
      done() {
        this.$refs.table.reRenderTable();
        this.selection = [];
      },
      //下载
      getFile(powerData) {
        if (this.selection.length == 0) {
          this.$message.warning('请选择一条数据');
          return;
        }
        if (this.powerFn(powerData)) {
          return;
        }

        this.selection.forEach((item) => {
          getFile(
            { objectName: item.storagePath[0].storePath },
            item.storagePath[0].name
          );
        });
      },
      updateLcyStatus(powerData) {
        if (this.selection.length == 0 || this.selection.length.length > 1) {
          this.$message.warning('请选择一条数据');
          return;
        }
        if (this.selection[0].checkOutUserName) {
          this.$message.warning(
            this.selection[0].name +
              '已被' +
              this.selection[0].checkOutUserName +
              '检出 无法归档'
          );
          return;
        }
        if (this.powerFn(powerData)) {
          return;
        }
        updateLcyStatus({ id: this.selection[0].id }).then((res) => {
          this.reload();
        });
      },
      noUpdateLcyStatus(powerData) {
        if (this.selection.length == 0 || this.selection.length.length > 1) {
          this.$message.warning('请选择一条数据');
          return;
        }
        if (this.powerFn(powerData)) {
          return;
        }
        noUpdateLcyStatus({ id: this.selection[0].id }).then((res) => {
          this.reload();
        });
      },
      // selectionChange( selection){
      //   console.log( selection,' selection')
      //   let data=selection[selection.length-1]
      //   this.current=data||this.current
      //   this.rowClick(this.current)
      // },
      /* 删除 */
      remove(row, powerData) {
        if (this.powerFn(powerData, row)) {
          return;
        }
        if (!row.checkOutUserName) {
          this.$message.warning('请先检出在删除');
          return;
        }

        if (isCheckOut(this.current)) {
          this.$message.warning(
            this.current.name +
              '已被' +
              this.current.checkOutUserName +
              '检出 无法删除'
          );
          return;
        }
        const loading = this.$loading({ lock: true });
        fileDeleteAPI([row.id])
          .then((msg) => {
            loading.close();
            this.$message.success('操作成功');
            this.reload();
          })
          .catch((e) => {
            loading.close();
            // this.$message.error(e.message);
          });
      },
      //发布
      openSendEdit(powerData) {
        if (this.selection.length == 0) {
          this.$message.warning('请选择一条数据');
          return;
        }
        if (this.selection[0].checkOutUserName) {
          this.$message.warning(
            this.selection[0].name +
              '已被' +
              this.selection[0].checkOutUserName +
              '检出 无法发布'
          );
          return;
        }
        if (this.powerFn(powerData)) {
          return;
        }
        this.$refs.sendEditRef.open('add', '', this.selection, this.fileType);
      },
      //移动
      move() {
        if (this.selection.length == 0) {
          this.$message.warning('请选择一条数据');
          return;
        }
        if (this.selection[0].checkOutUserName) {
          this.$message.warning(
            this.selection[0].name +
              '已被' +
              this.selection[0].checkOutUserName +
              '检出 无法移动'
          );
          return;
        }
        this.$refs.moveRef.open(this.selection[0]);
      },
      getTableList() {
        return JSON.parse(JSON.stringify(this.selection));
      }
    }
  };
</script>
<style scoped lang="scss">
  :deep(.el-tabs__content) {
    height: calc(100% - 39px);
    overflow: auto;
  }
  :deep(.ele-table-tool-title-content) {
    display: contents;
  }
</style>
