import { defineStore } from 'pinia'

import { UserStore } from '@/stores/user';

// import REST from '@api/rest-axios'
// import JSONAPI from '@api/json-axios'
import { print } from 'graphql/language/printer'
import gql from 'graphql-tag'



// import REST from '@api/rest-axios'
import GQL from '@api/graphql-axios'
// import JSONAPI from '@api/json-axios'

import ConcernementFields from '@api/gql/concernement.fragment.gql'
// import EntityFields from '@api/gql/entitydef.fragment.gql'

import _assign from 'lodash/assign';
import _assignIn from 'lodash/assignIn';
import _merge from 'lodash/merge';


export const ConcernementsStore = defineStore({
  id: 'concernements',
  state: () => ({
    map_mode: null,
    concernements_loading_nb: 0,
    concernements: [],
    concernementsByID: {},
    allEntitesById: {},
    allBesoinsById: {},
    allSuperpositions: [],
    allSuperpositions_bycids: {},
    allSuperpositions_clustered: [],
    allMapItems_byid: {},
    allProximites: [],
    opened_concernement: false,
    opened_entite_id: null,
    opened_recit: false,
    recit_plyr_player: null,
    ct_concernement: {},
    ct_entite: {},
    ct_cercle_politique: {},
    p_groupes_interets: {},
    p_reception_et_traitement: {},
    p_mise_en_oeuvre_decision: {},
    p_reception_application_decision: {},
    concernements_loaded: false,
    concernements_are_loading: false,
    concernement_active_revision: null,
    detailsZoomValue: 1,
    concernement_is_updating_nid: null
  }),
  getters: {
    
  },
  actions: {
    setMapMode(mode) {
      console.log(`set map_mode ${mode}`);
      // mode can be : terraindevie, proximite, superposition, puissancedagir, action, doleancer
      this.map_mode = mode;
    },
    loadConcernements () {
      console.log('concernements store loadConcernements');
      this.concernements_are_loading = true;
      return new Promise((resolve, reject) => {
        const ast = gql`{
          allconcernements {
            ...ConcernementFields
          }
        }
        ${ConcernementFields}
        `
        // console.log('ast', ast);
        GQL.post('', { query: print(ast) })
          .then(({ data : { data  : { allconcernements } } }) => {
            console.log('|||||||||||| loadconcernements loaded ||||||||||||||||||', allconcernements)
            this.concernements = [];
            this.parseConcernements(allconcernements, true)
            this.concernements_loaded = true;
            this.concernements_loading_nb ++;
            this.concernements_are_loading = false;
            resolve();
          })
          .catch(error => {
            console.warn('Issue with loadConcernements', error)
            this.concernements_are_loading = false;
            Promise.reject(error)
          })
      })
    },
    parseConcernements(allconcernements, init) {
      console.log('parse concernements');
      let temp_allSuperpositions = [];
      allconcernements.forEach((concernement) => {
        console.log(`parsing concernement ${concernement.id}`);
        concernement.visible = true;

        concernement.entites_byid = {};
        concernement.entitesagissantes_byid = {};
        concernement.has_proximites = false;
        concernement.has_superpositions = false;
        concernement.has_agissantes = false;
        
        concernement.entites.forEach(entite => {
          // console.log(`parsing entite ${entite.id}`);
          if (entite.entite) { // entite.entite may be null because of workflow confidentiality
            if (!concernement.entites_byid[entite.entite.id]) {
              concernement.entites_byid[entite.entite.id] = entite;
            }

            // record a flat list of all entités of all concernement for map-popup
            if (!this.allEntitesById[entite.entite.id]) {
              this.allEntitesById[entite.entite.id] = entite;
              this.allEntitesById[entite.entite.id].cid = concernement.id;
            }

            // Do not integrate the entite if not active
            if(entite.active){
              // record entite agissante
              if (entite.entite.agissante) {
                if (!concernement.entitesagissantes_byid[entite.entite.id]) {
                  concernement.entitesagissantes_byid[entite.entite.id] = entite;
                }
                concernement.has_agissantes = true;
              }

              // PROXIMITES
              if (entite.entite.proximite.length) {
                console.log("proximite", entite.entite.proximite);
                concernement.has_proximites = true;
              }
              
              // SUPERPOSITIONS
              if (entite.entite.superposition.length) {
                // create properties for later
                if (init) {
                  concernement.superpositions = {};
                  concernement.superposition_constraints_id = {};
                  concernement.all_superposed_concernements_id = [];
                  concernement.superposed_mapitem_id_by_mapitem_id = {};
                }
  
                entite.entite.superposition.forEach(entite_superpose => {
                  // console.log(`superposition eid:${entite.entite.id}, teid:${entite_superpose.id}`);
                  let already_recorded = false;
                  // loop through all already recorded superposition to complete the array instead of create duplicates
                  // TODO check if target cid and eid are accessible before recording the superposition
                  // check if half of the superpositions is already recorded, if yes complete it (add the missing concernement id)
                  for(let superposition of temp_allSuperpositions) { 
                    for(let superposition_item of superposition) {
                      if (superposition_item.eid === entite.entite.id && !superposition_item.cid) {
                        // console.log(`already_recorded, eid:${entite.entite.id}, teid:${entite_superpose.id}`, entite.entite.title);
                        already_recorded = true;
                        superposition_item.cid = concernement.id;
                        break;
                      }
                    }
                    if (already_recorded) {
                      break;
                    }
                  }
                  // if not already recorded, add it to the array. It is incomplete has it's missing one concernement id wich will be filled in next loops
                  if (!already_recorded) {
                    // console.log(`NOT already_recorded, eid:${entite.entite.id}, teid:${entite_superpose.id}`, entite.entite.title);
                    let s = [
                      { 
                        cid: concernement.id, 
                        eid: entite.entite.id
                      },
                      {
                        cid: null,
                        eid: entite_superpose.id
                      }
                    ];
                    // concernement.superpositions.push(s); 
                    temp_allSuperpositions.push(s);
  
                  }
                })
              }
            }
          }
        }); // end of concernement.entites loop
        
        // revisions
        concernement.active_revision = concernement.revision_id;
        concernement.revisions_byid = {};
        concernement.revisions.forEach(rev => {
          concernement.revisions_byid[rev.revision_id] = rev;
        });

        // puissance d'agir
        concernement.has_puissancedagir = concernement.besoins.length ? true : false;
        // console.log('concernement.besoins', concernement.besoins);
        concernement.besoins.forEach(besoin => {
          if (besoin) {
            this.allBesoinsById[besoin.id] = besoin;
          }
        });

        // doleance
        concernement.has_doleance = concernement.doleances.length ? true : false;
        if (concernement.has_doleance) {
          // console.log('concernement has doleance', concernement.doleances);
          concernement.opened_doleance = {
            id: concernement.doleances[0].id
          };
        }
        
        // recit
        concernement.has_recit = concernement.recit !== null;

        // common
        // if (!concernement_is_reloaded) {
          this.concernements.push(concernement);
          this.concernementsByID[concernement.id] = concernement;
        // }else{
        //   // this.concernements[concernement_index] = concernement;
        //   this.concernementsByID[concernement.id] = concernement;
        //   // TODO check that this.concernements and this.concernementsByID contains the same item
        // }

      }); // end of concernements loop
      // console.log('this.concernements', this.concernements);
      // console.log('this.concernementsByID', this.concernementsByID);

      // console.log('temp_allSuperpositions', temp_allSuperpositions);

      // cleaning superpositions, removing all incomplète onces
      this.allSuperpositions = [];
      temp_allSuperpositions.forEach(s => {
        if (s[0] && s[0].cid && s[0].eid && s[1] && s[1].cid && s[1].eid) {
          this.allSuperpositions.push(s);
          this.concernementsByID[s[0].cid].has_superpositions = true;
          this.concernementsByID[s[1].cid].has_superpositions = true;
        }
      });
      // console.log('this.allSuperpositions', this.allSuperpositions);

      // 1 check if cluster already exists and if yes complete with the next item of cluster
      // 2 if cluster deos not exists, create the cluster and fill it with first item of cluster

      // 1 check if cluster already exists and if yes complete with the next item of cluster
      // get superpositions by cluster
      for(let superpos_to_record of this.allSuperpositions){
        let recorded = false;
        // console.log('-- -- --');
        // console.log(`superpos_to_record : ${superpos_to_record[0].cid}-${superpos_to_record[0].eid}, ${superpos_to_record[1].cid}-${superpos_to_record[1].eid}`);
        // loop through alredy recorded clusters
        for(let [cluster_index, superpo_cluster] of this.allSuperpositions_clustered.entries()){
          // console.log('cluster_index', cluster_index);
          // for each cluster loop throug each superposition
          in_cluster_loop:{
            for(let s of superpo_cluster){
              // console.log(`s : ${s.cid}-${s.eid}`);
              // loop through each cid_eid couple of superpo to be recorded
              for(let i = 0; i <= 1; i++){
                // if one couple already recorded in the cluster, add the other one to the same cluster
                if (superpos_to_record[i].cid === s.cid && superpos_to_record[i].eid === s.eid){
                  // console.log('-- recorded');
                  let j = i === 0 ? 1 : 0;
                  // check if item is not already recorded in the cluster (in case of reparsing concernements)
                  let already_clustered = false;
                  for (let s2 of superpo_cluster) {
                    if (superpos_to_record[j].cid === s2.cid && superpos_to_record[j].eid === s2.eid){
                      already_clustered = true;
                      break;
                    }
                  }
                  // if not already recorded
                  if (!already_clustered) {
                    // add the right item to the cluster
                    this.allSuperpositions_clustered[cluster_index].push(superpos_to_record[j]);
                  }

                  // record the superposition on the concernement BY cluster index
                  // create array if not already exists
                  if(typeof this.concernementsByID[superpos_to_record[j].cid].superpositions[cluster_index] === 'undefined'){
                    this.concernementsByID[superpos_to_record[j].cid].superpositions[cluster_index] = [superpos_to_record];
                  }else if(!already_clustered){
                    this.concernementsByID[superpos_to_record[j].cid].superpositions[cluster_index].push(superpos_to_record);
                  }
                  recorded = true;
                  break in_cluster_loop;
                }
              }
            }
          }
        }

        // 2 if cluster deos not exists, create the cluster and fill it with first item of cluster
        if(!recorded){
          // console.log('-- not recorded');
          // create cluster and fill it with first item of couple
          this.allSuperpositions_clustered.push(superpos_to_record);
          // record superposition on each concernement of each couple member BY cluster index
          for( let i=0; i <= 1; i++){
            this.concernementsByID[superpos_to_record[i].cid].superpositions[this.allSuperpositions_clustered.length-1] = [superpos_to_record];
            // console.log(`concernement ${superpos_to_record[i].cid} superposition by cluster index`,this.concernementsByID[superpos_to_record[i].cid].superpositions);
          }
        }
      }
      // console.log('this.allSuperpositions_clustered', this.allSuperpositions_clustered);
      // console.log(`end of parsing concernements`);

    },
    setConcernementIsUpdating(nid){
      this.concernement_is_updating_nid = nid;
    },
    reloadConcernements () {
      console.log('reloadConcernements');
      return new Promise((resolve, reject) => {
        // reset the arrays
        this.concernements = [];
        this.concernementsByID = {};
        // this.concernements_loaded = false;
        this.loadConcernements()
          .then(()=>{
            resolve();
          });
      })
    },
    reloadConcernementEntites(nid){
      let tmp_conc = this.concernementsByID[nid];
      console.log(`reloadConcernementEntites len: ${tmp_conc.entites.length} revision: ${tmp_conc.revision_id} nid: ${nid} ${Math.random()*10000}`);
      return new Promise((resolve, reject) => {
        const ast = gql`{
          concernement(id:${nid}) {
            id
            entites {
              id
              revision_id
              active
              menacemaintien
              actuelfuture
              prise
              entite {
                title
                id
                agissante
                proximite {
                  id
                  title
                }
                superposition {
                  id
                  title
                }
              }
            }
            revision_id
            revisions {
              revision_id
              changed
              entites {
                id
                revision_id
                active
                menacemaintien
                prise
                actuelfuture
                entite {
                  id
                  title
                  agissante
                  proximite {
                    id
                    title
                  }
                  superposition {
                    id
                    title
                  }
                }
              }
            }
          }
        }
        `
        // console.log('ast', ast);
        GQL.post('', { query: print(ast) })
          .then(({ data : { data  : { concernement } } }) => {
            console.log(`reloadConcernementEntites loaded len: ${concernement.entites.length} revision: ${concernement.revision_id}`, concernement)
            let tmp_conc = this.concernementsByID[concernement.id];
            // merge old concernement entites with new once
            _assign(tmp_conc.entites, concernement.entites);
            // records and/or merge into general object and on conernement entitites_byid
            tmp_conc.entites.forEach(entite => {
              entite.cid = tmp_conc.id;
              if(entite.entite){
                if (this.allEntitesById[entite.entite.id]) {
                  _assign(this.allEntitesById[entite.entite.id], entite);
                }else{
                  this.allEntitesById[entite.entite.id] = entite;
                }
                if (tmp_conc.entites_byid[entite.entite.id]) {
                  _assign(tmp_conc.entites_byid[entite.entite.id], entite);
                }else{
                  tmp_conc.entites_byid[entite.entite.id] = entite;
                }
              }
            });
            // add and/or merge revisions
            tmp_conc.active_revision = concernement.revision_id;
            concernement.revisions.forEach(rev => {
              if(tmp_conc.revisions_byid[rev.revision_id]){
                _assign(tmp_conc.revisions_byid[rev.revision_id], rev);
              }else{
                tmp_conc.revisions_byid[rev.revision_id] = rev;
                tmp_conc.revisions.push(rev);
              }
            })
            let user = UserStore();
            user.getUserEntitees()
              .then(() => {
                console.log('reloadConcernementEntites graphql userentites loaded')
              })
              .catch(error => {
                console.warn('Issue with graphql userentites loading', error);
              })
            resolve(concernement);
          })
          .catch(error => {
            console.warn('Issue with reloadConcernementEntites', error)
            reject(error);
            Promise.reject(error)
          })
      })
    },
    reloadConcernementField(nid, field){
      console.log('reloadConcernementField', nid, field);
      // let tmp_conc = this.concernementsByID[nid];
      return new Promise((resolve, reject) => {
        const ast = gql`{
          concernement(id:${nid}) {
            id
            ${field}
          }
        }
        `
        GQL.post('', { query: print(ast) })
        .then(({ data : { data  : { concernement } } }) => {
          console.log(`reloadConcernementField loaded ${field}`, concernement)
          let tmp_conc = this.concernementsByID[concernement.id];
          // merge old concernement besoins with new once
          _merge(tmp_conc, concernement);
          
          resolve(concernement);
        })
        .catch(error => {
          console.warn('Issue with reloadConcernementField', error)
          reject(error);
          Promise.reject(error)
        })
      });
    },
    reloadConcernementBesoins(nid){
      let tmp_conc = this.concernementsByID[nid];
      // console.log(`reloadConcernementBesoins len: ${tmp_conc.entites.length} revision: ${tmp_conc.revision_id} nid: ${nid}`);
      return new Promise((resolve, reject) => {
        const ast = gql`{
          concernement(id:${nid}) {
            id
            besoins {
              author
              description
              id
              index
              confidentialite
              reponses {
                author
                avec
                id
                ou
                qui
                quoi
                can_update
                confidentialite
              }
            }
          }
        }
        `
        GQL.post('', { query: print(ast) })
        .then(({ data : { data  : { concernement } } }) => {
          console.log(`reloadConcernementBesoins loaded len: ${concernement.besoins.length}`, concernement)
          let tmp_conc = this.concernementsByID[concernement.id];
          // tmp_conc.besoins.forEach(besoin => {
          //   besoin.reponses.forEach(reponse => {
          //     console.log(`BEFORE _merge besoin id:${besoin.id} reponse id:${reponse.id}, paper_id:${reponse.paper_id}`);
          //   });
          // });
          // merge old concernement besoins with new once
          _merge(tmp_conc.besoins, concernement.besoins);
          // tmp_conc.besoins.forEach(besoin => {
          //   besoin.reponses.forEach(reponse => {
          //     console.log(`AFTER _merge besoin id:${besoin.id} reponse id:${reponse.id}, paper_id:${reponse.paper_id}`);
          //   });
          // });
          tmp_conc.has_puissancedagir = tmp_conc.besoins.length ? true : false;
          // records and/or merge into general object
          tmp_conc.besoins.forEach(besoin => {
            besoin.cid = tmp_conc.id;
            if (this.allBesoinsById[besoin.id]) {
              _merge(this.allBesoinsById[besoin.id], besoin);
            }else{
              this.allBesoinsById[besoin.id] = besoin;
            }
          });
          resolve(concernement);
        })
        .catch(error => {
          console.warn('Issue with reloadConcernementBesoins', error)
          reject(error);
          Promise.reject(error)
        })
      });
    },
    reloadProximites (entite_id) {
      console.log(`reloadProximites src_id:${entite_id}`);
      console.log('this.allEntitesById[entite_id]', this.allEntitesById[entite_id]);
      return new Promise((resolve, reject) => {
        let old_entite = this.allEntitesById[entite_id];
        const ast = gql`{
          entite(id:${entite_id}) {
            title
            id
            proximite {
              id
              title
            }
          
          }
        }
        `
        GQL.post('', { query: print(ast) })
          .then(({ data : { data  : { entite } } }) => {
            console.log(`reloadProximites loaded`, entite);
            let concernement = this.concernementsByID[old_entite.cid];
            console.log('concernement', concernement);
            if (entite.proximite.length) {
              concernement.has_proximites = true;
              // update the entites
              concernement.entites_byid[entite.id].entite.proximite = entite.proximite;
              // also update the current revision entite (needed for mapItem display)
              let revision_entites_len = concernement.revisions_byid[concernement.revision_id].entites.length;
              for (let i = 0; i < revision_entites_len; i++) {
                let rev_entite = concernement.revisions_byid[concernement.revision_id].entites[i];
                if (rev_entite.entite && rev_entite.entite.id === entite.id) {
                  concernement.revisions_byid[concernement.revision_id].entites[i].entite.proximite = entite.proximite;
                  break;
                }
              }
              // update the user's entite list
              let user = UserStore();
              console.log('user', user);
              user.getUserEntitees()
                .then(() => { // { data : { data  : { userentites } } }
                  console.log('reloadProximites graphql userentites loaded')
                  // this.user_entites = userentites;
                  resolve();
                })
                .catch(error => {
                  console.warn('Issue with graphql userentites loading', error)
                  Promise.reject(error)
                })
            }
          })
          .catch(error => {
            console.warn('Issue with reloadProximites', error);
          })
      });
    },
    reloadConcernementCerclePol(nid){
      // let tmp_conc = this.concernementsByID[nid];
      console.log(`reloadConcernementCerclePol nid: ${nid} ${Math.random()*10000}`);
      return new Promise((resolve, reject) => {
        const ast = gql`{
          concernement(id:${nid}) {
            id
            doleances {
              id
              author
              bundle
              path
              title
              uuid
              #1
              date_leprobleme {
                start
              }
              leprobleme
              lenquete
              groupesinterets {
                id
                revision_id
                date {
                  end
                  start
                }
                groupe_interets
                accorder_interets
                formuler
              }
              #2
              date_adresse {
                start
              }
              entite_adresse_doleance
              comment_enonce_doleance
              a_qui_adresse_doleance
              reception_traitement {
                id
                revision_id
                date {
                  end
                  start
                }
                entite_adressee
                doleance_formulee
                traite_doleance
                entite_recoit_doleance
              }
              #3
              date_decision {
                start
              }
              entites_decisionnaires
              decision_formulee
              mise_en_oeuvre_decision {
                id
                revision_id
                date {
                  end
                  start
                }
                entite_adresse_decision
                formule_decision
                entite_metenoeuvre_decisio
              }
              #4
              date_application {
                start
              }
              entite_adresse_application
              aqui_adresse_decision
              comment_formule_decision
              receptions_et_applications {
                id
                revision_id
                date {
                  end
                  start
                }
                applique_decision
                formule_decision_applic
                entite_recoit_decision
              }
              probleme_initial_resolu
              oui_nouvelle_situation
              non_adresse_doleance
            }
          }
        }
        `
        // console.log('ast', ast);
        GQL.post('', { query: print(ast) })
          .then(({ data : { data  : { concernement } } }) => {
            console.log(`reloadConcernementCerclePol loaded len: ${concernement.doleances.length} revision: ${concernement.revision_id}`, concernement)
            let tmp_conc = this.concernementsByID[concernement.id];
            // merge old concernement entites with new once
            _assign(tmp_conc.doleances, concernement.doleances);

            // redefine opened doleance if needed
            tmp_conc.has_doleance = tmp_conc.doleances.length ? true : false;
            if (tmp_conc.has_doleance) {
              // console.log('concernement has doleance', tmp_conc.doleances);
              if (!tmp_conc.opened_doleance) {
                tmp_conc.opened_doleance = {
                  id: tmp_conc.doleances[0].id
                };
              }
            }

            // resolve
            resolve(concernement);
          })
          .catch(error => {
            console.warn('Issue with reloadConcernementCerclePol', error)
            reject(error);
            Promise.reject(error)
          })
      });
    },
    loadContentTypeDefinition () {
      const body = {
        query: `
          query EntityDef($type: String!, $bundle: String!){
            entitydef(type: $type, bundle: $bundle) {
              fields {
                type
                field_name
                label
                description
              }
            }
          }`,
        variables: {}
      } 

      // concernement
      body.variables = { type: 'node', bundle: 'concernement' } 
      GQL.post('', body)
        .then(({ data: { data: { entitydef }}}) => {
          // console.log('loadContentTypeDefinition entitydef', entitydef);
          entitydef.fields.forEach(field => {
            this.ct_concernement[field.field_name] = field;
          });
          console.log('loadContentTypeDefinition entitydef concernement', this.ct_concernement);
          
        })

      // entite
      body.variables = { type: 'node', bundle: 'entite' } 
      GQL.post('', body)
        .then(({ data: { data: { entitydef }}}) => {
          // console.log('loadContentTypeDefinition entitydef', entitydef);
          entitydef.fields.forEach(field => {
            this.ct_entite[field.field_name] = field;
          });
          console.log('loadContentTypeDefinition entitydef entite', this.ct_entite);
          
        })

      // cercle_politique
      body.variables = { type: 'node', bundle: 'cercle_politique' } 
      GQL.post('', body)
        .then(({ data: { data: { entitydef }}}) => {
          // console.log('loadContentTypeDefinition entitydef', entitydef);
          entitydef.fields.forEach(field => {
            this.ct_cercle_politique[field.field_name] = field;
          });
          console.log('loadContentTypeDefinition entitydef cercle_politique', this.ct_cercle_politique);
          
        })

      // paragraphe groupes_interets
      body.variables = { type: 'paragraph', bundle: 'groupes_interets' } 
      GQL.post('', body)
        .then(({ data: { data: { entitydef }}}) => {
          // console.log('loadContentTypeDefinition entitydef', entitydef);
          entitydef.fields.forEach(field => {
            this.p_groupes_interets[field.field_name] = field;
          });
          console.log('loadContentTypeDefinition entitydef p_groupes_interets', this.p_groupes_interets);
          
        })

      // paragraphe reception_et_traitement
      body.variables = { type: 'paragraph', bundle: 'reception_et_traitement' } 
      GQL.post('', body)
        .then(({ data: { data: { entitydef }}}) => {
          // console.log('loadContentTypeDefinition entitydef', entitydef);
          entitydef.fields.forEach(field => {
            this.p_reception_et_traitement[field.field_name] = field;
          });
          console.log('loadContentTypeDefinition entitydef p_reception_et_traitement', this.p_reception_et_traitement);
          
        })

      // paragraphe mise_en_oeuvre_decision
      body.variables = { type: 'paragraph', bundle: 'mise_en_oeuvre_decision' } 
      GQL.post('', body)
        .then(({ data: { data: { entitydef }}}) => {
          // console.log('loadContentTypeDefinition entitydef', entitydef);
          entitydef.fields.forEach(field => {
            this.p_mise_en_oeuvre_decision[field.field_name] = field;
          });
          console.log('loadContentTypeDefinition entitydef p_mise_en_oeuvre_decision', this.p_mise_en_oeuvre_decision);
          
        })

      // paragraphe reception_application_decision
      body.variables = { type: 'paragraph', bundle: 'reception_application_decision' } 
      GQL.post('', body)
        .then(({ data: { data: { entitydef }}}) => {
          // console.log('loadContentTypeDefinition entitydef', entitydef);
          entitydef.fields.forEach(field => {
            this.p_reception_application_decision[field.field_name] = field;
          });
          console.log('loadContentTypeDefinition entitydef p_reception_application_decision', this.p_reception_application_decision);
          
        })

    },
    hideShowConcernement (id, state) {
      // console.log(`disableConcernement id: ${id}`);
      this.concernements.forEach((c, i) => {
        if (c.id === id) {
          this.concernements[i].visible = this.concernementsByID[id].visible = state;  
        }
      })
    },
    openCloseConcernements (cid, mi_id) {
      console.log(`openCloseConcernements cid: ${cid}, mi_id: ${mi_id}`);
      var state;
      let mapitem_id = mi_id ? mi_id : cid ? this.concernementsByID[cid].mapitems_ids[this.concernementsByID[cid].mapitems_ids.length -1] : null;
      this.opened_concernement = null;
      this.opened_recit = null;
      this.concernements.forEach((c, i) => {
        // console.log(`openCloseConcernements foreach id: ${id}, c.id: ${c.id}, state: ${state}`, id, c.id);
        c.opened = this.concernements[i].opened = this.concernementsByID[c.id].opened = cid === c.id;
        if (c.opened) {
          this.opened_concernement = c;
          this.opened_concernement.opened_mapitem_id = mapitem_id;
          if (c.has_recit && this.map_mode === "terraindevie") {
            this.opened_recit = c.recit;
          }
          this.concernement_active_revision = {cid: cid, rid: c.active_revision}
          // console.log('openCloseConcernements', this.opened_concernement.opened);
        }
      });
    },
    resetConcernementOpened () {
      this.opened_concernement = null;
      this.openCloseConcernements();
    },
    // setConcernementScale(cid, scale){
    //   console.log(`setConcernementScale ${cid} ${scale}`);
    //   this.concernementsByID[cid].scale = scale;
    // },
    setOpenedEntiteId(id){
      this.opened_entite_id = id;
    },
    setBesoinPaperId(paper_id, cid, bid, rid){
      console.log(`setBesoinPaperId paper_id: ${paper_id}, cid: ${cid}, bid: ${bid}, rid: ${rid}`);
          this.concernementsByID[cid].besoins.forEach((b,j) => {
            if(b.id === bid) {
              if (!rid) {
                this.concernementsByID[cid].besoins[j].paper_id = paper_id;
              } else {
                this.concernementsByID[cid].besoins[j].reponses.forEach((r,k) => {
                  if (r.id === rid) {
                    this.concernementsByID[cid].besoins[j].reponses[k].paper_id = paper_id;
                    console.log(`this.concernementsByID[${cid}].besoins[${j}].reponses[${k}].paper_id`, this.concernementsByID[cid].besoins[j].reponses[k].paper_id);
                  }
                })
              }
            }
          })
      //   }
      // })
    },
    setOpenedDoleance(cid, did){
      console.log(`setOpenedDoleance cid:${cid}, did:${did})`, cid, did);
      this.concernementsByID[cid].opened_doleance = {id: did};
      // console.log('this.opened_concernement.opened_doleance', this.opened_concernement.opened_doleance);
    },
    setOpenedDoleanceField(cid, did, field, index){
      console.log(`setOpenedDoleanceField cid, did, field, index`, cid, did, field, index);
      this.concernementsByID[cid].opened_doleance = {
        cid: cid,
        id: did,
        field: field,
        field_index: index
      };
    },
    setOpenedRecit (recit) {
      this.opened_recit = recit;
    },
    setRecitPlayer (player) {
      console.log('concernement store setRecitPlayer', player);
      this.recit_plyr_player = player;
    },
    setActiveRevision (cid, rid) {
      console.log(`setActiveRevision, cid:${cid}, rid:${rid}`);
      // this.concernementsByID[cid].active_revision = rid;
      this.concernement_active_revision = {cid: cid, rid: rid};
    },
    setDetailsZoomValue (z) {
      console.log(`concernement store setDetailsZoomValue ${z}`);
      this.detailsZoomValue = z;
    }

  }
})