<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,
      infos_opened: false,
      chevronright_path: mdiChevronRight,
      chevrondown_path: mdiChevronDown,
    }
  },
  computed: {
    ...mapState(ConcernementsStore,['map_mode',
                                    'opened_concernement',
                                    'concernementsByID',
                                    'ct_concernement',
                                    'ct_entite']),
    ...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';
    }
  },
  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=[];
    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;
    }
  },
  watch: {
    history_value: {
      handler (n, o) {
        // console.log(`TerrainDeVie watch history_value o:${o}, n:${n}`);
        this.setActiveRevision(this.cid, 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}`);
        this.loadEntite()
      },
      deep: true
    }
  },
  methods: {
    ...mapActions(ConcernementsStore, ['setActiveRevision']), // '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)
        })
    }
  },
  components: {
    CartoucheLayout,
    Entite,
    VueSlider,
    SvgIcon
  }
}

</script>

<template>
  <CartoucheLayout :cid="cid">
    <template v-slot:header>
      <div class="entite">
        <!-- TODO update entite with revisions -->
        <span v-if="entite && concernement.entites_byid[eid].menacemaintien < 0" class="menacemaintient">est menacé par</span>
        <span v-if="entite && concernement.entites_byid[eid].menacemaintien > 0" class="menacemaintient">est maintenu par</span>
        <h3 v-if="entite"><span class="entite-point">&bull;</span>&ThinSpace;{{ 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>
            <div v-html="concernement.description"/>
        </section>
        <section v-if="concernement.caillou" class="caillou">
            <label v-if="ct_concernement">{{ ct_concernement.field_caillou.description }}</label>
            <div v-html="concernement.caillou"/>
        </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">
        <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>
    </template>
  </CartoucheLayout> 
  
</template>

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