<template>
  <base-panel
    :loading="loading"
    :full-view="fullView"
    minimizable
    panel-type="submission"
    class="submission-panel"
    data-test="submission-panel"
    @minimize-panel="$store.commit('maximizeProject')"
    @maximize-panel="$store.commit('minimizeProject')">

    <!-- Title and summary-->
    <template slot="title">
      <v-card-title class="py-0">
        <h2
          v-if="submissionId"
          class="font-weight-thin primary--text">
          <b>Submission</b> | {{ submissionId }}
        </h2>
        <h2
          v-else
          class="font-weight-thin primary--text">
          Submit a New Batch of Samples?
        </h2>
      </v-card-title>

      <p
        v-if="submissionHasErrors"
        class="panel-details-items text-xs-left summary">
        <span
          v-for="(errorMessage, index) in errorMessages"
          :key="index"
          :class="statusClass">
          {{ errorMessage }}
        </span>
      </p>
      <p
        v-else-if="$get(submission, 'data.summary')"
        class="panel-details-items text-xs-left summary">
        <span :class="statusClass">{{ $get(submission, 'data.summary') }}</span>
      </p>
    </template>

    <!-- Submission Actions  -->
    <template slot="actions">
      <v-tooltip top>
        <v-icon
          v-if="$get(submission, 'submission_form')"
          slot="activator"
          small
          flat
          class="primary--text"
          @click="downloadCurrentForm">
          file_download
        </v-icon>
        <span>Download Current Form</span>
      </v-tooltip>

      <v-tooltip top>
        <v-icon
          slot="activator"
          small
          flat
          class="primary--text"
          @click="editSubmission">
          attach_file
        </v-icon>
        <span>Resubmit form</span>
      </v-tooltip>
    </template>

    <!-- Description-->
    <template slot="content">
      <v-container grid-list-md text-xs-left px-1>

        <!-- Description -->
        <v-layout row wrap my-3 class="panel-details-items">
          <v-flex sm12>
            <base-editable-field
              :model="submission"
              :loading="loading"
              :rules="[rules.required]"
              hint="This is for our future selfs"
              name="Description"
              field="description"
              @update-value="updateValue"/>
          </v-flex>

          <v-flex sm12>
            <base-static-field
              :model="submission"
              name="Status"
              field="processed"
              format="calendar"
              template="Processed on %"
              void-template="This form hasn't been processed"/>
          </v-flex>

          <v-flex sm12>
            <custom-fields :model="submission"/>
          </v-flex>

          <v-flex sm12>
            <base-editable-field
              :model="submission"
              :loading="loading"
              name="Notes"
              hint="Any extra information you want to add to the project."
              field="notes"
              @update-value="updateValue"/>
          </v-flex>

          <v-flex sm12>
            <tag-editable-field
              v-model="submission.tags"
              @update-value="updateValue"/>
          </v-flex>

        </v-layout>
      </v-container>

      <div v-if="submissionId">
        <!-- Tables  -->
        <DataTable
          :params="params"
          model="experiments"/>

        <DataTable
          :params="params"
          model="samples"/>

        <DataTable
          :params="params"
          model="individuals"/>
      </div>

    </template>

  </base-panel>
</template>

<script>
import BasePanel from '@/components/base/BasePanel.vue'
import DataTable from '@/components/search/DataTable.vue'
import BaseEditableField from '@/components/base/BaseEditableField'
import BaseStaticField from '@/components/base/BaseStaticField'
import CustomFields from '@/components/base/CustomFields'
import TagEditableField from '@/components/base/TagEditableField'

import { fetchRecord, updateRecord } from '@/utils/api'
import { EDIT_SUBMISSION } from '@/store/actions/modals'
import { SHOW_PANEL } from '@/store/actions/panels'
import rules from '@/utils/rules'

export default {
  name: 'SubmissionPanel',
  components: {
    BasePanel,
    DataTable,
    BaseEditableField,
    CustomFields,
    TagEditableField,
    BaseStaticField
  },
  data () {
    return {
      loading: false,
      submission: {},
      rules
    }
  },
  computed: {
    fullView () {
      return !this.$store.getters.isProjectPanelMaximized
    },
    submissionId () {
      return this.$store.getters.submissionId
    },
    projectId () {
      return this.$store.getters.projectId
    },
    params () {
      return {
        'submission': this.submissionId
      }
    },
    submissionHasErrors () {
      return this.$get(this.submission, 'data.errors', []).length
    },
    errorMessages () {
      let errors = []
      if (this.submissionHasErrors) {
        this.submission.data.errors.forEach(error => {
          Object.keys(error).forEach(type => {
            if (typeof error[type] !== 'string') {
              error[type].forEach(errorType => {
                errors.push(errorType)
              })
            }
          })
        })
      }
      return errors
    },
    statusClass () {
      return this.submissionHasErrors ? 'status-failed' : 'status-succeeded'
    }
  },
  watch: {
    submissionId () {
      this.fetchSubmission()
    }
  },
  created () {
    this.fetchSubmission()
  },
  methods: {
    async fetchSubmission () {
      if (this.submissionId) {
        this.loading = true
        const response = await fetchRecord('submissions', this.submissionId)
        this.loading = false
        this.submission = response

        this.$store.commit('minimizeProject')

        let submissionProjectId = response.projects[0]
        if (submissionProjectId !== this.projectId) {
          this.$store.dispatch(SHOW_PANEL, {
            project: submissionProjectId
          })
        }
      } else {
        this.$store.commit('maximizeProject')
      }
    },
    async updateValue (data) {
      if (Object.keys(data).length) {
        this.loading = true
        debugger
        const response = await updateRecord(
          'submissions',
          this.submissionId,
          data
        )
        this.submission = response
        this.loading = false
      }
    },
    downloadCurrentForm () {
      let formUrl = this.$get(this.submission, 'submission_form')
      window.location.assign(formUrl)
    },
    editSubmission () {
      const { submission } = this
      this.$store.dispatch(EDIT_SUBMISSION, {
        submission
      })
    }
  }
}
</script>

<style lang="scss">
.submission-panel .panel-content {
  height: calc(100vh - 386px);
}
</style>
