import React from "react";
import "../Style.css";
//Bootstrap and jQuery libraries
import { Link } from "react-router-dom";
import "bootstrap/dist/css/bootstrap.min.css";
import "jquery/dist/jquery.min.js";
import baseurl from "../../../services/apiconfig";
import $ from "jquery";
import { ToastContainer, toast } from "react-toastify";
import { getToken } from "../../../utils/Auth/token";
import jwt_decode from "jwt-decode"; 
const axios = require("axios");
const isAuthenticated = getToken();
var user = jwt_decode(isAuthenticated);
var tmp = [];
var JsonDataPer = [];

var PermissionArrayStore = [];
class Permission extends React.Component {
  componentDidMount() {
    //Getting ID From URL
    var url = window.location.pathname;
    var id = url.substring(url.lastIndexOf("/") + 1);
    /**
     * User Role
     */
    axios
      .get(baseurl.baseurl + `/role/getRolebyId?id=${id}`, {
        "Access-Control-Allow-Origin": "*",
        "Content-Type": "application/json",
      })
      .then((res) => {

        this.setState({
          id: res.data.data.id,
          role: res.data.data.role,
          additional_info: res.data.data.additional_info,
          permissionArr: res.data.data.permission ? JSON.parse(res.data.data.permission) : [],
        });
        this.SelectedPermissions()
      })
      .catch((err) => {
        //console.log("err",err)
        toast.error("Error occurred at API end (" + err.message + ")");
      });

    /***
     * Permission List
     */
    axios
      .get(baseurl.baseurl + `/role/backend/modules/list`)
      .then((res) => {
        this.setState({ moduleList: res.data.data });
      })
      .catch((err) => {
        //console.log("err",err)
        toast.error("Error occurred at API end (" + err.message + ")");
      });
  }

  constructor() {
    super();
    this.state = {
      additional_info: "",
      role: "",
      permissionId: [],
    };
  }
  handleChange(evt) {
    this.setState({
      [evt.target.name]: evt.target.value,
    }); 
    $(evt.target).parents('._parent_row').find("input[type=checkbox]").not(evt.target).removeAttr("checked").prop("checked", false);
      
  }
  /****
   * Handle Permission
   */

  // handleClick(evt) {

  //   this.setState({
  //     [evt.target.name]: evt.target.value,
  //   });

  //   var check = evt.target.checked;
  //   var Name = evt.target.value;
  //   var value = Name.split('-');
  //   if (evt.target.checked) {
  //     var checked = value[0];
  //     tmp.push(checked);
  //   } else {
  //     tmp.splice($.inArray(checked, tmp), 1);
  //   }
  // }
  SelectedPermissions() {
    this.state.permissionArr.map((k, v) => {
      k.submodules.map((vv, kk) => {
        var jsonOb = {
          name: vv.module,
          value: vv.permission,
        };
        PermissionArrayStore.push(jsonOb)
      });
    });
  }

  handlePermission(evt) {
    var permissions = $('.individual_checkbox');
    var PermissionArray = [];
    permissions.map((k, v) => {
      if ($(v).is(":checked")) {
        var name_ = $(v).attr('name');
        var value = $(v).val();
        var jsonOb = {
          name: name_,
          value: value,
        };
        PermissionArray.push(jsonOb)
      }
    });
    var subModule = [];
    var Name = this.state.permission;
    var perArr = [];
    this?.state?.moduleList &&
      this?.state?.moduleList?.map((data, key) => {
        var InnerJson = [];
        var parentModulePer = null;
        data?.SubModules?.map((v, k) => {
          var permission_ = "";
          var name_ = "permission[" + data?.Slug + "][" + v.module + "]";
          PermissionArray.map(function (person) {
            if (person.name == name_) {
              permission_ = person.value;
              return;
            }
          });
          InnerJson.push({
            "module": v.module,
            "permission": permission_,
            "others": ""
          })
          if(permission_ >= parentModulePer){
            parentModulePer = permission_;
          }
        })
        perArr.push({
          "module": data?.Slug,
          "permission": parentModulePer,
          "submodules": InnerJson,

        })

      });

    const JsonData = {
      RoleName: this.state.role,
      AdditionalInfo: this.state.additional_info,
      UpdatedBy: user?.id,
      Permissions: perArr,
    }
    axios
      .put(baseurl.baseurl + `/role/backend/update/permissions/${this.state.id}`, JsonData)
      .then((res) => {
        toast.success(res.data.message);
        window.location.reload();
      })
      .catch((err) => {
        //console.log("err",err)
        toast.error("Error occurred at API end (" + err.message + ")");
      });
  }

  render() {
    var permissions = [{
      "permission": "1",
      "text": "List",
    }, {
      "permission": "2",
      "text": "List | Edit",
    }, {
      "permission": "3",
      "text": "List | Add",
    }, {
      "permission": "4",
      "text": "List | Edit | Add",
    }, {
      "permission": "5",
      "text": "List | Edit | Add | Delete",
    },]
    return (
      <div>
        <ToastContainer />
        <section className="breadcrumbs">
          <span>
            <Link className="crumbs" to={"/dashboard"}>
              Home
            </Link>
          </span>{" "}
          <span>
            <span className="fa fa-circle dot"></span>
          </span>{" "}
          <Link className="crumbs" to={"/user"}>
            User Management
          </Link>{" "}
          <span>
            <span className="fa fa-circle dot"></span>
          </span>{" "}
          <span>User Permission</span>
        </section>
        <section className="content">
          <div className="row">
            <div className="col-md-12">
              <div className="box box-primary">
                <div className="box-header">
                  <h3 className="box-title"> Assign Permission</h3>
                </div>
                <hr />
                <div className="tab-content">
                  <div className="col-lg-12 col-sm-12 col-xs-12">
                    <h5><span className="heading">Role Name: </span>&nbsp;<span className="role_name text-tr">{this?.state?.role}</span></h5>
                  </div><br />
                  <form>

                    {this?.state?.moduleList &&
                      this?.state?.moduleList?.map((data, key) => {
                        return (
                          <>
                            <div className="col-lg-12 col-sm-12 col-xs-12">
                              <div className="form-group">
                                <strong>Module : </strong><span className="text-tr">{data?.ModuleName}</span>

                              </div>
                              {data?.SubModules &&
                                data?.SubModules.map((v, k) => {
                                  return <> <div className="mt-2">
                                    <p className="font_permission"><label className="text-tr">{v.module}</label></p>
                                    <div className="row _parent_row">
                                      {
                                        permissions.map((vv, kk) => {
                                          var permission_ = "";
                                          PermissionArrayStore.map(function (person) {
                                            if (person.name == v.module) {
                                              permission_ = person.value;
                                              return;
                                            }
                                          })
                                          return <>
                                            <div className={kk > 2 ? "sub_module col-lg-3" : "sub_module col-lg-2"}>
                                              <label class="checkbox checkbox-lg checkbox-light-primary checkbox-inline flex-shrink-0 m-0 mx-4">
                                                <input
                                                  type="checkbox"
                                                  value={vv.permission}
                                                  id="Checkbox"
                                                  name={"permission[" + data?.Slug + "][" + v.module + "]"}
                                                  class="checkBoxViewEdit individual_checkbox "
                                                  onClick={(evt) => this.handleChange(evt)}
                                                  defaultChecked={(permission_ == vv.permission) ? true : false}
                                                />
                                                <span></span>
                                                &nbsp; <small className="permission_"> {vv.text}</small>
                                              </label>
                                            </div></>
                                        })
                                      }

                                      <br />
                                    </div>
                                  </div>
                                  </>
                                })}
                            </div>
                            <hr></hr>
                          </>
                        );
                      })}
                    <div className="col-lg-12 col-sm-12 col-xs-12">
                      <div className="form-group">
                        <center>
                          <input
                            className="btn btn-warning"
                            type="button"
                            value="Update"
                            onClick={(evt) => this.handlePermission(evt)}
                          />
                        </center>
                      </div>
                    </div>
                  </form>
                </div>
              </div>
            </div>
          </div>
        </section >
      </div >
    );
  }
}
export default Permission;
