<template>
  <div id="role">
    <base-header class="bg-primary pb-6 pt-0">
      <div class="row align-items-center py-2">
        <div class="col-lg-6 col-7">
          <breadcrumb
            :link="[
              { name: 'Cài đặt' },
              { name: 'Quản lý quyền', active: true }
            ]"
          ></breadcrumb>
        </div>
      </div>
    </base-header>
    <div class="container-fluid mt--6 bg-secondary">
      <div class="row">
        <div class="col-md-4">
          <div class="card">
            <!-- Card header -->
            <div class="card-header">
              <!-- Title -->
              <h5 class="h3 mb-0">Danh sách nhóm quyền</h5>
              <div class="row">
                <div class="col-xl-6 col-md-12">
                  <button
                    type="button"
                    class="btn btn-success btn-block  mt-1"
                    @click="showModalCreateRole()"
                  >
                    Thêm mới nhóm quyền
                  </button>
                </div>
                <div class="col-xl-6 col-md-12">
                  <button
                    type="button"
                    @click="showModalEditRole()"
                    class="btn  btn-warning btn-block  mt-1"
                  >
                    Chỉnh sửa quyền -
                    {{
                      this.arrRole[this.listRoleActive]
                        ? this.arrRole[this.listRoleActive].name
                        : ""
                    }}
                  </button>
                </div>
              </div>
            </div>

            <!-- Card body -->
            <div class="card-body">
              <!-- List group -->
              <ul class="list-group list-group-flush list my--3">
                <li
                  class="list-group-item px-0"
                  v-for="(item, index) in arrRole"
                  :key="index"
                  @click="getRuleOfRole(item, index)"
                  :class="{ active: index == listRoleActive }"
                >
                  <div class="row align-items-center">
                    <div class="col-auto">
                      <!-- <a href="#" class="avatar rounded-circle">
                                          <img alt="Image placeholder" src="../assets/img/theme/team-1.jpg">
                                      </a> -->
                    </div>
                    <div class="col ml--2">
                      <h4 class="mb-0 role_title">
                        <a href="#!">{{ item.name }}</a>
                      </h4>
                      <!-- <span class="text-success">●</span> -->
                      <small class="role_description">{{
                        item.description
                      }}</small>
                    </div>
                    <div class="col-auto">
                      <i class="ni ni-bold-right pr-4"></i>
                    </div>
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </div>
        <div class="col-md-8 col-xl-6">
          <div class="card" v-if="arrRuleofRole.length == 0">
            <!-- Card header -->
            <div class="card-header">
              <!-- Title -->
              <h5 class="h3 mb-0">Chi tiết nhóm quyền</h5>
            </div>
            <!-- Card body -->
            <div class="card-body">
              <!-- List group -->
              <ul class="list-group list-group-flush list my--3">
                <li class="list-group-item px-0 text-center">
                  Rỗng
                </li>
              </ul>
            </div>
          </div>
          <div v-else id="accordion">
            <div
              class="card"
              v-for="(item, index) in arrRuleofRole"
              :key="index"
            >
              <!-- Card header -->
              <div
                class="card-header container-fluid"
                :id="'headingOne' + item.id"
              >
                <!-- Title -->
                <div class="row">
                  <div class="col-md-10">
                    <button
                      class="btn btn-link"
                      data-toggle="collapse"
                      :data-target="'#collapseOne' + item.id"
                      :aria-expanded="index == 0 ? 'true' : 'false'"
                      :aria-controls="'collapseOne' + item.id"
                    >
                      <i class="fas fa-chevron-down"></i>
                      {{ item.name }}
                    </button>
                    <button
                      type="button"
                      @click="showModalEditGroupRule(item)"
                      class="btn btn-sm btn-warning"
                      data-toggle="modal"
                      data-target="#modalEditRule"
                    >
                      Sửa
                      <i class="fas fa-edit"></i>
                    </button>
                  </div>
                </div>
              </div>
              <div
                :id="'collapseOne' + item.id"
                class="collapse"
                :aria-labelledby="'headingOne' + item.id"
                data-parent="#accordion"
              >
                <!-- Card body -->
                <div class="card-body p-0">
                  <!-- List group -->
                  <ul
                    class="list-group list-group-flush"
                    data-toggle="checklist"
                  >
                    <li
                      class="checklist-entry list-group-item flex-column align-items-start py-4 px-4"
                      v-for="(rule, i) in item.rules"
                      :key="i"
                    >
                      <div class="checklist-item checklist-item-warning">
                        <div class="checklist-info">
                          <h5 class="checklist-title mb-0">{{ rule.name }}</h5>
                        </div>
                        <div class="row">
                          <label
                            v-if="rule.access == 1"
                            class="custom-toggle custom-toggle-warning"
                          >
                            <input
                              type="checkbox"
                              checked
                              @change="changeRule(rule)"
                            />
                            <span
                              class="custom-toggle-slider rounded-circle"
                              data-label-off="No"
                              data-label-on="Yes"
                            ></span>
                          </label>
                          <label
                            v-else
                            class="custom-toggle custom-toggle-warning "
                          >
                            <input type="checkbox" @change="changeRule(rule)" />
                            <span
                              class="custom-toggle-slider rounded-circle"
                              data-label-off="No"
                              data-label-on="Yes"
                            ></span>
                          </label>
                          <button
                            type="button"
                            @click="showModalEditRule(rule)"
                            class="btn btn-sm btn-warning ml-2"
                            data-toggle="modal"
                            data-target="#modalEditRule"
                          >
                            Sửa
                            <i class="fas fa-edit"></i>
                          </button>
                        </div>
                      </div>
                    </li>
                  </ul>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- modal create - edit  role -->
      <div class="modal" tabindex="-1" role="dialog" id="modalCreateEditRole">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">{{ modal_title }}</h5>
              <button
                type="button"
                class="close"
                data-dismiss="modal"
                aria-label="Close"
              >
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <ValidationObserver ref="formCreateEditRole">
                <form>
                  <div class="form-group">
                    <label for="exampleInputEmail1">Tên quyền</label>
                    <ValidationProvider
                      name="Tên quyền"
                      rules="required"
                      v-slot="{ errors }"
                    >
                      <input
                        type="text"
                        class="form-control"
                        id="role_name"
                        v-model="roleObj.name"
                        placeholder="Enter role name"
                      />
                      <small
                        v-if="errors.length > 0"
                        class="form-text text-danger"
                        >{{ errors[0] }}
                      </small>
                    </ValidationProvider>
                  </div>
                  <div class="form-group">
                    <label for="exampleInputEmail1">Mô tả</label>
                    <textarea
                      type="text"
                      class="form-control"
                      id="role_description"
                      rows="5"
                      v-model="roleObj.description"
                      placeholder="Enter description"
                    />
                  </div>
                </form>
              </ValidationObserver>
            </div>
            <div class="modal-footer">
              <button
                type="button"
                class="btn btn-secondary"
                data-dismiss="modal"
                @click="closeModalCreateRole"
              >
                Đóng
              </button>
              <button
                type="button"
                @click="saveCreateRole"
                class="btn btn-primary"
              >
                Lưu lại
              </button>
            </div>
          </div>
        </div>
      </div>
      <!-- modal create - edit  rule -->
      <div class="modal" tabindex="-1" role="dialog" id="modalEditRule">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">{{ modal_title }}</h5>
              <button
                type="button"
                class="close"
                data-dismiss="modal"
                aria-label="Close"
              >
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <ValidationObserver ref="formEditRule">
                <form>
                  <div class="form-group">
                    <label for="exampleInputEmail1">Tên chức năng</label>
                    <ValidationProvider
                      name="Tên chức năng"
                      rules="required"
                      v-slot="{ errors }"
                    >
                      <input
                        type="text"
                        class="form-control"
                        v-if="check == true"
                        v-model="ruleObj.name"
                        placeholder="Enter rule name"
                      />
                      <input
                        type="text"
                        class="form-control"
                        v-else
                        v-model="groupRuleObj.name"
                        placeholder="Enter rule name"
                      />
                      <small
                        v-if="errors.length > 0"
                        class="form-text text-danger"
                        >{{ errors[0] }}
                      </small>
                    </ValidationProvider>
                  </div>
                </form>
              </ValidationObserver>
            </div>
            <div class="modal-footer">
              <button
                type="button"
                class="btn btn-secondary"
                data-dismiss="modal"
                @click="closeModalEditRule"
              >
                Đóng
              </button>
              <button
                type="button"
                @click="saveEditRule"
                class="btn btn-primary"
              >
                Lưu lại
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
// import { mapActions } from "vuex";
import $ from "jquery";
import { userService } from "@/_services";
export default {
  //   name: "user-profile",
  data() {
    return {
      arrRole: [],
      arrRuleofRole: [],
      listRoleActive: 0,
      modal_title: "",
      check: true,
      roleObj: {},
      roleObjTmp: {},
      ruleObj: {},
      ruleObjTmp: {},
      groupRuleObj: {},
      groupRuleObjTmp: {}
    };
  },
  computed: {},
  mounted() {
    this.getListRole();
  },
  methods: {
    getListRole() {
      userService
        .getListRole()
        .then(res => {
          this.arrRole = res;
          if (this.arrRole[0]) {
            this.getRuleOfRole(this.arrRole[0], 0);
            this.roleObj = this.arrRole[0];
          }
        })
        .catch(error => {
          console.log("error", error);
          this.$alertify.error(error.message, {
            duration: 4000
          });
        });
    },
    getRuleOfRole(item, index) {
      this.listRoleActive = index;
      this.roleObj = this.arrRole[index];
      userService
        .getRuleOfRole(item.id)
        .then(res => {
          this.arrRuleofRole = res;
        })
        .catch(error => {
          console.log("error", error);
          this.$alertify.error(error.message, {
            duration: 4000
          });
        });
    },
    // ======================================== ROLE =====================================
    saveCreateRole() {
      var self = this;
      this.$refs.formCreateEditRole.validate().then(success => {
        if (!success) return;
        userService
          .createRole(self.roleObj)
          .then(res => {
            self.arrRole.unshift(res.data);
            $("#modalCreateEditRole").modal("hide");
            this.$alertify.success(res.message, {
              duration: 4000
            });
          })
          .catch(error => {
            this.$alertify.error(error.message, {
              duration: 4000
            });
          });
      });
    },
    showModalCreateRole() {
      this.modal_title = "Thêm mới quyền";
      this.roleObj = {
        id: "",
        name: "",
        description: ""
      };
      $("#modalCreateEditRole").modal("show");
    },
    // show modal chỉnh sửa quyền
    showModalEditRole() {
      this.roleObj = this.arrRole[this.listRoleActive];
      this.roleObjTmp = Object.assign({}, this.roleObj);
      this.modal_title = "Chỉnh sửa quyền";
      $("#modalCreateEditRole").modal("show");
    },
    closeModalCreateRole() {
      this.roleObj = this.arrRole[this.listRoleActive] = this.roleObjTmp;
      $("#modalCreateEditRole").modal("hide");
    },
    // ======================================== RULE =====================================
    // show modal chỉnh sửa chức năng
    showModalEditRule(item) {
      this.modal_title = "Chỉnh sửa chức năng";
      this.ruleObj = item;
      this.ruleObjTmp = Object.assign({}, this.ruleObj);
      this.check = true;
    },
    // show modal chỉnh sửa nhóm chức năng
    showModalEditGroupRule(item) {
      this.modal_title = "Chỉnh sửa nhóm chức năng";
      this.groupRuleObj = item;
      this.groupRuleObjTmp = Object.assign({}, this.groupRuleObj);
      this.check = false;
    },
    changeRule(rule) {
      rule.access = rule.access == 1 ? 0 : 1;
      userService
        .updateAccessRule(
          // id của role
          this.arrRole[this.listRoleActive].id,
          // id của rule
          rule.id,
          rule.access
        )
        .then(res => {
          this.$alertify.success(res.message, {
            duration: 4000
          });
        })
        .catch(error => {
          console.log("error", error);
          this.$alertify.error(error.message, {
            duration: 4000
          });
        });
    },
    saveEditRule() {
      // save edit rule
      var self = this;
      if (self.check) {
        this.$refs.formEditRule.validate().then(success => {
          if (!success) return;
          console.log(self.ruleObj);
          delete self.ruleObj.access;
          userService
            .editRule(self.ruleObj)
            .then(res => {
              $("#modalEditRule").modal("hide");
              console.log(res);
              self.$alertify.success(res.message, {
                duration: 4000
              });
            })
            .catch(error => {
              console.log("error", error);
              self.$alertify.error(error.message, {
                duration: 4000
              });
            });
        });
      } else {
        this.$refs.formEditRule.validate().then(success => {
          if (!success) return;
          delete self.groupRuleObj.rules;
          userService
            .editGroupRole(self.groupRuleObj)
            .then(res => {
              $("#modalEditRule").modal("hide");
              this.$alertify.success(res.message, {
                duration: 4000
              });
            })
            .catch(error => {
              console.log("error", error);
              this.$alertify.error(error.message, {
                duration: 4000
              });
            });
        });
      }
    },
    closeModalEditRule() {
      if (this.check) {
        this.ruleObj.name = this.ruleObjTmp.name;
      } else {
        this.groupRuleObj.name = this.groupRuleObjTmp.name;
      }
      $("#modalEditRule").modal("hide");
    }
  }
};
</script>
<style lang="scss">
.list-group-item {
  cursor: pointer;
}
#role {
  .card {
    margin-bottom: 0px;
  }
}
#role {
  .card {
    .card-header {
      padding-top: 10px;
      padding-bottom: 10px;
    }
  }
}
#role {
  .card {
    .card-body {
      .list-group-item {
        padding-top: 15px !important;
        padding-bottom: 15px !important;
      }
    }
  }
}
#role {
  .card {
    .active {
      .role_description {
        color: #adb5bd;
      }
    }
  }
}
#role {
  .card {
    .active {
      .role_title {
        color: white;
      }
    }
  }
}
</style>
