<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-col :span="6">
        <el-input placeholder="输入部门名进行过滤" v-model="filterOrgText"></el-input>

        <el-tree
          class="filter-tree"
          :data="orgData"
          @node-click="handleOrgClick"
          default-expand-all
          highlight-current
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          v-loading="treeLoding"
          ref="tree"
          style="margin-top:10px;"
        ></el-tree>
      </el-col>
      <el-col :span="18">
        <div>
          <el-select
            v-model="listQuery.is_active"
            placeholder="状态"
            clearable
            style="width: 90px"
            class="filter-item"
            @change="handleFilter"
          >
            <el-option
              v-for="item in enabledOptions"
              :key="item.key"
              :label="item.display_name"
              :value="item.key"
            />
          </el-select>
          <el-input
            v-model="listQuery.name"
            placeholder="姓名"
            style="width: 200px;"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleFilter"
          >搜索</el-button>
          <el-button
            class="filter-item"
            style="margin-left: 10px;"
            type="primary"
            icon="el-icon-refresh-left"
            @click="resetFilter"
          >刷新重置</el-button>
        </div>
        <div style="margin-top:10px">
          <el-button type="primary" @click="handleAddUser" icon="el-icon-plus">新增</el-button>
        </div>
        <el-table
          :data="userList"
          style="width: 100%;margin-top:10px;"
          border
          fit
          v-loading="listLoading"
          highlight-current-row
          max-height="600"
        >
          <el-table-column type="index" width="50"></el-table-column>
          <el-table-column align="center" label="姓名">
            <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
          <el-table-column align="header-center" label="账户">
            <template slot-scope="scope">{{ scope.row.username }}</template>
          </el-table-column>
          <el-table-column align="header-center" label="部门">
            <template
              slot-scope="scope"
              v-if="scope.row.department_name != null"
            >{{ scope.row.department_name }}</template>
          </el-table-column>
          <!-- <el-table-column align="header-center" label="状态">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.is_active"
                :disabled="!checkPermission(['user_update'])"
                active-color="#409EFF"
                inactive-color="#F56C6C"
              />
            </template>
          </el-table-column>-->
          <el-table-column label="创建日期">
            <template slot-scope="scope">
              <span>{{ scope.row.date_joined }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(scope)"
                icon="el-icon-edit"
                :disabled="!checkPermission(['user_update'])"
                v-if="!scope.row.is_superuser"
              ></el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(scope)"
                icon="el-icon-delete"
                :disabled="!checkPermission(['user_delete'])"
                v-if="!scope.row.is_superuser"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.limit"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑用户':'新增用户'">
      <el-form
        :model="user"
        label-width="80px"
        label-position="right"
        :rules="rule1"
        ref="userForm"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="user.name" placeholder="姓名" />
        </el-form-item>
        <el-form-item label="账户" prop="username">
          <el-input v-model="user.username" placeholder="账户" />
        </el-form-item>
        <el-form-item label="所属部门" prop="department">
          <el-cascader
            v-model="user.department"
            :options="orgData"
            :props="{ checkStrictly: true }"
            clearable
            style="width:100%"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select v-model="user.roles" multiple placeholder="请选择" style="width:100%">
            <el-option
              v-for="item in roles"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="department">
          <el-upload
            class="avatar-uploader"
            :action="upUrl"
            accept="image/jpeg, image/gif, image/png, image/bmp"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="upHeaders"
          >
            <img v-if="user.avatar" :src="user.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmUser('userForm')">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
<script>
import { getUserList, createUser, deleteUser, updateUser } from "@/api/user";
import { getOrgList } from "@/api/org";
import { getRoles } from "@/api/role";
import { genTree, deepClone } from "@/utils";
import checkPermission from "@/utils/permission";
import { upUrl } from "@/api/file";
import { getToken } from "@/utils/auth";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination


const defaultUser = {
  id: "",
  name: "",
  username: "",
  department: null,
  avatar:""
};
export default {
  components: { Pagination },
  watch: {
    filterOrgText(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {
    return {
      user: {
        id: "",
        name: "",
        username: "",
        department: null,
        avatar:""
      },
      upHeaders: { Authorization: "JWT " + getToken() },
      upUrl: upUrl(),
      userList: [],
      roles: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      enabledOptions: [
        { key: "true", display_name: "激活" },
        { key: "false", display_name: "禁用" }
      ],
      dialogVisible: false,
      dialogType: "new",
      rule1: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        username: [{ required: true, message: "请输入账号", trigger: "change" }]
        // password: [
        //   { required: true, message: "请输入密码", trigger: "change" }
        // ],
      },
      filterOrgText: "",
      treeLoding: false,
      orgData: []
    };
  },
  computed: {},
  created() {
    this.getList();
    // this.getOrgList();
    this.getRoles();
  },
  methods: {
    checkPermission,
    handleAvatarSuccess(res, file) {
      if (res.code == 200) {
        this.user.avatar = res.data.path
      }else{
        this.$message.error("头像上传失败!");
      }
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleOrgClick(obj, node, vue) {
      this.listQuery.page = 1;
      this.listQuery.department = obj.id;
      this.getList();
    },
    getList() {
      this.listLoading = true;
      getUserList(this.listQuery).then(response => {
        this.userList = response.data.results;
        this.total = response.data.count;
        this.listLoading = false;
      });
    },
    // getOrgList() {
    //   this.treeLoding = true;
    //   getOrgList().then(response => {
    //     this.orgData = genTree(response.data);
    //     this.treeLoding = false;
    //   });
    // },
    getRoles() {
      getRoles().then(response => {
        this.roles = genTree(response.data);
      });
    },
    resetFilter() {
      this.listQuery = {
        page: 1,
        limit: 20
      };
      this.getList();
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleAddUser() {
      this.user = Object.assign({}, defaultUser);
      this.dialogType = "new";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["userForm"].clearValidate();
      });
    },
    handleEdit(scope) {
      this.user = Object.assign({}, scope.row); // copy obj
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["userForm"].clearValidate();
      });
    },
    handleDelete(scope) {
      this.$confirm("确认删除该用户吗?将丢失数据!", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error"
      })
        .then(async () => {
          await deleteUser(scope.row.id);
          this.userList.splice(scope.row.index, 1);
          this.$message({
            type: "success",
            message: "成功删除!"
          });
        })
        .catch(err => {
          console.error(err);
        });
    },
    
    async confirmUser(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          const isEdit = this.dialogType === "edit";
          if (isEdit) {
            updateUser(this.user.id, this.user).then(() => {
              for (let index = 0; index < this.userList.length; index++) {
                if (this.userList[index].id === this.user.id) {
                  this.userList.splice(index, 1, Object.assign({}, this.user));
                  break;
                }
              }
              this.dialogVisible = false;
              this.$message.success('成功')
            });
          } else {
            this.user.department = this.user.department.pop();
            createUser(this.user).then(res => {
              // this.user = res.data
              // this.userList.unshift(this.user)
              this.getList();
              this.dialogVisible = false;
              this.$message.success('成功')
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
