<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 CartoucheLayout from '@components/layout/CartoucheLayout.vue';

import SvgIcon from '@jamescoyle/vue-icon';
import { mdiChevronRight } from '@mdi/js';
import { mdiChevronDown } from '@mdi/js';
import { mdiPencilPlus } from '@mdi/js';
import { mdiPencilPlusOutline } from '@mdi/js';
import { mdiRhombus } from '@mdi/js';
import { mdiRhombusOutline } from '@mdi/js';
import { mdiStickerPlusOutline } from '@mdi/js';

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

export default {
  props: ['cid'],
  data(){
    return {
      opened_besoin_id: null,
      chevronright_path: mdiChevronRight,
      chevrondown_path: mdiChevronDown,
      pencilplus_path: mdiPencilPlus,
      pencilplusoutline_path: mdiPencilPlusOutline,
      rhombus_path: mdiRhombus,
      rhombusoutline_path: mdiRhombusOutline,
      mdiStickerPlusOutline_path: mdiStickerPlusOutline,
      reloading_concernements: false,
    }
  },
  computed: {
    ...mapState(UserStore,['isloggedin', 'csrf_token']),
    ...mapState(ConcernementsStore,['opened_concernement',
                                    'ct_concernement',
                                    'ct_entite',
                                    'allBesoinsById'
                                  ]),
    ...mapState(CommonStore,['hover_elmt'])
  },
  created () {
    console.log(`puissance d'agir content created, id: ${this.id}, opened_concernement:`,this.opened_concernement);
  },
  mounted() {
    
  },
  methods: {
    ...mapActions(CommonStore,['setHoverElmt']),
    ...mapActions(ConcernementsStore, ['reloadConcernementBesoins']),
    onClickBesoin(id){
      console.log("onClickBesoin", id);
      this.opened_besoin_id = id === this.opened_besoin_id ? null : id;
    },
    besoinClass(id){
      return this.opened_besoin_id === id ? "opened" : "";
    },
    onHoverItem(type, pid, bid, rid){
      console.log(`onHoverItem type:${type}, paper_id:${pid} bid:${bid}, rid:${rid}`);
      this.setHoverElmt({
        type: type,
        paper_id: pid,
        id: rid ? rid : bid,
        bid: rid ? bid : null,
        no_popup: true
      });
    },
    addBesoin(e){
      console.log('add besoin');
      this.reloading_concernements = true;
      // 1 create besoin node
      this.createBesoinNode()
        .then((besoin) => {
          console.log('createBesoinNode then node', besoin);
          // 2 record new besoin in concernement's field_besoin 
          this.recordConcernementBesoinField(besoin)
            .then((concernement) => {
              console.log('concernement', concernement);
              // reload the map item
              this.reloadConcernementBesoins(concernement.nid[0].value)
                .then(() => {
                  this.reloading_concernements = false;
                });
            })
        })
    },
    reloadBesoins(){
      this.reloadConcernementBesoins(this.cid);
    },
    createBesoinNode(){
      return new Promise((resolve, reject) => {
        // 1 create entite node
        const params_node_besoin = {
          type: 'besoin',
          body: [{value:'Description à personaliser'}],
          field_confidentialite: [{value:'confidentialite_public'}]
        };
        
        const configs = {
          headers: {'X-CSRF-Token': this.csrf_token}
        };

        REST.post(`/node?_format=json`, params_node_besoin, configs)
          .then(({ data }) => {
            console.log('REST post new node besoin', data);
            resolve(data)
          })
          .catch(error => {
            console.warn(`Issue with post new node besoin`, error)
            reject(error)
          })
      })
    },
    recordConcernementBesoinField(new_besoin){
      return new Promise((resolve, reject) => {
        // 3 record concernement field_entite

        // get all the field_entite values, we don't want to ersae everything
        let besoins = [];
        this.opened_concernement.besoins.forEach((besoin) =>{
          besoins.push({
            target_id: besoin.id
          })
        })
        // add the new field value
        besoins.push({
          target_id: new_besoin.nid[0].value
        })
        console.log('besoins', besoins);
        
        const params_node = {
          type: 'concernement',
          nid: [{value: this.cid}],
          'field_besoin': besoins
        };
        
        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')
      })
    },
    addRessource(besoin_id){
      console.log('addRessource', besoin_id);
      this.reloading_concernements = true;
      // 1 create reponse node
      this.createRessourceNode(besoin_id)
        .then((ressource) => {
          console.log('createRessourceNode then node', ressource);
          // 2 record new besoin in concernement's field_besoin 
          // this.recordBesoinRessourceField(besoin_id, ressource)
          //   .then((besoin) => {
          //     console.log('besoin', besoin);
              // reload the map item
              this.reloadConcernementBesoins(this.cid)
                .then(() => {
                  this.reloading_concernements = false;
                });
            // })
        })
    },
    createRessourceNode(besoin_id){
      return new Promise((resolve, reject) => {
        // 1 create entite node
        let besoin_title = this.allBesoinsById[besoin_id].title;
        const params_node_ressource = {
          type: 'reponse',
          title: [{value:`reponse-${besoin_title}-${Date.now()}`}],
          field_besoin_on_reponses: [{target_id: besoin_id}],
          field_confidentialite: [{value:'confidentialite_public'}]
        };
        
        const configs = {
          headers: {'X-CSRF-Token': this.csrf_token}
        };

        REST.post(`/node?_format=json`, params_node_ressource, configs)
          .then(({ data }) => {
            console.log('REST post new node ressource', data);
            resolve(data)
          })
          .catch(error => {
            console.warn(`Issue with post new node ressource`, error)
            reject(error)
          })
      })
    },
    recordBesoinRessourceField(besoin_id, new_reponse){
      return new Promise((resolve, reject) => {
        // 3 record concernement field_entite

        // get all the field_entite values, we don't want to ersae everything
        let reponses = [];
        this.allBesoinsById[besoin_id].reponses.forEach((reponse) =>{
          reponses.push({
            target_id: reponse.id
          })
        })
        // add the new field value
        reponses.push({
          target_id: new_reponse.nid[0].value
        })
        console.log('reponses', reponses);
        
        const params_node = {
          type: 'besoin',
          nid: [{value: besoin_id}],
          'field_reponse': reponses
        };
        
        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 besoin new field_reponse', data)
            resolve(data)
          })
          .catch(error => {
            console.warn(`Issue with patch node besoin field_reponse`, error)
            reject(error)
          })
        // resolve('test')
      })
    }
  },
  components: {
    CartoucheLayout,
    SvgIcon,
    ContentEditable,
    SelectEditable
  }
}

</script>

<template>
  <CartoucheLayout :cid="cid">
    <!-- <template v-slot:header>
    </template> -->

    
    <template v-slot:main>

      <ul class="besoins">
        <li
          v-for="besoin in opened_concernement.besoins"
          :key="besoin.id"
          class="besoin"
          :id="besoin.id"
          :class="besoinClass(besoin.id)"
          @mouseover="onHoverItem('besoin', besoin.paper_id, besoin.id)"
        >
          <svg-icon
            type="mdi" 
            :path="besoin.id !== opened_besoin_id ? chevronright_path : chevrondown_path"
            class="open-btn"
            @click="onClickBesoin(besoin.id)"
            ></svg-icon>
          <header @click="onClickBesoin(besoin.id)">
            <label 
              :class="{ 'hover': hover_elmt 
                              && (hover_elmt.type === 'besoin' || hover_elmt.type === 'reponse') 
                              && (hover_elmt.id === besoin.id || hover_elmt.bid === besoin.id) }"
              >
              <svg-icon
                type="mdi" 
                :path="rhombus_path"
                 />
                Besoin de l'enqueteur
            </label>

            <!-- <h4 class="besoin-description" v-html="besoin.description"/> -->
            <ContentEditable 
              tag="p"
              :value="besoin.description"
              :html="true"
              :contenteditable="opened_concernement.can_update"
              :data="{
                entitytype: 'node',
                bundle: 'besoin',
                id: besoin.id,
                field: {field_name: 'body', value:'value'}
              }"
              v-on:updated="reloadBesoins" />

              <SelectEditable 
                v-if="opened_concernement.can_update"
                label="Confidentialité"
                :value="besoin.confidentialite"
                :options="{
                  'confidentialite_prive': 'privé',
                  'confidentialite_interne': 'interne',
                  'confidentialite_public': 'public'
                }"
                :data="{
                  entitytype: 'node',
                  bundle: 'besoin',
                  nid: besoin.id,
                  field: 'field_confidentialite'
                }"
                v-on:updated="reloadBesoins" />
          </header>
          <ul class="reponses">
            <li
              v-for="reponse in besoin.reponses"
              :key="reponse.id"
              class="reponse"
              :id="reponse.id"
              @mouseover.stop="onHoverItem('reponse', reponse.paper_id, besoin.id, reponse.id)"
            >
              <label 
              :class="{ 'hover': hover_elmt 
                              && hover_elmt.type === 'reponse' 
                              && hover_elmt.id === reponse.id }"
                >
                <svg-icon
                type="mdi" 
                :path="hover_elmt && hover_elmt.type === 'reponse' && hover_elmt.id === reponse.id ? rhombus_path : rhombusoutline_path"
                 />
                Ressource</label>

              <SelectEditable 
                v-if="reponse.can_update"
                label="Confidentialité"
                :value="reponse.confidentialite"
                :options="{
                  'confidentialite_prive': 'privé',
                  'confidentialite_interne': 'interne',
                  'confidentialite_public': 'public'
                }"
                :data="{
                  entitytype: 'node',
                  bundle: 'reponse',
                  nid: reponse.id,
                  field: 'field_confidentialite'
                }"
                v-on:updated="reloadBesoins" />
                
              <section v-if="reponse.qui || reponse.can_update">
                <label for="reponse-qui">Qui</label>
                <!-- <p name="reponse-qui" v-html="reponse.qui" /> -->
                <ContentEditable 
                  tag="p"
                  :value="reponse.qui"
                  :html="true"
                  :contenteditable="reponse.can_update"
                  placeholder="Ajouter un élement de réponse."
                  :data="{
                    entitytype: 'node',
                    bundle: 'reponse',
                    id: reponse.id,
                    field: {field_name: 'field_qui', value:'value'}
                  }"
                  v-on:updated="reloadBesoins" />
              </section>
              <section v-if="reponse.quoi || reponse.can_update">
                <label for="reponse-quoi">Quoi</label>
                <!-- <p name="reponse-quoi" v-html="reponse.quoi" /> -->
                <ContentEditable 
                  tag="p"
                  :value="reponse.quoi"
                  :html="true"
                  :contenteditable="reponse.can_update"
                  placeholder="Ajouter un élement de réponse."
                  :data="{
                    entitytype: 'node',
                    bundle: 'reponse',
                    id: reponse.id,
                    field: {field_name: 'field_quoi', value:'value'}
                  }"
                  v-on:updated="reloadBesoins" />
              </section>    
              <section v-if="reponse.ou || reponse.can_update">
                <label for="reponse-ou">Où</label>
                <!-- <p name="reponse-ou" v-html="reponse.ou" /> -->
                <ContentEditable 
                  tag="p"
                  :value="reponse.ou"
                  :html="true"
                  :contenteditable="reponse.can_update"
                  placeholder="Ajouter un élement de réponse."
                  :data="{
                    entitytype: 'node',
                    bundle: 'reponse',
                    id: reponse.id,
                    field: {field_name: 'field_ou', value:'value'}
                  }"
                  v-on:updated="reloadBesoins" />
              </section>    
              <section v-if="reponse.avec || reponse.can_update">
                <label for="reponse-avec">Avec</label>
                <!-- <p name="reponse-avec" v-html="reponse.avec" /> -->
                <ContentEditable 
                  tag="p"
                  :value="reponse.avec"
                  :html="true"
                  :contenteditable="reponse.can_update"
                  placeholder="Ajouter un élement de réponse."
                  :data="{
                    entitytype: 'node',
                    bundle: 'reponse',
                    id: reponse.id,
                    field: {field_name: 'field_avec', value:'value'}
                  }"
                  v-on:updated="reloadBesoins" />
              </section>    
            </li>      
            <li>
              <template v-if="isloggedin && !opened_concernement.can_update">
              <div v-if="!reloading_concernements" @click="addRessource(besoin.id)" class="add-ressource-btn">
                <span>Proposer une ressource</span>
                <svg-icon type="mdi" :path="mdiStickerPlusOutline_path"/>
              </div>
              <div v-else class="add-ressource-btn">
                <div class="loading">Chargement</div>
              </div>
            </template>
            </li>
          </ul>
          <!-- <a 
              v-if="isloggedin && !opened_concernement.can_update"
              :href="'/api/node/add/reponse?besoin_id='+besoin.id" 
              target="_blank" 
              rel="noopener noreferrer"
              class="contribute-link mdi mdi-pencil-plus">
                <svg-icon type="mdi" :path="pencilplusoutline_path" /> contribuer à ce besoin
            </a> -->
            
      
        </li>
      </ul>
    </template>

    <template v-slot:footer>
    
      <template v-if="opened_concernement.can_update">
        <div v-if="!reloading_concernements" @click="addBesoin" class="add-besoin-btn">
          <span>Ajouter un besoin</span>
          <svg-icon type="mdi" :path="mdiStickerPlusOutline_path"/>
        </div>
        <div v-else class="add-besoin-btn">
          <div class="loading">Chargement</div>
        </div>
      </template>

    </template>


  </CartoucheLayout>
  
</template>