<template>
  <div v-if="day">
    <v-card :color="color(day)" max-width="250px" min-width="250px">
      <v-card-title v-if="day.date" class="subtitle-1 font-weight-bold">
        {{ day.name }} {{ day.date.getDate() }}.{{ day.date.getMonth() + 1 }}.{{
          day.date.getFullYear()
        }}
        <v-spacer />
        <v-btn icon small @click="dialog = true">
          <v-icon>{{ menuIcon }}</v-icon>
        </v-btn>
      </v-card-title>
      <v-card-text>
        <v-expand-transition>
          <v-row align="center" justify="center" v-if="day.loading">
            <v-progress-circular indeterminate color="grey" />
          </v-row>
        </v-expand-transition>

        <div v-for="(jobkinddateitem, index) in day.jobkinddate" :key="index">
          <div
            v-if="
              jobkinddateitem.job_kind
                ? jobkinddateitem.job_kind.id !== 0
                : false
            "
          >
            <v-expand-transition>
              <div v-show="!day.loading">
                <v-autocomplete
                  chips
                  return-object
                  multiple
                  :counter="jobkinddateitem.maxpersons"
                  v-model="jobkinddateitem.worker"
                  :items="filterUser(jobkinddateitem.job_kind)"
                  :item-text="item => item.firstname + ' ' + item.lastname"
                  :label="jobkinddateitem.job_kind.name"
                  filled
                  color="green"
                  @blur="focused = false"
                  @focus="focused = true"
                  :key="update"
                  @change="forceRenderer(jobkinddateitem)"
                >
                  <template v-slot:prepend-inner>
                    <v-icon>{{ account_add }}</v-icon>
                  </template>
                  <template v-slot:selection="data">
                    <v-chip
                      v-bind="data.attrs"
                      :input-value="data.selected"
                      close
                      @click="data.select"
                      @click:close="remove(jobkinddateitem, data.item)"
                      >{{ data.item.firstname }} {{ data.item.lastname }}
                    </v-chip>
                  </template>
                </v-autocomplete>
              </div>
            </v-expand-transition>
          </div>
        </div>
      </v-card-text>
      <v-card-actions v-if="!day.loading">
        <v-chip class="text-uppercase" :color="lockedColor">{{
          lockedText
        }}</v-chip>
        <v-spacer />
        <v-btn text @click="lock">{{ lockedTextBtn }}</v-btn>
      </v-card-actions>
    </v-card>
    <v-dialog v-model="dialog">
      <v-card>
        <v-card-title>
          Bearbeite Tag
        </v-card-title>
        <v-card-text>
          <div>
            <v-row v-if="!isBarDienstIn">
              <v-col cols="8">
                <v-text-field readonly outlined value="Bardienst" />
              </v-col>
              <v-col cols="2">
                <v-text-field
                  outlined
                  label="Maximale Personen"
                  type="number"
                  v-model="maxpersons"
                  @change="createBarJobKindDate(maxpersons)"
                />
              </v-col>
              <v-col cols="2"> </v-col>
            </v-row>
            <v-row
              v-for="(jobkinddateitem, index) in day.jobkinddate"
              :key="index"
            >
              <v-col cols="8">
                <v-text-field
                  v-if="!jobkinddateitem.new"
                  readonly
                  outlined
                  :value="jobkinddateitem.job_kind.name"
                />
                <v-autocomplete
                  v-else
                  outlined
                  :items="filterJobKinds(jobkinddateitem, index)"
                  :rules="rules"
                  item-text="name"
                  item-value="id"
                  v-model="jobkinddateitem.job_kind"
                  return-object
                ></v-autocomplete>
              </v-col>
              <v-col cols="2">
                <v-text-field
                  outlined
                  label="Maximale Personen"
                  type="number"
                  v-model="jobkinddateitem.maxpersons"
                />
              </v-col>
              <v-col cols="2">
                <div v-if="jobkinddateitem.job_kind !== null">
                  <div v-if="jobkinddateitem.job_kind.id !== 1">
                    <v-btn
                      v-if="jobkinddateitem.id === 0"
                      fab
                      x-small
                      color="green"
                      @click="undoDelteJobKindDate(index)"
                    >
                      <v-icon>{{ plusIcon }}</v-icon>
                    </v-btn>
                    <v-btn
                      v-else
                      fab
                      x-small
                      color="red"
                      @click="deleteJobKindDate(index)"
                    >
                      <v-icon>{{ minusIcon }}</v-icon>
                    </v-btn>
                  </div>
                </div>
                <div v-else>
                  <v-btn
                    v-if="jobkinddateitem.id === 0"
                    fab
                    x-small
                    color="green"
                    @click="undoDelteJobKindDate(index)"
                  >
                    <v-icon>{{ plusIcon }}</v-icon>
                  </v-btn>
                  <v-btn
                    v-else
                    fab
                    x-small
                    color="red"
                    @click="deleteJobKindDate(index)"
                  >
                    <v-icon>{{ minusIcon }}</v-icon>
                  </v-btn>
                </div>
              </v-col>
              <v-row v-if="jobkinddateitem.id === 0">
                <v-col>
                  <v-alert dense type="info"
                    >{{ jobkinddateitem.job_kind.name }} wird beim Speichern
                    gelöscht.</v-alert
                  >
                </v-col>
              </v-row>
            </v-row>
          </div>
          <v-row>
            <v-spacer />
            <v-btn
              fab
              small
              color="green darken-1"
              @click="addJobKindDate()"
              :disabled="disableAddBtn"
            >
              <v-icon>{{ plusIcon }}</v-icon>
            </v-btn>
          </v-row>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text color="primary" @click="dialog = false">
            Abbrechen
          </v-btn>
          <v-btn text color="primary" @click="saveJobKind()">
            Speichern
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
import { mdiAccountPlus, mdiDotsVertical, mdiPlus, mdiMinus } from '@mdi/js'
export default {
  name: 'Day',
  props: {
    day: Object
  },
  data() {
    return {
      account_add: mdiAccountPlus,
      menuIcon: mdiDotsVertical,
      plusIcon: mdiPlus,
      minusIcon: mdiMinus,
      searchInput: null,
      focused: false,
      dialog: false,
      update: 0,
      maxpersons: 2,
      rules: [
        data => {
          if (data === null) return false
          var list = this.day.jobkinddate.filter(a => {
            if (a.job_kind === null) return false
            else {
              return a.job_kind.id === data.id
            }
          })
          return list.length > 1 ? data.name + 'ist schon vorhanden' : false
        }
      ],
      workerRules: [
        (data, test) => {
          console.log(data, test)
          return false
        }
      ],
      backup: null
    }
  },
  created() {
    this.setLoading(this.day.date)
  },
  methods: {
    ...mapActions({
      addUser: 'sm/addUser',
      deleteUser: 'sm/deleteUser',
      setLoading: 'sm/setDayLoading',
      setNotLoading: 'sm/setDayNotLoading',
      lockDay: 'sm/lockDay',
      updateJobKindDate: 'sm/updateJobKindDate'
    }),
    forceRenderer(jobkind) {
      console.log(jobkind)
      this.update += 1
      console.log('before', jobkind.worker, jobkind.backupWorker)
      if (jobkind.backupWorker !== jobkind.worker && this.focused) {
        let addedUser = null
        for (let user in jobkind.worker) {
          if (!jobkind.backupWorker.includes(jobkind.worker[user])) {
            addedUser = jobkind.worker[user]
            this.addUser({
              date: this.day.date.getTime() / 1000,
              user: addedUser,
              year: this.day.date.getFullYear(),
              month: this.day.date.getMonth() + 1,
              day: this.day.date.getDate(),
              job_kind: jobkind.job_kind
            })
          }
        }
        let deletedUser = null
        for (let user in jobkind.backupWorker) {
          if (!jobkind.worker.includes(jobkind.backupWorker[user])) {
            deletedUser = jobkind.backupWorker[user]
            this.deleteUser({
              startdatetime: this.day.date,
              date: this.day.date.getTime() / 1000,
              user: deletedUser,
              year: this.day.date.getFullYear(),
              month: this.day.date.getMonth() + 1,
              day: this.day.date.getDate()
            })
          }
        }
      }
      jobkind.backupWorker = [...jobkind.worker]
    },
    // eslint-disable-next-line no-unused-vars
    remove(jobkind, deletedUser) {
      jobkind.worker.indexOf()
      const obj = jobkind.worker.find(a => {
        return a.username === deletedUser.username
      })
      const index = jobkind.worker.indexOf(obj)
      if (index >= 0) jobkind.worker.splice(index, 1)
      this.forceRenderer(jobkind)
    },
    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'
      }
    },
    lock() {
      this.lockDay({
        year: this.day.date.getFullYear(),
        month: this.day.date.getMonth() + 1,
        day: this.day.date.getDate(),
        locked: !this.day.locked
      })
    },
    createBarJobKindDate(maxpersons) {
      this.day.jobkinddate.push({
        id: -1,
        job_kind: Object.assign(
          {},
          this.jobkinds.find(a => {
            return a.id === 1
          })
        ),
        maxpersons: maxpersons,
        daydate: {
          year: this.day.date.getFullYear(),
          month: this.day.date.getMonth() + 1,
          day: this.day.date.getDate()
        },
        worker: [],
        backupWorker: []
      })
    },
    addJobKindDate() {
      this.day.jobkinddate.push({
        id: -1,
        job_kind: null,
        maxpersons: 2,
        new: true,
        daydate: {
          year: this.day.date.getFullYear(),
          month: this.day.date.getMonth() + 1,
          day: this.day.date.getDate()
        },
        worker: [],
        backupWorker: []
      })
    },
    mop(jobkind) {
      console.log(jobkind.worker)
    },
    deleteJobKindDate(index) {
      if (this.day.jobkinddate[index].id === -1) {
        this.day.jobkinddate.splice(index, 1)
      } else {
        this.day.jobkinddate[index].backupid = this.day.jobkinddate[index].id
        this.day.jobkinddate[index].id = 0
      }
    },
    undoDelteJobKindDate(index) {
      this.day.jobkinddate[index].id = this.day.jobkinddate[index].backupid
    },
    saveJobKind() {
      this.updateJobKindDate({
        data: this.day.jobkinddate,
        date: this.day.date
      })
      this.dialog = false
    },
    filterWorker() {},
    filterUser(jobkind) {
      var filtered = this.dbUsers.filter(user => {
        var test = this.day.jobkinddate.find(item => {
          if (item.job_kind === null) {
            return false
          }
          if (item.job_kind.id === jobkind.id) {
            return false
          }
          return item.worker.find(work => {
            return work.id === user.id
          })
        })
        if (test) {
          return false
        }
        if (jobkind.workgroup === null) {
          return true
        }
        return user.workgroups.find(workgroup => {
          if (jobkind.workgroup && workgroup) {
            return jobkind.workgroup.id === workgroup.id
          } else return true
        })
      })
      return filtered
    },
    // eslint-disable-next-line no-unused-vars
    filterJobKinds(jobkinddateitem, index) {
      var retVal = this.jobkinds.filter(jobkind => {
        return jobkind.id !== 1
      })
      retVal = retVal.filter(jobkind => {
        return !this.day.jobkinddate.find(item => {
          if (item.job_kind === jobkinddateitem.job_kind) {
            return false
          } else {
            if (item.job_kind !== null && jobkind !== null)
              if (item.job_kind.id === jobkind.id) return true
          }
          return false
        })
      })
      return retVal
    }
  },
  computed: {
    ...mapGetters({
      allUsers: 'sm/allUsers',
      dbUsers: 'usermanager/users',
      disabled: 'sm/disabled',
      jobkinds: 'jkm/jobkinds'
    }),
    worker() {
      return this.day.worker
    },
    tada() {
      return this.day.jobkinddate
    },
    lockedColor() {
      return this.day.locked ? 'red' : 'green'
    },
    lockedText() {
      return this.day.locked ? 'gesperrt' : 'frei'
    },
    lockedTextBtn() {
      return this.day.locked ? 'freigeben' : 'sperren'
    },
    isBarDienstIn() {
      for (var jobkinddate in this.day.jobkinddate) {
        if (!(this.day.jobkinddate[jobkinddate].job_kind === null))
          if (this.day.jobkinddate[jobkinddate].job_kind.id === 1) return true
      }
      return false
    },
    existJobKinds() {
      var retVal = [...this.jobkinds]
      retVal.splice(
        retVal.findIndex(a => {
          return a.id === 1
        }),
        1
      )
      return retVal
    },
    disableAddBtn() {
      var barset = this.isBarDienstIn ? 0 : 1
      return this.day.jobkinddate.length === this.jobkinds.length - barset
    }
  },
  watch: {
    worker(newValue, oldValue) {
      if (oldValue !== newValue && this.focused) {
        let addedUser = null
        for (let user in newValue) {
          if (!oldValue.includes(newValue[user])) {
            addedUser = newValue[user]
            this.addUser({
              date: this.day.date.getTime() / 1000,
              user: addedUser,
              year: this.day.date.getFullYear(),
              month: this.day.date.getMonth() + 1,
              day: this.day.date.getDate()
            })
          }
        }
        let deletedUser = null
        for (let user in oldValue) {
          if (!newValue.includes(oldValue[user])) {
            deletedUser = oldValue[user]
            this.deleteUser({
              startdatetime: this.day.date,
              date: this.day.date.getTime() / 1000,
              user: deletedUser,
              year: this.day.date.getFullYear(),
              month: this.day.date.getMonth() + 1,
              day: this.day.date.getDate()
            })
          }
        }
      }
    },
    dialog(newValue) {
      if (newValue) {
        this.backup = [...this.day.jobkinddate]
      } else {
        this.day.jobkinddate = [...this.backup]
        this.backup = []
      }
    }
  }
}
</script>

<style scoped></style>
