<template>
  <div class="row q-gutter-sm q-pa-sm">
    <template v-for="condition in computedConditions">
      <q-input filled dense v-bind="condition.componentProps" readonly :value="computedValue[condition.name]" v-if="condition.componentName === 'date'"
        @input="onDateChange($event, condition)">
        <template v-slot:append>
          <q-icon
            v-show="computedValue[condition.name]"
            name="close"
            @click.native="onDateChange(undefined, condition)"
            class="cursor-pointer"
          />
          <q-icon name="event" class="cursor-pointer">
            <q-popup-proxy :ref="`${condition.name}DateProxy`" transition-show="scale" transition-hide="scale">
              <q-date :value="condition.value" mask="YYYY-MM-DD" @input="(value) => {onDateChange(value, condition); $refs[`${condition.name}DateProxy`][0].hide()}" />
            </q-popup-proxy>
          </q-icon>
        </template>
      </q-input>
      <template v-else-if="condition.componentName === 'date-range'">
        <q-input filled dense v-bind="condition.startProps" readonly :value="computedValue[condition.name+'Start']"
          @click.stop="$refs[`${condition.name}StartDateProxy`][0].show()"
          @input="onDateChange($event, condition, 'Start')">
          <template v-slot:append>
            <q-icon
              v-show="computedValue[condition.name+'Start']"
              name="close"
              @click.native="onDateChange(undefined, condition, 'Start')"
              class="cursor-pointer"
            />
            <q-icon name="event" class="cursor-pointer">
              <q-popup-proxy :ref="`${condition.name}StartDateProxy`" transition-show="scale" transition-hide="scale">
                <q-date :value="condition.startTime" mask="YYYY-MM-DD" @input="(value) => {onDateChange(value, condition, 'Start'); $refs[`${condition.name}StartDateProxy`][0].hide()}" />
              </q-popup-proxy>
            </q-icon>
          </template>
        </q-input>
        <span class="flex self-center">至</span>
        <q-input filled dense v-bind="condition.endProps" readonly :value="computedValue[condition.name+'End']"
          @click.stop="$refs[`${condition.name}EndDateProxy`][0].show()"
          @input="onDateChange($event, condition, 'End')">
          <template v-slot:append>
            <q-icon
              v-show="computedValue[condition.name + 'End']"
              name="close"
              @click.native="onDateChange(undefined, condition, 'End')"
              class="cursor-pointer"
            />
            <q-icon name="event" class="cursor-pointer">
              <q-popup-proxy :ref="`${condition.name}EndDateProxy`" transition-show="scale" transition-hide="scale">
                <q-date :value="condition.endTime" mask="YYYY-MM-DD" @input="(value) => {onDateChange(value, condition, 'End'); $refs[`${condition.name}EndDateProxy`][0].hide()}" />
              </q-popup-proxy>
            </q-icon>
          </template>
        </q-input>
      </template>
      <q-btn v-else-if="condition.componentName === 'q-btn'" v-bind="condition.componentProps" @click="condition.onClick && condition.onClick()"></q-btn>
      <template v-else-if="condition.componentName === 'kyb-select-entity'">
        <kyb-select-entity
          :value="computedValue[condition.name]"
          v-bind="condition.componentProps"
          @input="onOptionsChange($event, condition)"
          :hide-toolbar="!!computedValue[condition.name].length"
        >
        </kyb-select-entity>
      </template>
      <component
        v-model="valueInner[condition.name]"
        :is="condition.componentName"
        v-bind="condition.componentProps"
        @input="$emit('input', valueInner)"
        v-else
      >
      </component>
    </template>
  </div>
</template>

<script>
import { extend, date } from 'quasar'
export default {
  name: 'kyb-table-condition',
  model: {
    prop: 'value',
    event: 'input'
  },
  props: {
    value: Object,
    mdata: Object,
    conditions: Array
  },
  data: function() {
    return {
      valueInner: extend({}, this.value),
      defaultProps: {
        'q-select': {
          componentProps: {
            optionValue: 'value',
            optionLabel: 'label',
            mapOptions: true,
            outlined: true,
            dense: true,
            emitValue: true,
            bgColor: 'white'
          }
        },
        'q-input': {
          componentProps: {
            outlined: true,
            dense: true,
            inputStyle: 'border-width: 0;',
            bgColor: 'white'
          }
        },
        date: {
          componentProps: {
            inputStyle: 'border-width: 0;'
          }
        },
        'date-range': {
          startProps: {
            outlined: true,
            bgColor: 'white',
            inputStyle: 'border-width: 0;'
          },
          endProps: {
            outlined: true,
            bgColor: 'white',
            inputStyle: 'border-width: 0;'
          }
        },
        'kyb-select-entity': {
          componentProps: {
            inputProps: {
              outlined: true,
              bgColor: 'white',
              inputStyle: 'border-width: 0;'
            }
          }
        },
        'q-btn': {
        }
      }
    }
  },
  watch: {
    value(newVal) {
      this.valueInner = extend({}, newVal)
    }
  },
  computed: {
    computedValue() {
      const valueObj = {}
      this.conditions && this.conditions.forEach(condition => {
        const { componentName } = condition
        if (componentName === 'date-range') {
          const _value = (this.valueInner && this.valueInner[condition.name]) || '___between-'
          const vStr = _value.substring('___between'.length)
          const [ start, end ] = vStr.split('-')
          valueObj[condition.name + 'Start'] = start !== '' ? date.formatDate(start * 1, 'YYYY-MM-DD') : ''
          valueObj[condition.name + 'End'] = end !== '' ? date.formatDate(end * 1, 'YYYY-MM-DD') : ''
        } else if (componentName === 'date') {
          this.valueInner[condition.name] !== undefined && (valueObj[condition.name] = date.formatDate(this.valueInner[condition.name], 'YYYY-MM-DD'))
        } else if (componentName === 'kyb-select-entity') {
          valueObj[condition.name] = this.valueInner[condition.name] !== undefined ? [this.valueInner[condition.name]] : []
        }
      })
      return valueObj
    },
    computedConditions() {
      const todayStr = date.formatDate(parseInt(Date.now() / 86400000) * 86400000, 'YYYY-MM-DD')
      const conditions = this.conditions ? this.conditions.map(condition => {
        const { componentName } = condition
        const defaultCondition = {
          ...this.defaultProps[componentName]
        }
        if (componentName === 'date-range') {
          defaultCondition.startTime = this.computedValue[condition.name + 'Start'] || todayStr
          defaultCondition.endTime = this.computedValue[condition.name + 'End'] || todayStr
        } else if (componentName === 'date') {
          defaultCondition.value = this.computedValue[condition.name] || todayStr
        }
        return extend(true, {}, defaultCondition, condition)
      }) : []
      return conditions
    }
  },
  methods: {
    onDateChange(value, condition, dir) {
      const valueLong = value !== undefined ? new Date(value).getTime() : undefined
      if (condition.componentName === 'date-range') {
        const _value = this.valueInner[condition.name] || '___between-'
        const vStr = _value.substring('___between'.length)
        let [ start, end ] = vStr.split('-')
        if (dir === 'Start') {
          start = valueLong || ''
        } else {
          end = valueLong !== undefined ? valueLong + 86400000 - 1 : ''
        }
        this.valueInner[condition.name] = `___between${start}-${end}`
      } else {
        this.valueInner[condition.name] = valueLong
      }
      this.$emit('input', this.valueInner)
    },
    onOptionsChange(value, condition) {
      this.valueInner[condition.name] = value.length > 0 ? value[0] : undefined
      this.$emit('input', this.valueInner)
    }
  },
  mounted() { }
}
</script>
