<template>
  <div>
    <q-modal ref="modal" class="maximized">
      <s-carousel ref="slider" class="text-black full-height" style="padding:0px">
        <div slot="slide" style="overflow-y:auto;text-align:left" class="bg-primary">
            <h4><span class="text-bold">{{ $t("layout.layout_Personal_basic_information") }}</span></h4>
            <div id="view-flexbox" style="text-align:left" :class="{'with-border': border}">
                <!--<div v-for="(column,index) in columns" v-if="row[0] !== undefined">-->
                <div v-for="(column,index) in columns">
                    <div v-if="column.insert === true" class="list no-border">
                        <div class="row gutter wrap items-center"> 
                            <div class="sm-width-1of3 bg-width-1of5 width-1of5">
                                {{ column.label }}：
                            </div>
                            <div class="sm-width-2of3 bg-width-4of5 width-4of5">
                              <div class="item-content" >
                                <div v-if="column.type.toLowerCase() === 'text' || column.type.toLowerCase() === 'label'" class="form-group" v-bind:class="{ 'form-group--error': Object($v.row[column.field]).$error }">
                                    <input type="text" class="form__input full-width" v-model.trim="row[column.field]" @input="$v.row[column.field].$touch()" @focus="$event.target.select()">
                                    <!--<pre>row: {{ $v }}</pre>-->
                                </div>
                                <div v-if="column.type.toLowerCase() === 'password'" class="form-group">
                                    <input type="password" class="form__input full-width" v-model.trim="row[column.field]" @focus="$event.target.select()">
                                </div>
                                <div v-if="column.type.toLowerCase() === 'radio'">
                                    <q-radio v-model.trim="row[column.field]" :val="index"></q-radio>
                                </div>
                                <div v-if="column.type.toLowerCase() === 'checkbox'">
                                    <q-checkbox v-model.trim="row[column.field]" v-bind:value="checkValue(row[column.field],2,column,row)"
                                     @input="checkValue(row[column.field],1,column,row)" ></q-checkbox>
                                </div>
                                <div v-if="column.type.toLowerCase() === 'toggle'">
                                    <q-toggle class="orange" v-model.trim="row[column.field]" v-bind:value="checkValue(column[column.field],2,column,row)"
                                     @input="checkValue(column[column.field],1,column,row)" ></q-toggle>
                                </div>
                                <div v-if="column.type.toLowerCase() === 'date' || column.type.toLowerCase() === 'datetime' || column.type.toLowerCase() === 'datetime'">
                                    <q-datetime v-model.trim="row[column.field]" type="date" @focus="$event.target.select()" class="full-width" :min="range.min" :max="range.max" 
                                    :default-selection="defaultSelection">
                                    </q-datetime>
                                </div>

                                <div v-if="column.type.toLowerCase() === 'select' && (column.modify === true || (row._add === true && column.insert === true))">
                                  <s-autocomplete v-model="row[column.field]" @search="search2" :id="column.field" 
                                    :min-characters="column.minCharacters === undefined ? 0 : column.minCharacters"
                                    :max-characters="column.maxCharacters === undefined ? 6 : column.maxCharacters"
                                    :allowOther="column.allowOther"
                                    @selected="selected" :delay="0">
                                    <s-input-frame class="s-input" :stack-label="column.floatlabel" :float-label="column.floatlabel" >
                                      <q-search v-model="row[column.field]" @input="$v.row[col.field].$touch()"></q-search>
                                    </s-input-frame>
                                  </s-autocomplete>
                                </div>
                                <div v-if="column.type.toLowerCase() === 'radioselect' && (column.modify === true || (row._add === true && column.insert === true))">
                                  <q-select type="radio" v-model="row[column.field]" :options="optionObject(column.options)"></q-select>
                                </div>
                                <div v-if="column.type.toLowerCase() === 'checkboxselect' && (column.modify === true || (row._add === true && column.insert === true))">
                                  <q-select type="checkbox" v-model="row[column.field]" :options="optionObject(column.options)"></q-select>
                                </div>

                                <span class="form-group__message" style="color:red;font-weight:bold" v-if="Object($v.row[column.field]).required !==undefined && !Object($v.row[column.field]).required">{{column.label}}為必填欄位</span>
                                <span class="form-group__message warning" style="color:red;font-weight:bold" v-if="Object($v.row[column.field]).minLength !==undefined && !Object($v.row[column.field]).minLength">{{column.label}}長度至少需 {{Object($v.row[column.field]).$params.minLength.min}} 字.</span>
                                <span class="form-group__message warning" style="color:red;font-weight:bold" v-if="Object($v.row[column.field]).between !==undefined && !Object($v.row[column.field]).between">{{column.label}}需介於</span>
                                <span class="form-group__message warning" style="color:red;font-weight:bold" v-if="Object($v.row[column.field]).alpha !==undefined && !Object($v.row[column.field]).alpha">{{column.label}}須為英文字母</span>
                                <span class="form-group__message warning" style="color:red;font-weight:bold" v-if="Object($v.row[column.field]).alphaNum !==undefined && !Object($v.row[column.field]).alphaNum">{{column.label}}須為英文字母或數字</span>
                                <span class="form-group__message warning" style="color:red;font-weight:bold" v-if="Object($v.row[column.field]).numeric !==undefined && !Object($v.row[column.field]).numeric">{{column.label}}須為數字</span>
                                <span class="form-group__message warning" style="color:red;font-weight:bold" v-if="Object($v.row[column.field]).email !==undefined && !Object($v.row[column.field]).email">{{column.label}}須為email格式</span>
                                <span class="form-group__message warning" style="color:red;font-weight:bold" v-if="Object($v.row[column.field]).url !==undefined && !Object($v.row[column.field]).url">{{column.label}}須為url格式</span>
                                <span class="form-group__message warning" style="color:red;font-weight:bold" v-if="Object($v.row[column.field]).sameAs !==undefined && !Object($v.row[column.field]).sameAs">{{column.label}}需與{{Object($v.row[column.field]).$params.sameAs.eq}}相同</span>
                              </div>
                                
                            </div>
                        </div>

                    </div>
                </div>
              <button tabindex="0" class="green" @click="saveData()">
                <i>save</i>
                {{ $t("global.button.Save_file") }}
              </button>
              <button tabindex="0" class="green" @click="cancel()">
                <i>cancel</i>
                {{ $t("global.button.Exit") }}
              </button>
            </div>
        </div>
      </s-carousel>
    </q-modal>

    <s-vueDialog ref="layoutModal" v-if="showModal" :blocking="blocking" :header="header" :footer="footer" :body="body" :type="type" :icon="icon" :custom="custom"
     :async="async" @action="action" @close="showModal = false;">
    </s-vueDialog>    
  </div>

</template>
<script>
import vueResource from 'vue-resource'
import Vue from 'vue'
import Vuelidate from 'vuelidate'
import moment from 'moment'
// import '../../../plugins/bootstrape/css/bootstrap.css'
import { required, minLength, maxLength, between, alpha, alphaNum, numeric, email, sameAs, url } from 'vuelidate/lib/validators'
Vue.use(Vuelidate)
Vue.use(vueResource)

export default {
  props: {
    columns: {
      type: Array,
      default: []
    },
    row: {
      type: Object,
      default: {}
    }
  },
  data () {
    return {
      showModal: false,
      icon: '',
      header: '',
      footer: '',
      body: '',
      type: '',
      operation: '',
      custom: [],
      border: false,
      defaultSelection: moment('1950-01-01T10:40:14.674Z').format(),
      range: {
        min: moment('1950-01-01T10:40:14.674Z').subtract(3, 'days').format(),
        max: moment().add(4, 'hours').add(10, 'minutes').add(1, 'month').format()// .add(1, 'month').add(1, 'year')
      }
    }
  },
  created () {
    this.columns.forEach((column, i) => {
      if (column.type === 'toggle') {
        if (this.row[column.field] === undefined || this.row[column.field] === '') {
          this.row[column.field] = false
        }
      }
    })
  },
  methods: {
    optionObject (functionName) {
      var option = ''
      if (typeof done !== 'function') {
        return functionName
      }
      else {
        option = this.$emit(functionName, () => {
        })
        // console.log(option)
        return option
      }
    },
    format (row, col) {
      return col.format ? col.format(row[col.field], row) : row[col.field]
    },
    startslide (operation) {
      this.operation = operation
      if (this.$refs.slider.slide >= this.$refs.slider.slidesNumber) {
        this.$refs.modal.close()
      }
      else {
        this.$refs.modal.open()
        // this.$refs.slider.next()
      }
    },
    checkValue (val, type, col, row) {
      var val2 = false
      if (type === 2) {
        if (val === true || val === 1) {
          val2 = true
        }
        else {
          val2 = false
        }
      }
      else {
        if (val === true || val === 1) {
          val2 = false
        }
        else {
          val2 = true
        }
      }
      return val2
    },
    saveData () {
      var flag = false
      this.columns.forEach(
        (value, index) => {
          if (this.$v.row[value.field] !== undefined && this.$v.row[value.field].$invalid === true && flag === false) {
            flag = true
          }
        }
      )
      if (flag === true) {
        this.header = this.$t('global.dialog.title_Message')
        this.body = this.$t('global.dialog.message_has_error')
        this.footer = ''
        this.type = 'INFO'
        this.icon = 'WARNING'
        this.async = 'YES'
        this.blocking = true
        this.custom = []
        this.showModal = true
      }
      else {
        this.header = this.$t('global.dialog.title_Message')
        this.body = this.$t('global.dialog.title_quest_isconfirm')
        this.footer = ''
        this.type = 'YES|CANCEL'
        this.icon = 'WARNING'
        this.async = 'YES'
        this.blocking = true
        this.custom = []
        this.showModal = true
      }
    },
    action (actionReturn) {
      if (actionReturn === 'YES') {
        this.$refs.modal.close()
        this.$emit('saveData', this.row, this.operation)
      }
    },
    cancel () {
      this.$refs.modal.close()
    },
    objects (field) {
      return field
    },
    convertToText (obj) {
      var string = []
      if (typeof (obj) === 'object' && (obj.join === undefined)) {
        string.push('{')
        for (var prop in obj) {
          string.push(prop, ': ', this.convertToText(obj[prop]), ',')
        }
        string.push('}')
      }
      else if (typeof (obj) === 'object' && !(obj.join === undefined)) {
        string.push('[')
        for (prop in obj) {
          string.push(this.convertToText(obj[prop]), ',')
        }
        string.push(']')
      }
      else if (typeof (obj) === 'function') {
        string.push(obj.toString())
      }
      else {
        string.push(JSON.stringify(obj))
      }

      return string.join('')
    }
  },
  validations () {
    var object = []
    this.columns.forEach(
      (value, index) => {
        var Bruce = Object.create(null)
        if (value.validations !== undefined) {
          if (value.validations.required === true) {
            Bruce.required = required
          }
          if (value.validations.minLength !== undefined && value.validations.minLength !== '') {
            Bruce.minLength = minLength(value.validations.minLength)
          }
          if (value.validations.maxLength !== undefined && value.validations.maxLength !== '') {
            Bruce.maxLength = maxLength(value.validations.maxLength)
          }
          if (value.validations.between !== undefined && value.validations.between !== '') {
            var res = value.validations.between.split(',')
            if (res.length > 1) {
              Bruce.between = between(res[0], res[1])
            }
          }
          if (value.validations.alpha === true) {
            Bruce.alpha = alpha
          }
          if (value.validations.alphaNum === true) {
            Bruce.alphaNum = alphaNum
          }
          if (value.validations.numeric === true) {
            Bruce.numeric = numeric
          }
          if (value.validations.email === true) {
            Bruce.email = email
          }
          if (value.validations.url === true) {
            Bruce.url = url
          }
          if (value.validations.sameAs !== undefined && value.validations.sameAs !== '') {
            Bruce.sameAs = sameAs(value.validations.sameAs)
          }
        }
        for (var key in this.row) {
          if (key === value.field) {
            object[value.field] = Bruce
          }
        }
      }
    )
    // var json = JSON.parse(JSON.stringify({ row: this.convertToText(object) }))
    const rules = {}
    var json = { row: Object.assign(rules, object) }
    return json
  }
}
</script>
