<template>
  <div class="dashboard-container">
    <div class="search-content">
      <el-input style="width: 220px;" v-model="searchData.deptName" placeholder="请输入部门名称" clearable></el-input>
      <el-select style="width: 220px;" clearable placeholder="请选择状态" v-model="searchData.status">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <div class="search-btn">
        <!-- <el-button type="primary" @click="searchBtn()">搜索</el-button>
        <el-button @click="reset()">重置</el-button> -->
        <div class="search" @click="searchBtn()">查询</div>
        <div class="reset" @click="reset()">重置</div>
      </div>
    </div>
    <div class="table-content">
      <div style="width: 100%;height: 30px;">
        <div class="btn" @click="addTopDept()">
          <span class="icon font_family">&#xe604;</span>
          新增
        </div>
        <div class="btn" @click="exportDeptList()">
          <span class="icon font_family">&#xe605;</span>
          <a>导出</a>
        </div>
      </div>
      <el-table :indent="50" ref="tableRef" v-loading="loading" :data="deptList" row-key="deptId"
        :default-expand-all="true" highlight-current-row style="width: 100%"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="deptName" label="部门名称" width="320"></el-table-column>
        <el-table-column prop="deptCode" label="部门编码"></el-table-column>
        <el-table-column prop="orderNum" label="排序" width="200"></el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template slot-scope="scope">
            <div class="startUsing" v-if="scope.row.status == '1'">启用</div>
            <div class="Deactivate" v-else>停用</div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="remarks" label="备注" show-overflow-tooltip></el-table-column>         -->
        <el-table-column label="创建时间" align="center" prop="createTime" width="200">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
          <template slot-scope="scope">
            <el-button type="text" style="color: #2866DD;font-size: 14px;"
              @click="handleUpdate(scope.row, scope.row.status)">修改</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="text" style="color: #2866DD;font-size: 14px" @click="handleAdd(scope.row)"
              v-hasPermi="['system:dept:add']">新增</el-button>
            <el-divider direction="vertical"></el-divider>
            <el-button type="text" style="color: #2866DD;font-size: 14px" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
        <template v-slot:empty>
          <svg-icon icon-class="search-none" style="font-size: 64px" />
          <p>暂无数据</p>
        </template>
      </el-table>
      <editDeptDialog :editDeptData="editDeptData" @updateDept="updateDept"></editDeptDialog>
      <addDeptDialog :addDeptData="addDeptData" v-if="addDeptData.dialogVisible" @addDeptBtn="addDeptBtn"></addDeptDialog>
      <addTopDeptDialog v-if="addTopDeptData.dialogVisible" :addTopDeptData="addTopDeptData"
        @addTopDeptBtn="addTopDeptBtn"></addTopDeptDialog>
    </div>
  </div>
</template>

<script>
import { Message } from "element-ui";
import { mapGetters } from 'vuex'
import { getDeptList, delDept, updateDept, exportDeptList, addDept } from '@/api/sysManage'
import editDeptDialog from './components/editDeptDialog.vue'
import addDeptDialog from './components/addDeptDialog.vue'
import addTopDeptDialog from './components/addTopDeptDialog.vue'
export default {
  name: 'home',
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  components: {
    editDeptDialog,
    addDeptDialog,
    addTopDeptDialog
  },
  data() {
    return {
      searchData: {
        deptName: '',
        status: ''
      },
      loading: true,
      deptList: [],
      statusOptions: [
        {
          label: '启用',
          value: '1'
        },
        {
          label: '停用',
          value: '2'
        }
      ],
      editDeptData: {
        dialogVisible: false,
        data: {}
      },
      addDeptData: {
        dialogVisible: false,
        data: {}
      },
      addTopDeptData: {
        dialogVisible: false,
      }
    }
  },
  created() {
    this.getDeptList(this.searchData)
  },
  methods: {
    handleUpdate(row, status) {
      if (status == "1") {
        row.status = true
      } else {
        row.status = false
      }
      this.editDeptData.data = { ...row }
      this.editDeptData.dialogVisible = true
    },
    handleAdd(row) {
      this.addDeptData.data = row
      this.addDeptData.dialogVisible = true
    },
    addTopDept() {
      this.addTopDeptData.dialogVisible = true
    },
    addDeptBtn(payload) {
      let updateData = { ...payload }
      delete updateData.parentName
      if (updateData.status) {
        updateData.status = 1
      } else {
        updateData.status = 2
      }
      addDept(updateData).then(res => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '添加成功！'
          });
          this.getDeptList(this.searchData)
          this.addDeptData.dialogVisible = false
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      })
    },
    addTopDeptBtn(payload) {
      let updateData = { ...payload }
      if (updateData.status) {
        updateData.status = 1
      } else {
        updateData.status = 2
      }
      delete updateData.parentName
      addDept(updateData).then(res => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '添加成功！'
          });
          this.getDeptList(this.searchData)
          this.addTopDeptData.dialogVisible = false
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      })
    },
    exportDeptList() {
      let params = {
        deptName:this.searchData.deptName,
        status:this.searchData.status
      }
      exportDeptList(params).then(res => {
    
        if (res.type == "application/json") {
          const reader = new FileReader(); 
          reader.readAsText(res, 'utf-8'); 
          reader.onload = function () {
            const msg = JSON.parse(reader.result);
            if(msg.code == 200){
              const blob = new Blob([res], { type: 'text/plain;charset=utf-8' });
              const url = window.URL.createObjectURL(blob);
              const a = document.createElement('a');
              a.href = url;
              a.download = '部门信息.xlsx';
              a.click();
              window.URL.revokeObjectURL(url);
            } else{
              Message({
                type: 'error',
                message: msg.msg
              });
            }      
          }
        }else{
          const blob = new Blob([res], { type: 'text/plain;charset=utf-8' });
          const url = window.URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = '部门信息.xlsx';
          a.click();
          window.URL.revokeObjectURL(url);
        }



      })
    },
    getDeptList(params) {
      getDeptList(params).then(res => {
        this.loading = true;
        if (res.code == 200) {
          this.deptList = this.handleTree(res.data, "deptId")
          // this.deptList = res.data
          this.loading = false;
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    parseTime(time, pattern) {
      if (arguments.length === 0 || !time) {
        return null
      }
      const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
      let date
      if (typeof time === 'object') {
        date = time
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time)
        } else if (typeof time === 'string') {
          time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000
        }
        date = new Date(time)
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      }
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
        if (result.length > 0 && value < 10) {
          value = '0' + value
        }
        return value || 0
      })
      return time_str
    },
    //删除部门
    handleDelete(scope) {
      this.$confirm('确定要删除吗?', '信息提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delDept(scope.deptId).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: '删除成功！'
            });
            this.getDeptList(this.searchData)
          } else {
            this.$message({
              type: 'error',
              message: res.msg
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //修改
    editDept(scope) {
      let newScope = { ...scope }
      if (newScope.status == '1') {
        newScope.status = false
      } else {
        newScope.status = true
      }
      this.editDeptData.data = { ...scope }
      this.editDeptData.dialogVisible = true
    },
    updateDept(payload) {
      updateDept(payload).then(res => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: '修改成功！'
          });
          this.editDeptData.dialogVisible = false
          this.getDeptList(this.searchData)
        } else {
          this.$message({
            type: 'error',
            message: res.msg
          });
        }
      })
    },
    searchBtn() {
      this.getDeptList(this.searchData)
    },
    reset() {
      this.searchData = {
        deptName: '',
        status: ''
      }
      this.getDeptList(this.searchData)
    },
    handleTree(data, id, parentId, children) {
      let config = {
        id: id || 'id',
        parentId: parentId || 'parentId',
        childrenList: children || 'children'
      };

      var childrenListMap = {};
      var nodeIds = {};
      var tree = [];

      for (let d of data) {
        let parentId = d[config.parentId];
        if (childrenListMap[parentId] == null) {
          childrenListMap[parentId] = [];
        }
        nodeIds[d[config.id]] = d;
        childrenListMap[parentId].push(d);
      }

      for (let d of data) {
        let parentId = d[config.parentId];
        if (nodeIds[parentId] == null) {
          tree.push(d);
        }
      }

      for (let t of tree) {
        adaptToChildrenList(t);
      }

      function adaptToChildrenList(o) {
        if (childrenListMap[o[config.id]] !== null) {
          o[config.childrenList] = childrenListMap[o[config.id]];
        }
        if (o[config.childrenList]) {
          for (let c of o[config.childrenList]) {
            adaptToChildrenList(c);
          }
        }
      }
      return tree;
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.dashboard-container {
  .search-content {
    width: 100%;
    height: 74px;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding-left: 10px;

    .el-input {
      margin: 0 10px;
    }

    .el-select {
      margin: 0 10px;
    }

    .search-btn {
      display: flex;
      align-items: center;
      height: 100%;
      margin-left: 10px;

      div {
        // margin: 0 6px;
        display: inline-block;
        width: 80px;
        height: 40px;
        border-radius: 2px;
        font-size: 14px;
        line-height: 40px;
        text-align: center;
      }

      div:hover {
        cursor: pointer;
      }

      .search {
        margin-right: 10px;
        background-color: #2766DD;
        color: #F7F8FB;
      }

      .search:hover {
        background-color: #4D85F4;
      }

      .reset {
        color: #333334;
        border: 1px solid #D7D7D7;
      }

      .reset:hover {
        color: #1F9FFF;
        border: 1px solid #1F9FFF;
      }
    }
  }

  .table-content {
    margin-top: 15px;
    width: 100%;
    background-color: #fff;
    padding: 0 20px;

    .btn {
      margin: 15px 20px 15px 0;
      cursor: pointer;
      float: left;
      text-align: center;
      width: 98px;
      height: 34px;
      border-radius: 2px;
      border: 1px solid #ABC7FD;
      line-height: 34px;
      font-weight: 400;
      font-size: 14px;
      color: #2250C8;
      background-color: #E7EEFF;
    }

    .btn:hover {
      color: #FFFFFF;
      background-color: #2250C8;
      border: 1px solid #2250C8;
    }

    .btn:active {
      color: #FFFFFF;
      background-color: #194DA4;
      border: 1px solid #194DA4;
    }

    .startUsing {
        width: 54px;
        height: 24px;
        margin: 14.5px auto 0;
        line-height: 24px;
        text-align: center;
        font-size: 12px;
        color: #00974D;
        border-radius: 4px;
        background-color: #E7FAF0;
        border: 1px solid #BEFDDD;
      }

      .Deactivate {
        width: 54px;
        height: 24px;
        margin: 14.5px auto 0;
        line-height: 24px;
        text-align: center;
        font-size: 12px;
        color: #FF9933;
        border-radius: 4px;
        background-color: #FFF3E8;
        border: 1px solid #FDE6CF;
      }
    .operateBtn {
      display: flex;
      justify-content: center;
      color: #1E9FFF;

      div {
        margin: 0 5px;
        cursor: pointer;
      }
    }

    .pagination {
      margin: 10px 0;
      width: 100%;
      height: 20px;

      .el-pagination {
        float: right;
      }
    }
  }

}
</style>
