<template>
  <div class="ele-body">
    <el-card shadow="never" v-loading="loading" body-style="padding-bottom: 0;">
      <el-row :gutter="15">
        <el-col :md="6" style="margin-bottom: 15px;">
          <!-- 操作按钮 -->
          <div class="ele-table-tool ele-table-tool-default">
            <el-button @click="showEdit=true" type="primary" icon="el-icon-plus" class="ele-btn-icon" size="small">添加
            </el-button>
            <el-button @click="edit" type="warning" icon="el-icon-edit" class="ele-btn-icon" :disabled="!current"
                       size="small">修改
            </el-button>
            <el-button @click="remove" type="danger" icon="el-icon-delete" class="ele-btn-icon" :disabled="!current"
                       size="small">删除
            </el-button>
          </div>
          <!-- 机构列表 -->
          <div class="org-tree-group">
            <el-tree ref="orgTree" :data="data" :props="{label:'organizationName'}" :expand-on-click-node="false"
                     node-key="organizationId" :default-expand-all="true" @node-click="choose" highlight-current/>
          </div>
        </el-col>
        <el-col :md="18" style="margin-bottom: 15px;">
          <user-list v-if="current" :organization-id="current.organizationId" :organization-list="organizationList"/>
        </el-col>
      </el-row>
    </el-card>
    <!-- 编辑弹窗 -->
    <el-dialog :title="editForm.organizationId?'修改机构':'添加机构'" :visible.sync="showEdit" width="600px"
               @closed="editForm={}" :destroy-on-close="true" custom-class="ele-dialog-form" :lock-scroll="false">
      <el-form :model="editForm" ref="editForm" :rules="editRules" label-width="82px">
        <el-row :gutter="15">
          <el-col :sm="12">
            <el-form-item label="上级机构:">
              <treeselect v-model="editForm.parentId" :options="organizationList"
                          placeholder="请选择上级机构" :defaultExpandLevel="4"
                          :normalizer="(d)=>{return { id: d.organizationId, label: d.organizationName }}"/>
            </el-form-item>
            <el-form-item label="机构名称:" prop="organizationName">
              <el-input v-model="editForm.organizationName" placeholder="请输入机构名称" clearable/>
            </el-form-item>
            <el-form-item label="机构全称:" prop="organizationFullName">
              <el-input v-model="editForm.organizationFullName" placeholder="请输入机构全称" clearable/>
            </el-form-item>
            <el-form-item label="机构代码:" prop="organizationCode">
              <el-input v-model="editForm.organizationCode" placeholder="请输入机构代码" clearable/>
            </el-form-item>
          </el-col>
          <el-col :sm="12">
            <el-form-item label="机构类型:" prop="organizationType">
              <el-select v-model="editForm.organizationType" placeholder="请选择机构类型" class="ele-fluid" clearable>
                <el-option v-for="(item,index) in organizationTypeList" :key="index"
                           :label="item.dictDataName" :value="item.dictDataId"/>
              </el-select>
            </el-form-item>
            <el-form-item label="排序号:" prop="sortNumber">
              <el-input-number v-model="editForm.sortNumber" controls-position="right" :min="0"
                               placeholder="请输入排序号" class="ele-fluid ele-text-left"/>
            </el-form-item>
            <el-form-item label="备注:">
              <el-input v-model="editForm.comments" placeholder="请输入备注" :rows="4" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="showEdit=false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'  // 下拉树
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import UserList from './user-list'

export default {
  name: "SysOrganization",
  components: {UserList, Treeselect},
  data() {
    return {
      loading: true,  // 加载状态
      data: [],  // 列表数据
      where: {},  // 搜索条件
      current: null,  // 选中数据
      showEdit: false,  // 是否显示表单弹窗
      editForm: {},  // 表单数据
      editRules: {  // 表单验证规则
        organizationName: [
          {required: true, message: '请输入机构名称', trigger: 'blur'}
        ],
        organizationFullName: [
          {required: true, message: '请输入机构全称', trigger: 'blur'}
        ],
        organizationCode: [
          {required: true, message: '请输入机构代码', trigger: 'blur'}
        ],
        organizationType: [
          {required: true, message: '请选择机构类型', trigger: 'blur'}
        ],
        sortNumber: [
          {required: true, message: '请输入排序号', trigger: 'blur'}
        ]
      },
      organizationList: [],  // 全部机构
      organizationTypeList: []  // 机构类型列表
    }
  },
  mounted() {
    this.query();
    this.queryOrganizationType();  // 获取机构类型
  },
  methods: {
    /* 查询 */
    query() {
      this.loading = true;
      this.$http.get('/sys/organization', {params: this.where}).then(res => {
        this.loading = false;
        if (res.data.code === 0) {
          this.data = this.$util.toTreeData(res.data.data, 'organizationId', 'parentId');
          setTimeout(() => {
            this.choose(this.data[0]);
          }, 100);
          if (Object.keys(this.where).length === 0) this.organizationList = this.data;
        } else {
          this.$message.error(res.data.msg || '获取数据失败');
        }
      }).catch(e => {
        this.loading = false;
        this.$message.error(e.message);
      });
    },
    /* 选择数据 */
    choose(row) {
      if (row != null) {
        this.current = row;
        this.$refs.orgTree.setCurrentKey(row.organizationId);
      } else {
        this.current = null;
      }
    },
    /* 显示编辑 */
    edit() {
      this.editForm = Object.assign({}, this.current, {parentId: this.current.parentId || null});
      this.showEdit = true;
    },
    /* 保存编辑 */
    save() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({lock: true});
          this.$http[this.editForm.organizationId ? 'put' : 'post']('/sys/organization',
              Object.assign({}, this.editForm, {parentId: this.editForm.parentId || 0})
          ).then(res => {
            loading.close();
            if (res.data.code === 0) {
              this.showEdit = false;
              this.$message({type: 'success', message: res.data.msg});
              this.query();
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            loading.close();
            this.$message.error(e.message);
          });
        } else {
          return false;
        }
      });
    },
    /* 删除 */
    remove() {
      this.$confirm('确定要删除选中的机构吗?', '提示', {type: 'warning'}).then(() => {
        const loading = this.$loading({lock: true});
        this.$http.delete('/sys/organization/' + this.current.organizationId).then(res => {
          loading.close();
          if (res.data.code === 0) {
            this.$message({type: 'success', message: res.data.msg});
            this.query();
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(e => {
          loading.close();
          this.$message.error(e.message);
        });
      }).catch(() => 0);
    },
    /* 查询机构类型 */
    queryOrganizationType() {
      this.$http.get('/sys/dictdata', {
        params: {dictCode: 'organization_type'}
      }).then(res => {
        if (res.data.code === 0) {
          this.organizationTypeList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    }
  }
}
</script>

<style scoped>
.org-tree-group {
  border: 1px solid hsla(0, 0%, 60%, .15);
  height: calc(100vh - 262px);
  box-sizing: border-box;
}

.org-tree-group >>> .el-tree-node__content {
  height: 40px;
}

.org-tree-group >>> .el-tree-node__content > .el-tree-node__expand-icon {
  margin-left: 10px;
}
</style>