<template lang="pug">
  el-container
    el-aside(width="300px" style="height:700px;")
      el-card.treeCard(:body-style="{ padding: '0px',height:'75vh'}")
        div(slot="header")
          span.title-bold() 组织机构树
        el-tree.elTree(:data="data" :props="defaultProps" :default-expand-all="true" @node-click="handleNodeClick")
    el-main(style="padding:0px;height:700px;")
      el-card.tableCard()
        span(slot="header")
          span.title-bold.title-left-color() 部门配置
          el-button(type="primary" icon="el-icon-plus" size='mini'  style="float:right;transform:translateY(6px);margin-right:20px;" :disabled="!ruleForm.parentId"  @click="addOrUpdateHandle()") 新增
        el-table(:data="dataList" :stripe="true" v-loading="dataListLoading" style="width: 100%;" :header-cell-style="{background:'#EEF8FF',color:'#333333'}" highlight-current-row)
          el-table-column(prop="name" header-align="center" align="center" label="部门名称")
          el-table-column(prop="code" header-align="center" align="center" label="部门编码")
          el-table-column(prop="remark" header-align="center" align="center" label="部门描述")
          el-table-column(prop header-align="center" align="center" label="操作" width='200px')
            template(slot-scope="scope")
              el-button(type="primary" plain size="mini" v-if="isAuth('sys:org:update')" @click="addOrUpdateHandle(scope.row)") 修改
              el-button(type="danger" plain size="mini" v-if="isAuth('sys:org:delete')" @click="deleteHandle(scope.row)") 删除
        el-pagination(background @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"  :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"  layout="total, sizes, prev, pager, next, jumper")
      el-dialog(width="50%" :append-to-body="true" :visible.sync="visible"  :modal-append-to-body="false"  @close="closeForm()")
        div(slot='title' )
          span.title-bold() {{!ruleForm.id ? '新增机构': '修改机构'}}
        el-form(:model="ruleForm" :inline="false" :rules="rules" ref="ruleForm" label-width="110px" @submit.native.prevent)
          el-card(shadow="never")
            el-row(:span='24')
              el-col(:span='23')
                el-form-item(label="上级部门名称:" prop="parentName")
                  el-input(v-model="ruleForm.parentName" placeholder="请输入内容" clearable disabled)
              el-col(:span='11')
                el-form-item(label="本级部门编码:" prop="code")
                  el-input(v-model="ruleForm.code" placeholder="请输入本级部门编码" clearable)
              el-col(:span='11' :offset='1')
                el-form-item(label="本级部门名称:" prop="name")
                  el-input(v-model="ruleForm.name" placeholder="请输入本级部门名称" clearable)
              el-col(:span='23')
                el-form-item(label="部 门 描 述:" prop="remark")
                  el-input(v-model="ruleForm.remark"  type="textarea" :rows="5" resize="none" placeholder="请输入部门描述")
        div( slot="footer" style=" text-align: center;" )
          el-button(type='danger' plain size='medium'  @click="closeForm") 取 消
          el-button(type='primary' size='medium'  @click="addsave") 保存
</template>

<script>
export default {
  data () {
    return {
      word: '', //查询
      dataList: [], //列表
      dataListLoading: false,
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      addOrUpdateVisible: false,
      ruleForm: {},
      visible: false,
      orgInfo: {},
      orgId: '',
      rules: {//添加规则
        code: [{ required: true, message: '本级部门编码不能为空', trigger: 'blur' }],
        name: [{ required: true, message: '本级部门名称不能为空', trigger: 'blur' }]
      },
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        id: 'id'
      }
    }
  },
  watch: {
    totalPage() { //注意这个函数的名字必须和你监听data中的属性的名字一样，这样才能当你data中的属性发生变化时，触发这个函数
      let pages = Math.ceil(this.totalPage / this.pageSize)//新数据总页数
      //总页数小于当前页数则重新加载列表数据
      if (pages < this.pageIndex) {
          this.pageIndex = pages || 1
          this.getDataList()//获取表格数据的方法
      }
    }
  },
  created () {
    this.getList()
    this.orgInfo = this.data[0]
  },
  methods: {
    getList () {
      this.$http({
        url: this.$http.adornUrl('/sysOrg/orgAllList'),
        method: 'GET'
      }).then(data => {
        if (data && data.code === 0) {
          this.data = data.list
        }
      })
    },
    handleNodeClick (data) {
      this.ruleForm.parentId = data.id
      this.ruleForm.parentName = data.name
      this.orgId = data.id
      this.orgInfo = data
      this.getDataList()
    },
    getDataList () {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrl('/sysOrg/orgList'),
        method: 'post',
        params: {
          page: this.pageIndex,
          limit: this.pageSize,
          id: this.orgId
        }
      }).then(data => {
        if (data && data.code === 0) {
          this.dataList = data.page.records
          this.totalPage = data.page.total
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    }, // 删除
    deleteHandle (row) {
      row.deleted = 1
      this.$confirm(`确认删除该部门?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl('/sysOrg/deleteById'),
            method: 'post',
            data: row
          }).then(res => {
            if (res && res.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                  this.getList()
                }
              })
            } else {
              this.$message.error(res.msg)
            }
          })
        })
        .catch(err => {
          this.$message.error(err)
        })
    },
    //添加或修改事件
    addOrUpdateHandle (row, flagType) {
      this.visible = true
      console.log('orgInfo2:', this.orgInfo)
      console.log('ruleForm2:', this.ruleForm)
      if (row) {
        this.ruleForm = row
      } else {
        this.ruleForm = {}
        this.ruleForm.parentId = this.orgInfo.id
        this.ruleForm.parentName = this.orgInfo.name
      }
    },
    // 提交
    addsave () {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/sysOrg/${!this.ruleForm.id ? 'save' : 'update'}`
            ),
            method: 'post',
            data: this.ruleForm
          }).then(data => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.getDataList()
                  this.getList()
                  this.$nextTick()
                }
              })
            } else {
              this.$message.error(data)
            }
          })
        }
      })
    },
    closeForm () {
      this.visible = false
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    }
  }
}
</script>
<style>

</style>
