<template>
  <div class="new-settings-wrap">
    <div class="setting-wrap title-wrap">
      <div class="header" @click="openSetting('widget_title')">
        <div class="text-section">
          <span>Widget Title</span>
        </div>
        <div class="icon-section">
          <svg class="icon">
            <use xlink:href="/assets/img/mads-common-icons.svg#arrow-down"></use>
          </svg>
        </div>
      </div>
      <div class="content" v-if="openedSetting === 'widget_title'">
        <b-form-input v-model="settings.title.text" type="text" placeholder="Title"></b-form-input>
        <svg class="icon text-format" id="formatter-popover">
          <use xlink:href="/assets/img/mads-common-icons.svg#text-format"></use>
        </svg>
        <b-popover
          target="formatter-popover"
          placement="bottom"
          triggers="hover focus"
        >
          <text-formatter
          :defaultSettings="settings.title.text_settings"
          @formatter-updated="titleTextFormatter"
          ></text-formatter>
        </b-popover>
      </div>
    </div>
    <div class="setting-wrap background-position-wrap">
      <div class="header" @click="openSetting('background_and_position')">
        <div class="text-section">
          <span>Background & position</span>
        </div>
        <div class="icon-section">
          <svg class="icon">
            <use xlink:href="/assets/img/mads-common-icons.svg#arrow-down"></use>
          </svg>
        </div>
      </div>
      <div class="content" v-if="openedSetting === 'background_and_position'">
        <div class="background-color-wrap">
          <span>Widget Background Color/Gradient</span>
          <b-form-input v-model="settings.background_and_position.background" type="color" class="color"></b-form-input>
        </div>
      </div>
    </div>
    <!-- <div class="data-point-wrap">
      <div>Data Point</div>
      <div>
        <span>Data Point 1</span>
      </div>
    </div> -->
    <div class="setting-wrap horizontal-lines-wrap">
      <div class="header" @click="openSetting('threshold_lines')">
        <div class="text-section">
          <span>Horizontal Lines(Threshold Lines)</span>
        </div>
        <div class="icon-section">
          <svg class="icon">
            <use xlink:href="/assets/img/mads-common-icons.svg#arrow-down"></use>
          </svg>
        </div>
      </div>
      <div class="content" v-if="openedSetting === 'threshold_lines'">
        <div v-for="(line, index) in settings.threshold_lines" :key="index" class="threshold">
          <b-form-input v-model="line.value" @input="onChangeThresholdValue" type="number" class="value"></b-form-input>
          <multiselect v-model="line.dashStyle" :options="['Dash', 'Solid']" placeholder="" :select-label="''" :selected-label="''" :deselect-label="''" :allow-empty="false" class="line-type"></multiselect>
          <b-form-input v-model="line.color" type="color" class="color"></b-form-input>
          <svg class="icon" @click="deleteTethreSholdLine(index)">
            <use xlink:href="/assets/img/mads-common-icons.svg#dustbin"></use>
          </svg>
        </div>
        <div>
          <b-button @click="addNewThreshold()">Add New</b-button>
        </div>
      </div>
    </div>
    <div class="setting-wrap band-setting">
      <div class="header" @click="openSetting('bands')">
        <div class="text-section">
          <span>Band Setting(Y-axis)</span>
        </div>
        <div class="icon-section">
          <svg class="icon">
            <use xlink:href="/assets/img/mads-common-icons.svg#arrow-down"></use>
          </svg>
        </div>
      </div>
      <div class="content" v-if="openedSetting === 'bands'">
        <div v-for="(band, index) in settings.bands" :key="index" class="band">
          <div class="band-color">
            <span>{{band.text}}</span>
            <b-form-input v-model="band.color" type="color" class="color"></b-form-input>
          </div>
          <div class="status-indicator">
            <div class="d-flex justify-content-between">Status Indication
              <svg class="icon" :id="`popover-${index}`">
                <use xlink:href="/assets/img/mads-common-icons.svg#text-format"></use>
              </svg>
            </div>
            <b-form-input v-model="band.statusText" type="text" placeholder="enter status"></b-form-input>
            <!-- <div>
              <span>Select Status box</span>
              <multiselect :options="['Good', 'Cold', 'Hot', 'Low', 'High']" placeholder="" :select-label="''" :selected-label="''" :deselect-label="''" :allow-empty="false"></multiselect>
            </div> -->
            <b-popover
              :target="`popover-${index}`"
              placement="bottom"
              title="Text Format"
              triggers="hover focus"
            >
              <text-formatter
                :index="index"
                :defaultSettings="band.text_settings"
                @formatter-updated="bandsTextFormatter"
              ></text-formatter>
            </b-popover>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import TextFormatter from './common/textFormatter.vue'
export default {
  components: { TextFormatter },
  data () {
    return {
      openedSetting: 'widget_title',
      settings: {
        title: {
          text: '',
          text_settings: {
            'align': 'left',
            'decorations': {
              'isBold': false,
              'isItalic': false,
              'isUnderline': false
            },
            'fontColor': '#495057',
            'fontSize': '14px'
          }
        },
        background_and_position: {
          background: '#ffffff'
        },
        data_point: [],
        threshold_lines: [],
        bands: []
      }
    }
  },
  props: {
    visualProp: {
      type: Object,
      required: true
    },
    selectedNodes: {
      type: Array,
      required: true
    },
    instanceSeriesData: {
      type: Array,
      required: true
    },
    seriesDataMapping: {
      type: Object,
      required: true
    }
  },
  methods: {
    createSeriesData () {
      let seriesData = []
      let colors = ['#2980b9', '#2ecc71', '#f1c40f', '#2c3e50', '#7f8c8d']

      this.$_.forEach(this.selectedNodes, (node, index) => {
        let mappingKey = node.parentId + '.' + node.uuid
        let serieNameMapping = this.seriesDataMapping[mappingKey]

        let axes = [
          {
            'name': 'y',
            'source_type': 'pds',
            'source_metadata': {
              'entity_type': 'sensor',
              'entity_id': node.parentId,
              'parameter': node.uuid,
              'path': node.path
            }
          }
        ]
        seriesData.push({
          axes: axes,
          color: serieNameMapping ? serieNameMapping['color'] : colors[index % 5],
          name: serieNameMapping ? serieNameMapping['name'] : node.name,
          unit: serieNameMapping ? serieNameMapping['unit'] : ''
        })
      })

      this.seriesData = this.$_.concat([], seriesData)
    },
    onChangeThresholdValue () {
      this.createBands(this.settings.threshold_lines)
    },
    addNewThreshold () {
      let thresholdLines = this.$_.concat([], this.settings.threshold_lines, {
        value: null,
        dashStyle: 'solid',
        color: '#3F2FFE'
      })

      this.settings = this.$_.merge({}, this.settings, {
        threshold_lines: thresholdLines
      })
    },
    getSettings () {
      return this.settings
    },
    openSetting (setting) {
      this.openedSetting = setting
    },
    createBands (thresholdLines) {
      let bands = []
      let totalThresholdLines = thresholdLines.length
      let textSettings = {
        align: 'left',
        decorations: {
          isBold: false,
          isItalic: false,
          isUnderline: false
        },
        fontColor: '#495057',
        fontSize: '15px'
      }
      this.$_.forEach(thresholdLines, (threshold, index) => {
        if (index === 0) {
          bands.push({
            value: parseInt(threshold.value),
            text: `Below ${threshold.value}`,
            color: '#2897D6',
            statusText: '',
            text_settings: textSettings
          })
        } else if (index === (totalThresholdLines - 1)) {
          bands.push({
            value: parseInt(threshold.value),
            text: `${thresholdLines[index - 1].value} to ${threshold.value}`,
            color: '#2897D6',
            statusText: '',
            text_settings: textSettings
          })
          bands.push({
            value: Number.MAX_VALUE,
            text: `Above ${threshold.value}`,
            color: '#2897D6',
            statusText: '',
            text_settings: textSettings
          })
        } else {
          bands.push({
            value: parseInt(threshold.value),
            text: `${thresholdLines[index - 1].value} to ${threshold.value}`,
            color: '#2897D6',
            statusText: '',
            text_settings: textSettings
          })
        }
      })

      this.settings = this.$_.merge({}, this.settings, {
        bands: bands
      })
    },
    getSeriesData () {
      return this.seriesData
    },
    isValidate () {
      this.$emit('isValidate', true)
    },
    titleTextFormatter (data) {
      Object.assign(this.settings.title.text_settings, data)
    },
    bandsTextFormatter (data, index) {
      Object.assign(this.settings.bands[index].text_settings, data)
    },
    deleteTethreSholdLine (index) {
      this.settings.threshold_lines.splice(index, 1)
    }
  },
  watch: {
    selectedNodes () {
      this.createSeriesData()
    },
    visualProp () {
      if (!this.$_.isEmpty(this.visualProp)) {
        this.settings = this.$_.merge({}, this.visualProp)
      }
    },
    settings: {
      handler () {
        this.isValidate()
      },
      deep: true
    }
  },
  mounted () {
    this.seriesData = this.$_.map(this.instanceSeriesData || [], (series) => {
      let axes = this.$_.map(series.axes || [], (axis) => {
        return {
          name: axis.name,
          source_metadata: axis.source_details,
          source_type: axis.source_type
        }
      })

      return {
        axes: axes,
        color: series.color,
        name: series.name,
        unit: series.unit
      }
    })
  }
}
</script>

<style lang="scss" scoped>
  .new-settings-wrap {
    margin-right: 10px;
  }
  .setting-wrap {
    margin-top: 10px;
    margin-bottom: 15px;
    .threshold {
      display: flex;
      margin-bottom: 10px;
      align-items: center;
      justify-content: space-between;
      .value, .line-type {
        width: 42% !important;
        height: 40px !important;
      }
    }
    .band {
      padding-bottom: 10px;
      border-bottom: 1px solid rgba(212, 217, 219, 0.5);
      .band-color {
        display: flex;
        align-items: center;
        color: #212429;
        .color {
          margin: 0 0 0 auto;
        }
      }
      .status-indicator {
        background: #F8F9FA;
        padding: 5px;
        border-radius: 4px;
      }
    }
  }
  .header {
    border-bottom: 1px solid rgba(212, 217, 219, 0.5);
    padding-bottom: 4px;
    display: flex;
    align-items: center;
    .text-section {
      width: calc(100% - 20px);
      span {
        font-weight: bold;
        font-size: 15px;
        color: #000000;
        cursor: pointer;
      }
    }
    .icon-section {
      width: 20px;
      cursor: pointer;
      .icon {
        width: 12px;
        height: 11px;
        fill: #727272;
      }
    }
  }
  .content {
    position: relative;
    color: #495057;
    padding-top: 10px;
    padding-right: 20px;
    .icon {
      width: 20px;
      height: 20px;
    }
    .text-format {
      position: absolute;
      top: -24px;
      right: 30px;
      cursor: icon;
    }
    .background-color-wrap {
      display: flex;
    }
  }
  input[type="color"] {
    border: none;
    &[type=text] {
      width: 90px;
      height: 38px;
    }
    &[type=color] {
      width: 35px;
      height: 35px;
      cursor: pointer;
    }
  }
</style>
