<template>
  <div>
    <!-- 搜索表单 -->
    <el-form :model="table.where" class="ele-form-search ele-table-tool-default" size="small"
             @keyup.enter.native="$refs.table.reload()"
             @submit.native.prevent>
      <el-row :gutter="15">
        <el-col :md="6" :sm="12">
          <el-form-item>
            <el-input v-model="table.where.username" placeholder="请输入用户账号" clearable size="small"/>
          </el-form-item>
        </el-col>
        <el-col :md="6" :sm="12">
          <el-form-item>
            <el-input v-model="table.where.nickname" placeholder="请输入用户名" clearable size="small"/>
          </el-form-item>
        </el-col>
        <el-col :md="12" :sm="12">
          <div class="ele-form-actions">
            <el-button type="primary" @click="$refs.table.reload()" icon="el-icon-search" class="ele-btn-icon"
                       size="small">查询
            </el-button>
            <el-button @click="add" type="primary" icon="el-icon-plus" class="ele-btn-icon" size="small">添加</el-button>
            <el-button @click="remove()" type="danger" icon="el-icon-delete" class="ele-btn-icon" size="small">删除
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <!-- 数据表格 -->
    <ele-data-table ref="table" :config="table" :choose.sync="choose" height="calc(100vh - 261px)"
                    highlight-current-row>
      <el-table-column type="selection" width="45" align="center" fixed="left"/>
      <el-table-column prop="username" label="用户账号" sortable="custom" min-width="110px" show-overflow-tooltip/>
      <el-table-column prop="nickname" label="用户名" sortable="custom" min-width="100px" show-overflow-tooltip/>
      <el-table-column prop="sexName" label="性别" sortable="custom" show-overflow-tooltip/>
      <el-table-column prop="phone" label="手机号" sortable="custom" min-width="100px" show-overflow-tooltip/>
      <el-table-column label="角色" show-overflow-tooltip>
        <template slot-scope="{row}">
          <el-tag v-for="item in row.roles" :key="item.roleId" type="primary" size="mini">{{ item.roleName }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" sortable="custom" min-width="110px" show-overflow-tooltip>
        <template slot-scope="{row}">{{ row.createTime | toDateString }}</template>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="75px" sortable="custom">
        <template slot-scope="{row}">
          <el-switch v-model="row.state" @change="editState(row)" :active-value="0" :inactive-value="1"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80px" align="center" :resizable="false">
        <template slot-scope="{row}">
          <el-link @click="edit(row)" icon="el-icon-edit" type="primary" :underline="false">修改</el-link>
          <!--<el-popconfirm title="确定要删除此用户吗？" @onConfirm="remove(row)" class="ele-action">
            <el-link slot="reference" icon="el-icon-delete" type="danger" :underline="false">删除</el-link>
          </el-popconfirm>-->
        </template>
      </el-table-column>
    </ele-data-table>
    <!-- 编辑弹窗 -->
    <el-dialog :title="editForm.userId?'修改用户':'添加用户'" :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.organizationId" :options="organizationList"
                          placeholder="请选择所属机构" :defaultExpandLevel="4"
                          :normalizer="(d)=>{return { id: d.organizationId, label: d.organizationName }}"/>
            </el-form-item>
            <el-form-item label="用户账号:" prop="username">
              <el-input v-model="editForm.username" placeholder="请输入账号" clearable
                        :disabled="editForm.userId?true:false"/>
            </el-form-item>
            <el-form-item label="用户名:" prop="nickname">
              <el-input v-model="editForm.nickname" placeholder="请输入用户名" clearable/>
            </el-form-item>
            <el-form-item label="性别:" prop="sex">
              <el-select v-model="editForm.sex" placeholder="请选择性别" class="ele-block" clearable>
                <el-option label="男" :value="1"/>
                <el-option label="女" :value="2"/>
              </el-select>
            </el-form-item>
            <el-form-item label="角色:" prop="roleIds">
              <el-select v-model="editForm.roleIds" placeholder="请选择角色" class="ele-block" clearable multiple>
                <el-option v-for="(item,index) in roleList" :key="index" :label="item.roleName" :value="item.roleId"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12">
            <el-form-item label="手机号:">
              <el-input v-model="editForm.phone" placeholder="请输入手机号" clearable/>
            </el-form-item>
            <el-form-item label="邮箱:">
              <el-input v-model="editForm.email" placeholder="请输入邮箱" clearable/>
            </el-form-item>
            <el-form-item label="个人简介:">
              <el-input v-model="editForm.introduction" placeholder="请输入个人简介" :rows="4" type="textarea"/>
            </el-form-item>
            <el-form-item label="登录密码:" prop="password" v-if="!editForm.userId">
              <el-input v-model="editForm.password" placeholder="请输入登录密码" show-password/>
            </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'

export default {
  name: "SysUserList",
  components: {Treeselect},
  props: {
    organizationId: Number,  // 机构id
    organizationList: Array  // 全部机构
  },
  data() {
    return {
      table: {url: '/sys/user/page', where: {organizationId: this.organizationId}},  // 表格配置
      choose: [],  // 表格选中数据
      showEdit: false,  // 是否显示表单弹窗
      editForm: {},  // 表单数据
      editRules: {  // 表单验证规则
        username: [
          {required: true, message: '请输入账号', trigger: 'blur'}
        ],
        nickname: [
          {required: true, message: '请输入用户名', trigger: 'blur'}
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'blur'}
        ],
        roleIds: [
          {required: true, message: '请选择角色', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '请输入登录密码', trigger: 'blur'}
        ]
      },
      roleList: []  // 角色列表
    }
  },
  mounted() {
    this.queryRoles();  // 查询角色列表
  },
  methods: {
    /* 显示添加 */
    add() {
      this.editForm.organizationId = this.organizationId;
      this.showEdit = true;
    },
    /* 显示编辑 */
    edit(row) {
      this.editForm = Object.assign({}, row);
      this.editForm.roleIds = row.roles.map(d => d.roleId);
      this.showEdit = true;
    },
    /* 保存编辑 */
    save() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({lock: true});
          this.$http[this.editForm.userId ? 'put' : 'post']('/sys/user', this.editForm).then(res => {
            loading.close();
            if (res.data.code === 0) {
              this.showEdit = false;
              this.$message({type: 'success', message: res.data.msg});
              this.$refs.table.reload();
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            loading.close();
            this.$message.error(e.message);
          });
        } else {
          return false;
        }
      });
    },
    /* 删除 */
    remove(row) {
      if (!row) {  // 批量删除
        if (this.choose.length === 0) return this.$message.error('请至少选择一条数据');
        let ids = this.choose.map(d => d.userId);
        this.$confirm('确定要删除选中的用户吗?', '提示', {type: 'warning'}).then(() => {
          const loading = this.$loading({lock: true});
          this.$http.delete('/sys/user/batch', {data: ids}).then(res => {
            loading.close();
            if (res.data.code === 0) {
              this.$message({type: 'success', message: res.data.msg});
              this.$refs.table.reload();
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            loading.close();
            this.$message.error(e.message);
          });
        }).catch(() => 0);
      } else {  // 单个删除
        const loading = this.$loading({lock: true});
        this.$http.delete('/sys/user/' + row.userId).then(res => {
          loading.close();
          if (res.data.code === 0) {
            this.$message({type: 'success', message: res.data.msg});
            this.$refs.table.reload();
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(e => {
          loading.close();
          this.$message.error(e.message);
        });
      }
    },
    /* 更改状态 */
    editState(row) {
      const loading = this.$loading({lock: true});
      this.$http.put('/sys/user/state/' + row.userId, {state: row.state}).then(res => {
        loading.close();
        if (res.data.code === 0) {
          this.$message({type: 'success', message: res.data.msg});
        } else {
          row.state = !row.state ? 1 : 0;
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        loading.close();
        this.$message.error(e.message);
      });
    },
    /* 查询角色列表 */
    queryRoles() {
      this.$http.get('/sys/role').then(res => {
        if (res.data.code === 0) {
          this.roleList = res.data.data;
        } else {
          this.$message.error(res.data.msg);
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    }
  },
  watch: {
    /* 监听机构id变化 */
    organizationId() {
      this.table.where.organizationId = this.organizationId;
      this.$refs.table.reload();
    }
  }
}
</script>

<style scoped>

</style>