<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';

export default {
  props: ['cid', 'eid'],
  data(){
    return {
      concernement: null,
      entite: null,
      history_value: 0,
      history_slider_ops: null,
      details_value: 0,
      details_slider_ops: null,
      infos_opened: false,
      chevronright_path: mdiChevronRight,
      chevrondown_path: mdiChevronDown,
      mainscrolled: 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 str;
      if (this.concernement.entites_byid[this.eid].menacemaintien > 0) {
        str = 'maintenu';
      } else {
        str = 'menacé'
      }
      return `Pouvez-vous nommer par qui ou par quoi cet élément est ${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){
      this.mainscrolled = scrolled;
    }
  },
  components: {
    CartoucheLayout,
    Entite,
    VueSlider,
    SvgIcon
  }
}

</script>

<template>
  <CartoucheLayout :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: mainscrolled}">{{ entity_title_label }}</label>
        <h3 v-if="entite" class="entite-title">{{ entite.title }}</h3>
      </div>
    </template>
    
    <template v-slot:main>
      <!-- concernement -->
      <template v-if="!entite">
        <section v-if="concernement.description" class="description">
            <label v-if="ct_concernement">{{ ct_concernement.field_description.description }}</label>
            <p v-html="concernement.description"/>
            <!-- <p>{{ concernement.description }}</p> -->
        </section>
        <section v-if="concernement.caillou" class="caillou">
            <label v-if="ct_concernement">{{ ct_concernement.field_caillou.description }}</label>
            <!-- <p v-html="concernement.caillou"/> -->
            <p>{{ concernement.caillou }}</p>
        </section>
      </template>

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