<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form>
        <el-form-item>
          <el-input v-model="listQuery.name" placeholder="请输入部门名称" clearable style="width: 280px" @keyup.enter.native="handleFilter" />
          <el-button type="primary" icon="el-icon-search" @click="handleFilter">
            查询
          </el-button>
          <el-button type="primary" icon="el-icon-edit" @click="showCreate">
            添加
          </el-button>
          <el-button type="danger" icon="el-icon-delete" @click="deleteDepartment">
            删除
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="list"
      :data="list"
      border
      row-key="id"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      highlight-current-row
      @row-click="onRowClick"
      @selection-change="handleSelectionChange"
      @select="rowSelect"
      @select-all="selectAll"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column type="index" align="center" label="序号" width="80" />
      <el-table-column label="部门名称" prop="name" style="width: 60px;" />
      <el-table-column :formatter="formatter.getChineseName" align="center" label="负责人" prop="leader" style="width: 60px;" />
      <el-table-column align="center" label="创建时间" prop="createTime" style="width: 60px;" />
      <el-table-column align="center" label="最近修改时间" prop="updateTime" style="width: 60px;" />
      <el-table-column align="center" label="管理" width="150">
        <template slot-scope="scope">
          <el-button type="primary" icon="edit" @click="showUpdate(scope.$index)">
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="totalCount>0" :total="totalCount" :page-num.sync="listQuery.pageNum" :page-row.sync="listQuery.pageSize" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="closeDialog">
      <el-form ref="tempDepartment" :model="tempDepartment" class="small-space" label-width="80px">
        <el-form-item label="部门名称" required>
          <el-input v-model="tempDepartment.name" type="text" size="small" />
        </el-form-item>
        <el-form-item label="负责人" size="small" required>
          <el-select v-model="tempDepartment.leader" filterable placeholder="请选择" clearable>
            <el-option v-for="item in leaders" :key="item.id" :label="item.nickname" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="部门代码（选填）">
          <el-input v-model="tempDepartment.code" type="text" size="small" style="width: 200px" />
        </el-form-item>
        <el-form-item label="成员">
          <template>
            <el-transfer v-model="departmentUserList" :props="{key: 'id', label: 'nickname'}" :button-texts="['移除', '添加']" :titles="['未分配员工', '部门成员']" :data="unAllotUserList" />
          </template>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button v-if="dialogStatus==='create'" type="success" @click="createDepartment">
          创 建
        </el-button>
        <el-button v-if="dialogStatus==='update'" type="primary" @click="updateDepartment">
          修 改
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import { updateDepartmentFn, deleteDepartmentFn, addDepartmentFn } from '@/api/common'

export default {
  name: 'DepartmentList',
  components: { Pagination },
  data() {
    return {
      list: [],
      totalCount: 0,
      dialogStatus: 'create',
      dialogFormVisible: false,
      listQuery: {
        pageNum: 1,
        pageSize: 20
      },
      textMap: {
        update: '编辑',
        create: '新建部门'
      },
      tempDepartment: {
      },
      // 所有用户
      unAllotUserList: [],
      departmentUserList: [],
      leaders: [],
      multipleSelection: [],
      isIndeterminate: true
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      // 查询列表
      this.api({
        url: '/department/tree',
        method: 'get',
        params: this.listQuery
      }).then(data => {
        data.forEach(row => {
          row.isChecked = false
        })
        this.list = data
      })
    },
    showCreate() {
      this.leaders = this.$store.getters.allUser
      this.tempDepartment = {}
      this.getUserListByDepartmentIdOrNull(0)
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    showUpdate($index) {
      this.leaders = this.$store.getters.allUser
      const department = this.list[$index]
      this.tempDepartment = department
      this.getUserListByDepartmentIdOrNull(department.id)
      this.getUserListByDepartmentId(department.id)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    getUserListByDepartmentId(departmentId) {
      this.api({
        url: '/user/getUserListByDepartmentId',
        method: 'get',
        params: {
          departmentId: departmentId
        }
      }).then((data) => {
        if (data != null) {
          data.forEach(user => {
            this.departmentUserList.push(user.id)
          })
        }
      })
    },
    getUserListByDepartmentIdOrNull(departmentId) {
      this.api({
        url: '/user/getUserListByDepartmentIdOrNull',
        method: 'get',
        params: {
          departmentId: departmentId
        }
      }).then((data) => {
        this.unAllotUserList = data
      })
    },
    createDepartment() {
      // 添加
      this.$refs['tempDepartment'].validate(valid => {
        if (valid) {
          this.tempDepartment.userList = this.departmentUserList
          addDepartmentFn(this.tempDepartment).then(() => {
            this.$message.success('添加成功。')
            this.getList()
            this.dialogFormVisible = false
          })
        } else {
          return false
        }
      })
    },
    updateDepartment() {
      // 修改用户信息
      this.$refs['tempDepartment'].validate(valid => {
        if (valid) {
          this.tempDepartment.userList = this.departmentUserList
          updateDepartmentFn(this.tempDepartment).then(() => {
            this.$message.success('修改成功。')
            this.getList()
            this.dialogFormVisible = false
          })
        } else {
          return false
        }
      })
    },
    deleteDepartment() {
      if (this.multipleSelection.length <= 0) {
        this.$message.warning('请选择要删除的数据。')
        return
      }
      const pks = []
      this.multipleSelection.forEach(department => {
        pks.push(department.id)
      })
      this.$confirm('确定删除此科室吗？可能会导致下属人员没有科室', '提示', {
        confirmButtonText: '确定',
        showCancelButton: '取消',
        type: 'warning'
      }).then(() => {
        deleteDepartmentFn({ pks: pks }).then(() => {
          this.$message({ message: '删除成功。', type: 'success' })
          this.getList()
        })
      })
    },
    handleFilter() {
      // 查询事件
      this.listQuery.pageNum = 1
      this.getList()
    },
    onRowClick(row) {
      this.$refs.list.toggleRowSelection(row)
    },
    handleSelectionChange: function(val) {
      this.multipleSelection = val
    },
    closeDialog() {
      this.unAllotUserList = []
      this.departmentUserList = []
    },
    /**
     * 注意在获取初始数据时，所有节点（包括子节点）都增加一个isChecked 标志参数
     *
     * @param selection
     * @param row
     */
    rowSelect(selection, row) {
      if (row.children) { // 只对有子节点的行响应
        if (!row.isChecked) { // 由行数据中的元素isChecked判断当前是否被选中
          row.children.map((item) => { // 遍历所有子节点
            this.$refs.list.toggleRowSelection(item, true) // 切换该子节点选中状态
            /*
            方法名                    说明                                      参数
                                 用于多选表格，切换某一行的选中状态，         row, selected
            toggleRowSelection   如果使用了第二个参数，则是设置这一行
                                 选中与否（selected 为 true 则选中）
             */
            item.isChecked = true
          })
          row.isChecked = true // 当前行isChecked标志元素切换为false
        } else {
          row.children.map((item) => {
            this.$refs.list.toggleRowSelection(item, false)
            item.isChecked = false
          })
          row.isChecked = false
        }
        // console.log(this.multipleSelection, row);
      }
    },
    selectAll(selection) {
      // selection 是选中的数据集合
      this.$refs.list.data.map((items) => { // 使用$ref获取注册的子组件信息，用data获取所有行，并用map函数遍历行
        if (items.children) {
          if (!items.isChecked) { // 若遍历出来的行未选中
            this.$refs.list.toggleRowSelection(items, true) // 行变为选中状态
            items.isChecked = true // 更新标志参数
            items.children.map((item) => { // 遍历子节点并改变状态与标志参数
              this.$refs.list.toggleRowSelection(item, true)
              item.isChecked = true
            })
          } else { // 选中状态同理
            this.$refs.list.toggleRowSelection(items, false)
            items.isChecked = false
            items.children.map((item) => {
              this.$refs.list.toggleRowSelection(item, false)
              item.isChecked = false
            })
          }
        } else {
          items.isChecked = !items.isChecked
        }
      })
      // console.log(this.orgs)
    }
  }
}
</script>
