<template>
  <div class="add-update-widgets">
    <section v-show="selectedSectionIndex === 1" class="select-widget">
      <div class="widgets-section">
        <div class="widgets">
          <b-row v-if="editMode && this.selectedWidget">
            <b-col lg="6" md="6" sm="12" class="widget">
              <div class="widget-container edit">
                <div class="widget-image">
                  <img :src="this.selectedWidget.image_url" alt="">
                </div>
                <div class="widget-info">
                  <h3>{{this.selectedWidget.label}}</h3>
                </div>
              </div>
            </b-col>
          </b-row>
          <div v-else>
            <ul class="widgets-classification">
              <li :class="{'active': selectedClassification === 'timeseries'}" @click="selectClassfication('timeseries')">Timeseries</li>
              <li :class="{'active': selectedClassification === 'gauge'}" @click="selectClassfication('gauge')">Gauge</li>
              <li :class="{'active': selectedClassification === 'cards'}" @click="selectClassfication('cards')">Cards</li>
              <!-- <li :class="{'active': selectedClassification === 'command'}" @click="selectClassfication('command')">Control</li> -->
            </ul>
            <div class="widgets-container">
              <b-row v-if="widgetsLoaded && (selectedClassification !== 'command')">
                <b-col lg="6" md="6" sm="6" class="widget" v-for="(widget, index) in widgetClassifcation[selectedClassification]" :key="index">
                  <div class="widget-container" @click="setSelectedWidget(widget)" :class="{'active': selectedWidget && selectedWidget.id === widget.id}">
                    <div class="widget-image">
                      <img :src="widget.image_url" alt="">
                    </div>
                    <div class="widget-info">
                      <h3>{{widget.label}}</h3>
                    </div>
                  </div>
                </b-col>
              </b-row>
              <b-row v-else>
                <b-col lg="6" md="6" sm="6" class="widget" v-for="(widget, index) in commandWidgets" :key="index">
                  <div class="widget-container" @click="setCommandWidget(widget)" :class="{'active': selectedWidget && selectedWidget.id === widget.id}">
                    <div class="widget-image">
                      <img :src="widget.image_url" alt="">
                    </div>
                    <div class="widget-info">
                      <h3>{{widget.name}}</h3>
                    </div>
                  </div>
                </b-col>
              </b-row>
            </div>
          </div>
        </div>
      </div>
    </section>
    <section v-show="selectedSectionIndex === 2" class="select-data">
      <div class="data-type-section">
        <div class="vue-tree-container" v-show="selectedWidget && selectedClassification !== 'command'">
          <mads-tree
            ref="tree"
            :treeView="'file'"
            :treeOptions="treeOptions"
            :hiddenEntities="[]"
            :selectedNodes="selectedNodes"
            :selectableEntities="['SensorParameter']"
            :isAnyNodeSelected="selectedNodes.length > 0"
            :type="'organization'"
            :apiKey="'dash_mgmt'"
            :currentUser="currentUser"
            :selectedDashboard="selectedDashboard"
            :selectedProject="selectedProject"
            :dashboardService="dashboardService"
            :treeService="treeService"
            :entityService="entityService"
            :orgService="orgService"
            :dataInsightService="dataInsightService"
            :selectableParamType="selectedWidget && selectedWidget.widget_data_type"
            @on-node-select="onChangeData"
          ></mads-tree>
        </div>
        <div v-if="selectedClassification === 'command'" class="gateways-wrap">
          <span>Select Gateway</span>
          <b-form-radio-group v-model="gatewayId">
            <b-form-radio :value="gateway.id" v-for="(gateway, index) in gateways" :key="index">{{ gateway.name }}</b-form-radio>
          </b-form-radio-group>
        </div>
      </div>
    </section>
    <section v-show="selectedSectionIndex === 3" class="settings">
      <div class="settings-classification" v-if="selectedWidget">
        <div class="widget-category settings-category">
          <span class="category" :class="{'active': selectedSettingsType === 'visualSettings'}" @click="setSettingsType('visualSettings')">Visual Settings</span>
          <span class="category" :class="{'active': selectedSettingsType === 'dataSettings'}" @click="setSettingsType('dataSettings')" v-if="isDataSettingsRequired && dataSettingsVisible()">Data Settings</span>
        </div>
        <div class="settings-common" v-show="selectedSettingsType === 'visualSettings'">
          <visual-settings
            ref="visualSettings"
            :isNewWidget="isNewWidget()"
            :settings="visualSettings"
            :vProps="visualProp"
            :imageService="imageService"
            :category="selectedWidget.category"
            :selectedNodes="selectedNodes"
            :seriesData="seriesData"
            :seriesDataMapping="seriesDataMapping"
            @isValidate="isValidate">>
          </visual-settings>
        </div>
        <div class="settings-common" v-show="(isDataSettingsRequired && dataSettingsVisible()) && selectedSettingsType === 'dataSettings'">
          <series-settings
            v-show="!isNewWidget()"
            ref="seriesSettings"
            :selectedNodes="selectedNodes"
            :dataProp="dataProp"
            :dataSettings="dataSettings"
            :seriesDataMapping="seriesDataMapping">
          </series-settings>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import madsTree from '../../modals/madsTree/index.vue'
import SeriesSettings from './higchartSettings/seriesSettings.vue'
import VisualSettings from './higchartSettings/visualSettings.vue'

export default {
  components: {
    madsTree,
    SeriesSettings,
    VisualSettings
  },
  props: {
    selectedSectionIndex: {
      type: Number,
      required: true
    },
    editMode: {
      type: Boolean,
      default: false
    },
    widgetData: {
      type: Object
    },
    dashboardService: {},
    imageService: {},
    currentUser: {},
    selectedDashboard: {},
    selectedProject: {},
    selectedPanel: {},
    treeService: {},
    entityService: {},
    orgService: {},
    dataInsightService: {}
  },
  data () {
    return {
      selectedClassification: 'timeseries',
      selectedWidget: null,
      widgetDetail: null,
      widgetClassifcation: {},
      widgetList: [],
      commandWidgets: [],
      gateways: [],
      gatewayId: null,
      selectedSettingsType: 'visualSettings',
      selectedDataSeries: [],
      visualSettings: [],
      dataSettings: [],
      dataProp: {},
      visualProp: {},
      seriesDataMapping: {},
      treeOptions: {
        selectable: true,
        singleSelect: false
      },
      selectedNodes: [],
      widgetsLoaded: false,
      isDataSettingsRequired: true,
      seriesData: []
    }
  },
  methods: {
    isNewWidget () {
      let widgetName = this.selectedWidget.category[1]
      return this.$_.includes(['multi_line', 'average_card', 'average_comparison_card', 'status_indicator_card', 'multi_data', 'static_location'], widgetName)
    },
    getUniqueKey () {
      let result = ''
      let characters = 'abcdefghijklmnopqrstuvwxyz0123456789'
      let charactersLength = characters.length
      for (var i = 0; i < 20; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength))
      }
      return result
    },
    selectClassfication (classification) {
      this.selectedClassification = classification
    },
    setSettingsType (type) {
      this.selectedSettingsType = type
    },
    setSelectedWidget (widget) {
      this.selectedWidget = null
      this.loadSelectedWidget(widget.id)
      let widgetCategory = widget.category[1]

      if (this.$_.includes(['static_card', 'image_card', 'user_card', 'static_location'], widgetCategory)) {
        this.$emit('hide-section', 1)
        this.isDataSettingsRequired = false
      } else {
        this.$emit('show-section', 1)
        this.isDataSettingsRequired = true
      }
    },
    setCommandWidget (widget) {
      this.selectedWidget = widget
    },
    dataSettingsVisible () {
      let widgetCategory = this.selectedWidget ? this.selectedWidget.category[1] : ''

      if (this.$_.includes(widgetCategory, 'card')) {
        return false
      } else {
        return true
      }
    },
    setDataSeries () {
      this.$refs.seriesSettings.setDataSeries()
    },
    loadSelectedWidget (id) {
      this.dashboardService
        .readIdWidget(id)
        .then(response => {
          this.widgetDetail = response

          this.dataSettings = this.widgetDetail.data_settings
          this.dataProp = this.$_.merge({}, this.widgetDetail.data_prop)
          this.visualSettings = this.widgetDetail.visual_settings

          if (!this.editMode) {
            this.visualProp = this.widgetDetail.visual_prop
          }

          if (this.dataProp.axes) {
            this.treeOptions = this.$_.merge({}, this.treeOptions, {
              singleSelect: !this.dataProp.axes.multiple
            })
          }
          this.selectedWidget = response
        })
    },
    loadWidgets () {
      this.dashboardService
        .readFilteredWidgets({ page_number: 1, page_size: 100 })
        .then(response => {
          this.$_.forEach(response.data, (classification) => {
            this.widgetClassifcation[classification.classification] = classification.widgets
          })
          this.widgetsLoaded = true
        })
    },
    loadCommandWidgets () {
      this.dashboardService
        .readCommandWidgets({ orgId: this.currentUser.org.id })
        .then(response => {
          this.commandWidgets = response.command_widget_types
        })
    },
    loadGateways () {
      this.dashboardService
        .readGateways({ orgId: this.currentUser.org.id })
        .then(response => {
          this.gateways = response.gateways
        })
    },
    onChangeData () {
      this.selectedNodes = this.$refs.tree.getSelectedNodes()
    },
    saveWidgetInstance () {
      if (this.selectedClassification === 'command') {
        this.createCommandWidget()
      } else {
        let uniqueKey = this.getUniqueKey()

        let params = {
          label: 'Label' + uniqueKey,
          visual_properties: this.$refs.visualSettings.getVisualProps(),
          widget_settings: {},
          series_data: this.$refs.seriesSettings.getDataSeries()
        }

        let config = { orgId: this.currentUser.org.id, panelId: this.selectedPanel.id, widgetId: this.selectedWidget.id }
        this.dashboardService.createWidgetInstance(config, params)
          .then((_) => {
            this.$toastr.success('Widget added successfully', 'Success', { closeButton: true, closeDuration: 0 })
          })
          .catch((error) => {
            this.$toastr.error(error.title, 'Error', { closeButton: true, closeDuration: 0 })
          })
      }
    },
    updateWidgetInstance () {
      let params = {
        label: this.widgetData.label,
        visual_properties: this.$refs.visualSettings.getVisualProps(),
        series_data: this.$refs.seriesSettings.getDataSeries()
      }
      let config = { orgId: this.currentUser.org.id, panelId: this.selectedPanel.id, widgetId: this.selectedWidget.id, id: this.widgetData.id }
      this.dashboardService.updateWidgetInstance(config, params)
        .then((_) => {
          this.$toastr.success('Widget updated successfully', 'Success', { closeButton: true, closeDuration: 0 })
          this.$emit('on-update-widget-instance')
        })
        .catch((error) => {
          this.$toastr.error(error.title, 'Error', { closeButton: true, closeDuration: 0 })
        })
    },
    createCommandWidget () {
      let widgetParameters = this.selectedWidget.widget_parameters
      let config = { orgId: this.currentUser.org.id, panelId: this.selectedPanel.id }

      let params = {
        dashboard_id: this.selectedDashboard.id,
        gateway_id: this.gatewayId,
        label: 'LED Control Panel',
        data_settings: widgetParameters.data_settings,
        visual_settings: widgetParameters.visual_settings,
        module: this.selectedWidget.module
      }
      this.dashboardService.createCommandWidget(config, params)
        .then((response) => {
        })
    },
    isWidgetSelected () {
      return !!this.selectedWidget
    },
    isDataNodeSelected () {
      let selectedNodes = this.$refs.tree.getSelectedNodes()
      return !!selectedNodes.length
    },
    isValidate (isValidate) {
      this.$emit('isValidate', isValidate)
    }
  },
  mounted () {
    this.loadWidgets()
    this.loadCommandWidgets()
    this.loadGateways()

    if (this.widgetData) {
      let widgetCategory = this.widgetData.widget_category[1]
      this.loadSelectedWidget(this.widgetData.widget_id)

      if (this.$_.includes(['image_card', 'static_card', 'user_card', 'static_location'], widgetCategory)) {
        this.isDataSettingsRequired = false
      } else {
        let yAxisIndex = 0

        if (this.widgetData.series_data.length) {
          this.$_.forEach(this.widgetData.series_data[0].axes, (axis, index) => {
            if (axis.name === 'y' || axis.name === 'columns') {
              yAxisIndex = index
            }
          })

          this.$_.forEach(this.widgetData.series_data, (series) => {
            let sourceDetails = series.axes[yAxisIndex].source_details
            this.selectedNodes = this.$_.concat(this.selectedNodes, {
              id: sourceDetails.parameter,
              type: 'SensorParameter',
              sensor_id: sourceDetails.entity_id,
              path: sourceDetails.path,
              parentId: sourceDetails.entity_id,
              uuid: sourceDetails.parameter
            })
          })
        }

        this.isDataSettingsRequired = true
      }

      this.visualProp = this.widgetData.visual_properties
      this.seriesDataMapping = this.$_.reduce(this.widgetData.series_data, (mapping, data) => {
        let yAxis = this.$_.find(data.axes, (axis) => {
          return (axis.name === 'y') || (axis.name === 'columns')
        })
        let key = yAxis.source_details.entity_id + '.' + yAxis.source_details.parameter
        mapping[key] = {
          color: data.color,
          name: data.name,
          unit: data.unit
        }
        return mapping
      }, {})
    }
  }
}
</script>

<style lang="scss" scoped>
  .add-update-widgets{
    height: 440px;
  }
  .widget-category {
    display: flex;
    align-items: center;
    justify-content: center;
    .category {
      width: 80px;
      height: 35px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 16px;
      color: #797979;
      cursor: pointer;
      &.active {
        color: white;
        background: #4cbce2;
        border-radius: 5px;
        padding: 5px 0 5px 0;
      }
    }
    &.settings-category {
      width: 100%;
      justify-content: center;
      margin-bottom: 10px;
      padding: 11px;
      background: black;
      border-radius: 5px 5px 0 0;
      .category {
        width: 140px;
      }
      span{
        color: lightgray;
        font-weight: bold;
      }
    }
  }
  .select-widget {
    height: 440px;
  }
  .widgets-section {
    height: 100%;
    .widgets {
      max-width: 1200px;
      margin: 0 auto;
      height: 100%;
      .widget-container {
        background: #f9f9f9;
        box-shadow: 0 3px 4px #ddd;
        .widget-image {
          height: 155px;
          max-height: 155px;
          background-color: #fff;
          img {
            width: 100%;
            height: 100%;
            cursor: pointer;
            object-fit: cover;
            object-position: top;
          }
        }
        .widget-info {
          border-top: 1px solid #EDEDED;
          padding: 10px;
          text-align: center;
          h3 {
            text-transform: capitalize;
            margin: 0;
            font-size: 14px;
          }
        }
        &.active {
          border: 3px solid #2469a0;
          border-radius: 5px;
        }
        &.edit {
          border: 1px solid #e2e2e2;
          .widget-image {
            height: 120px;
            max-height: 120px;
          }
          .widget-info {
            h3 {
              font-size: 12px;
            }
          }
        }
      }
      .widgets-container {
        padding: 0 10px 10px 10px;
      }
      .widgets-classification {
        padding: 11px;
        background: black;
        border-radius: 5px 5px 0 0;
        list-style: none;
        padding-left: 0;
        display: flex;
        justify-content: center;
        li {
          font-size: 16px;
          padding: 0 15px;
          cursor: pointer;
          min-width: 120px;
          text-align: center;
          color: lightgray;
          font-weight: bold;
          padding: 5px 0 5px 0;
          &.active {
            color: white;
            background: #4cbce2;
            border-radius: 5px;
            padding: 5px 0 5px 0;
          }
        }
      }
      .row {
        justify-content: left;
        margin-left: 0px;
        overflow: auto;
        height: 355px;
        &::-webkit-scrollbar{
          width: 6px;
        }
        &::-webkit-scrollbar-track {
          background: #f1f1f1;
        }
        &::-webkit-scrollbar-thumb {
          background: #2469a0;
          height: 45px;
          border-radius: 10px;
        }
        &::-webkit-scrollbar-thumb:hover {
          background: #555;
        }
      }
      .widget {
        margin: 20px 0;
      }
    }
  }
  .select-data {
    height: 100%;
    padding: 16px 0px 0px 30px;
    margin-right: 31px;
    ul {
      list-style: none;
      padding-left: 0;
      display: flex;
    }
    .data-type-section {
      height: calc(100% - 20px);
      .vue-tree-container {
        border: 1px solid #e2e2e2;
        height: 100%;
        border-radius: 4px;
        padding-bottom: 20px;
        overflow: auto;
      }
    }
  }
  .settings {
    overflow: scroll;
    margin-bottom: 60px;
    .settings-common {
      padding: 0 8px;
    }
    .settings-classification{
      padding: 0 0px 10px 0px;
      height: 512px;
    }
  }
</style>

<style lang="scss">
  .widget-background {
    display: flex;
    align-items: center;
    padding-left: 20px;
    padding-top: 10px;
    .or {
      padding: 0 10px;
    }
    .multiselect {
      width: 100% !important;
    }
    .option {
      display: flex;
      align-items: center;
    }
    .option_gradient {
      width: calc(100% - 120px);
      height: 45px;
      border-radius: 4px;
    }
    .option_title {
      width: 120px;
      // padding-left: 20px;
    }
  }
  .settings {
    .settings-toggle-btn {
      display: flex;
      margin-top: 20px;
      background-color: #4c92c3 !important;
      color: white !important;
      font-size: 15px;
      border-radius: 4px;
      align-items: center;
      .icon {
        width: 18px;
        height: 18px;
        fill: white;
        transform: rotate(-180deg);
      }
      span {
        padding-left: 10px;
      }
      &.collapsed {
        .icon {
          transform: rotate(0deg);
        }
      }
    }
  }
  .gateways-wrap {
    > span {
      font-size: 15px;
      margin-bottom: 10px;
      display: inline-block;
    }
    .custom-control-inline {
      display: flex;
    }
  }
  .add-update-widgets{
    .multiselect__single{
      font-size: 15px;
      background: #F5FBFF;
    }
    .multiselect__tags{
      background: #F5FBFF;
    }
    .multiselect__input{
      background: #F5FBFF;
      font-size: 15px;
    }
  }
</style>
