<template>
<div class="container-fluid">
  <section class="content">
    <div class="header pb-2">
      <div class="header-body">
        <div class="row align-items-center py-4">
          <div class="col-lg-6 col-7">
            <nav
              aria-label="breadcrumb"
              class="d-none d-md-inline-block ml-md-4"
            >
              <ol class="breadcrumb breadcrumb-links">
                <li class="breadcrumb-item">
                  <a href="#"><i class="fas fa-home"></i></a>
                </li>
                <li class="breadcrumb-item">
                  <a href="#">Dashboards</a>
                </li>
                <li class="breadcrumb-item active" aria-current="page">
                  ໝວດໝູ່ ສິນຄ້າ
                </li>
              </ol>
            </nav>
          </div>
          <div class="col-lg-6 col-5 text-right"></div>
        </div>
      </div>
    </div>
    <div class="row" v-if="isLoggedIn">
      <div class="col-md-6 col-lg-4" v-if="$store.getters['getroles'].includes('setting_session_add')">
        <div class="card" id="EditCat">
          <form @submit.prevent="AddSes">
            <div class="card-header border-0">
              <div class="row d-flex justify-content-between px-2">
                <div>
                  <h3 class="mb-0">ເພີ່ມປະເພດສິນຄ້າ</h3>
                </div>
                <div></div>
              </div>
            </div>
            <div class="card-body mt--4">
              <label class="form-control-label"
                >ຊື່ໝວດໝູ່: <span class="text-red">* </span></label
              >
              <div class="input-group input-group-merge">
                <div class="input-group-prepend">
                  <span class="input-group-text"
                    ><i class="fas fa-file-signature"></i
                  ></span>
                </div>
                <input
                  type="text"
                  class="form-control"
                  v-model="FormSes.name"
                  ref="session_name_focus"
                />
              </div>
              <div class="d-flex justify-content-between mt-2">
                <div style="width: 48%">
                  <label class="form-control-label">ເລືອກໝວດໝູ່ຫຼັກ: </label>
                  <div class="input-group input-group-merge mb-2">
                    <div class="input-group-prepend">
                      <span class="input-group-text"
                        ><i class="fa fa-id-card"></i
                      ></span>
                    </div>
                    <select class="form-control" v-model="FormSes.cat_id">
                      <option value="">== ເລືອກ ==</option>
                      <option
                        v-bind:value="ls.id"
                        :key="ls.id"
                        v-for="ls in lsesion"
                      >
                        {{ ls.s_name }}
                      </option>
                    </select>
                  </div>
                </div>
                <div style="width: 48%">
                  <label class="form-control-label">ເລືອກໝວດໝູ່ຍ່ອຍ: </label>
                  <div class="input-group input-group-merge mb-2">
                    <div class="input-group-prepend">
                      <span class="input-group-text"
                        ><i class="fa fa-id-card"></i
                      ></span>
                    </div>
                    <select class="form-control" v-model="FormSes.subcat_id">
                      <option value="">== ເລືອກ ==</option>
                      <option
                        v-bind:value="ls.id"
                        :key="ls.id"
                        v-for="ls in susesion"
                      >
                        {{ ls.s_name }}
                      </option>
                    </select>
                  </div>
                </div>
              </div>
              <div>
                <label class="form-control-label">ລາຍລະອຽດ: </label>
                <div class="input-group input-group-merge">
                  <div class="input-group-prepend">
                    <span class="input-group-text"
                      ><i class="fas fa-info-circle"></i
                    ></span>
                  </div>
                  <input
                    type="text"
                    class="form-control"
                    placeholder="ລາຍລະອຽດ"
                    v-model="FormSes.detail"
                  />
                </div>
              </div>
              <div class="d-flex justify-content-end mt-2">
                <button type="submit" :disabled="ChekF" class="btn btn-info">
                  ບັນທຶກຂໍ້ມູນ</button
                ><button
                  type="button"
                  @click="CancelAddCat"
                  class="btn btn-secondary"
                >
                  ຍົກເລີກ
                </button>
              </div>
            </div>
          </form>
        </div>
      </div>

      <div class="col-md-6 col-lg-8">
        <div class="card">
          <div class="card-header border-0">
            <div class="row d-flex justify-content-between px-2">
              <div>
                <h3 class="mb-0">ລາຍການປະເພດສິນຄ້າ</h3>
              </div>
              <div>
                <div class="form-group" style="margin-bottom: 0">
                  <div class="input-group input-group-merge">
                    <input
                      class="form-control"
                      type="text"
                      placeholder="ຄົ້ນຫາໝວດສິນຄ້າ..."
                      v-model="searchCat"
                      v-on:keyup="searchCatup($event)"
                    />
                    <div class="input-group-append">
                      <span class="input-group-text"
                        ><i class="fas fa-search"></i
                      ></span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="table-responsive">
            <div class="p-2 custom-control custom-checkbox">
              ການຈັດລຽງ:

              <div
                class="custom-control custom-radio custom-control-inline ml-2"
              >
                <input
                  type="radio"
                  id="sort1"
                  name="sort1"
                  value="asc"
                  v-model="sort"
                  :checked="sort == 'asc'"
                  class="custom-control-input"
                />
                <label class="custom-control-label" for="sort1"
                  >ນ້ອຍຫາໃຫບ່</label
                >
              </div>
              <div class="custom-control custom-radio custom-control-inline">
                <input
                  type="radio"
                  id="sort2"
                  name="sort1"
                  value="desc"
                  v-model="sort"
                  :checked="sort == 'desc'"
                  class="custom-control-input"
                />
                <label class="custom-control-label" for="sort2"
                  >ໃຫຍ່ຫານ້ອຍ</label
                >
              </div>

              <input
                type="checkbox"
                class="custom-control-input"
                v-model="shSubcat"
                :checked="shSubcat"
                id="sortCheck1"
              />
              <label class="custom-control-label ml-4" for="sortCheck1"
                >ສະແດງໝວດໝູ່ຍ່ອຍ</label
              >
            </div>
            <table class="table align-items-center table-flush">
              <thead class="thead-light">
                <tr>
                  <!-- <th width="30">ID</th> -->
                  <th class="text-lefttable-user-info">ຊື່ໝວດໝູ່</th>
                  <th width="80" class="text-center" v-if="$store.getters['getroles'].includes('setting_session_edit') || $store.getters['getroles'].includes('setting_session_remove')">ຈັດການ</th>
                </tr>
              </thead>
              <tr v-if="LoadingSes">
                  <td colspan="2" class="text-center">
                     <content-loader viewBox="-10 10 450 110" >
                            <rect x="0" y="0" rx="3" ry="3" width="350" height="5" />
                            <rect x="10" y="20" rx="3" ry="3" width="320" height="5" />
                            <rect x="0" y="40" rx="3" ry="3" width="370" height="5" />
                            <rect x="10" y="60" rx="3" ry="3" width="350" height="5" />
                            <rect x="0" y="80" rx="3" ry="3" width="300" height="5" />
                            <rect x="10" y="100" rx="3" ry="3" width="380" height="5" />
                      </content-loader>
                  </td>
                </tr>
              <tbody v-if="!LoadingSes">
                
                <tr v-if="SessionNoData">
                  <td colspan="2" class="text-center">ບໍ່ມີຂໍ້ມູນ</td>
                </tr>
                <tr v-for="ses in Session.data" :key="ses.id">
                  <td>
                    <i class="fas fa-dot-circle mr-2"></i>
                    <b> {{ ses.s_name }}</b>
                    <span v-if="shSubcat">
                      <ul v-for="sub in allSes" :key="sub.id">
                        <li
                          v-if="
                            sub.s_cat_id == ses.id && sub.s_subcat_id == null
                          "
                          class="pl-4 m-2"
                        >
                          <i class="fas fa-angle-double-right"></i>
                          {{ sub.s_name }}
                          <a
                            href="#EditCat"
                            @click="EditCat(e, ses.id, sub.id, '')"
                            class="badge badge-pill badge-info"
                            ><i class="fas fa-edit"></i
                          ></a>
                          |
                          <a
                            href="javascript:void(0)"
                            @click="DelCat(sub.id)"
                            class="badge badge-pill badge-danger"
                            ><i class="fas fa-trash-alt"></i
                          ></a>

                          <ul v-for="subb in allSes" :key="subb.id">
                            <li
                              v-if="sub.id == subb.s_subcat_id"
                              class="my-2 pl-4 m-2"
                            >
                              <i class="fas fa-angle-right"></i>
                              {{ subb.s_name }}
                              <a
                                href="#EditCat"
                                @click="EditCat(e, ses.id, sub.id, subb.id)"
                                class="badge badge-pill badge-info"
                                ><i class="fas fa-edit"></i
                              ></a>
                              |
                              <a
                                href="javascript:void(0)"
                                @click="DelCat(subb.id)"
                                class="badge badge-pill badge-danger"
                                ><i class="fas fa-trash-alt"></i
                              ></a>
                            </li>
                          </ul>
                        </li></ul
                    ></span>
                  </td>
                  <td v-if="$store.getters['getroles'].includes('setting_session_edit') || $store.getters['getroles'].includes('setting_session_remove')">
                    <div class="col-auto">
                      <button
                        type="button"
                        class="btn btn-sm btn-neutral mr-0"
                        data-toggle="dropdown"
                        aria-haspopup="true"
                        aria-expanded="false"
                      >
                        <i class="fas fa-ellipsis-h"></i>
                      </button>
                      <div class="dropdown-menu dropdown-menu-right" style="">
                        <a v-if="$store.getters['getroles'].includes('setting_session_edit')" class="dropdown-item" href="#EditCat" @click="EditCat(e, ses.id, '', '')" ><i class="fas fa-user-edit text-info"></i >ແກ້ໄຂຂໍ້ມູນ</a >
                        <a v-if="$store.getters['getroles'].includes('setting_session_remove')" class="dropdown-item" href="javascript:void(0)" @click="DelCat(ses.id)" ><i class="fas fa-trash text-red"></i>ລຶບຂໍ້ມູນ</a >
                      </div>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
            <vuePagination
              :pagination="Session"
              @paginate="GetAllSes()"
              :offset="4"
            ></vuePagination>
          </div>
        </div>
      </div>
    </div>
  </section>
</div>
</template>

<script>
export default {
  name: "StoreSetting",

  components: {},

  directives: {},
  watch: {
    "FormSes.cat_id"() {
      this.FormSes.subcat_id = "";
    },
    sort() {
      this.GetAllSes();
    },
    "$store.state.status"() {
      this.allSes = this.$store.getters["getallsession"];
      this.Session = this.$store.getters["getsession"];
    },
  },
  data() {
    return {
      Session: [],
      allSes: [],
      //Session: this.$store.getters["getsession"], //$store.getters["getsession"]
      //allSes: this.$store.getters["getallsession"], //$store.getters["getallsession"]
      FormSes: {
        name: "",
        cat_id: "",
        subcat_id: "",
        detail: "",
      },
      FormType: true,
      FormIdUpdate: "",
      LoadingSes: false,
      polling: null,
      searchCat: "",
      sort: "asc",
      shSubcat: false,
      isLoggedIn: false,
      //lsesion: this.Session.data.filter((e)=>e.s_sub_id =='')
    };
  },

  mounted() {},
  computed: {
    ChekF() {
      if (this.FormSes.name == "") {
        return true;
      } else {
        return false;
      }
    },
    SessionNoData() {
      if (this.Session == "") {
        return true;
      } else {
        if (this.Session.data.length == 0) {
          return true;
        } else {
          return false;
        }
      }
    },
    lsesion() {
      if (this.allSes != "") {
        return this.allSes.filter((e) => e.s_cat_id == null);
      } else {
        return "";
      }
    },
    susesion() {
      if (this.allSes != "") {
        let dat = this.allSes.filter((e) => e.s_cat_id != null);
        let dat2 = dat.filter((e) => e.s_cat_id == this.FormSes.cat_id);
        return dat2.filter((e) => e.s_subcat_id == null);
      } else {
        return "";
      }
    },
  },
  methods: {
    searchCatup(e) {
      if (!this.searchCat) {
        this.doSearch();
      }
      if (e.which == 13) {
        this.doSearch();
      }
    },
    doSearch() {
      this.LoadingSes = true;
      this.$axios.get("/sanctum/csrf-cookie").then((response) => {
        axios
          .get(`/api/store/setting?page=1&s=${this.searchCat}`)
          .then((response) => {
            this.Session = response.data.que;
            this.$Progress.finish();
            this.LoadingSes = false;
          })
          .catch(() => {
            console.error(error);
            this.$Progress.fail();
          });
      });
    },
    async EditCat(e, id, catid, subcatid) {
      //console.log(id+'|'+catid+'|'+subcatid)

      if (catid == "" && subcatid == "") {
        let item = this.allSes.find((i) => i.id == id);
        this.FormSes.name = item.s_name;
        this.FormSes.cat_id = "";
        this.FormSes.subcat_id = "";
        this.FormSes.detail = item.s_detail;
        this.FormIdUpdate = item.id;
        //console.log(item.s_cat_id)
      }
      if (id != "" && catid != "" && subcatid == "") {
        let item = this.allSes.find((i) => i.id == catid);
        this.FormSes.name = item.s_name;
        this.FormSes.cat_id = item.s_cat_id;
        this.FormSes.subcat_id = "";
        this.FormSes.detail = item.s_detail;
        this.FormIdUpdate = item.id;
      }
      if (id != "" && catid != "" && subcatid != "") {
        //console.log(id+'|'+catid+'|'+subcatid)
        //this.FormSes.subcat_id = ''
        let item = this.allSes.find((i) => i.id == subcatid);
        this.FormSes.name = item.s_name;
        this.FormSes.cat_id = item.s_cat_id;
        this.FormSes.detail = item.s_detail;
        this.FormIdUpdate = item.id;
        this.FormSes.subcat_id = await item.s_subcat_id;
      }
      this.FormType = false;
      this.polling = setInterval(() => {
        this.$refs.session_name_focus.focus();
        clearInterval(this.polling);
      }, 900);
    },
    AddSes() {
      if (this.FormType) {
        this.$Progress.start();
        this.$axios.get("/sanctum/csrf-cookie").then((response) => {
          axios
            .post("/api/store/setting/add", {
              session_name: this.FormSes.name,
              cat_id: this.FormSes.cat_id,
              subcat_id: this.FormSes.subcat_id,
              detail: this.FormSes.detail,
              sort: this.sort,
            })
            .then((response) => {
              if (response.data.success) {
                this.Session = response.data.que;
                this.allSes = response.data.all_que;
                this.$store.dispatch({ type:"reSetSession" })
                this.FormType = true;
                this.$Progress.finish();
                this.$notify( { group: "sucess", title: "ສຳເລັດ!", text: response.data.message }, 2000 );
              } else {
                this.$notify({ group: "error", title: "ບໍ່ສຳເລັດ!", text: 'ຜິດຜາດ: '+response.data.message }, 4000)
                this.$Progress.fail();
              }
            })
            .catch((error) => {
              this.$notify( { group: "error", title: "ບໍ່ສຳເລັດ!", text: "ຜິດຜາດ: " + error.message, }, 4000 );
              // console.error(error);
            });
        });
      } else {
        this.$axios.get("/sanctum/csrf-cookie").then((response) => {
          axios
            .post(`/api/store/setting/update/${this.FormIdUpdate}`, {
              s_name: this.FormSes.name,
              s_cat_id: this.FormSes.cat_id,
              s_subcat_id: this.FormSes.subcat_id,
              s_detail: this.FormSes.detail,
              sort: this.sort,
            })
            .then((response) => {
              
              if (response.data.success) {
                this.FormType = true;
                this.FormSes.name = "";
                this.FormSes.cat_id = "";
                this.FormSes.subcat_id = "";
                this.FormSes.detail = "";
                this.FormIdUpdate = "";
                this.Session = response.data.que;
                this.allSes = response.data.all_que;
                this.$store.dispatch({ type:"reSetSession" })
                this.$Progress.finish();
                this.$notify( { group: "sucess", title: "ສຳເລັດ!", text: response.data.message }, 2000 );
              } else {
               // this.error = response.data.message;
                this.$notify( { group: "error", title: "ບໍ່ສຳເລັດ!", text: "ຜິດຜາດ: " + response.data.message }, 4000 );
                //console.error(error);
                this.$Progress.fail();
              }
            })
            .catch((error) => {
              this.$notify( { group: "error", title: "ບໍ່ສຳເລັດ!", text: "ຜິດຜາດ: " + error.message, }, 4000 );
              this.$Progress.fail();
              //console.error(error);
            });
        });
      }
    },
    DelCat(id) {
      let item = this.allSes.find((i) => i.id == id);
      if (item.s_cat_id == null && item.s_subcat_id == null) {
        let item2 = this.allSes.filter((e) => e.s_cat_id == item.id);
        if (item2.length == 0) {
          // console.log('Ok')
          this.Del(id);
        } else {
          this.$swal.fire( "ບໍ່ສຳເລັດ!", "ລະບົບບໍ່ອານຸຍາດໃຫ້ລຶບອອກຈາກຖານຂໍ້ມູນ ເນື່ອງຈາກຍັງຖຶກນຳໃຊ້ຢູ່.", "error" );
        }
      } else {
        let itemCat = this.allSes.find((i) => i.id == id);
        if (itemCat.s_subcat_id == null) {
          let itemCat2 = this.allSes.filter((e) => e.s_subcat_id == itemCat.id);
          if (itemCat2.length == 0) {
            //console.log('Del Cat Ok')
            this.Del(id);
          } else {
            this.$swal.fire( "ບໍ່ສຳເລັດ!", "ລະບົບບໍ່ອານຸຍາດໃຫ້ລຶບອອກຈາກຖານຂໍ້ມູນ ເນື່ອງຈາກຍັງຖຶກນຳໃຊ້ຢູ່.", "error" );
          }
        } else {
          let items = this.allSes.find((i) => i.id == id);
          if (items.s_cat_id != null && items.s_subcat_id != null) {
            // console.log('Del Sub Cat Ok')
            this.Del(id);
          } else {
            this.$swal.fire( "ບໍ່ສຳເລັດ!", "ລະບົບບໍ່ອານຸຍາດໃຫ້ລຶບອອກຈາກຖານຂໍ້ມູນ ເນື່ອງຈາກຍັງຖຶກນຳໃຊ້ຢູ່.", "error" );
          }
        }
      }
      /*

            */
    },
    Del(id) {
      this.$swal
        .fire({
          title: "ທ່ານແນ່ໃຈບໍ່?",
          text: "ທີ່ຈະລຶບຂໍ້ມູນນີ້!",
          icon: "warning",
          showCancelButton: true,
          confirmButtonColor: "#3085d6",
          cancelButtonColor: "#d33",
          confirmButtonText: "ລຶບເລີຍ!",
          cancelButtonText: "ຍົກເລີກ",
        })
        .then((result) => {
          if (result.isConfirmed) {
            this.$Progress.start();
            this.$axios.get("/sanctum/csrf-cookie").then((response) => {
              this.$axios
                .delete(`/api/store/setting/delete/${id}`)
                .then((response) => {
                  this.GetAllSes();

                  if (response.data.success) {
                    this.$Progress.finish();
                    this.$notify( { group: "sucess", title: "ສຳເລັດ!", text: response.data.message }, 2000 );
              
                  } else {
                   this.$notify( { group: "error", title: "ບໍ່ສຳເລັດ!", text: "ຜິດຜາດ: " + response.data.message }, 4000 );
                    this.$Progress.fail();
                  }
                })
                .catch((error) => {
                  this.$notify( { group: "error", title: "ບໍ່ສຳເລັດ!", text: "ຜິດຜາດ: " + error.message, }, 4000 );
                  //console.error(error)
                  this.$Progress.fail();
                });
            });
          }
        });
    },
    CancelAddCat() {
      this.FormType = true;
      this.FormSes.name = "";
      this.FormSes.cat_id = "";
      this.FormSes.subcat_id = "";
      this.FormSes.detail = "";
      this.FormIdUpdate = "";
    },
    GetAllSes(bpage) {
      this.LoadingSes = true;
      this.$Progress.start();
      if (typeof bpage == "undefined") {
        this.$axios.get("/sanctum/csrf-cookie").then((response) => {
          axios
            .get(
              `/api/store/setting?page=${this.Session.current_page}&sort=${this.sort}`
            )
            .then((response) => {
              this.LoadingSes = false;
              this.$store.dispatch({ type:"reSetSession" })
              //console.log(response.data.all_que)
              if(response.data.message){
                this.$notify( { group: "error", title: "ບໍ່ສຳເລັດ!", text: "ຜິດຜາດ: " + response.data.message, }, 4000 );
               this.$Progress.fail();
              } else {
                  if (response.data.que.data.length < 1) {
                  let bp = this.Session.current_page - 1;
                  if (bp >= 1) {
                    this.GetAllSes(bp);
                  } else {
                    this.Session = response.data.que;
                    this.allSes = response.data.all_que;
                  }
                } else {
                  this.Session = response.data.que;
                  this.allSes = response.data.all_que;
                  this.$Progress.finish();
                }
              }

            })
            .catch((error) => {
              this.$notify( { group: "error", title: "ບໍ່ສຳເລັດ!", text: "ຜິດຜາດ: " + error.message, }, 4000 );
              this.LoadingSes = false;
              this.Session = "";
              this.allSes = "";
              //console.error(error);
              this.$Progress.fail();
            });
        });
      } else {
        this.$axios.get("/sanctum/csrf-cookie").then((response) => {
          axios
            .get(`/api/store/setting?page=${bpage}&sort=${this.sort}`)
            .then((response) => {
              this.LoadingSes = false;
              if(response.data.message){
                this.$notify( { group: "error", title: "ບໍ່ສຳເລັດ!", text: "ຜິດຜາດ: " + response.data.message }, 4000 );
                this.$Progress.fail();
              } else {
                this.$store.dispatch({ type:"reSetSession" })
                this.Session = response.data.que;
                this.allSes = response.data.all_que;
                this.$Progress.finish();
              }
              

            })
            .catch((error) => {
               this.$notify( { group: "error", title: "ບໍ່ສຳເລັດ!", text: "ຜິດຜາດ: " + error.message }, 4000 );
              this.LoadingSes = false;
             // console.error(error);
              this.$Progress.fail();
            });
        });
      }
    },
  },
  created() {
    this.$axios.get(`/api/users/checkauth`).then((response) => {
      if (!response.data.isLogin) {
        window.location.href = "/";
      }
    });
    this.GetAllSes();
    if (!this.$store.getters["getallsession"]) {
      this.$store.dispatch({ type: "reSetSession" });
    }

    if(window.Laravel.isLoggedin){
           this.isLoggedIn = true
        }

  },

  beforeRouteEnter(to, from, next) {
    if (!window.Laravel.isLoggedin) {
      window.location.href = "/";
    }
    next();
  },
};
</script>

<style lang="scss" scoped></style>
