<template>
  <div id="app">
    <div style="background-color: #1d325f; width: 100%; height: 100%">
      <!-- 通訊錄 -->
      <b-tabs pills cards style="margin-left:5vw">
        <b-tab title="通訊錄">
          <b-container class="contact-list-container">
             <span class="mainPageTitle" style="margin-left: 5px; font-size: 28px">
                通訊錄
             </span>
             <multiselect
          v-model="searchCompany"
          style="width: 100%; margin-top: 5px"
          placeholder="查詢公司名稱"
          deselect-label="已選擇"
          :options="companies.paramsValue"
          :multiple="false"
          selectLabel="搜尋"
          selectedLabel="已選擇"
          deselectLabel="取消選擇"
        >
          <span slot="noResult">查無此公司名稱</span>
        </multiselect>
        <div class="mt-2" style="height: calc(80vh - 65px); overflow: auto">
          <b-list-group v-for="(item, i) in list" :key="i">
            <b-list-group-item style="padding: 10px" @click="openInfo(item)">
              <b-avatar
                button
                :text="item.name.substring(0, 1)"
                @click="openInfo(item)"
              ></b-avatar>&nbsp;&nbsp;
              <span style="font-weight: 900;">{{ item.name }}</span>
              <b-badge
                v-show="item.title !== ''"
                variant="primary"
                style="
                  float: right;
                  padding-left: 8px;
                  margin-top: 8px;
                  font-size: 14px;
                "
              >
                {{ item.title }}
              </b-badge>
            </b-list-group-item>
          </b-list-group>
        </div>
        <modal
          :is-open="AddressBookModalOpen"
          title="聯絡資訊"
          @closeEvent="AddressBookModalOpen = false"
        >
          <addressBook
            :directoryInfo="content"
            @closeEvent="AddressBookModalOpen = false"
          />
        </modal>
      </b-container>
    </b-tab>
     <!-- 個人待辦事項 -->
     <b-tab title="個人待辦事項">
          <b-container class="contact-list-container">
            <b-row>
              <span class="mainPageTitle" style="margin-left: 15px; font-size: 28px">
                 個人待辦事項
              </span>
            </b-row>
            <div class="mt-3">
          <b-button-group style="border-radius: 3px !important;">
            <b-button
              class="btn_list"
              :class="{
                'bg-primary': visibility == 'doing',
                'text-white': visibility == 'doing'
              }"
              @click.prevent="doingTodo"
            >
              待完成
            </b-button>
            <b-button
              class="btn_list"
              :class="{
                'bg-primary': visibility == 'done',
                'text-white': visibility == 'done'
              }"
              @click.prevent="doneTodo"
            >
              已完成
            </b-button>
          </b-button-group>
          <b-button class="btn1" variant="info" @click="addTodo">
            <b-icon icon="bookmark-plus" aria-hidden="true" />&nbsp;新增事項
          </b-button>
          <hr style="margin-top: 10px; margin-bottom: 10px;" />
          <span class="alarm" style="font-size: 14px;">距離結束剩3日：<div class="circle" /></span>
          <div class="todo-list mt-2" style="height: calc(80vh - 155px); overflow: auto">
            <ul
              class="list-group list-group-flush"
              style="list-style-type: none; font-weight: 600; font-size: 14px"
            >
              <div
                v-for="(item, i) in this.filteredTodo"
                :key="i"
              >
                <li
                  class="list-group-item"
                  style="
                    border-radius: 8px;
                    padding: 10px;
                    padding-left: 30px;
                  "
                  :class="{'alarmInfo': Date.parse(new Date(item.endingTime)).valueOf() - 86400000 * 3 <= Date.parse(new Date()).valueOf() && item.endingTime !== null && item.completed === false}"
                >
                  <b-icon
                    class="btn p-1"
                    icon="x"
                    aria-hidden="true"
                    style="height: 28px; width: auto; float: right; margin-top: -2px;"
                    size="sm"
                    @click="removeTodo(item)"
                  />
                  <b-row>
                    <input
                      type="checkbox"
                      class="form-check-input"
                      v-model="item.completed"
                      @click="finishTodo(item)"
                    >
                    <div v-if="Date.parse(new Date(item.endingTime)).valueOf() - 86400000 * 3 <= Date.parse(new Date()).valueOf() && item.endingTime !== null && item.completed === false">
                      <span
                        class="form-check-label"
                        :class="{'completed': item.completed}"
                        variant="danger"
                        style="
                          font-size: 16px;
                          padding-left: 5px;
                          display: block;
                          overflow: hidden;
                          white-space: nowrap;
                          text-overflow: ellipsis;
                          cursor: pointer;
                          color: #721c24;
                        "
                        @click="editTodo(item._id)"
                      >
                        {{ item.title }}
                      </span>
                    </div>
                    <span
                      v-else
                      class="form-check-label"
                      :class="{'completed': item.completed}"
                      variant="primary"
                      style="
                        font-size: 16px;
                        padding-left: 5px;
                        display: block;
                        overflow: hidden;
                        white-space: nowrap;
                        text-overflow: ellipsis;
                        cursor: pointer;
                      "
                      @click="editTodo(item._id)"
                    >
                      {{ item.title }}
                    </span>
                  </b-row>
                </li>
              </div>
            </ul>
          </div>
        </div>
        <modal
      :is-open="AddTodoListModalOpen"
      title="新增個人待辦事項"
      @closeEvent="closeAddEvent"
          >
         <addTodoList @closeEvent="closeAddEvent" />
        </modal>
        <modal
           :is-open="EditTodoListModalOpen"
           title="編輯個人待辦事項"
           @closeEvent="closeEditEvent"
         >
        <editTodoList
             :get-content="todoId"
             @closeEvent="closeEditEvent"
         />
        </modal>
      </b-container>
      </b-tab>
      </b-tabs>
      <!-- 標案行事曆 -->
      <b-container
      v-if="visibility !== 'personalTodo'"
      class="calendar-container">
        <span class="mainPageTitle" style="margin-left: 5px; font-size: 28px">
          標案行事曆
        </span>
        <modal
          :isOpen="EditEventModalOpen"
          title="檢視事件"
          @closeEvent="EditEventModalOpen = false"
        >
          <editEvent @closeEvent="EditEventModalOpen = false" />
        </modal>
        <FullCalendar
          class="fullCalendar mt-2"
          ref="fullCalendar"
          :options="calendarOptions"
        >
          <template #eventContent="arg">
            <div style="getEventTitleStyle(arg.event.start, arg.event.end)" >
              <span style="cursor:pointer;">
                <b>{{ arg.timeText }}</b>
                <i :class="{'event-title-wrap': isOneDayEvent(arg.event.start, arg.event.end)}">{{ arg.event.title }}</i>
              </span>
            </div>
          </template>
        </FullCalendar>
      </b-container>
    </div>
  </div>
</template>

<script>
import { mapActions, mapState } from 'vuex'
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
import interactionPlugin from '@fullcalendar/interaction'
import timeGridPlugin from '@fullcalendar/timegrid'
import listPlugin from '@fullcalendar/list'
import editEvent from '@/views/Calendar/ModalContent/editEvent.vue'
import addTodoList from '@/views/HomePage/ModalContent/addTodoList.vue'
import editTodoList from '@/views/HomePage/ModalContent/editTodoList.vue'
import addressBook from '@/views/HomePage/ModalContent/addressBook.vue'
import Multiselect from 'vue-multiselect'
import 'vue-multiselect/dist/vue-multiselect.min.css'

export default {
  components: {
    modal: () => import('@/views/Modal/index.vue'),
    FullCalendar,
    Multiselect,
    editEvent,
    addTodoList,
    editTodoList,
    addressBook
  },
  // props: ['claImg'],
  data () {
    return {
      list: [],
      filteredTodo: [],
      todoId: '',
      searchCompany: null,
      content: {}, // 通訊錄資訊
      AddressBookModalOpen: false,
      AddTodoListModalOpen: false,
      EditTodoListModalOpen: false,
      EditEventModalOpen: false,
      AddPersonEventModalOpen: false,
      companies: {
        _id: '',
        paramsValue: []
      },
      calendarOptions: {
        plugins: [dayGridPlugin, interactionPlugin, timeGridPlugin, listPlugin],
        initialDate: new Date(), // 顯示今日日期
        initialView: 'dayGridMonth',
        locale: 'zh-cn', // 日曆語言
        firstDay: '1', // 每周第一天 (星期日則為 0，需為整數)
        weekNumberCalculation: 'ISO', // 指定"ISO"结果为ISO8601周數。指定"ISO"將firstDay的默認值更改為1（Monday）
        buttonText: {
          // today: '當日',
          month: '月',
          week: '周',
          day: '天'
        },
        headerToolbar: {
          right: 'today prev,next',
          center: 'title',
          left: 'dayGridMonth dayGridWeek dayGridDay'
        },
        eventTimeFormat: { // 顯示時間的格式
          hour: 'numeric',
          minute: '2-digit',
          hour12: false
        },
        editable: false,
        selectable: true,
        selectMirror: true,
        dayMaxEvents: true,
        weekends: true,
        eventClick: this.handleEventClick,
        eventsSet: this.handleEvents,
        eventTextColor: 'black',
        events: [],
        customButtons: {
          // 自定義按鈕
          today: {
            text: '當日',
            click: () => {
              let calendarApi = this.$refs.fullCalendar.getApi()
              calendarApi.today()
            }
          },
          next: {
            click: () => {
              let calendarApi = this.$refs.fullCalendar.getApi()
              calendarApi.next()
            }
          },
          prev: {
            click: () => {
              let calendarApi = this.$refs.fullCalendar.getApi()
              calendarApi.prev()
            }
          }
        }
      },
      visibility: 'doing'
    }
  },
  async mounted () {
    await this.getEvents()
    // 通訊錄
    this.companies = await this.lookupParam('companies')
    await this.$store.dispatch('project/lookupDirectories')
    this.list = this.directoryList
    // 待辦事項
    await this.$store.dispatch('staff/getTodoList')
    if (this.visibility === 'doing') {
      this.todoList.forEach((item) => {
        if (!item.completed) this.filteredTodo.push(item)
      })
    }
  },
  methods: {
    ...mapActions('schedule', ['getScheduleList']),
    ...mapActions('paramsSetting', ['lookupParam']),
    ...mapActions('staff', ['initTodo', 'patchFinishTodo', 'deleteTodo', 'lookUpTodo']),
    async handleEventClick (clickInfo) {
      let lookId = clickInfo.event.extendedProps.scheduleId
      if (clickInfo.event.backgroundColor === '#eb9114') {
        // 會議另開
        await this.$store.dispatch('schedule/getScheduleContent', lookId)
        this.$router.push({
          name: 'ConferenceDetail',
          query: { fid: this.schedule.conferenceId }
        })
      } else {
        this.EditEventModalOpen = true

        const endStr = clickInfo.event.endStr
        const endDateObject = new Date(endStr)
        endDateObject.setDate(endDateObject.getDate()) // Adding one day

        const formattedEndDate =
  endDateObject.toISOString().slice(0, 10)

        await this.lookSchedule(clickInfo, formattedEndDate, lookId)
      }
    },
    async lookSchedule (data, end, id) {
      await this.$store.dispatch('schedule/getScheduleContent', id)
      await this.$store.dispatch('schedule/lookupSchedule', {
        id: id,
        title: data.event.title,
        start: data.event.startStr,
        end: end,
        scheduleType: this.schedule.scheduleType,
        color: this.schedule.color,
        thing: this.schedule.thing,
        chronology: this.schedule.chronology,
        imageFile: this.schedule.imageFile
      })
    },
    getFormattedTime (time) {
      return this.formatTime(time)
    },
    formatTime (time) {
      if (time && time.length >= 3) {
        return time.substr(0, time.length - 3)
      } else {
        return ''
      }
    },
    async getEvents () {
      await this.getScheduleList()
      await this.$store.dispatch('conference/getConferenceList')
      this.calendarOptions.events = this.scheduleList.map(obj => {
        let titlePrefix = ''

        if (obj.scheduleType === '會議') {
          // 查找對應會議的開始時間
          const conference = this.conference.find(conf => conf._id === obj.conferenceId)
          if (conference) {
            titlePrefix = `${this.getFormattedTime(conference.conference_time)} - `
          }
        }

        return {
          title: titlePrefix + obj.title,
          start: obj.start,
          end: obj.end,
          color: obj.color,
          scheduleId: obj._id
        }
      })
    },
    isOneDayEvent (start, end) {
      const startDate = new Date(start)
      const endDate = new Date(end)
      const oneDay = 24 * 60 * 60 * 1000

      return endDate - startDate <= oneDay
    },
    openInfo (data) {
      this.AddressBookModalOpen = true
      this.content = data
    },
    async addTodo () {
      this.AddTodoListModalOpen = true
      await this.initTodo()
    },
    removeTodo: async function (todo) { // 刪除待辦事項
      const h = this.$createElement
      if (!confirm('確定刪除嗎?')) return
      await this.deleteTodo(todo._id)
      await this.$store.dispatch('staff/getTodoList')
      this.filteredTodo = []
      if (this.visibility === 'doing') {
        this.todoList.forEach((item) => {
          if (!item.completed) this.filteredTodo.push(item)
        })
      } else {
        this.todoList.forEach((item) => {
          if (item.completed) this.filteredTodo.push(item)
        })
      }
      this.$message({
        message: h('span', { style: 'color: teal' }, '刪除成功'),
        type: 'success',
        duration: '1500'
      })
    },
    finishTodo: async function (todo) {
      if (todo.completed === true) {
        todo.completed = false
        await this.patchFinishTodo({id: todo._id, data: todo})
        this.filteredTodo = []
        this.todoList.forEach((item) => {
          if (item.completed) this.filteredTodo.push(item)
        })
      } else {
        todo.completed = true
        await this.patchFinishTodo({id: todo._id, data: todo})
        this.filteredTodo = []
        this.todoList.forEach((item) => {
          if (!item.completed) this.filteredTodo.push(item)
        })
      }
    },
    async editTodo (id) {
      this.todoId = id
      this.EditTodoListModalOpen = true
      await this.lookUpTodo(id)
    },
    async closeAddEvent () {
      this.AddTodoListModalOpen = false
      await this.$store.dispatch('staff/getTodoList')
      this.filteredTodo = []
      if (this.visibility === 'doing') {
        this.todoList.forEach((item) => {
          if (!item.completed) this.filteredTodo.push(item)
        })
      } else {
        this.todoList.forEach((item) => {
          if (item.completed) this.filteredTodo.push(item)
        })
      }
    },
    async closeEditEvent () {
      this.EditTodoListModalOpen = false
      await this.$store.dispatch('staff/getTodoList')
      this.filteredTodo = []
      if (this.visibility === 'doing') {
        this.todoList.forEach((item) => {
          if (!item.completed) this.filteredTodo.push(item)
        })
      } else {
        this.todoList.forEach((item) => {
          if (item.completed) this.filteredTodo.push(item)
        })
      }
    },
    doingTodo () {
      this.filteredTodo = []
      this.visibility = 'doing'
      if (this.visibility === 'doing') {
        this.todoList.forEach((item) => {
          if (!item.completed) this.filteredTodo.push(item)
        })
      }
    },
    doneTodo () {
      this.filteredTodo = []
      this.visibility = 'done'
      if (this.visibility === 'done') {
        this.todoList.forEach((item) => {
          if (item.completed) this.filteredTodo.push(item)
        })
      }
    }
  },
  computed: {
    getEventTitleStyle () {
      return (start, end) => {
        const startDate = new Date(start)
        const endDate = new Date(end)
        const oneDay = 24 * 60 * 60 * 1000

        if (endDate - startDate <= oneDay) {
          return {
            whiteSpace: 'normal'
          }
        } else {
          return {
            whiteSpace: 'nowrap'
          }
        }
      }
    },
    ...mapState({
      schedule: (state) => state.schedule.Schedule,
      scheduleList: (state) => state.schedule.ScheduleList,
      directoryList: (state) => state.project.list,
      todoList: (state) => state.staff.todoList,
      conferenceList: (state) => state.conference.ConferenceList,
      conference: (state) => state.conference.ConferenceList
    })
  },
  watch: {
    searchCompany: {
      handler (newVal, oldValue) {
        if (newVal === null) {
          this.list = this.directoryList
        } else {
          this.list = this.directoryList
          this.list = this.list.filter(obj => obj.company === newVal)
        }
      },
      immediate: true
    }
  }
}
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Noto+Sans+TC:wght@500;700&display=swap');
::-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;
}
.event-title-wrap {
  white-space: normal;
  overflow: hidden;
  text-overflow: ellipsis;
}
.contact-list-container{
  padding-top: 20px;
  border-radius: 5px;
  background-color: white;
  width: 26%;
  height: 90%;
  margin-left: 30px;
  float: left;
  }
.mainPageTitle {
  font-family: 'Noto Sans TC', sans-serif;
  font-weight: 700;
}
.calendar-container{
  padding-top: 20px;
  border-radius: 5px;
  background-color: white;
  width: 60%;
  height: 90%;
  margin-left: 30px;
  float: left;
  overflow: hidden;
  }

.alarm {
  font-family: 'Noto Sans TC', sans-serif;
  font-weight: 500;
}
.alarmInfo {
  /* border-color: #f5c6cb; */
  background-color: #f5c6cb;
}
.word {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.btn1 {
  background-color: rgb(75, 102, 255);
  font-size: 14px;
  float: right;
  padding: 5px 7px;
  color: #ffffff;
  border: none;
}
.btn_list {
  padding: 5px 7px;
  color: rgb(0, 0, 0);
  background-color: rgb(255, 255, 255);
  border: none;
  font-size: 14px;
}
.completed {
  text-decoration: line-through
}
.circle {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 999em;
  background-color: rgb(255, 0, 0);
}
html,
body,
#app {
  height: calc(100vh - 55px);
  width: 100%;
}
</style>
