<template>
  <div style="margin-top: 10px;">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div>
          <el-input
            placeholder="请输入用户名、手机号、姓名"
            class="filter-item"
            style="width: 300px;"
            v-model="listQuery.keywords"
            @keyup.enter.native="handleFilter"
          />

          <el-select
            v-has="'sysOrg:combobox'"
            placeholder="组织名"
            clearable
            class="filter-item"
            v-model="listQuery.orgId"
          >
            <el-option
              v-for="item in this.orgList"
              :key="item.identify"
              :label="item.name"
              :value="item.orgId"
            >
            </el-option>
          </el-select>
          <el-button
            v-waves
            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-circle-plus-outline"
            @click="handleCreate"
            >新建</el-button
          >
        </div>

        <!-- 分页 -->
        <swPage
          v-if="total > 0"
          key="1"
          :listQuery="listQuery"
          :total="total"
          pos="topLeft"
          @retPage="retPage"
        />
      </div>
      <div class="text item" style="width: 100%;height:auto;">
        <el-table
          v-loading="listLoading"
          :key="tableKey"
          :data="list"
          stripe
          border
          fit
          highlight-current-row
          width="1000"
        >
          <el-table-column
            label="用户ID"
            align="center"
            prop="userId"
            width="200"
          >
          </el-table-column>

          <el-table-column
            label="用户名"
            align="center"
            prop="username"
            width="200"
          >
          </el-table-column>

          <el-table-column
            label="昵称"
            align="center"
            prop="nickname"
            width="200"
          >
          </el-table-column>

          <el-table-column
            label="角色"
            align="center"
            prop="roleName"
            width="200"
          >
          </el-table-column>

          <el-table-column
            label="组织名"
            align="center"
            prop="orgName"
            width="200"
          >
          </el-table-column>

          <el-table-column label="状态" align="center" width="200">
            <template slot-scope="scope">
              <span>{{ scope.row.status | statusFilter }}</span>
            </template>
          </el-table-column>

          <el-table-column
            label="手机"
            align="center"
            prop="mobile"
            width="200"
          >
          </el-table-column>

          <el-table-column label="操作" align="center" width="300">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.userId !== -1000"
                type="primary"
                size="mini"
                title="编辑"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              />
              <el-button
                v-if="scope.row.type === 1 && scope.row.userId !== -1000"
                title="删除"
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              />
              <el-button
                v-if="scope.row.type === 1 && scope.row.userId !== -1000"
                title="禁用"
                type="warning"
                size="mini"
                icon="forbit"
                @click="
                  scope.row.status === 1
                    ? closeUser(scope.row)
                    : openUser(scope.row)
                "
              >
                <svg-icon icon-class="forbit" />
              </el-button>
              <el-button
                type="warning"
                size="mini"
                title="授权"
                v-if="scope.row.userId !== -1000"
                @click="handleUserRole(scope.row)"
              >
                <svg-icon icon-class="authorize" />
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <swPage
          v-if="total > 0"
          key="2"
          :listQuery="listQuery"
          :total="total"
          pos="btmRight"
          @retPage="retPage"
        />
      </div>
    </el-card>

    <!-- 新增或编辑对话框-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="midData"
        label-position="right"
        label-width="70px"
        style="width: 90%; margin-left:10px;"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="ID" v-show="isUpdate">
              <el-input v-model="midData.userId" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="midData.username" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password" v-show="!isUpdate">
              <el-input v-model="midData.password" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="midData.email" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="midData.mobile" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="昵称">
              <el-input v-model="midData.nickname" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="qq">
              <el-input v-model="midData.qq" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="微信">
              <el-input v-model="midData.weichat" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="固话">
              <el-input v-model="midData.tel" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="公司名称">
              <el-input v-model="midData.company" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="头像">
              <el-input v-model="midData.avatar" />
            </el-form-item>
          </el-col>
        </el-row>
        <!--地址-->
        <el-row>
          <el-form-item label="详细地址">
            <el-input v-model="midData.address" />
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
          >确认</el-button
        >
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogResVisible" title="分配角色">
      <el-form
        ref="contactForm"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="角色">
          <el-tree
            ref="resTree"
            :data="resTree"
            :props="defaultProps"
            show-checkbox
            node-key="roleId"
            default-expand-all
            highlight-current
            style="background-color: #ecf5ff"
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateUserRole()">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import waves from "@/directive/waves";
import swPage from "@/views/common/swPage";

import {
  fetchList,
  createUser,
  updateUser,
  getUserById,
  deleteUser,
  getUserRoleTree,
  closeUser,
  updateUserRole,
  openUser
} from "@/api/auth/user";
import { orgCombobox } from "@/api/auth/org";
const statusOptions = [
  { key: 0, display_name: "view.disable" },
  { key: 1, display_name: "view.normal" }
];

const statusKeyValue = statusOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name;
  return acc;
}, {});

export default {
  name: "userIndex",
  directives: {
    waves
  },
  components: {
    swPage
  },
  filters: {
    statusFilter(key) {
      return statusKeyValue[key];
    }
  },
  computed: {
    hasOrgCombobox: function() {
      return sessionStorage.getItem("userBtns").includes("sysOrg:combobox");
    }
  },
  data() {
    return {
      pList: null,
      cList: null,
      dList: null,
      addr: {
        provId: null,
        cityId: null,
        dictId: null,
        address: null
      },
      tableKey: 0,
      list: null,
      total: null,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        keywords: null,
        orgId: null
      },
      resTree: null,
      dialogResVisible: false,
      dialogFormVisible: false,
      dialogStatus: "",
      defaultProps: {
        children: "children",
        label: "roleName"
      },
      checkedKeys: [],
      textMap: {
        update: "编辑",
        create: "新建"
      },
      isUpdate: false,
      statusOptions,
      midData: {
        //用户数据
        userId: "",
        username: null,
        password: "",
        system: "0",
        email: "",
        mobile: "",
        status: "0",
        nickname: "",
        qq: "",
        weichat: "",
        company: "",
        address: "",
        avatar: "",
        orgId: "",
        addr: null
      },
      currentUserId: "", // 当前选中的用户ID
      rules: {
        username: [
          { required: true, message: "请填写名称", trigger: "blur" },
          {
            pattern: /^[a-zA-Z0-9][a-zA-Z0-9_-]{1,10}$/,
            message: "字母数字横线,字母数字开头"
          }
        ],
        password: [{ required: true, message: "请填写名称", trigger: "blur" }],
        mobile: [{ required: true, message: "请手机号", trigger: "blur" }],
        email: [
          { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }
        ]
      },
      orgList: [] //组织列表
    };
  },
  created() {
    var orgQuery = sessionStorage
      .getItem("userBtns")
      .includes("sysOrg:combobox");
    if (orgQuery) {
      //console.log('orgQuery='+orgQuery)
      this.getorgList();
    }
  },
  methods: {
    getorgList() {
      orgCombobox().then(response => {
        this.orgList = response.data;
      });
    },
    getList() {
      this.listLoading = true;
      fetchList(this.listQuery).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false;
        }, 0.5 * 1000);
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    retPage() {
      //分页
      this.getList();
    },
    resetMidData() {
      this.midData = {
        userId: "",
        username: "",
        password: "",
        system: 0,
        email: "",
        mobile: "",
        status: 1,
        nickname: "",
        qq: "",
        weichat: "",
        company: "",
        address: "",
        avatar: "",
        orgId: "",
        addr: ""
      };
    },
    handleCreate() {
      this.resetMidData();
      this.isUpdate = false;
      this.dialogFormVisible = true;
      this.dialogStatus = "create";
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },

    handleUpdate(row) {
      this.dialogFormVisible = true;
      this.resetMidData();
      this.isUpdate = true;
      this.dialogStatus = "update";
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
      // 获取用户详情
      getUserById(row.userId).then(response => {
        this.addr.provId = response.data.provCode;
        this.cList = response.cityList;
        this.addr.cityId = response.data.cityCode;
        this.dList = response.dictList;
        this.addr.dictId = response.data.dictCode;
        this.midData = response.data;
      });
    },
    updateUserRole() {
      // 全选和半选的全部传给后台
      var checkedKeys = this.$refs.resTree
        .getCheckedKeys(false)
        .concat(this.$refs.resTree.getHalfCheckedKeys());

      var userRoleData = {
        userId: this.currentUserId,
        roleIdSet: checkedKeys
      };
      updateUserRole(userRoleData).then(() => {
        this.dialogResVisible = false;
        this.$notify({
          title: "成功",
          message: "更新成功",
          type: "success",
          duration: 3000
        });
      });
    },
    handleUserRole(row) {
      //加载组织树
      this.currentUserId = row.userId;
      // request -> /sysOrgUserRole/list
      getUserRoleTree(row.userId).then(response => {
        this.resTree = response.data.list;
        this.$refs.resTree.setCheckedKeys(response.data.roleSelectedList);
      });
      this.dialogResVisible = true;
    },
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.midData.addr = this.addr;
          createUser(this.midData).then(() => {
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 3000
            });
            //重新加载数据
            this.getList();
          });
        }
      });
    },
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.midData.provCode = this.addr.provId;
          this.midData.cityCode = this.addr.cityId;
          this.midData.dictCode = this.addr.dictId;
          updateUser(this.midData).then(() => {
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 3000
            });
            //重新加载数据
            this.getList();
          });
        }
      });
    },
    handleDelete(row) {
      this.$confirm("是否删除该记录", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let del = {
            userId: row.userId
          };
          deleteUser(del).then(() => {
            this.$message({
              type: "success",
              message: "删除成功"
            });
            this.getList();
          });
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消" });
        });
    },
    closeUser(row) {
      this.$confirm("是否禁用该用户", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          closeUser(row.userId).then(() => {
            this.$message({
              type: "success",
              message: "禁用成功"
            });
            this.getList();
          });
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消" });
        });
    },
    openUser(row) {
      this.$confirm("是否启用该用户", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          openUser(row.userId).then(() => {
            this.$message({
              type: "success",
              message: "启用成功"
            });
            this.getList();
          });
        })
        .catch(() => {
          this.$message({ type: "info", message: "已取消" });
        });
    }
  }
};
</script>

<style scoped>
.box-card {
  width: 100%;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
</style>
