<template>
  <div>
    <CustomSubHeader>
      <CBreadcrumb class="border-0 mb-0">{{ title }}</CBreadcrumb>
      <CButton size="sm" color="primary" class="mr-auto" :to="{ name: 'admin-occasion' }">برگشت به صفحه قبل</CButton>
      <CButton v-if="$route.params.details === 'new'" size="sm" color="success" class="mr-1" @click="post">افزودن
      </CButton>
      <CButton v-else size="sm" color="success" class="mr-1" @click="update">بروزرسانی</CButton>
    </CustomSubHeader>
    <CRow style="display : flex ; flex-direction: column">
      <CRow>
        <CCol lg="6">
          <CCard>
            <CCardBody>
              <CCol sm="12">
                <CTextarea :class="validation.title ? 'err' : null" label="عنوان" :description="
                      validation.title ? validation.title.msg : null
                    " v-model="occasion.title" />
              </CCol>
              <el-divider></el-divider>
              <CCol sm="12">
                <CRow style="align-items: baseline;">
                  <CCol col="md-3" class="mb-2">
                    <span>تاریخ شروع</span>
                  </CCol>
                  <CCol col="md-9">
                    <date-picker clearable :min="nowDate" format="YYYY-MM-DD" display-format="jMMMM jD"
                                 v-model="occasion.startDate"></date-picker>
                  </CCol>
                  <p style="margin-top : 5px !important ; color: red;" class="form-err" v-if="validation.startDate">
                    {{ validation.startDate.msg }}
                  </p>
                </CRow>
              </CCol>
              <CCol sm="12">
                <CRow style="align-items: baseline;">
                  <CCol col="md-3" class="mb-2">
                    <span>تاریخ اتمام</span>
                  </CCol>
                  <CCol col="md-9">
                    <date-picker clearable :min="occasion.startDate || nowDate" format="YYYY-MM-DD" display-format="jMMMM jD"
                                 v-model="occasion.endDate"></date-picker>
                  </CCol>
                  <p style="margin-top : 5px !important ; color: red;" class="form-err" v-if="validation.endDate">
                    {{ validation.endDate.msg }}
                  </p>
                </CRow>
              </CCol>
            </CCardBody>
          </CCard>
        </CCol>
        <CCol lg="6">
          <CCard>
            <CCardBody>
              <CCol sm="12">
                <el-checkbox v-model="occasion.publish"
                  label="نمایش مناسبت" />
              </CCol>
              <el-divider></el-divider>
              <CCol sm="12">
                <h6 class="mt-2">ترتیب نمایش</h6>
                <el-select style="width:100%" class="mt-2" v-model="occasion.index" placeholder="">
                  <el-option
                      v-for="item in allOccasion.length + 10"
                      v-if="!allOccasion.find((item2) => item2.index === item)"
                      :key="item"
                      :label="item"
                      :value="item">
                  </el-option>
                </el-select>
                <p style="margin-top : 5px !important ; color: red;" class="form-err" v-if="validation.index">
                  {{ validation.index.msg }}
                </p>
              </CCol>
            </CCardBody>
          </CCard>
        </CCol>
      </CRow>
      <CRow>
        <CCol>
          <CCard>
            <CCardBody>
              <CCol sm="12">
                <h5>بنر</h5>
                <el-divider />
                <CCol>
                  <img :src="occasion.mainCover" style="width: 100%;" alt="" />
                </CCol>
                <input type="file" ref="cover" @change="imagePreview" />
                <p style="margin-top : 5px !important ; color: red;" class="form-err" v-if="validation.cover">
                  {{ validation.cover.msg }}
                </p>
                <p class="mt-3 text-muted">
                  عکس 1920*180 باشد. در غیر این صورت اتوماتیک بریده می شود.
                </p>
              </CCol>
            </CCardBody>
          </CCard>
        </CCol>
      </CRow>
    </CRow>
  </div>
</template>

<script>
  import axiosUploadProcess from "@/mixins/axiosUploadProcess";
  import moment from "moment-jalaali";

  export default {
    data() {
      return {
        occasion: null,
        validation: {},
        editorConfig: {
          language: "en",
          extraPlugins: ["bidi", "justify"],
        },
        loading : false,
        allOccasion : null
      };
    },
    mixins: [axiosUploadProcess],
    computed: {
      title() {
        return this.$route.params.details === "new" ?
          "افزودن مناسبت جدید" :
          "مشاهده جزئیات مناسبت";
      },
      nowDate(){
        return moment().format('YYYY-MM-DD')
      },
    },
    methods: {
      imagePreview(e) {
        this.occasion.cover = URL.createObjectURL(e.target.files[0]);
      },
      post() {
        this.validation = {};
        const data = new FormData();
        data.append("title", this.occasion.title.trim());
        data.append("startDate", this.occasion.startDate);
        data.append("endDate", this.occasion.endDate);
        data.append("index", this.occasion.index);
        data.append("publish", this.occasion.publish);
        data.append("status", this.occasion.status);
        if (this.$refs.cover.files[0])
          data.append("cover", this.$refs.cover.files[0]);

        this.$axios
          .post(`/api/admin/occasion`, data, this.axiosConfig)
          .then((response) => {
            this.$message({
              type: "success",
              message: "مناسبت با موفقیت ایجاد شد.",
            });
            this.$router.push({
              name: "admin-occasion",
            });
          })
          .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;
            else console.log(err.response.data);
          });
      },
      update() {
        this.validation = {};

        const data = new FormData();
        data.append("title", this.occasion.title.trim());
        data.append("startDate", this.occasion.startDate);
        data.append("endDate", this.occasion.endDate);
        data.append("index", this.occasion.index);
        data.append("publish", this.occasion.publish);
        data.append("status", this.occasion.status);
        if (this.$refs.cover.files[0])
          data.append("cover", this.$refs.cover.files[0]);

        this.$axios
          .put(`/api/admin/occasion/${this.occasion._id}`, data, this.axiosConfig)
          .then((response) => {
            this.$message({
              type: "success",
              message: "اطلاعات بروزرسانی شد.",
            });
            this.$nuxt.refresh();
          })
          .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;
            else console.log(err.response.data);
          });
      },
    },
    head() {
      return {
        title: this.title,
      };
    },
    layout: "admin",
    async asyncData({$axios, $auth, params, query, error}) {
      try {
        const allOccasion = await $axios.get(`/api/admin/occasion/allOccasion`);

        if (params.details !== "new") {
          const occasion = await $axios.get(`/api/admin/occasion/${params.details}`);

          return {
            occasion: occasion.data,
            allOccasion : allOccasion.data
          };
        } else {
          return {
            allOccasion : allOccasion.data,
            occasion: {
              title: '',
              mainCover: '',
              startDate: '',
              endDate: '',
              index: null,
              publish: true
            },
          };
        }
      } catch (e) {
        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>
