<template>
  <div class="user_roles">
    <apass-list
      search-placeholder="请输入关键字"
      :list-total="roleTotal"
      @list-action="listAction"
    >
      <el-breadcrumb separator="/" slot="breadcrumb">
        <el-breadcrumb-item to="/authority">权限管理</el-breadcrumb-item>
        <el-breadcrumb-item to="/authority/users">用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>分配角色</el-breadcrumb-item>
      </el-breadcrumb>
      <template slot="header-left">
        <el-button type="primary" @click="setUserRoles">
          保存
        </el-button>
      </template>
      <div class="apass_table" slot="list">
        <el-table class="user_roles_table" :border="false" :data="roleList">
          <el-table-column width="50" align="right"></el-table-column>
          <el-table-column width="300">
            <template slot="header">
              <span style="margin-left: 25px;">角色</span>
            </template>
            <template slot-scope="scope">
              <el-checkbox
                class="apass_checkbox"
                v-model="scope.row.selected"
                @change="updateRoles"
              >
                {{ scope.row.role_name }}
              </el-checkbox>
            </template>
          </el-table-column>
          <el-table-column label="说明">
            <template slot-scope="scope">
              <span v-text="scope.row.detail"></span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </apass-list>
  </div>
</template>

<script>
import apassList from "@/components/apass-list";

export default {
  components: { apassList },
  data: () => ({
    roleTotal: 0,
    roleList: [],
    showDialog: false,
    userRoles: null,
    roles: null,
  }),
  computed: {
    roleIds() {
      return this.roleList.map((item) => item.role_id);
    },
  },
  methods: {
    listAction(filters) {
      // console.log(filters);

      if (this.roles === null) {
        this.getUserRoles(() => {
          this.getRoleList(filters);
        });
      } else {
        this.getRoleList(filters);
      }
    },
    getRoleList(filters) {
      this.$http
        .get(`/apaas/backmgt/role/list`, {
          params: {
            search: filters.keyword,
            page: filters.page,
            limit: filters.size,
          },
        })
        .then(({ data }) => {
          data.data.forEach((item) => {
            item.selected = this.roles.indexOf(item.role_id) > -1;
          });

          this.roleTotal = data.total;
          this.roleList = data.data;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getUserRoles(cb) {
      this.$http
        .get(`/apaas/backmgt/user/roles/${this.$route.params.id}`)
        .then(({ data }) => {
          let userRoles = data.data.map((item) => item.role_id);

          this.userRoles = userRoles;
          this.roles = userRoles;

          typeof cb === "function" && cb();
        })
        .catch((error) => {
          console.log(error);
        });
    },
    updateRoles() {
      this.roles = this.roles
        .filter((item) => {
          return this.roleIds.indexOf(item) === -1;
        })
        .concat(
          this.roleList
            .filter((item) => {
              return item.selected;
            })
            .map((item) => {
              return item.role_id;
            })
        );

      // console.log(this.roles);
    },
    setUserRoles() {
      let add = [];
      let remove = [];
      let requests = [];

      this.roles.forEach((item) => {
        if (this.userRoles.indexOf(item) === -1) {
          add.push(item);
        }
      });

      this.userRoles.forEach((item) => {
        if (this.roles.indexOf(item) === -1) {
          remove.push(item);
        }
      });

      if (add.length > 0) {
        requests.push(
          this.$http.post(`/apaas/backmgt/user/addRole`, {
            user_id: this.$route.params.id,
            role_id: add,
          })
        );
      }

      if (remove.length > 0) {
        requests.push(
          this.$http.post(`/apaas/backmgt/role/userDel`, {
            user_id: this.$route.params.id,
            role_id: remove,
          })
        );
      }

      if (requests.length > 0) {
        Promise.all(requests)
          .then(({ data }) => {
            this.$message({
              message: `分配角色成功.`,
              type: "success",
            });
            
            setTimeout(() => {
              this.$router.push("/authority/users");
            }, 200);
          })
          .catch((error) => {
            this.$message({
              message: "分配角色失败.",
              type: "warning",
            });
          });
      } else {
        this.$message({
          message: "您没有进行任何修改.",
          type: "warning",
        });
      }
    },
  },
};
</script>

<style scoped>
.user_roles {
  height: 100%;
}
</style>
