<!--
      descript: 国籍搜索组件
        author: zhanghelong
        param: props
        example:
-->
<template>
  <div class="web-select-box">
    <div class="root-select-mask" v-if="isReadOnly"></div>
    <div class="weui-value weui-cell_access nation-wrap" ref="nationInput">
      <za-input class="nation-input" @formChange="onInputChange" :inset="true" :formModel="inputModel" :name="name"> </za-input>
      <div v-if="!formModel.rules.hiddenArrow" class="weui-cell__ft"></div>
    </div>
    <div class="search-wrap" v-show="searchBarShow">
      <search ref="searchBar"
      :placeholder="placeholder" 
      @on-cancel="cancelSearch" 
      @on-result-click="selectResult"
      @on-change="getResult"
      :results="searchResults"></search>
    </div>
  </div>
</template>
<script>
import { search } from '../../../vux'
import zaInput from '../../input/input'
import rootSelectMx from '../mixin/select-mixin'
import countries from '../../../../libs/countries'
export default {
  name: 'za-search',
  components: {
    search,
    zaInput
  },
  mixins: [rootSelectMx],
  data() {
    return {
      innerErrors: null,
      innerValue: '',
      inputError: '',
      inputValid: false,
      inputModel: {
        rules: {
          type: 'za-input',
          vRules: 'required',
          // readOnly: true,
          placeholder: '请输入'
        },
        value:''
      },
      isReadOnly: !!this.formModel.rules.readOnly || !!this.formModel.rules.disabled,
      searchBarShow: false,
      initResults: [],
      searchResults: []
    }
  },
  props: ['formModel', 'name', 'index'],
  watch: {
    innerValue(v) {
      // this.inputModel.rules.readOnly = !(v && v.length)
      this.onValidate().then(()=>{
        this.commit()
      })
    },
    'formModel.value': {
      deep: true,
      handler(v) {
        this.innerValue = this.formModel.value
        this.inputModel.value = this.formModel.value || ''
      }
    },
    'formModel.rules': {
      deep: true,
      handler(v) {
        this.isReadOnly = !!this.formModel.rules.readOnly || !!this.formModel.rules.disabled
        this.inputModel.rules = Object.assign(this.inputModel.rules, this.formModel.rules.detail)
        this.setInitResults()
      }
    }
  },
  computed: {
    placeholder() {
      this.inputModel.rules.placeholder = this.formModel.rules.placeholder
      return this.formModel.rules.placeholder || '请选择'
    }
  },
  created() {
    this.innerValue = this.formModel.value
    this.inputModel.value = this.formModel.value || ''
    this.setInitResults()
  },
  mounted() {
    setTimeout(() => {
      this.$refs['nationInput'].addEventListener('click', () => {
        this.onInputFocus()
      })
    }, 0)
  },
  methods: {
    setInitResults() {
      if(!this.formModel.rules.results || !Array.isArray(this.formModel.rules.results)) {
        const self = this
        switch (this.formModel.rules.dataType) {
          case 'country': 
          this.searchResults = this.initResults = countries
          break
          default: 
          console.error(`请设置${self.name}搜索数据`)
          break
        }
      } else {
        this.searchResults = this.initResults = this.formModel.rules.results
      }
    },
    selectResult(item) {
      this.inputModel.value = item.title
      this.searchBarShow = false
    },
    getResult(val) {
      this.onEvent('onSearchChange', {
        name: this.name,
        event: null,
        type: 'change',
        triggerType: 'onchange',
        value: val
      })
      this.searchResults = this.initResults.filter((value) => {
        return value.title.indexOf(val) > -1
      })
    },
    cancelSearch() {
      this.searchBarShow = false
    },
    onInputFocus() {
      this.searchBarShow = true
      setTimeout(() => {
        this.$refs['searchBar'].setFocus()
      }, 0)
    },
    onValidate() {
      return new Promise((resolve, reject) => {
        let mod = this.innerModel()
        this.isValid = mod.isValid
        if (this.isValid) {
          resolve(true)
        } else {
          reject(false)
        }
      }).catch(e => { return false })
    },
    onInputChange(v) {
      this.inputValid = v.isValid
      this.inputError = v.msg
      this.$nextTick(() => {
        this.onEvent('onchange', {
          name: this.name,
          event: null,
          type: 'change',
          triggerType: 'onchange',
          value: v.value
        })
        this.onValidate()
        this.commit()
      })
    },
    __errorMsg() {
      let _msg = this.innerValue ? null : (this.formModel.rules.placeholder || '请选择国籍')
      if (!this.inputValid) {
        return _msg || this.inputError
      }
      return _msg
    },
    innerModel() {
      this.isValid = !!this.inputModel.value
      // if not required
      if (!this.formModel.rules.vRules || (this.formModel.rules.vRules.indexOf('required') === -1)) {
        // if not touched
        this.isValid = true
      }
      // return value
      return {
        name: this.name,
        value: this.inputModel.value,
        msg: this.__errorMsg(),
        isValid: this.isValid
      }
    }
  }
}
</script>
<style lang='less' scoped>
.search-wrap{
  background-color: #fff;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 99;
}
.nation-wrap{
  display: flex;
  .nation-input{
    flex: 1;
  }
}
</style>
