<template>
  <div>
    <Form :label-width="75">
      <FormItem label="区域类型">
        <Select size="large" class="form-input" v-model="form.type" @on-change="fetchCityListByType">
          <Option :value="item.value" :key="index" v-for="(item, index) in area_type">{{ item.label }}</Option>
        </Select>
        
      </FormItem>
      <FormItem label="上级区域">
        <Select 
          class="form-input" 
          v-model="form.parent_name" 
          filterable
          remote
          :remote-method="fetchCityList"
          @on-change="change"
          size="large"
          :loading="searchLoading">
          <Option :value="item.name" :key="item.id" v-for="item in parents">{{ item.name }}</Option>
        </Select>
      </FormItem>
      <FormItem label="区域名称">
        <Input size="large" class="form-input" v-model="form.name" />
        
      </FormItem>
    </Form>
    
  </div>
</template>

<script>
import { fetchCityList } from 'api/region'
import pinyin from 'js-pinyin'
export default {
  props: {
    form: Object,
    isEdit: Boolean
  },
  data () {
    return {
      searchLoading: false,
      area_type: [
        {
          value: 0,
          label: '国家'
        },
        {
          value: 1,
          label: '省份'
        },
        {
          value: 2,
          label: '城市'
        },
        {
          value: 3,
          label: '区县'
        },
        {
          value: 4,
          label: '街道'
        }
      ],
      parents: []
    }
  },
  components: {
  },
  mounted () {
    // this.fetchCityList('')
  },
  watch: {
    'form.name' (val) {
      this.form.first_alphabet = ''
      if (val) {
        this.form.first_alphabet = pinyin.getCamelChars(val).slice(0, 1)
      }
    }
  },
  methods: {
    fetchCityListByType (type) {
      this.form.parent_name = ''
      this.parents = []
      if (this.isEdit) {
        this.fetchCityList('')
        return
      }
      this.fetchCityList('', true)
    },
    fetchCityList (searchKey, noSetFirst) {
      if (!isNaN(searchKey)) searchKey = ''
      this.searchLoading = true
      fetchCityList({type: this.form.type - 1, searchKey, page_size: 999, page_num: 1}).then(res => {
        this.parents = res.data.list
        if (!noSetFirst) {
          this.form.parent_name = res.data.list[0] && res.data.list[0].name || ''
        }
        this.searchLoading = false
      })
    },
    change (value) {
      const findItem = this.parents.find(item => item.name === value)
      console.log(findItem, value, this.parents)
      if (findItem) {
        this.form.parent_id = findItem.id
      }
    }
  }
}
</script>

<style lang="less" scoped>
.form-input {
  width: 300px;
}
</style>