<template>
  <div>
<!--    <TheSidebar :branch="branches"/>-->
    <CRow class="d-flex flex-row" :class="branches.length ? '' : 'justify-content-center'">
<!--      <CCol class="col-12 col-md-6 col-xl-4">-->
<!--        <CCard class="my-card" @click="addBranch()">-->
<!--          <CCardBody class="d-flex flex-column justify-content-center align-items-center">-->
<!--            <i class="far fa-plus" style="font-size: 28px"></i>-->
<!--            <p class="mt-4">اضافه کردن شعبه</p>-->
<!--          </CCardBody>-->
<!--        </CCard>-->
<!--      </CCol>-->
      <CCol class="col-12 col-md-6 col-xl-4" v-for="(item , index) in branches" :key="index">
        <CCard class="my-card-dynamic">
          <NuxtLink class="link-style" :to="{name : 'admin-branch' , params:{branch: item._id}}">
            <CCardBody class="d-flex flex-row align-items-center">
              <template>
<!--                <el-image v-if="!item.logo.includes('undefined')" style="width: 100px; height: 100px" :src="$config.apiUrl + item.logo" fit="contain"></el-image>-->
                <el-image style="width: 100px; height: 100px;" src="/favicon.png" fit="contain"></el-image>
              </template>
              <p class="mt-4 mr-4 list-services">{{ item.title }}</p>
            </CCardBody>
          </NuxtLink>
          <CCardFooter class="d-flex justify-content-between align-items-center">
<!--            <NuxtLink v-if="hasPermission('super-admin') || hasPermission('branch')" class="btn btn-info" :to="{name : 'admin-branches-branch' , params:{branch: item._id}}">بروزرسانی</NuxtLink>-->
            <div>
              <span class="ml-2" v-if="item.active">فعال</span>
              <span class="ml-2" v-else>غیر فعال</span>
              <span><i class="fad fa-circle" :style="item.active ? 'color: #0ce10c' : 'color: red'"></i></span>
            </div>
          </CCardFooter>
        </CCard>
      </CCol>
    </CRow>
  </div>
</template>

<script>
import moment from "moment-jalaali"
// import login from "@/pages/admin/login";
import axiosUploadProcess from "@/mixins/axiosUploadProcess";
// import HorizontalScroll from 'vue-horizontal-scroll'
// import 'vue-horizontal-scroll/dist/vue-horizontal-scroll.css'
import TheSidebar from "@/components/admin/TheSidebar";


export default {
  components: {TheSidebar},
  data() {
    return {
      mark: '',
      title: 'داشبورد',
      list_title: 'لیست',
      branches: [],
      loading: false,
      validation: {},
    }
  },
  computed: {
    colorTheme: {
      get() {
        return `rgba(${this.hexToRgb(this.branches.colorTheme)} ,1)`
      },
      set(value) {
        this.branches.colorTheme = value
      }
    },
  },
  methods: {
    jDate(date) {
      return moment(date).format("jYYYY/jMM/jDD")
    },
    imagePreview(e) {
      this.branches.logo = URL.createObjectURL(e.target.files[0]);
    },
    addInfo() {
      this.validation = {};
      const data = new FormData();
      data.append("title", this.branches?.title?.trim());
      data.append("caption", this.branches?.caption?.trim());
      data.append("email", this.branches.email);
      data.append("tel", this.branches.tel);
      data.append("location", '[49.67720236907016,34.07654928061605]');
      data.append("address", this.branches.address);
      data.append("socials", JSON.stringify(this.branches.socials));
      data.append("colorTheme", this.branches.colorTheme);
      if (this.$refs.logo.files[0]) data.append("logo", this.$refs.logo.files[0]);


      this.$axios
          .post(`/api/admin/store`, data, this.axiosConfig)
          .then((response) => {
            this.$message({
              type: "success",
              message: "اطلاعات شما با موفقیت ثبت شد",
            });
            window.location.replace('/admin')
          })
          .catch((err) => {
            if (err.response.status === 401) {
              return this.$message({
                type: "error",
                message: "لطفا دوباره وارد سیستم شوید.",
              });
            }
            if (err.response.status === 403) {
              return this.$message({
                type: "error",
                message: err.response.data.message,
              });
            }
            if (err.response.status === 500) {
              return this.$message({
                type: "error",
                message: "مشکلی در ارسال درخواست پیش آمده",
              });
            }
            if (err.response.status === 422) {
              this.validation = err.response.data.validation;
              this.$message({
                type: 'warning',
                message: 'پارامتر هارو بررسی کنید'
              })
            } else console.log(err.response.data);
          });
    },
    addBranch() {
      this.$router.push({name : 'admin-branches-branch' , params:{branch: 'new'}})
    },
    status(store) {

    },
    hasPermission(permission) {
      if (this.$auth.loggedIn) return this.$auth.user.permissions.includes(permission)
      else return false
    },
  },
  head() {
    return {
      title: this.title,
      // link: [
      //   {rel: 'icon', type: 'image/x-icon', href: '/favicon.png'}
      // ],
    }
  },
  layout: 'admin',
  mixins: [axiosUploadProcess],
  async asyncData({$axios, $store, error}) {
    try {
      const requests = [
        $axios.$get(`/api/admin/store/getAll`),
      ]


      const fetch = await Promise.all(requests)

      const [branches] = fetch

      return {
        branches
      }

    } catch (e) {
      console.log(e.message)
      if (e?.response?.status === 401) {
        error({
          status: 401,
          message: "لطفا دوباره وارد سیستم شوید.",
        });
      }
      if (e?.response?.status === 403) {
        error({
          status: 403,
          message: e?.response?.data?.message,
        });
      }
      if (e?.response?.status === 500) {
        error({
          status: 500,
          message: "مشکلی در گرفتن اطلاعات پیش آمده",
        });
      } else
        error({
          status: 404,
          message: "اطلاعات مورد نظر پیدا نشد",
        });
    }
  }
}
</script>
