<template>
  <div id="workEditor">
    <div id="title">
      <label class="action_title_label">{{ $t('action_title') }}</label>
      <p class="action_title">{{ work.socialAction.text }}</p>
    </div>
    <div id="startDate">
      <label>{{ $t('startDate') }}</label>
      <input type="date" v-model="startDate" />
    </div>
    <div id="endDate">
      <label>{{ $t('endDate') }}</label>
      <input type="date" v-model="endDate" />
    </div>
    <div id="comment">
      <label>Commentaire</label>
      <ckeditor 
        :editor="editor"
        v-model="note"
        tag-name="textarea"
      ></ckeditor>
    </div>
    <div id="objectives" class="objectives_list">
      <div class="title" aria="hidden">
        <div><h3>Motifs - objectifs - dispositifs</h3></div>
        <div><h3>Orientations - résultats</h3></div>
      </div>

      <!-- results which are not attached to an objective -->
      <div v-if="hasResultsForAction">
        <div class="results_without_objective">
          {{ $t('results_without_objective') }}
        </div>
        <div>
          <add-result :availableResults="resultsForAction" destination="action"></add-result>  
        </div>
      </div> 

      <!-- results which **are** attached to an objective -->
      <div v-for="g in goalsPicked">
        <div>
          <div @click="removeGoal(g)" class="objective-title">
            <i class="fa fa-times"></i>
            {{ g.goal.title.fr }}
          </div> 
        </div>
        <div>
          <add-result destination="goal" :goal="g.goal"></add-result>  
        </div>
      </div>

      <!-- box to add goal -->
      <div class="add_goal">
        <div>
          <div v-if="showAddObjective">

            <p>Motifs, objectifs et dispositifs disponibles pour ajout&nbsp;:</p>

            <ul class="list-objectives">
              <li v-for="g in availableForCheckGoal" @click="addGoal(g)" class="badge bg-primary">
                <i class="fa fa-plus"></i>
                {{ g.title.fr }} 
              </li>
            </ul>
          </div>
          <ul class="record_actions">
            <li>
              <button @click="toggleAddObjective" class="sc-button bt-create">
                Ajouter un objectif
              </button>
            </li>
          </ul>
        </div>
        <div><!-- empty for results --></div>
      </div>
    </div>


    <div id="persons">
      <h2>{{ $t('persons_involved') }}</h2>

      <ul>
        <li v-for="p in personsReachables" :key="p.id">
          <input type="checkbox" :value="p.id" v-model="personsPicked">
          <person :person="p"></person>
        </li>
      </ul>
    </div>


    <div id="handlingThirdParty">
      <h2>Tiers traitant</h2>

      <div v-if="!hasHandlingThirdParty">
        <p class="chill-no-data-statement">
          Aucun tiers traitant
        </p>

        <ul class="record_actions">
          <li>
            <add-persons
               buttonTitle="Indiquer un tiers traitant"
               modalTitle="Choisir un tiers"
               v-bind:key="handlingThirdPartyPicker.key"
               v-bind:options="handlingThirdPartyPicker.options"
               @addNewPersons="setHandlingThirdParty"
               ref="handlingThirdPartyPicker"> <!-- to cast child method -->
            </add-persons>
          </li>
        </ul>
      </div>
      <div v-else>
        <p>{{ handlingThirdParty.text }}</p>
        <show-address :address="handlingThirdParty.address"></show-address>

        <ul class="record_actions">
          <li>
            <button class="sc-button bt-delete" @click="removeHandlingThirdParty">
              Supprimer le tiers traitant
            </button>
          </li>
        </ul>
      </div>

    </div>


    <div id="thirdParties">
      <h2>Tiers intervenants</h2>

      <div v-if="!hasThirdParties">
        <p class="chill-no-data-statement">Aucun tiers intervenant</p>

      </div>
      <div v-else>
        <ul>
          <li v-for="t in thirdParties">
            <p>{{ t.text }}</p>
            <show-address :address="t.address"></show-address>

            <ul class="record_actions">
              <button class="sc-button bt-delete" @click="removeThirdParty(t)"></button>
            </ul>
          </li>
        </ul>
      </div>

      <ul class="record_actions">
        <li>
          <add-persons
             buttonTitle="Ajouter des tiers"
             modalTitle="Choisir des tiers"
             v-bind:key="thirdPartyPicker.key"
             v-bind:options="thirdPartyPicker.options"
             @addNewPersons="addThirdParties"
             ref="thirdPartyPicker"> <!-- to cast child method -->
          </add-persons>
        </li>
      </ul>
    </div>

    <div id="errors" v-if="errors.length > 0">
      <p>Veuillez corriger les erreurs suivantes:</p>
      <ul>
        <li v-for="e in errors">{{ e }}</li>
      </ul> 
    </div>
  </div>

  <ul class="record_actions sticky-form-buttons">
    <li v-if="!isPosting">
      <button
        class="sc-button bt-save"
        @click="submit"
      >
        {{ $t('action.save') }}
      </button>
    </li>
    <li v-if="isPosting">
      <button
        class="sc-button bt-save"
        disabled
      >
        {{ $t('action.save') }}
      </button>
    </li>
  </ul>

</template>

<style lang="scss">

#workEditor {
  display: grid;
  grid-template-areas: 
    "title title"
    "startDate endDate"
    "comment comment"
    "objectives objectives"
    "persons persons"
    "handling handling"
    "tparties tparties"
    "errors errors"
    ;

  grid-template-columns: 50%;
  column-gap: 1rem;
  
  #title {
    grid-area: title;

    .action_title_label {
      margin-bottom: 0;
    }
    .action_title {
      margin-top: 0;
      font-weight: bold;
      font-size: 1.5rem;
    }
  }
  #startDate {
    grid-area: startDate;
  }
  #endDate {
    grid-area: endDate;
  }
  #comment {
    grid-area: comment;
  }
  #objectives {
    grid-area: objectives;

    > div.title {
      background-color: var(--chill-light-gray);
      color: white;

      h3 {
        text-align: center;
      }
    }

    > div {
      display: grid;
      grid-template-areas: "obj res";
      grid-template-columns: 50%;
      column-gap: 1rem;

      > div {
        &:nth-child(1) {
          grid-area: obj;
        }

        &:nth-child(2) {
          grid-area: res;
        }
      }

      > div.results_without_objective {
        background: repeating-linear-gradient(
        45deg,
        var(--chill-light-gray),
        var(--chill-light-gray) 10px,
        var(--chill-llight-gray) 10px,
        var(--chill-llight-gray) 20px
      );

        text-align: center;
        font-weight: 700;
        padding-top: 1.5rem;
      }
    }

    ul.list-objectives {
      list-style-type: none;
      padding: 0;

      li {
        margin: 0.5rem;
      }
    }

    div.objective-title {
      margin-top: 1rem;
      font-size: 1.5rem;
      font-weight: bold;
      text-align: center;


      i.fa {
        padding: 0.25rem;
      }

      i.fa-times {
        background-color: red;
        color: white;
      }
    }

    li.badge, div.badge {
      padding-bottom: 0;
      padding-top: 0;
      padding-left: 0;

      i.fa {
        padding: 0.25rem;
      }

      i.fa-plus {
        background-color: green;
      }

    }
  }
  #persons {
    grid-area: persons;
  }
  #handlingThirdParty {
    grid-area: handling;
  }
  #thirdParties {
    grid-area: tparties;
  }
  #errors {
    grid-area: errors;
  }
}

</style>

<script>

import { mapState, mapGetters, } from 'vuex';
import { dateToISO, ISOToDate, ISOToDatetime } from 'ChillMainAssets/js/date.js';
import CKEditor from '@ckeditor/ckeditor5-vue';
import ClassicEditor from 'ChillMainAssets/modules/ckeditor5/index.js';
import AddResult from './_components/AddResult.vue';
import Person from 'ChillPersonAssets/vuejs/_components/Person/Person.vue';
import AddPersons from 'ChillPersonAssets/vuejs/_components/AddPersons.vue';
import ShowAddress from 'ChillMainAssets/vuejs/_components/ShowAddress.vue';

const i18n = {
  messages: {
    fr: {
      action_title: "Action d'accompagnement",
      startDate: "Date de début",
      endDate: "Date de fin",
      results_without_objective: "Résultats - orientations sans objectifs",
      add_objectif: "Ajouter un motif - objectif - dispositif",
      persons_involved: "Usagers concernés",
    }
}
};

export default {
  name: 'App',
  components: {
    ckeditor: CKEditor.component,
    AddResult,
    AddPersons,
    Person,
    ShowAddress,
  },
  i18n,
  data() {
    return {
      editor: ClassicEditor,
      showAddObjective: false,
      handlingThirdPartyPicker: {
        key: 'handling-third-party',
        options: {
          type: [ 'thirdparty' ],
          priority: null,
          uniq: true
        },
      },
      thirdPartyPicker: {
        key: 'third-party',
        options: {
          type: [ 'thirdparty' ],
          priority: null,
          uniq: false,
        },
      }
    };
  },
  computed: {
    ...mapState([
      'work',
      'resultsForAction',
      'goalsPicked',
      'personsReachables',
      'handlingThirdParty',
      'thirdParties',
      'isPosting',
      'errors',
    ]),
    ...mapGetters([
      'hasResultsForAction',
      'hasHandlingThirdParty',
      'hasThirdParties',
    ]),
    startDate: {
      get() {
        console.log('get start date', this.$store.state.startDate);
        return dateToISO(this.$store.state.startDate);
      },
      set(v) {
        this.$store.commit('setStartDate', ISOToDate(v));
      }
    },
    endDate: {
      get() {
        console.log('get end date', this.$store.state.endDate);
        return dateToISO(this.$store.state.endDate);
      },
      set(v) {
        this.$store.commit('setEndDate', ISOToDate(v));
      }
    },
    note: {
      get() {
        return this.$store.state.note;
      },
      set(v) {
        this.$store.commit('setNote', v);
      }
    },
    availableForCheckGoal() {
      let pickedIds = this.$store.state.goalsPicked.map(g => g.goal.id);
      console.log('pickeds goals id', pickedIds);
      console.log(this.$store.state.goalsForAction);

      return this.$store.state.goalsForAction.filter(g => !pickedIds.includes(g.id));
    },
    personsPicked: {
      get() {
        let s = this.$store.state.personsPicked.map(p => p.id);
        console.log('persons picked', s);

        return s;
      },
      set(v) {
        console.log('persons picked', v); 
        this.$store.commit('setPersonsPickedIds', v);
      }
    },
  },
  methods: {
    toggleAddObjective() {
      this.showAddObjective = !this.showAddObjective;
    },
    addGoal(g) {
      console.log('add Goal', g);
      this.$store.commit('addGoal', g);
    },
    removeGoal(g) {
      console.log('remove goal', g);
      this.$store.commit('removeGoal', g);
    },
    setHandlingThirdParty({ selected, modal }) {
      console.log('setHandlingThirdParty', selected);
      this.$store.commit('setHandlingThirdParty', selected.shift().result);
      this.$refs.handlingThirdPartyPicker.resetSearch();
      modal.showModal = false;
    },
    removeHandlingThirdParty() {
      console.log('removeHandlingThirdParty');
      this.$store.commit('setHandlingThirdParty', null);
    },
    addThirdParties({ selected, modal}) {
      console.log('addThirdParties', selected);
      this.$store.commit('addThirdParties', selected.map(r => r.result));
      this.$refs.thirdPartyPicker.resetSearch();
      modal.showModal = false;
    },
    removeThirdParty(t) {
      console.log('remove third party', t);
      this.$store.commit('removeThirdParty', t);
    },
    submit() {
      this.$store.dispatch('submit');
    },
  }
};

</script>
