<template>
  <div class="assets-detail" v-loading="isLoading">
    <div class="go-back" @click="goBack">
      <ods-icon name="arrow-left" size="22" color="$--color-primary"></ods-icon>
    </div>
    <div class="asset-info">
      <header>
        <h2>Activo {{ currentAsset && currentAsset.id }}</h2>
      </header>
      <div>
        <ods-form class="asset-info-form" label-position="top" :model="assetInfo" ref="assetInfo">
          <ods-row :gutter="32">
            <ods-col :span="8">
              <ods-form-item label="Id" prop="id">
                <ods-input v-model="assetInfo.id" disabled></ods-input>
              </ods-form-item>
            </ods-col>
            <ods-col :span="8">
              <ods-form-item label="Tipo" prop="type">
                <ods-input v-model="assetInfo.type" disabled></ods-input>
              </ods-form-item>
            </ods-col>
            <ods-col :span="8">
              <ods-form-item label="Grupo" prop="group">
                <ods-input v-model="assetInfo.group" disabled></ods-input>
              </ods-form-item>
            </ods-col>
          </ods-row>
          <ods-row :gutter="32">
            <ods-col :span="8">
              <ods-form-item label="Estado" prop="state">
                <ods-input v-model="assetInfo.state" type="email" disabled></ods-input>
              </ods-form-item>
            </ods-col>
            <ods-col :span="16">
              <ods-form-item label="Ubicación" prop="location">
                <ods-input v-model="assetInfo.location" disabled></ods-input>
              </ods-form-item>
            </ods-col>
          </ods-row>
        </ods-form>
      </div>

      <!-- <h2 class="title-devices">Dispositivos</h2> -->

      <!-- <device-alerts /> -->

      <div>
        <ods-tabs v-model="activeTab" @tab-click="handleClick">
          <ods-tab-pane :label="`Ruta ${routeId}`" name="route">
            <div class="route-timeline">
              <route-list-expandable
                :isLast="routePoints.future && !routePoints.future.length"
                :list="routePoints.past"
                :pointType="'past'"
                :total="routePoints.total"
              />
              <route-list-expandable
                :isLast="routePoints.past && !routePoints.past.length"
                :list="routePoints.future"
                :pointType="'future'"
                :total="routePoints.total"
              />
            </div>
          </ods-tab-pane>
          <ods-tab-pane label="Alertas" name="alerts">
            <ods-table :data="tableData" style="width: 100%">
              <ods-table-column prop="date" label="Fecha" width="180"></ods-table-column>
              <ods-table-column prop="name" label="Nombre" width="180"></ods-table-column>
              <ods-table-column prop="address" label="Dirección"></ods-table-column>
            </ods-table>
          </ods-tab-pane>
        </ods-tabs>
      </div>
    </div>
  </div>
</template>

<script>
import moment from 'moment';
import {mapGetters, mapActions, mapMutations} from 'vuex';

import RouteListExpandable from '@/components/assets/RouteListExpandable';
import DeviceAlerts from '@/components/device-alerts/DeviceAlerts.vue';

export default {
  name: 'assets-detail',
  components: {
    DeviceAlerts,
    RouteListExpandable,
  },
  data() {
    return {
      assetId: null,
      isLoading: true,
      activeTab: 'route',
      assetInfo: {
        id: '-',
        type: '-',
        group: '-',
        state: '-',
        location: '-',
      },
      tableData: [
        {
          date: '2016-05-03',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles',
        },
        {
          date: '2016-05-02',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles',
        },
        {
          date: '2016-05-04',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles',
        },
        {
          date: '2016-05-01',
          name: 'Tom',
          address: 'No. 189, Grove St, Los Angeles',
        },
      ],
      routeId: null,
      routePoints: [],
    };
  },
  async mounted() {
    this.assetId = this.$route.params.id;

    if (this.assetId) {
      this.isLoading = true;

      // const asset = await this.fetchAssetById(this.assetId)

      // const route = asset.data
      // const routeId = route.extrainfo.routeId
      // this.routeId = routeId

      // const points = await Promise.all([
      //   this.getRoutePoints(this.assetId, routeId),
      //   this.getAssetLocations(this.assetId, routeId)
      // ])

      // this.loadAssetsDetail(points[0], points[1])
      this.isLoading = false;
    } else {
      this.$router.replace({path: '/map/assets'});
    }
  },
  computed: {...mapGetters(['currentAsset', 'getAssets', 'getFeatureCollection'])},
  methods: {
    ...mapActions([
      'fetchAssets',
      'fetchAssetById',
      'fetchRoutePoints',
      'fetchAssetLocations',
    ]),
    ...mapMutations(['setCurrentAsset', 'clearCurrentAsset']),
    async getRoutePoints(assetId, journeyId) {
      return this.fetchRoutePoints({assetId, journeyId});
    },
    async getAssetLocations(assetId, journeyId) {
      return this.fetchAssetLocations({assetId, journeyId});
    },
    loadAssetsDetail(routePoints, assetPoints) {
      const currentAsset = this.currentAsset;

      if (!currentAsset) {
        this.$router.replace({path: '/map/assets'});

        return;
      }

      this.assetInfo = {
        id: currentAsset.id || currentAsset.assetId,
        type: currentAsset.typeProduct || currentAsset.type,
        group: currentAsset.subtype || '-',
        state: currentAsset.selected || '-',
        location: '[-15.444534, 28.13791]',
      };

      const mapElement = document.getElementById('dataIframe');
      // POI layer
      if (mapElement) {
        this.createMapPoints(assetPoints);
      }

      this.routePoints = this.formatJourneyPoints(routePoints);
    },
    formatJourneyPoints(routePoints = []) {
      const pastRoutePoints = [];
      const futureRoutePoints = [];

      for (let index = 0; index < routePoints.length; index++) {
        const checkpoint = routePoints[index].checkpointList[0];

        const point = {
          index,
          id: checkpoint.gisId,
          status: checkpoint.status,
          arrivalDate: moment(checkpoint.arrivalDate).format(
            'DD/MM/YYYY HH:mm:ss',
          ),
          realArrivalDate:
            checkpoint.realArrivalDate
            && moment(checkpoint.realArrivalDate).format('DD/MM/YYYY HH:mm:ss'),
        };

        if (checkpoint.arrivalDate && checkpoint.realArrivalDate) {
          point.bulletClass = 'past-bullet';
          pastRoutePoints.push(point);
        } else {
          point.bulletClass = 'future-bullet';
          futureRoutePoints.push(point);
        }
      }

      const pastPointsLength = pastRoutePoints.length;
      const futurePointsLength = futureRoutePoints.length;

      if (pastPointsLength) {
        pastRoutePoints[0].bulletClass = 'origin-bullet';
      } else if (futurePointsLength) {
        futureRoutePoints[0].bulletClass = 'destiny-bullet';
      }

      if (futurePointsLength) {
        futureRoutePoints[futurePointsLength - 1].bulletClass = 'destiny-bullet';
      } else if (pastPointsLength) {
        pastRoutePoints[pastPointsLength - 1].bulletClass = 'origin-bullet';
      }

      return {
        past: pastRoutePoints,
        future: futureRoutePoints,
        total: routePoints.length,
      };
    },
    createMapPoints(assetPoints) {
      const mapElement = document.getElementById('dataIframe');

      const mapContext = mapElement.contentWindow;

      const coordinateLines = [];
      const newFeatureCollectionRoute = {
        type: 'FeatureCollection',
        name: 'Feature Route',
        features: [],
      };

      mapContext.clearLayers();
      // Create route
      for (let i = 0; i < assetPoints[0].trackedGeometryList.length; i++) {
        const trackedPoint = assetPoints[0].trackedGeometryList[i];

        const newRoute = {
          type: 'Feature',
          properties: {
            id: trackedPoint.id,
            status: trackedPoint.status,
            date: moment(trackedPoint.trackedTime.$date).format(
              'DD/MM/YYYY HH:mm:ss',
            ),
          },
          geometry: trackedPoint.geometry,
        };

        newFeatureCollectionRoute.features.push(newRoute);
        coordinateLines.push(trackedPoint.geometry.coordinates);
      }

      // Render line points
      mapContext.createNewLayerLines(coordinateLines);

      // Render route points
      mapContext.createNewLayerPoints(
        'Route',
        newFeatureCollectionRoute,
        'motion_dentro_poi',
        'motion_dentro_poi',
      );

      // Listener change data of POI selected
      window.document.addEventListener(
        'sendStationEvent',
        this.sendStationEventCallback,
        false,
      );
    },
    sendStationEventCallback(e) {
      const asset = e.detail;

      this.assetInfo = {
        id: asset.id,
        type: asset.typeProduct,
        group: asset.subtype,
        state: asset.selected,
        location: asset.name,
      };

      this.clearCurrentAsset();
      this.setCurrentAsset({currentAsset: asset});
    },
    goBack() {
      const mapElement = document.getElementById('dataIframe');

      if (mapElement) {
        const mapContext = mapElement.contentWindow;

        const currentFeatureCollection = this.getFeatureCollection;

        mapContext.clearLayers();
        mapContext.createNewLayerPoints(
          'Route',
          currentFeatureCollection,
          'sensor_blue',
          'sensor_red',
        );
        mapContext.setInitPosition();
        mapContext.activateClustering();

        this.$router.replace({path: '/map/assets'});
      }
    },
    handleClick(tab) {
      console.log('Tab selected: ', tab.paneName);
    },
  },
};
</script>

<style lang="scss" scoped>
@mixin big-bullet {
  position: absolute;
  display: flex;
  left: -16px;
  top: -10px;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  align-items: center;
  justify-content: center;
}

@mixin small-bullet {
  position: absolute;
  top: -1px;
  left: -7px;
  width: 12px;
  height: 12px;
  border-radius: 50%;
}
.assets-detail {
  padding: 24px;
  box-shadow: 0 1px 20px rgba(0, 0, 0, 0.1);
  background-color: $--color-white;
  h2 {
    font-size: $size-ms;
    color: #222;
    &.title-devices {
      margin-bottom: 20px;
    }
  }
  .go-back {
    cursor: pointer;
  }
  .asset-info {
    margin-top: 30px;
    > header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 40px;
      h2 {
        color: #444;
        font-weight: $font-weight-regular;
        font-size: 12px;
      }
      a {
        color: $--color-primary;
        font-size: 10px;
        font-weight: $font-weight-medium;
        text-transform: uppercase;
        cursor: pointer;
      }
    }
  }
  .asset-info-form {
    margin: 20px 0;
  }
  .route-timeline {
    margin-top: 20px;
    padding-left: 5px;
    > header {
      margin-bottom: 20px;
      width: 65px;
      margin-left: auto;
      align-items: center;
      p {
        margin-left: 5px;
      }
    }
    .route-list {
      margin-left: 10px;

      li {
        position: relative;
        padding-bottom: 40px;
        padding-left: 40px;
        border-left: 3px solid $--color-primary;

        &.future-point {
          border-style: dashed;

          &.no-opacity .point-data {
            opacity: 1;
          }
          .point-data {
            opacity: 0.4;
          }

          &:last-of-type {
            border: none;
          }

          &:last-of-type .destiny-bullet {
            left: -4px;
          }
        }

        &.past-point {
          &:last-of-type {
            border: none;
          }

          &:last-of-type .origin-bullet {
            left: -4px;
          }
        }

        h2 {
          font-size: $size-xs;
          margin-bottom: 10px;
        }
        h3 {
          font-size: $size-ml;
          margin-bottom: 10px;
        }
        p {
          font-size: $size-ml;
          font-weight: $font-weight-regular;
        }
        .origin-bullet {
          @include small-bullet;
          background-color: $--color-primary;
        }
        .past-bullet {
          @include big-bullet;
          background-color: $--color-primary;
        }
        .future-bullet {
          @include big-bullet;
          border: 2px solid $--color-secondary;
          background-color: $--color-white;
        }
        .destiny-bullet {
          @include small-bullet;
          border: 2px solid $--color-secondary;
          background-color: $--color-white;
        }
      }
    }
  }

  .route-point-item {
    time {
      font-size: $size-xs;
    }
    .future-bullet .route-bullet {
      color: $--color-primary;
    }
    .past-bullet .route-bullet {
      color: $--color-white;
    }
    .destiny-bullet .route-bullet,
    .origin-bullet .route-bullet {
      display: none;
    }
    .route-bullet {
      font-size: $size-xs;
    }
  }
}
</style>
