<script>

import { mapActions, mapState } from 'pinia'
import { ConcernementsStore } from '@stores/concernements'
import { UserStore } from '@/stores/user'
// import { CommonStore } from '@/stores/common'

import REST from '@api/rest-axios'


import { print } from 'graphql/language/printer'
import gql from 'graphql-tag'
import GQL from '@api/graphql-axios'
import EntiteFields from '@api/gql/entite.fragment.gql'


import CartoucheLayout from '@components/layout/CartoucheLayout.vue';
import Entite from '@components/contents/Entite.vue';

import VueSlider from 'vue-slider-component'
import 'vue-slider-component/theme/default.css'

import SvgIcon from '@jamescoyle/vue-icon';
import { mdiChevronRight } from '@mdi/js';
import { mdiChevronDown } from '@mdi/js';
import { mdiStickerPlusOutline } from '@mdi/js';
import { mdiCloseBox } from '@mdi/js';

import ContentEditable from '@components/editable/ContentEditable.vue';
import CheckboxEditable from '@components/editable/CheckboxEditable.vue';
import SelectEditable from '@components/editable/SelectEditable.vue';

// import vueAutocomplete from "@venegrad/vue3-autocomplete"
import VueSimpleSuggest from '@vojtechlanka/vue-simple-suggest';

export default {
  props: ['cid', 'eid'],
  data(){
    return {
      concernement: null,
      entite: null,
      history_value: 0,
      history_slider_ops: null,
      details_value: 1,
      details_slider_ops: null,
      infos_opened: false,
      chevronright_path: mdiChevronRight,
      chevrondown_path: mdiChevronDown,
      headerreduced: false,
      mdiStickerPlusOutline_path: mdiStickerPlusOutline,
      reloading_concernements: false,
      prox_default_values: [],
      prox_new_value: {},
      prox_suggestions: [],
      mdiCloseBox_path: mdiCloseBox,
    }
  },
  computed: {
    ...mapState(ConcernementsStore,['map_mode',
                                    'opened_concernement',
                                    'concernementsByID',
                                    'ct_concernement',
                                    'ct_entite',
                                    'detailsZoomValue',
                                    'allEntitesById'
                                    // 'concernements_are_loading'
                                  ]),
    ...mapState(UserStore,['name',
                           'csrf_token',
                           'isloggedin',
                           'user_entites']),
    created(){
      let d = new Date(this.concernement.created); 
      console.log('d', d);
      return d.toLocaleDateString("fr-FR");//.toISOString().split('T')[0];
    },
    changed(){
      let d = new Date(this.concernement.changed); 
      console.log('d', d);
      return d.toLocaleDateString("fr-FR");//.toISOString().split('T')[0];
    },
    display_concernement(){
      return this.ct_concernement && !this.entite && this.map_mode !== 'puissancedagir' && this.map_mode !== 'doleancer';
    },
    entity_title_label(){
      let menacemaintien_str;
      if (this.concernement.entites_byid[this.eid].menacemaintien > 0) {
        menacemaintien_str = 'maintenu';
      } else {
        menacemaintien_str = 'menacé';
      }

      let actuelfuture_str;
      if (this.concernement.entites_byid[this.eid].actuelfuture > 0) {
        actuelfuture_str = 'sera';
      } else {
        actuelfuture_str = 'est';
      }
      
      return `Pouvez-vous nommer par qui ou par quoi cet élément ${actuelfuture_str} ${menacemaintien_str} ?`;
    }
  },
  created () {
    this.concernement = this.concernementsByID[this.cid];

    console.log(`terraindevie created, cid: ${this.cid}, eid: ${this.eid}, this.concernement:`, this.concernement);

    //entite
    if (this.eid) {
      this.loadEntite()
    }

    // revisions        
    let data=[];
    if (this.concernement && this.concernement.revisions) {
      this.concernement.revisions.forEach(rev => {
        if (rev.entites.length > 3) {
          let d = new Date(rev.changed);
          data.push({
            'id': rev.revision_id,
            'changed': d.toLocaleDateString("fr-FR")
          })
          this.history_value = Math.max(this.history_value, parseInt(rev.revision_id));
        }
      });
    }

    if (data.length > 1) {
      this.history_slider_ops = {
        dotSize:10,
        data: data,
        'data-value': 'id',
        'data-label': 'changed',
        adsorb: true,
        'hide-label': true
      } 
    } else {
      this.history_slider_ops = null;
    }

    // details
    this.details_slider_ops = {
      min: 1,
      max: 4,
      interval: 0.05,
      'hide-label': true,
      tooltip: 'none',
      dotSize:10,
    } 

  },
  // mounted(){
  //   console.log('terrain de vie mounted', this);
  //   // this.$refs.cartouche_main.addEventListener('scroll', (event) => {
  //   //   console.log('main is scrolling', event);
  //   // })
  // },
  watch: {
    history_value: {
      handler (n, o) {
        // console.log(`TerrainDeVie watch history_value o:${o}, n:${n}`);
        this.setActiveRevision(this.cid, n);
      },
      deep: true
    },
    details_value: {
      handler (n, o) {
        // console.log(`TerrainDeVie watch history_value o:${o}, n:${n}`);
        this.setDetailsZoomValue(n);
      },
      deep: true
    },
    detailsZoomValue:  {
      handler (n, o) {
        // console.log(`TerrainDeVie watch history_value o:${o}, n:${n}`);
        this.details_value = n;
      },
      deep: true
    },
    cid: {
      handler (n,o) {
        console.log(`TerrainDeVie watch cid o:${o}, n:${n}`);
        if (n) {
          this.concernement = this.concernementsByID[n];
        }
      },
      deep: true
    },
    eid: {
      handler (n, o) {
        console.log(`TerrainDeVie watch eid o:${o}, n:${n}`);
        if (n) {
          this.loadEntite()
        }else{
          this.entite = null;
        }
      },
      deep: true
    },
    user_entites: {
      handler (n, o) {
        console.log('TerrainDeVie watch user_entites');
        if (n) {
          this.checkForUserProxmite();
        }
      },
      deep: true
    }
  },
  methods: {
    ...mapActions(ConcernementsStore, ['setActiveRevision',
                                        'setDetailsZoomValue',
                                        'loadConcernements',
                                        'setConcernementIsUpdating',
                                        'reloadConcernements',
                                        'reloadConcernementEntites',
                                        'reloadConcernementField',
                                        'reloadProximites'
                                      ]),
    ...mapActions(UserStore, ['getUserEntitees']),
                                      
    onClickInfos(){
      this.infos_opened = !this.infos_opened;
    },
    loadEntite(){
      const ast = gql`{
        entite (id: ${this.eid}) {
          ...EntiteFields
        }
      }
      ${EntiteFields}
      `
      console.log('ast', ast);
      GQL.post('', { query: print(ast) })
        .then(({data: { data: { entite }}}) => {
          console.log('load entite loaded', entite)
          this.entite = entite;

          // record the paragraphe field id from concernement wher the entity is referenced
          this.concernement.entites.forEach(parag_entite => {
            if (parag_entite.entite && parag_entite.entite.id === this.entite.id) {
              this.parag_entite = parag_entite;
            }
          });

          // this.setProxSuggestions()
          this.checkForUserProxmite();
        })
        .catch(error => {
          console.warn('Issue with load entite', error)
        })
    },
    onMainScrolled(scrolled){
      // console.log('this.$refs', this.$refs);
      let cartouche_main = this.$refs.cartouche_layout.$refs.cartouche_main;
      // console.log('cartouche_main', cartouche_main);
      if(scrolled && cartouche_main.scrollHeight > 600){
        this.headerreduced = true;
      } else {
        this.headerreduced = false;
      }
    },
    // triggered when focus out and gql patch xhr triggered
    onFieldIsUpdating(cid){
      this.setConcernementIsUpdating(cid);
    },
    // triggered when gql patch done
    onFieldUpdated(cid){
      this.setConcernementIsUpdating(null);
      this.reloadConcernementEntites(cid);
    },
    concernementFieldIsUpdating(field){
      this.setConcernementIsUpdating(this.cid);
    },
    concernementFieldUpdated(field){
      this.setConcernementIsUpdating(null);
      this.reloadConcernementField(this.cid, field);
    },
    onContentEditableFocusOut(e){
      console.log('onContentEditableFocusOut', e);
      let new_field_content = e.target.innerText;
      console.log('onContentEditableFocusOut', new_field_content);
      console.log('onContentEditableFocusOut this.concernement.title', this.concernement.title);
    },
    addEntite(e){
      console.log('add entite');
      this.reloading_concernements = true;
      // 1 create entite node
      this.createEntiteNode()
        .then((entite) => {
          console.log('createEntiteNode then node', entite);
          // 2 create entite paragraph with entite in it
          this.createEntiteParag(entite)
            .then((parag) => {
              console.log('createEntiteParag then parag', parag);
              // 3 record on concernement field_entites
              this.recordConcernementEntiteField(parag)
                .then((concernement) => {
                  console.log('concernement', concernement);
                  // reload the map item
                  this.reloadConcernementEntites(concernement.nid[0].value)
                    .then(() => {
                      this.reloading_concernements = false;
                    });
                })
            })
        })

    },
    createEntiteNode(){
      return new Promise((resolve, reject) => {
        // 1 create entite node
        const params_node_entite = {
          type: 'entite',
          title: [{value:'Titre à personaliser'}],
          field_confidentialite: [{value:'confidentialite_public'}]
        };
        
        const configs = {
          headers: {'X-CSRF-Token': this.csrf_token}
        };

        REST.post(`/node?_format=json`, params_node_entite, configs)
          .then(({ data }) => {
            console.log('REST post new node entite', data);
            resolve(data)
          })
          .catch(error => {
            console.warn(`Issue with post new node cercle_politique`, error)
            reject(error)
          })
      })
    },
    createEntiteParag(entite){
      return new Promise((resolve, reject) => {
        // 2 create paragraphe
        const params_parag_entite = {
          type: [{target_id: 'entite_concernement'}],
          parent_type:{value: 'node'},
          parent_id:{value: this.cid},
          parent_field_name:{value: 'field_entite'}, // entity reference revision 
          'field_entite':[{target_id: entite.nid[0].value}] // entity reference
        };
        
        const configs = {
          headers: {'X-CSRF-Token': this.csrf_token}
        };

        REST.post(`/entity/paragraph?_format=json`, params_parag_entite, configs)
          .then(({ data }) => {
            console.log('REST post new source parag', data);
            resolve(data)
      
          })
          .catch(error => {
            console.warn(`Issue with post new paragraph source`, error)
            reject(error)
          })
      })
    },
    recordConcernementEntiteField(parag){
      return new Promise((resolve, reject) => {
        // 3 record concernement field_entite

        // get all the field_entite values, we don't want to ersae everything
        let entites = [];
        this.concernement.entites.forEach((entite) =>{
          entites.push({
            target_id: entite.id,
            target_revision_id: entite.revision_id
          })
        })
        // add the new field value
        entites.push({
          target_id: parag.id[0].value,
          target_revision_id: parag.revision_id[0].value
        })
        console.log('entites', entites);
        
        const params_node = {
          type: 'concernement',
          nid: [{value: this.cid}],
          'field_entite': entites
        };
        
        const configs = {
          headers: {'X-CSRF-Token': this.csrf_token}
        };

        REST.patch(`/node/${this.cid}?_format=json`, params_node, configs)
          .then(({ data }) => {
            console.log('REST patch entite new field_entite', data)
            resolve(data)
          })
          .catch(error => {
            console.warn(`Issue with patch node entite field_entite`, error)
            reject(error)
          })
        // resolve('test')
      })
    },
    // setProxSuggestions(){
    //   this.prox_suggestions = [];
    //   // check that entite is well referenced in a loaded concernement
    //   this.user_entites.forEach((entite) => {
    //     if (this.allEntitesById[entite.id]) {
    //       // check if not already proximited
    //       let tobesuggested = true;
    //       this.prox_default_values.forEach((default_entite) => {
    //         if (default_entite.id === entite.id) {
    //           tobesuggested = false;
    //         }
    //       })
    //       if (tobesuggested) {
    //         this.prox_suggestions.push(entite)
    //       }
    //     }
    //   })
    //   console.log('this.prox_suggestions', this.prox_suggestions);
    //   // this.checkForUserProxmite();
    // },
    checkForUserProxmite(){
      if (this.entite && this.isloggedin && !this.entite.can_update ) {
        console.log('checkForUserProxmite', this.entite);
        // this.prox_suggestions.forEach((user_entite) => {
        this.prox_default_values = [];
        this.prox_suggestions = [];
        this.user_entites.forEach((user_entite) => {
          console.log('user_entite', user_entite);
          console.log('entite', this.allEntitesById[user_entite.id]);
          if (this.allEntitesById[user_entite.id]) {
            let tobesuggested = true
            this.allEntitesById[user_entite.id].entite.proximite.forEach((prox_field_entite) => {
              if(prox_field_entite.id === this.entite.id) {
                this.prox_default_values.push(user_entite);
                tobesuggested = false
              }
            })
            if (tobesuggested) {
              this.prox_suggestions.push(user_entite)  
            }
          }
        })
        console.log('this.prox_default_values', this.prox_default_values);
      }
    },
    onProximiteSelected(src_entite){
      console.log('onProximiteSelected', src_entite);
      console.log('onProximiteSelected', this.prox_new_value);
      if (src_entite) {
        this.proxvaluetitle = src_entite.title;
        // get all the field_proximite values, we don't want to ersae everything
        let proximites = [];
        this.allEntitesById[src_entite.id].entite.proximite.forEach((target_entite) =>{
          proximites.push({
            target_id: target_entite.id,
          })
        })
        // add the new field value
        proximites.push({
          target_id: this.entite.id,
        })
        console.log('proximites', proximites);

        this.recordProximites(src_entite.id, proximites);
      }
    },
    deleteProximite(src_entite){
      console.log('deleteProximite', src_entite);
      if (src_entite) {
        // get all the field_proximite values, excpet the one we want to delete
        let proximites = [];
        this.allEntitesById[src_entite.id].entite.proximite.forEach((target_entite) =>{
          if(target_entite.id !== this.entite.id){
            proximites.push({
              target_id: target_entite.id,
            })
          }
        })
        this.recordProximites(src_entite.id, proximites);
      }
    },
    recordProximites(src_id, proximites){
      console.log(`recordProximites proximites`, proximites);
      
      const params_node = {
        type: 'entite',
        nid: [{value: src_id}],
        'field_proximite': proximites
      };

      const configs = {
        headers: {'X-CSRF-Token': this.csrf_token}
      };

      REST.patch(`/node/${src_id}?_format=json`, params_node, configs)
        .then(({ data }) => {
          console.log('REST patch entite new field_proximite', data)
          this.reloadProximites(src_id)
            .then(() => {
              if (this.$refs.simplesuggest) {
                console.log('Proximites reloaded, $refs', this.$refs.simplesuggest);
                // clear the autocomplete field 
                this.$refs.simplesuggest.setText('');
                this.$refs.simplesuggest.selected = null;
                this.$refs.simplesuggest.isSelectedUpToDate = false;
                this.$refs.simplesuggest.clearSuggestions();
              }
            })
        })
        .catch(error => {
          console.warn(`Issue with patch node entite field_proximite`, error)
          // reject(error)
        })
    },
    

  },
  components: {
    CartoucheLayout,
    Entite,
    VueSlider,
    SvgIcon,
    ContentEditable,
    CheckboxEditable,
    SelectEditable,
    VueSimpleSuggest
  }
}

</script>

<template>
  <CartoucheLayout ref="cartouche_layout" :cid="cid" :eid="eid" @main_scrolled="onMainScrolled">
    <template v-slot:header>
      <div class="entite">
        <!-- TODO update entite with revisions -->
        <label v-if="entite" class="menacemaintient" :class="{ hidden: headerreduced}">{{ entity_title_label }}</label>
        <!-- <h3 v-if="entite" class="entite-title">{{ entite.title }}</h3> -->
        <ContentEditable 
          v-if="entite"
          tag="h3"
          :value="entite.title" 
          class="entite-title" 
          :contenteditable="entite.can_update"
          :data="{
            entitytype: 'node',
            bundle: 'entite',
            id: this.entite.id,
            field: {field_name: 'title', value:'value'}
          }"
          v-on:updating="onFieldIsUpdating(cid)"
          v-on:updated="onFieldUpdated(cid)"/>

        <!-- proximité -->
        <section
          v-if="entite && isloggedin && !entite.can_update"
          id="new-proxomite"
          class="editable-proximites"
          >
          <label>Mes proximités</label>
          <div class="wrapper">
            <ul v-if="prox_default_values.length">
              <li v-for="(prox_entite, i) in prox_default_values" v-key="i">
                <em>{{ prox_entite.title }}</em>
                <!-- <span 
                  class="delete"
                  @click="deleteProximite(prox_entite)"
                  > -->
                  <svg-icon
                    type="mdi" 
                    :path="mdiCloseBox_path"
                    class="delete"
                    @click="deleteProximite(prox_entite)"
                    ></svg-icon>
                <!-- </span> -->
              </li>
            </ul>
            <template v-if="prox_suggestions.length" >
              <span>Lier <em>{{ entite.title }}</em> a une de mes entitées</span>
              <VueSimpleSuggest
                ref="simplesuggest"
                mode="select"
                :list="prox_suggestions"
                v-model="prox_new_value"
                display-attribute="title"
                value-attribute="id"
                filter-by-query="true"
                min-length="0"
                placeholder="Tappez le nom de votre entite..."
                @update:model-select="onProximiteSelected" 
              />
            </template>
          </div>
        </section>

        <section class="entite-params" v-if="entite && entite.can_update">
          <!-- active -->
          <CheckboxEditable
            :checked="this.parag_entite.active"
            label="Active" 
            :data="{
              entitytype: 'paragraph',
              bundle: 'entite_concernement',
              id: this.parag_entite.id,
              field: 'field_active'}"
              v-on:updated="reloadConcernementEntites(cid)"/>

          <!-- agissante -->
          <CheckboxEditable
            :checked="entite.agissante"
            label="Entité action" 
            :data="{
              entitytype: 'node',
              bundle: 'entite',
              id: this.entite.id,
              field: 'field_entite_agissante'}"
              v-on:updated="reloadConcernementEntites(cid)"/>

          <!-- confidentialité -->
          <SelectEditable
            label="Confidentialité"
            :value="entite.confidentialite"
            :options="{
              'confidentialite_prive': 'privé',
              'confidentialite_interne': 'interne',
              'confidentialite_public': 'public'}"
            :data="{
              entitytype: 'node',
              bundle: 'entite',
              nid: this.entite.id,
              field: 'field_confidentialite'}"
              v-on:updated="reloadConcernementEntites(cid)"/>
        </section>


      </div>
    </template>
    
    <template v-slot:main>
      <!-- concernement -->
      <template v-if="!entite">
        <section v-if="concernement.description || concernement.can_update" class="description">
            <label v-if="ct_concernement">{{ ct_concernement.field_description.description }}</label>
            
            <ContentEditable 
              tag="p"
              :value="concernement.description"
              :html="true" 
              :class="{ ellipsed: headerreduced }" 
              :contenteditable="concernement.can_update"
              :data="{
                entitytype: 'node',
                bundle: 'concernement',
                id: this.concernement.id,
                field: {field_name: 'field_description', value:'value'}
              }" 
              v-on:updating="concernementFieldIsUpdating('description')"
              v-on:updated="concernementFieldUpdated('description')"/>

        </section>
        <section v-if="concernement.caillou || concernement.can_update" class="caillou">
            <label v-if="ct_concernement">{{ ct_concernement.field_caillou.description }}</label>
            
            <ContentEditable 
              tag="p"
              :value="concernement.caillou" 
              :class="{ ellipsed: headerreduced }" 
              :contenteditable="concernement.can_update"
              :data="{
                entitytype: 'node',
                bundle: 'concernement',
                id: this.concernement.id,
                field: {field_name: 'field_caillou', value:'value'}
              }" 
              v-on:updating="concernementFieldIsUpdating('caillou')"
              v-on:updated="concernementFieldUpdated('caillou')"/>

        </section>
        <template v-if="concernement.can_update">
          <div v-if="!reloading_concernements" @click="addEntite" class="add-entite-btn">
            <span>Ajouter une entité</span>
            <svg-icon type="mdi" :path="mdiStickerPlusOutline_path"/>
          </div>
          <div v-else class="add-entite-btn">
            <div class="loading">Chargement</div>
          </div>
        </template>
      </template>

      <!-- entite -->
      <Entite 
        v-if="entite" 
        :concernement="concernement" 
        :entite="entite" 
        :eid="eid" 
        v-on:reloadEntite="loadEntite"/>
      <!-- v-on:updating="onFieldIsUpdating(cid)"
        v-on:updated="onFieldUpdated(cid)" -->

    </template>

    <template v-slot:footer>
      <section class="infos">
        <svg-icon
            type="mdi" 
            :path="!infos_opened ? chevronright_path : chevrondown_path"
            class="open-btn"
            @click="onClickInfos"
            ></svg-icon>
          <div 
            class="author info" 
            @click="onClickInfos">
              <span>une enquête de</span> {{ concernement.author.username }}<br/>
          </div>
          <div class="wrapper" :class="{ 'opened': infos_opened }">
            <div class="info structure" v-if="concernement.author.structure.length"><span>avec</span> {{ concernement.author.structure[0].name }}<br/></div>
            <div class="info lieu" v-if="concernement.lieu.length"><span>à</span> {{ concernement.lieu[0].name }}<br/></div>
            <div class="info created"><span>démarrée le</span> {{ created }}<br/></div>
            <div class="info changed"><span>mise à jour le</span> {{ changed }}</div>
            <div class="info recit-colophon" v-if="concernement.recit_colophon" v-html="concernement.recit_colophon"/>
          </div>
      </section>
      
      <section class="sliders"  v-if="history_slider_ops || details_slider_ops">
        <section class="historique" v-if="history_slider_ops">
          <label>Historique</label>
          <!-- <h3>{{ history_value }}</h3> -->
          <vue-slider
            ref="slider"
            v-model="history_value"
            v-bind="history_slider_ops"
          ></vue-slider>
        </section>
        <section class="details" v-if="details_slider_ops && map_mode === 'terraindevie'">
          <label>Détails</label>
          <!-- <h3>{{ details_value }}</h3> -->
          <vue-slider
            ref="details_slider"
            v-model="details_value"
            v-bind="details_slider_ops"
          ></vue-slider>
        </section>
      </section>
    </template>
  </CartoucheLayout> 
  
</template>

<style lang="css">
  span.entite-point{
    color: #01ffe2;
  }
</style>