<script>

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

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 ContentEditable from '@components/editable/ContentEditable.vue';
import CheckboxEditable from '@components/editable/CheckboxEditable.vue';
import SelectEditable from '@components/editable/SelectEditable.vue';

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,
    }
  },
  computed: {
    ...mapState(ConcernementsStore,['map_mode',
                                    'opened_concernement',
                                    'concernementsByID',
                                    'ct_concernement',
                                    'ct_entite',
                                    'detailsZoomValue']),
    ...mapState(UserStore,['name']),
    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
    }
  },
  methods: {
    ...mapActions(ConcernementsStore, ['setActiveRevision', 'setDetailsZoomValue']), // 'loadConcernementsRevisions'
    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
        })
        .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;
      }
    },
    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);
    }
  },
  components: {
    CartoucheLayout,
    Entite,
    VueSlider,
    SvgIcon,
    ContentEditable,
    CheckboxEditable,
    SelectEditable
  }
}

</script>

<template>
  <CartoucheLayout ref="cartouche_layout" :cid="cid" @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'}
          }" />

        <CheckboxEditable 
          v-if="entite && entite.can_update"
          :checked="entite.agissante"
          label="Entité action" 
          :data="{
            entitytype: 'node',
            bundle: 'entite',
            nid: this.entite.id,
            field: 'field_entite_agissante'
          }" />

        <SelectEditable 
          v-if="entite && entite.can_update"
          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'
          }" />

      </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'}
              }" />

        </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'}
              }" />

        </section>
      </template>

      <!-- entite -->
      <Entite v-if="entite" :concernement="concernement" :entite="entite" :eid="eid" v-on:reloadEntite="loadEntite"/>
    </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>