<template>
  <el-container
    class="fullheight"
    style="border: 1px solid #eee"
  >
    <el-aside
      :width="isShowAside ? '200px' : '0px'"
      style="border-right: 1px solid #eee;transition: all 0.2s cubic-bezier(0, 0, 0.2, 1);"
    >
      <!-- <file-tree ref='tree' @load="loadData"></file-tree> -->
      <div class="tree-header flex">
        <el-input
          placeholder="请输入"
          v-model="filterText"
          clearable
        >
          <i
            slot="prefix"
            class="el-input__icon el-icon-search"
          ></i>
        </el-input>
        <div :class="
            isIeExplorer
              ? 'tree-button-group is-ie-explorer flex'
              : 'tree-button-group flex'
          ">
          <i
            :class="{'icon-zhankai': !isExpand, 'icon-shouqi': isExpand}"
            :title="isExpand ? '收起' : '展开'"
            @click="handleExpandCollapse"
          />
          <i
            class="icon-sync"
            :class="{'icon-spin': loading}"
            title="刷新"
            @click="refresh"
          />
        </div>
      </div>
      <el-tree
        :data="treeData"
        :props="props"
        :load="loadNode"
        :filter-node-method="filterNode"
        :default-checked-keys="defaultCheckedKeys"
        :default-expanded-keys="defaultExpandedKeys"
        node-key="id"
        @node-click="handleNodeClick"
        accordion
        ref="tree"
        highlight-current
        style="background: #fafafa"
      >
        <span
          class="custom-tree-node"
          slot-scope="{node, data}"
        >

          <span>
            <i
              class="el-icon-s-order icon"
              style="padding-right: 4px"
            ></i>{{node.label }}</span>
          <el-dropdown
            @command="handleCommand"
            v-if="data.code=='root'"
          >
            <div class="el-dropdown-link">
              <i
                class="icon-more"
                title="更多操作"
              />
            </div>
            <el-dropdown-menu
              slot="dropdown"
              v-methodauth="'file_type_add'"
            >
              <el-dropdown-item
                icon="el-icon-plus"
                :command="{node:node,data,action:'add'}"
              >添加</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-dropdown
            @command="handleCommand"
            v-else
          >
            <div class="el-dropdown-link">
              <i
                class="icon-more"
                title="更多操作"
              />
            </div>
            <el-dropdown-menu
              slot="dropdown"
              v-methodauth="'file_type_add'"
            >
              <el-dropdown-item
                icon="el-icon-plus"
                :command="{node:node,data,action:'add'}"
                v-methodauth="'file_type_add'"
              >添加</el-dropdown-item>
              <el-dropdown-item
                icon="el-icon-edit"
                :command="{node:node,data,action:'edit'}"
                v-methodauth="'file_type_update'"
              >编辑</el-dropdown-item>

              <el-dropdown-item
                icon="el-icon-delete"
                :command="{node:node,data,action:'delete'}"
                divided
                v-methodauth="'file_type_del'"
              >删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </span>
      </el-tree>
      <el-dialog
        class="addDialog"
        :title="title"
        :visible.sync="dialogVisible2"
        width="600px"
        top='8vh'
        :before-close="handleClose"
      >
        <el-form
          ref="form"
          data-vv-scope="form"
          status-icon
          :model="treeForm"
          :rules="treeRules"
          label-width="100px"
        >
          <el-form-item
            label="父节点"
            prop="pName"
          >
            <el-input
              v-model="treeForm.pName"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item
            label="分类名称"
            prop="name"
          >
            <el-input
              v-model="treeForm.name"
              placeholder="请输入内容"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="分类编码"
            prop="code"
          >
            <el-input
              v-model="treeForm.code"
              placeholder="请输入编码"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
        <span
          slot="footer"
          class="dialog-footer"
        >
          <el-button @click="handleClose">取 消</el-button>
          <el-button
            type="primary"
            @click="handleConfirm"
          >确 定</el-button>
        </span>
      </el-dialog>
    </el-aside>
    <el-container style="background-color: #fff;">
      <div
        class="shrink"
        @click="handleHideMenu"
      ><i :class="isShowAside ? 'el-icon-arrow-left': 'el-icon-arrow-right'"></i></div>
      <div style="width:100%;height:100%">
        <at-table
          @load="loadData"
          :data="data"
          :page-result="pageResult"
          ref="AtTable"
          :dialogTitle="dialogTitle"
          :dialogVisible="dialogVisible"
          :elAuth="'file_update'"
          @select-all="handleSelect"
          @select="handleSelect"
          @handleDialogCancel="handleDialogCancel"
          @handleDialogClose="handleDialogClose"
          @handleDialogSubmit="handleDialogSubmit"
          @row-dblclick="handleRowDBClick"
        >
          <template v-slot:searchInput>
            <el-form
              ref="searchForm"
              :model="searchForm"
              label-width="80px"
              class="search-top"
              @submit.native.prevent
            >
              <!-- <project-info-selector
            v-model="searchForm.projectId"
            @keyup.enter.native="handleSearch"
          ></project-info-selector> -->
              <el-input
                v-model="searchForm.documentNumber"
                placeholder="请输入编号(文号)"
                clearable
                @keyup.enter.native="handleSearch"
              ></el-input>
              <el-input
                v-model="searchForm.establishmentName"
                placeholder="请输入名称"
                clearable
                @keyup.enter.native="handleSearch"
              ></el-input>
              <el-button
                size="small"
                @click="handleSearch"
                type="primary"
                class="el-icon-search search-btn"
              >查询</el-button>
              <el-button
                size="small"
                @click="handleReset"
                type="primary"
                plain
                class="el-icon-refresh"
              >重置</el-button>
            </el-form>
          </template>
          <template v-slot:operationBtn>
            <el-button
              size="small"
              type="primary"
              @click="handleAdd"
              icon="el-icon-plus"
              v-methodauth="'file_add'"
            >添加</el-button>
            <ht-delete-button
              :url="deleteUrl"
              :htTable="$refs.AtTable"
              :requestMethod="'POST'"
              v-methodauth="'file_del'"
            >删除</ht-delete-button>
            <!-- <import-file :importData="importData" @load="load"></import-file>
        <el-button
          size="small"
          type="primary"
          @click="handleExport"
          icon="el-icon-download"
          plain
          style="margin-left: 10px"
          >导出</el-button
        > -->
          </template>
          <template>
            <el-table-column
              type="selection"
              width="55"
              align="center"
            >
            </el-table-column>
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="60"
            >
            </el-table-column>
            <!-- <el-table-column
          prop="projectInfo.projectCode"
          label="项目代码"
          align="center"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <el-table-column
          prop="projectName"
          label="项目名称"
          align="center"
          :show-overflow-tooltip="true"
        >
        </el-table-column> -->
            <el-table-column
              prop="documentNumber"
              label="编号(文号)"
              align="center"
              min-width="100"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="establishmentName"
              label="文件名称"
              align="center"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="establishmentDate"
              label="批复日期"
              align="center"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="describe"
              label="描述"
              align="center"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="remarks"
              label="备注"
              align="center"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
          </template>
          <!-- 弹框 -->
          <template v-slot:dialogContent>
            <el-form
              ref="ruleForm"
              data-vv-scope="form"
              :model="form"
              :rules="rules"
              label-width="100px"
              v-if="dialogVisible"
            >
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="文件名称"
                    prop="establishmentName"
                  >
                    <el-input
                      v-model="form.establishmentName"
                      placeholder="请输入文件名称"
                      clearable
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item
                    label="编号(文号)"
                    prop="documentNumber"
                  >
                    <el-input
                      v-model="form.documentNumber"
                      placeholder="请输入编号(文号)"
                      clearable
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item
                    label="批复日期"
                    prop="establishmentDate"
                  >
                    <el-date-picker
                      v-model="form.establishmentDate"
                      type="date"
                      placeholder="请选择批复日期"
                      class="basisType"
                      value-format="yyyy-MM-dd"
                      format="yyyy-MM-dd"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item
                label="描述"
                prop="describe"
              >
                <el-input
                  v-model="form.describe"
                  placeholder="请输入描述"
                  type="textarea"
                ></el-input>
              </el-form-item>
              <file-table
                @handleFile="accessoryInfo"
                :file="form.accessoryInfo"
              />
            </el-form>
          </template>
          <!-- <project-info-dialog
        ref="project"
        :single="true"
        @select="handleSelectProject"
      ></project-info-dialog> -->
        </at-table>
      </div>
    </el-container>
  </el-container>
</template>
<script>
import req from '@/request.js'
export default {
  name: 'FileLibrary',
  data() {
    return {
      title: '',
      treeForm: {},
      dialogVisible2: false, //添加树型节点
      typeKey: '',
      filterText: '', //树型搜索内容
      isIeExplorer: false, //
      isExpand: false,
      loading: false,
      props: {
        label: 'name',
        code: 'code',
        id: 'id',
        children: 'children',
        pcode: 'pcode',
        isLeaf: 'leaf' // 指定节点是否为叶子节点，仅在指定了 lazy 属性的情况下生效
      },
      treeData: [{name: '文件库管理', code: 'root', id: '1', children: []}],
      defaultCheckedKeys: [], //默认选中节点
      defaultExpandedKeys: ['1'], //默认展开节点
      node: '',
      resolve: '',
      //表单验证
      treeRules: {
        pName: {
          required: true,
          message: '请输入',
          trigger: 'blur'
        },
        name: {
          required: true,
          message: '请输入',
          trigger: 'blur'
        },
        code: {
          required: true,
          message: '请输入',
          trigger: 'blur'
        }
      },
      //  importData: {
      //   title: '文件导入',
      //   templateName: '文件模板.xls',
      //   downloadUrl: './../static/excel/AnnualPlan.xlsx',
      //   importUrl:
      //     window.context.cqxy +
      //     '/biz/projectApproval/decisionBasis/decisionAnnualPlan/v1/importExcelData',
      //   projectId: '',
      // },
      projectObj: [], //获取的所有项目数组
      searchForm: {
        documentNumber: '',
        establishmentName: '',
        typeId: ''
      }, //顶部搜索参数
      data: [],
      pageResult: {
        page: 1,
        pageSize: 20,
        total: 0
      },
      form: {
        documentNumber: '',
        establishmentName: '',
        establishmentDate: '',
        describe: '',
        accessoryInfo: [],
        typeInfo: {}
      },
      dialogVisible: false, //表格
      dialogTitle: '添加',
      //表单验证
      rules: {
        // documentNumber: {
        //   required: true,
        //   message: '请输入',
        //   trigger: 'blur'
        // },
        establishmentName: {
          required: true,
          message: '请输入',
          trigger: 'blur'
        }
        // establishmentDate: {
        //   required: true,
        //   message: '请输入',
        //   trigger: 'blur'
        // }
      },
      typeId: '',
      isShowAside: true //左侧菜单默认显示
    }
  },
  computed: {
    deleteUrl: function() {
      return window.context.cqxy + '/biz/fileLibrary/v1/delete'
    }
  },

  mounted() {
    this.getTreeData()
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    handleReset() {
      this.searchForm.documentNumber = ''
      this.searchForm.establishmentName = ''
      this.$refs['searchForm'].resetFields()
      this.pageResult = {
        page: 1,
        pageSize: 20,
        total: 0
      }
      this.$nextTick(() => {
        this.$refs.AtTable.load()
      })
    },
    //导入后重新加载数据
    load() {
      this.$refs.AtTable.load()
    },
    //获取附件信息
    accessoryInfo(info) {
      let newInfo = []
      info.forEach(item => {
        item.projectId = 'fileLibrary'
        item.group = 'fileLibrary'
        newInfo.push(item)
      })
      this.form.accessoryInfo = newInfo
    },
    //查询
    handleSearch() {
      this.pageResult = {
        page: 1,
        pageSize: 20,
        total: 0
      }
      this.$nextTick(() => {
        this.$refs.AtTable.load()
      })
    },
    afterSaveData() {
      setTimeout(() => {
        this.dialogVisible = false
        this.$refs.AtTable.load()
        this.form.documentNumber = ''
        this.form.establishmentName = ''
        this.form.establishmentDate = ''
        this.form.describe = ''
        this.form.accessoryInfo = []
      }, 500)
    },
    handleAdd() {
      let obj = {
        documentNumber: '',
        establishmentName: '',
        establishmentDate: '',
        describe: '',
        accessoryInfo: []
      }
      this.form = {...this.form, ...obj}
      // this.form.documentNumber = ''
      // this.form.establishmentName = ''
      // this.form.establishmentDate = ''
      // this.form.describe = ''
      // this.form.accessoryInfo = []
      if (this.form.typeInfo && this.form.typeInfo.id) {
        this.dialogTitle = '添加'
        this.dialogVisible = true
      } else {
        this.$message('请选择一条子节点')
      }
    },
    handleRowDBClick(data) {
      // if (this.getMethodauth('file_update')) {
        this.dialogTitle = '修改'
        this.dialogVisible = true
        this.form = data
      // }
    },

    handleSelect(selection) {},
    //取消
    handleDialogCancel() {
      this.dialogVisible = false
      // this.form.documentNumber = ''
      // this.form.establishmentName = ''
      // this.form.establishmentDate = ''
      // this.form.describe = ''
      // this.form.accessoryInfo = []
    },
    //关闭窗口
    handleDialogClose(val) {
      this.dialogVisible = false
      this.form.documentNumber = ''
      this.form.establishmentName = ''
      this.form.establishmentDate = ''
      this.form.describe = ''
      this.form.accessoryInfo = []
    },
    //提交保存
    handleDialogSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid && this.form.accessoryInfo.length !== 0) {
          this.loading = true
          this.form.accessoryInfo.forEach(item => {
            if (item.id) {
              delete item.id
            }
          })
          this.$http
            .post('${cqxy}/biz/fileLibrary/v1/save', this.form)
            .then(res => {
              if (res.status == 200) {
                setTimeout(() => {
                  this.$message.success(res.data.message)
                  this.afterSaveData()
                }, 500)
              } else {
                this.$message.error(res.data.message)
              }
              this.loading = false
            })
        } else if (this.form.accessoryInfo.length === 0) {
          this.$message.error('至少上传一个附件')
        } else {
          this.$message({
            message: '*号必填项,不能为空!',
            type: 'warning'
          })
          return false
        }
      })
    },

    loadData(param, cb) {
      let query = []
      let search = {
        type_id_: this.searchForm.typeId,
        document_number_: this.searchForm.documentNumber,
        establishment_name_: this.searchForm.establishmentName
      }
      if (this.dialogVisible) {
        search.type_id_ = this.form.typeId
      }
      for (let i in search) {
        if (search[i]) {
          query.push({
            group: 'advance',
            operation: 'LIKE',
            property: i,
            relation: 'AND',
            value: search[i]
          })
        }
      }
      if (param.querys && param.querys.length) {
        param.querys.push(...query)
      } else {
        param.querys = query
      }

      this.$http
        .post('${cqxy}/biz/fileLibrary/v1/page', param)
        .then(
          resp => {
            let response = resp.data.value
            this.data = response.rows
            this.pageResult = {
              page: response.page,
              pageSize: response.pageSize,
              total: response.total
            }
          },
          error => {
            reject(error)
          }
        )
        .finally(() => {
          if (cb) {
            cb()
          }
        })
    },
    handleClose() {
      this.dialogVisible2 = false
    },
    //初始节点
    getTreeData() {
      let pcode = 'root'
      let formData = new FormData()
      formData.append('pCode', pcode)
      this.$http
        .post('${cqxy}/biz/fileLibrary/type/v1/getByParentId', formData)
        .then(res => {
          let resp = res.data.value
          this.treeData[0].children = resp
        })
    },
    //点击节点
    handleNodeClick(data) {
      this.searchForm = {}
      this.form = {}
      //根组件查询全部节点数据
      if (data.code && data.code == 'root') {
        this.$refs.AtTable.load()
      } else {
        if (data.children && data.children.length == 0) {
          this.searchForm.typeId = data.id
          this.form.typeId = data.id
          this.form.typeInfo = {...data}
          this.$refs.AtTable.load()
        }
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data[this.props.label].indexOf(value) !== -1
    },
    loadNode(node, resolve) {},
    // 树状菜单的全部展开和收起
    handleExpandCollapse() {
      let elTree = this.$refs.tree
      for (var i = 0; i < elTree.store._getAllNodes().length; i++) {
        elTree.store._getAllNodes()[i].expanded = this.isExpand
      }
      this.isExpand = !this.isExpand
    },
    //树状刷新
    refresh() {
      this.loading = true
      this.$emit('refresh', () => {
        this.loading = false
        this.filterText = ''
        this.getTreeData()
      })
      setTimeout(() => {
        this.loading = false
        this.filterText = ''
      }, 2000)
    },
    closeBefore() {
      setTimeout(() => {
        this.dialogVisible2 = false
        this.getTreeData()
      }, 500)
    },
    //确定添加节点
    handleConfirm() {
      this.$http
        .post('${cqxy}/biz/fileLibrary/type/v1/batchSave', this.treeForm)
        .then(res => {
          if (res.data.state) {
            this.$message.success(res.data.message)
            this.closeBefore()
          } else {
            this.$message.error(res.data.message)
            this.dialogVisible2 = false
          }
        })
    },
    //树状更多下拉操作
    handleCommand(command) {
      let node = command.node
      let data = command.data
      let action = command.action
      switch (action) {
        case 'add':
          this.dialogVisible2 = true
          this.title = '添加'
          this.treeForm = {
            pName: data.name,
            pcode: data.code,
            code: '',
            name: '',
            hasChildren: 0,
            children: []
          }
          break
        case 'edit':
          this.dialogVisible2 = true
          this.title = '编辑'
          if (data.pcode == 'root') {
            this.treeForm = {pName: '文件库管理', ...data}
          } else {
            this.treeForm = {pName: data.name, ...data}
          }
          break
        case 'delete':
          this.del(data)
          break
        default:
          break
      }
    },
    del(data) {
      this.$confirm('是否继续删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          let formData = new FormData()
          formData.append('ids', data.id)
          this.$http
            .post('${cqxy}/biz/fileLibrary/type/v1/delete', formData)
            .then(res => {
              if (res.data.state) {
                this.$message.success(res.data.message)
                this.closeBefore()
              } else {
                this.$message.error(res.data.message)
                this.dialogVisible2 = false
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    //隐藏目录
    handleHideMenu() {
      this.isShowAside = !this.isShowAside
    },
    //返回一个boolean类型，是否显示列表按钮
    getMethodauth(elAuth) {
      let allMethod = window.sessionStorage.allMethod
      let methodAuth = window.sessionStorage.methodAuth
      let allMethodArray = allMethod && allMethod.split(',')
      let methodAuthArray = methodAuth && methodAuth.split(',')
      // 无权限则隐藏按钮
      if (
        methodAuthArray &&
        methodAuthArray.includes(elAuth) &&
        allMethodArray &&
        allMethodArray.includes(elAuth)
      ) {
        return true
      } else {
        return false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/common.scss';
.form-empty {
  position: absolute;
  text-align: center;
  width: 300px;
  font-size: 20px;
  top: 200px;
  left: 50%;
  margin-left: -150px;
  color: rgba(0, 0, 0, 0.5);
}
div.tree-header {
  min-height: 30px;
  /deep/ .el-input--small .el-input__inner {
    border: none;
  }
}
div.tree-header >>> .el-input__inner {
  border-width: 0;
  padding-right: 0;
}
div.tree-button-group i {
  cursor: pointer;
  display: inline;
  font-size: 18px;
  font-weight: bold;
  margin-right: 10px;
}
div.tree-button-group i:hover {
  color: lightcoral;
}
.tree-button-group {
  margin-left: 10px;
}
.is-ie-explorer {
  margin-right: 25px;
}
.flex {
  display: flex;
}
>>> .el-dropdown {
  display: none;
}
>>> .el-header {
  border-bottom: 1px solid #ccc;
  button {
    float: right;
    margin-left: 5px;
  }
}

>>> .el-tree-node__content:hover .el-dropdown {
  display: inline-block;
}

>>> .navbar-collapse {
  position: relative;
  top: -60%;
  cursor: pointer;
  width: 20px;
}

>>> .navbar-collapse.navbar-collapse-right {
  top: 40%;
}

>>> .navbar-collapse:hover {
  transform: scale(1) translateY(2px);
}

>>> .navbar-collapse:hover .navbar-collapse-arrow {
  color: #333333;
}

>>> .navbar-collapse-arrow {
  position: relative;
  top: 38%;
  right: 15px;
  font-size: 18px;
  color: #a8a8a8;
}

>>> .navbar-collapse-bg {
  transition: all 0.12s ease;
  height: 50px;
  border-bottom: 8px solid transparent;
  border-right: none;
  border-left: 12px solid #ebebeb;
  border-top: 8px solid transparent;
  opacity: 0.9;
}
.el-aside-footer {
  position: absolute;
  bottom: 18px;
}

.custom-tree-node {
  width: calc(100% - 40px);
  // flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.icon-more {
  font-size: 12px;
  color: #909399;
}
.custom-tree-node .icon-more {
  visibility: hidden;
  font-weight: bold;
}

.custom-tree-node:hover .icon-more {
  visibility: visible;
}
.addDialog /deep/ .el-dialog__body {
  padding-left: 80px;
  padding-right: 80px;
}
.shrink {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  height: 50px;
  border-bottom: 8px solid transparent;
  border-right: none;
  border-left: 12px solid #ebebeb;
  border-top: 8px solid transparent;
  opacity: 0.9;
  cursor: pointer;
  i {
    position: absolute;
    top: 50%;
    left: -14px;
    transform: translateY(-50%);
  }
  &:hover {
    color: #21aeff;
  }
}
</style>