<template>
  <div class="container">
    <!-- 編輯事件 -->
    <div class="LeftContainer">
      <b-row>
        <b-col class="label_col" style="padding: 10px 15px 0 30px" cols="3">
          <span>起始日期:</span>
        </b-col>
        <b-col cols="9">
          <div style="margin-left: -20px;">
            <b-form-datepicker
              style="width: 95%; font-size: 16px"
              v-if="isEdit"
              v-model="schedule.start"
            />
            <div v-else style="margin-top: 10px">
              <span style="font-weight: normal; color: black">
                {{ schedule.start.split('T')[0] }}
              </span>
            </div>
          </div>
        </b-col>
      </b-row>
      <b-row style="margin-top: 12px">
        <b-col class="label_col" style="padding: 10px 15px 0 30px" cols="3">
          <span>結束日期:</span>
        </b-col>
        <b-col cols="9">
          <div style="margin-left: -20px;">
            <b-form-datepicker
              style="width: 95%; font-size: 16px"
              v-if="isEdit"
              v-model="schedule.end"
            />
            <div v-else style="margin-top: 10px">
              <span style="font-weight: normal; color: black">
                {{ schedule.end}}
              </span>
            </div>
          </div>
        </b-col>
      </b-row>
      <b-row style="margin-top: 12px">
        <b-col class="label_col" style="padding: 10px 15px 0 30px" cols="3">
          <span>標題:</span>
        </b-col>
        <b-col cols="9">
          <div style="margin-left: -20px;">
            <b-form-input
              style="width: 95%; font-size: 16px"
              placeholder="請填寫事件標題"
              v-if="isEdit"
              v-model="schedule.title"
            />
            <div v-else style="margin-top: 10px">
              <span style="font-weight: normal; color: black">
                <span
                  v-show="schedule.chronology === true"
                  style="font-weight: 900; color: red"
                >
                  大事紀
                </span>
                <span style="font-weight: normal; color: black; font-size: 16px">
                  {{ schedule.title }}
                </span>
              </span>
            </div>
          </div>
        </b-col>
      </b-row>
      <b-row style="margin-top: 10px">
        <b-col class="label_col" style="padding: 10px 15px 0 30px" cols="3">
          <span>類別:</span>
        </b-col>
        <b-col cols="7" v-if="isEdit">
          <div style="margin-left: -20px;">
            <multiselect
              v-model="scheduleType"
              style="width: 95%; margin-top: 5px"
              placeholder="請選擇事件類別"
              deselect-label="已選擇"
              :options="eventCategory.paramsItems"
              :multiple="false"
              label="name"
              selectLabel="選擇"
              selectedLabel="已選擇"
              deselectLabel="取消選擇"
            >
              <span slot="noResult">查無此事件類別</span>
            </multiselect>
          </div>
        </b-col>
        <b-col v-if="isEdit" class="mt-3" style="padding: 0; margin-left: -10px;" cols="2">
          <div v-if="isEdit">
            <input
              type="checkbox"
              style="width: 15px; height: 15px"
              v-model="schedule.chronology"
              @click="checkedChronology"
            />
            大事紀
          </div>
        </b-col>
        <div v-else>
          <div style="margin-top: 10px; margin-left: -5px">
            <span style="font-weight: normal; color: black; font-size: 16px">
              {{ schedule.scheduleType }}
            </span>
          </div>
        </div>
      </b-row>
      <b-row style="margin-top: 18px">
        <b-col class="label_col" style="padding-left: 30px" cols="3">
          <span>說明:</span>
        </b-col>
        <b-col cols="9">
          <div v-if="isEdit" style="margin-left: -20px">
            <b-form-textarea
              rows="6"
              no-resize
              style="
                width: 95%;
                height: 210px;
                padding: 8px 12px 10px;
                font-size: 16px;
              "
              v-model="schedule.thing"
            />
          </div>
          <div v-else style="margin-left: -30px; margin-top: -8px;">
            <b-form-textarea
              rows="6"
              no-resize
              style="
                width: 95%;
                height: 210px;
                padding: 8px 12px 10px;
                font-size: 16px;
              "
              :disabled="isEdit === false"
              v-model="schedule.thing"
            />
          </div>
        </b-col>
      </b-row>
      <b-row
        v-show="isHavePermission"
        style="margin-top: 10px; float: right; padding-right: 37px"
      >
        <b-button v-if="isEdit" class="btn" @click="eventSaved(getContent)">
          儲存
        </b-button>
        <b-button v-else class="btn" @click="isEdit = true">編輯</b-button>
        <b-button v-show="!isEdit" class="btn_delete" @click="eventDelete(getContent)">
          刪除
        </b-button>
      </b-row>
    </div>
    <!-- 照片 -->
    <div class="RightContainer" v-show="this.schedule.chronology === true">
      <span style="color: black"><span style="font-weight: 900;">圖片說明</span>&nbsp;&nbsp;
        <span style="color: red; font-size: 14px;">*僅限上傳6張照片</span>
      </span>
      <hr style="margin-top: 10px; margin-bottom: 10px;" />
      <div v-if="isEdit" class="pb-2" style="overflow-y: auto; overflow-x: hidden; height: 430px;">
        <div style="margin-top: 5px">
          <div
            v-for="img in schedule.imageFile"
            :key="img._id"
            style="margin-top: 3px"
          >
            <b-row style="padding-top: 10px; padding-right: 15px">
              <b-col cols="4">
                <lyztw-image-container
                  :data="img"
                  @on-delete="removeImage"
                  edit-mode
                  size="130"
                  deleteBtnIcon="delete"
                />
              </b-col>
              <b-col cols="8">
                <b-form-textarea
                  v-model="img.description"
                  placeholder="針對圖片說明"
                  rows="6"
                  no-resize
                  style="
                    width: 100%;
                    height: 130px;
                    padding: 8px 12px 10px;
                    font-size: 16px;
                  "
                />
              </b-col>
            </b-row>
          </div>
          <div v-show="this.images.length < 6">
            <lyztw-add-image-btn
              size="130"
              @on-select="addImage"
              @on-drop="addImage"
              @on-paste="addImage"
            >
              <div>拖曳或是雙擊上傳圖片</div>
            </lyztw-add-image-btn>
          </div>
        </div>
      </div>
      <div v-else class="pb-2" style="overflow-y: auto; overflow-x: hidden; height: 430px;">
        <div
          v-for="img in schedule.imageFile"
          :key="img._id"
          style="margin-top: 3px"
        >
          <b-row style="padding-top: 10px; padding-right: 15px">
            <b-col cols="4">
              <lyztw-image-container :data="img" size="130" />
            </b-col>
            <b-col cols="8">
              <div style="margin-left: -18px;">
                <b-form-textarea
                  v-model="img.description"
                  rows="6"
                  no-resize
                  style="
                    width: 100%;
                    height: 110px;
                    padding: 8px 12px 10px;
                    font-size: 16px;
                  "
                  :disabled="isEdit === false"
                />
              </div>
            </b-col>
          </b-row>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'
import Multiselect from 'vue-multiselect'
import 'vue-multiselect/dist/vue-multiselect.min.css'
import moment from 'moment'

export default {
  props: ['getContent'],
  data () {
    return {
      isEdit: false,
      isHavePermission: false,
      adjustedEndDate01: '',
      eventCategory: {
        _id: '',
        paramsItems: []
      },
      scheduleType: null,
      images: [],
      calendar: []
    }
  },
  components: {
    Multiselect
  },
  async mounted () {
    this.eventCategory = await this.$store.dispatch(
      'paramsSetting/lookupParam',
      'schedule_classification'
    )
    this.eventCategory.paramsItems = this.eventCategory.paramsItems.filter(obj =>
      obj.name !== '會議' && obj.backgroundColor !== '#eb9114'
    )
    this.scheduleType = {
      name: this.schedule.scheduleType,
      backgroundColor: this.schedule.color
    }
    this.usePermission()
    if (
      this.$route.name === 'Memorabilia' &&
      this.calendar[0].permission === 2
    ) {
      this.isHavePermission = true
    }
    this.schedule.end = new Date(this.schedule.end)
    this.schedule.end.setDate(this.schedule.end.getDate() - 1)
    this.schedule.end = this.schedule.end.toISOString().split('T')[0]
    // console.log(this.schedule.imageFile)
  },
  filters: {
    ellipsis (value) {
      if ((value && value.length) || value > 18) { return value.slice(0, 10) + '...' }
      return value
    }
  },
  methods: {
    ...mapActions('schedule', [
      'deleteSchedule',
      'patch',
      'lookupFile',
      'getScheduleList'
    ]),
    ...mapActions('paramsSetting', ['lookupParam']),
    async eventSaved (id) {
      let startDate = new Date(this.schedule.start)
      let endDate = new Date(this.schedule.end)
      if (
        Date.parse(startDate).valueOf() > Date.parse(endDate).valueOf() ||
        this.schedule.title === undefined ||
        this.schedule.scheduleType === undefined ||
        this.schedule.scheduleType === null ||
        this.schedule.scheduleType === ''
      ) {
        alert('「日期填寫有誤」或「尚有內容未填」!!')
      } else {
        let yes = confirm('確定儲存?')
        if (yes) {
          for (const image of this.schedule.imageFile) {
            if (image.mime === undefined && image.name === undefined) {
              delete image.src
            }
          }
          await this.patch(id)
          this.isEdit = false
          this.$emit('closeEvent')
        } else {
          alert('取消儲存')
        }
      }
    },
    async eventDelete (data) {
      try {
        if (!confirm('確定刪除?')) return
        await this.deleteSchedule(data)
        this.$emit('closeEvent')
        alert('刪除成功!!')
      } catch (error) {
        this.$emit('closeEvent')
        alert('刪除失敗!!')
      }
    },
    checkedChronology () {
      try {
        if (this.schedule.chronology === false) {
          this.schedule.chronology = true
        } else {
          this.schedule.chronology = false
        }
      } catch (error) {
        // console.log(error)
      }
    },
    addImage (imgFile) {
      if (this.schedule.imageFile.length < 6) {
        this.schedule.imageFile.push({
          src: imgFile.src,
          _id: Math.random().toString().split('.').pop(),
          file: imgFile.file,
          description: ''
        })
      }
    },
    removeImage (imgFile) {
      this.schedule.imageFile.splice(
        this.schedule.imageFile.findIndex((image) => image._id === imgFile._id),
        1
      )
    },
    usePermission () {
      // 確認權限
      Object.values(this.currentUser.tenderPermissions).forEach((obj) => {
        if (obj.tenderId === this.currentUser.defaultTender) {
          let permission = obj.permission
            .filter((name) => name.title === '行事曆')
            .map((val) => {
              return val.functionItem
            })
          for (const element of permission) {
            this.calendar = element
          }
        }
      })
    }
  },
  computed: {
    adjustedEndDate () {
      if (this.schedule.end) {
        if (this.isEdit) {
          const adjustedDate = moment(this.schedule.end).subtract(1, 'days')
          return adjustedDate.format('YYYY-MM-DD HH')
        } else {
          const adjustedDate = moment(this.schedule.end).subtract(1, 'days')
          return adjustedDate.format('YYYY-MM-DD')
        }
      } else {
        return ''
      }
    },
    ...mapState({
      schedule: (state) => state.schedule.Schedule,
      scheduleList: (state) => state.schedule.ScheduleList,
      currentUser: (state) => state.user.current
    })
  },
  watch: {
    scheduleType: {
      handler (newVal, oldValue) {
        if (newVal === null) {
          this.schedule.scheduleType = ''
          this.schedule.color = ''
        } else {
          this.schedule.scheduleType = newVal.name
          this.schedule.color = newVal.backgroundColor
        }
      },
      immediate: true
    },
    adjustedDate: {
      handler (newVal) {
        console.log(newVal)
      }
    }
  }
}
</script>

<style scoped>
@import url("https://fonts.googleapis.com/icon?family=Material+Icons");

::-webkit-scrollbar {
  width: 3px;
}
::-webkit-scrollbar-track {
  border-radius: 10px;
  background: #f1f1f1;
}
::-webkit-scrollbar-thumb {
  border-radius: 15px;
  background: #888;
}
::-webkit-scrollbar-thumb:hover {
  background: #555;
}
.custom-select {
  color: black !important;
  box-shadow: none;
  -webkit-box-shadow: none;
}
.custom-select:disabled {
  color: black !important;
  opacity: 1;
  background-color: #ffffff;
  background-image: none !important;
  border: 0;
}
.active-tab-class {
  background-color: #000000;
}
.form-control {
  color: black !important;
}
.form-control:disabled {
  background-color: #ffffff;
  background: none;
  border: 0;
  color: black;
}
.btn {
  background-color: rgb(75, 102, 255);
  font-size: 16px;
  margin-top: 15px;
  margin-left: 15px;
  padding: 5px 7px;
  color: #ffffff;
  box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);
  border: none;
}
.btn:hover {
  color: rgb(255, 255, 255);
  background-color: rgb(49, 68, 175);
  transform: translateY(1);
}
.btn_delete {
  background-color: rgb(255, 0, 0);
  font-size: 16px;
  padding: 5px 7px;
  color: #ffffff;
  box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);
  border: none;
}
.btn_delete:hover {
  color: rgb(255, 255, 255);
  background-color: rgb(199, 0, 0);
}
.container {
  margin-right: 20px;
  width: auto;
  height: auto;
  padding: 0px;
  overflow: hidden;
  display: flex;
  justify-content: space-between;
  padding-right: 0px;
  /* flex-shrink: 0; */
}
.LeftContainer {
  width: 600px;
  height: 520px;
  /* flex-shrink: 0; */
}
.RightContainer {
  width: 650px;
  height: 510px;
  background: rgba(98, 113, 221, 0.1);
  padding: 8px 20px;
  border-radius: 5px;
}
.label_col {
  color: black !important;
}
.col-8 {
  padding-left: 0px;
}
.col-4 {
  padding-right: 0px;
}
</style>
