<template>
  <div class="app-container">
    <div class="mymain-container">
      <div>
        <el-select v-model="value1" multiple placeholder="显示层级">
          <el-option v-for="item in levels" :key="item.value" :label="item + '级'" :value="item"> </el-option>
        </el-select>
        <span style="display: inline-block; width: 220px; margin-left: 10px"
          ><el-input v-model="input" placeholder="模糊搜索"></el-input
        ></span>
      </div>

      <div class="table">
        <el-table :data="showList" border>
          <el-table-column prop="level" label="级别" width="50"></el-table-column>
          <el-table-column prop="name" label="部门名称"> </el-table-column>
          <el-table-column prop="" label="结构">
            <template slot-scope="scope">
              {{ scope.row.pname.join(' / ') }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="状态" class-name="status-col" width="80">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status ? 'success' : 'danger'">{{
                scope.row.status ? '启用' : '禁用'
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="268" fixed="right">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-plus"
                @click="openMainForm('add', scope.row.websitId)"
                >添加子部门</el-button
              >
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="openMainForm('edit', scope.row.websitId)"
                >编辑</el-button
              >
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="handleDelete(scope.row.websitId)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination clearfix">
        <div class="fr">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[15, 20, 30, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="listTotal"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <!-- 添加编辑部门 -->
    <el-dialog
      :title="mainFormType == 'add' ? '添加部门' : '编辑部门'"
      :visible.sync="mainFormVisible"
      :show-close="false"
      width="40%"
      :close-on-click-modal="false"
    >
      <el-form ref="mainForm" :model="mainForm" :rules="mainFormRules" label-position="top" label-width="80px">
        <el-form-item label="上级部门" prop="parentId">
          <el-cascader
            style="width: 100%"
            :options="dataList2"
            :props="{ checkStrictly: true, value: 'websitId', label: 'name' }"
            v-model="mainForm.parentId"
            filterable
            clearable
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input placeholder="请输入部门名称" v-model="mainForm.name"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="mainForm.status">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelMainForm">取 消</el-button>
        <el-button type="primary" @click="submitMainForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentList, addDepartment, editDepartment, getDepartmentDetail, deleteDepartment } from '@/api/setting'
export default {
  data() {
    return {
      dataList: [], // 列表数据
      dataList2: [], // 列表数据
      listLoading: true, // 列表加载loading
      currentPage: 1, // 当前页码
      pageSize: 15, // 每页数量
      editId: null,
      mainFormType: 'add',
      mainFormVisible: false,
      input: '',
      value1: [],
      levels: [],
      mainForm: {
        parentId: '',
        name: '',
        status: true,
      },
      mainFormRules: {
        name: [{ required: true, message: '请填写部门名称', trigger: 'blur' }]
      }
    }
  },

  created() {
    this.getList()
  },

  computed: {
    showList() {
      return [...this.dataList]
        .filter(item => {
          return (
            (this.value1.length ? !!~this.value1.indexOf(item.level) : true) &&
            (this.input ? !!~item.name.indexOf(this.input) || !!~item.pname.indexOf(this.input) : true)
          )
        })
        .splice((this.currentPage - 1) * this.pageSize, this.pageSize)
    },
    listTotal() {
      return [...this.dataList].filter(item => {
        return (
          (this.value1.length ? !!~this.value1.indexOf(item.level) : true) &&
          (this.input ? !!~item.name.indexOf(this.input) || !!~item.pname.indexOf(this.input) : true)
        )
      }).length
    }
  },
  watch: {
    value1() {
      this.$nextTick(() => {
        this.currentPage = 1
      })
    },
    input() {
      this.$nextTick(() => {
        this.currentPage = 1
      })
    }
  },
  methods: {
    // 获取部门列表
    getList() {
      var list_ = []
      var levels = []
      function dg(list, level = 1, pname = []) {
        for (let { children, name, ...item } of list) {
          var n_ = ''
          for (var i = 1; i < level; i++) n_ += ` - `
          list_.push({ ...item, name: n_ + name, level, pname: [...pname] })
          if (!~levels.indexOf(level)) levels.push(level)
          if (children && children.length) dg(children, level + 1, [...pname, name])
        }
      }
      getDepartmentList().then(res => {
        this.dataList2 = res.data
        dg(res.data)
        this.dataList = list_
        this.levels = levels
      })
    },

    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      // this.getList()
    },

    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val
      // this.getList()
    },

    // 操作 - 删除
    handleDelete(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          showClose: false,
          type: 'warning'
        }).then(() => {
          deleteDepartment({ id: id }).then(res => {
        this.getList()
        this.$successMsg()
      })
        }).catch(() => {

        });

    },

    // 打开 新增编辑 部门表单
    openMainForm(type, id) {
      this.mainFormType = type
      this.mainFormVisible = true
      if (type == 'add') {
        this.mainForm.parentId = id
      } else {
        this.editId = id
        getDepartmentDetail({ id }).then(res => {
          this.mainForm = {
            parentId: res.data.parentId,
            name: res.data.name,
            status: res.data.status,
          }
        })
      }
    },

    // 取消 新增编辑 部门表单
    cancelMainForm() {
      this.mainFormVisible = false
      this.$refs.mainForm.resetFields()
      this.mainForm.name = ''
    },

    // 提交 部门表单
    submitMainForm() {
      this.$refs.mainForm.validate(valid => {
        if (valid) {
          let parentId = null
          if (this.mainForm.parentId instanceof Array) {
            parentId = this.mainForm.parentId[this.mainForm.parentId.length - 1]
          } else {
            parentId = this.mainForm.parentId
          }
          let params = {
            parentId,
            name: this.mainForm.name,
            status: this.mainForm.status,
          }
          if (this.mainFormType == 'edit') {
            params.websitId = this.editId
            editDepartment(params).then(res => {
              this.cancelMainForm()
              this.getList()
              this.$successMsg('编辑成功')
            })
          } else {
            addDepartment(params).then(res => {
              this.cancelMainForm()
              this.getList()
              this.$successMsg('添加成功')
            })
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss"></style>
