<template>
  <div v-if="day">
    <v-card :color="color(day)" :max-width="long ? '' : '20em'">
      <v-card-title v-if="day.date" class="subtitle-1 font-weight-bold">
        {{ name }} den {{ day.date.getDate() }}.{{ day.date.getMonth() + 1 }}.{{
          day.date.getFullYear()
        }}
      </v-card-title>
      <v-card-text>
        <v-expand-transition>
          <v-row align="center" justify="center" v-if="dayLoading">
            <v-progress-circular indeterminate color="grey" />
          </v-row>
        </v-expand-transition>
        <v-expand-transition>
          <div v-show="!dayLoading">
            <div
              v-for="(jobkinddateitem, index) in day.jobkinddate"
              :key="index"
            >
              <div class="title black--text text-sm-center">
                {{ jobkinddateitem.job_kind.name }}
              </div>
              <v-combobox
                multiple
                filled
                disabled
                readonly
                :counter="jobkinddateitem.maxpersons"
                v-model="jobkinddateitem.worker"
                :item-text="item => item.firstname + ' ' + item.lastname"
                item-value="username"
                chips
                append-icon=""
              >
                <template v-slot:selection="data">
                  <v-chip
                    >{{ data.item.firstname }} {{ data.item.lastname }}</v-chip
                  >
                </template>
              </v-combobox>
            </div>
          </div>
        </v-expand-transition>
      </v-card-text>
      <v-card-actions class="text--secondary" v-if="!dayLoading" :key="update">
        <v-spacer />
        <v-menu
          v-model="menu"
          open-on-hover
          close-on-click
          close-on-content-click
          offset-y
        >
          <template v-slot:activator="{ on }">
            <v-btn
              text
              v-on="on"
              v-show="filterAddJob.length > 0 && !userInWorker() && !day.locked"
            >
              Eintragen
            </v-btn>
          </template>
          <v-list>
            <v-list-item
              v-for="(jobkinddateitem, index) in filterAddJob"
              :key="index"
              @click="addingJob(jobkinddateitem)"
            >
              <v-list-item-title>
                {{ jobkinddateitem.job_kind.name }}
              </v-list-item-title>
            </v-list-item>
          </v-list>
        </v-menu>
        <v-menu v-model="menu_invite" :close-on-content-click="false" offset-y>
          <template v-slot:activator="{ on }">
            <v-btn
              v-show="
                jobkindWithSpace.length !== 0 && !day.locked && userInWorker()
              "
              text
              v-on="on"
              >Einladen</v-btn
            >
          </template>
          <v-card :loading="jobInvitesLoading">
            <v-card-title>
              Einladungen
            </v-card-title>
            <v-card-text>
              <v-div
                      bottom
                      v-for="(invite, index) in getInvites(day.date)"
                      :key="index"
              >
                <v-chip v-on="on" style="margin: 5px">
                  {{ invite.to_user.firstname }}
                  {{ invite.to_user.lastname }}
                </v-chip>
              </v-div>
              <v-divider style="margin-bottom: 5px" />
              <v-autocomplete
                v-model="job_invites"
                label="Einladungen senden an"
                return-object
                multiple
                filled
                :item-text="item => item.firstname + ' ' + item.lastname"
                item-value="id"
                chips
                deletable-chips
                :items="filteredDBUsers()"
              >
              </v-autocomplete>
            </v-card-text>
            <v-card-actions>
              <v-spacer />
              <v-btn
                text
                :disabled="job_invites.length === 0"
                @click="sendInvites()"
              >
                {{ job_invites.length >= 1 ? 'Einladungen' : 'Einladung' }}
                senden
              </v-btn>
            </v-card-actions>
          </v-card>
        </v-menu>
        <v-menu
          v-model="menu_request"
          :close-on-content-click="false"
          offset-y
          v-if="day.locked && userInWorker()"
        >
          <template v-slot:activator="{ on }">
            <v-btn v-show="day.locked && userInWorker()" text v-on="on">
              Abgeben
            </v-btn>
          </template>
          <v-card :loading="jobRequestsLoading">
            <v-card-title>
              Dienstabgabenanfrage
            </v-card-title>
            <v-card-text>
              <div v-if="jobRequestsLoading">
                <v-progress-circular indeterminate />
              </div>
              <div v-if="!jobRequestsLoading">
                <v-div
                  bottom
                  v-for="(request, index) in getRequests(day.date)"
                  :key="index"
                >
                  <v-chip v-on="on" style="margin: 5px">
                    {{ request.to_user.firstname }}
                    {{ request.to_user.lastname }}
                  </v-chip>
                </v-div>
              </div>
              <v-divider style="margin-bottom: 5px" />
              <v-autocomplete
                v-model="job_requests"
                label="Anfragen senden an"
                return-object
                multiple
                filled
                :item-text="item => item.firstname + ' ' + item.lastname"
                item-value="id"
                chips
                deletable-chips
                :items="filteredDBUsersWithJobKind()"
              >
              </v-autocomplete>
            </v-card-text>
            <v-card-actions>
              <v-spacer />
              <v-btn text @click="sendRequests()">
                Anfragen
              </v-btn>
            </v-card-actions>
          </v-card>
        </v-menu>
        <v-btn
          v-show="!day.locked && userInWorker()"
          text
          @click="deletingJob()"
          >Austragen</v-btn
        >
      </v-card-actions>
    </v-card>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { mdiAccountPlus } from '@mdi/js'
export default {
  name: 'Day',
  props: {
    day: Object,
    long: Boolean,
    loading: Boolean
  },
  data() {
    return {
      account_add: mdiAccountPlus,
      searchInput: null,
      requestUser: null,
      menu: false,
      menu_invite: false,
      menu_request: false,
      update: 0,
      job_invites: [],
      job_requests: []
    }
  },
  created() {
    //setInterval(() => {console.log(this.day.loading)},100)
  },
  methods: {
    ...mapActions({}),
    sendInvites() {
      var sendData = []
      this.job_invites.forEach(item => {
        sendData.push({
          from_user: this.activeUser,
          to_user: item,
          date: {
            year: this.day.date.getFullYear(),
            month: this.day.date.getMonth() + 1,
            day: this.day.date.getDate()
          }
        })
      })
      this.$emit('sendInvites', sendData)
      setTimeout(() => {
        this.job_invites = []
      }, 200)
      this.menu_invite = false
    },
    sendRequests() {
      var sendData = []
      this.job_requests.forEach(item => {
        sendData.push({
          from_user: this.activeUser,
          to_user: item,
          date: {
            year: this.day.date.getFullYear(),
            month: this.day.date.getMonth() + 1,
            day: this.day.date.getDate()
          },
          job_kind: this.getJob_Kind()
        })
      })
      this.$emit('sendRequests', sendData)
      setTimeout(() => {
        this.job_requests = []
      }, 200)
      this.menu_request = false
    },
    color: day => {
      if (day) {
        if (day.date.getDay() === 0 || day.date.getDay() === 1) {
          return 'grey lighten-4'
        } else {
          var retVal = 'yellow'
          retVal = 'light-green'
          for (var jobkind in day.jobkinddate) {
            if (
              day.jobkinddate[jobkind].worker.length >=
              day.jobkinddate[jobkind].maxpersons
            )
              retVal = 'light-green'
            else return 'yellow'
          }
          return retVal
        }
      } else {
        return 'grey lighten-4'
      }
    },
    user(worker) {
      return worker.username === this.activeUser.username
    },
    addingJob(jobkinddateitem) {
      this.$emit('addingJob', {
        year: this.day.date.getFullYear(),
        month: this.day.date.getMonth() + 1,
        day: this.day.date.getDate(),
        job_kind: jobkinddateitem.job_kind
      })
      this.menu = false
      setTimeout(() => {
        this.update += 1
      }, 200)
    },
    deletingJob() {
      this.$emit('deletingJob', {
        year: this.day.date.getFullYear(),
        month: this.day.date.getMonth() + 1,
        day: this.day.date.getDate()
      })
      setTimeout(() => {
        this.update += 1
      })
    },
    userInWorker() {
      var jobkinddate = this.day.jobkinddate.find(item => {
        return item.worker.find(workeritem => {
          return workeritem.id === this.activeUser.id
        })
      })
      return !!jobkinddate
    },
    deletingInvite(jobInvite) {
      let sendData = { ...jobInvite }
      sendData.on_date = {
        year: sendData.on_date.getFullYear(),
        month: sendData.on_date.getMonth() + 1,
        day: sendData.on_date.getDate()
      }
      this.$emit('deleteJobInvite', sendData)
    },
    deletingRequest(jobRequest) {
      let sendData = { ...jobRequest }
      sendData.on_date = {
        year: sendData.on_date.getFullYear(),
        month: sendData.on_date.getMonth() + 1,
        day: sendData.on_date.getDate()
      }
      this.$emit('deleteJobRequest', sendData)
      this.menu_request = false
      setTimeout(() => {
        this.menu_request = true
      }, 200)
    },
    getJob_Kind() {
      var jobkinddate = this.day.jobkinddate.find(item => {
        return item.worker.find(user => {
          return this.activeUser.id === user.id
        })
      })
      return jobkinddate.job_kind
    },
    filteredDBUsersWithJobKind() {
      console.log(this.day.jobkinddate)
      var retVal = this.filteredDBUsers()
      var job_kind = this.getJob_Kind()

      retVal = retVal.filter(user => {
        if (job_kind.workgroup ? job_kind.workgroup.if === null : true) {
          return true
        } else {
          if (user.workgroups ? user.workgroups.length > 0 : false) {
            return user.workgroups.find(wg => {
              return wg.id === job_kind.workgroup.id
            })
          }
        }
        return false
      })

      return retVal
    },
    filteredDBUsers() {
      var retVal = this.allUsers.filter(user => {
        var test = this.day.jobkinddate.find(item => {
          return item.worker.find(workeritem => {
            return workeritem.id === user.id
          })
        })
        return !test
      })
      retVal = retVal.filter(user => {
        let getedDay = this.getDay(this.day.date)
        let test = getedDay
          ? getedDay.find(day => {
              return day.to_user.id === user.id
            })
          : false
        return !test
      })
      return retVal
    }
  },
  computed: {
    ...mapGetters({
      activeUser: 'user/user',
      allUsers: 'usermanager/users',
      getDay: 'jobInvites/getDayFromMe',
      getInvites: 'jobInvites/getDayWorkerFromMe',
      getRequests: 'jobRequests/getDayWorkerFromMe',
      jobInvitesLoading: 'jobInvites/jobInvitesLoading',
      jobRequestsLoading: 'jobRequests/jobRequestsLoading'
    }),
    jobkindWithSpace() {
      var retVal = this.day.jobkinddate.filter(item => {
        if (item.maxpersons <= item.worker.length) return false
        else return true
      })
      return retVal
    },
    filterAddJob() {
      var retVal = this.day.jobkinddate.filter(item => {
        if (item.maxpersons <= item.worker.length) {
          return false
        }
        if (!item.job_kind.workgroup) {
          return true
        } else {
          if (this.activeUser.workgroups) {
            return this.activeUser.workgroups.find(workgroup => {
              return workgroup.id === item.job_kind.workgroup.id
            })
          }
        }
      })
      return retVal
    },

    name() {
      const name = this.day.date.getDay()
      if (name === 0) return 'Sonntag'
      else if (name === 1) return 'Montag'
      else if (name === 2) return 'Dienstag'
      else if (name === 3) return 'Mittwoche'
      else if (name == 4) return 'Donnerstag'
      else if (name === 5) return 'Freitag'
      else return 'Samstag'
    },
    dayLoading() {
      return this.loading
    }
  }
}
</script>

<style scoped></style>
