import Vue from 'vue'
import './SntAddressForm.scss'
import { mapActions } from 'vuex'
import {
  searchAddressByDistrict,
  searchAddressByAmphoe,
  searchAddressByProvince
} from 'thai-address-database'
import { VSpacer, VAutocomplete, VForm } from 'vuetify/lib'
import Telephone from '../common/Telephone.vue'

export default Vue.extend({
  name: 'SntAddressForm',
  components: { Telephone, VSpacer, VAutocomplete, VForm },
  data () {
    return {
      nameRules: [
        (v) => !!v || 'จำเป็นต้องมี'
      ],
      surNameRules: [
        (v) => !!v || 'จำเป็นต้องมี'
      ],
      additionalRules: [
        (v) => !!v || 'จำเป็นต้องมี'
      ],
      mooRules: [
        (v) => !!v || 'จำเป็นต้องมี'
      ],
      tumbonRules: [
        (v) => !!v || 'จำเป็นต้องมี'
      ],
      amphoeRules: [
        (v) => !!v || 'จำเป็นต้องมี'
      ],
      provinceRules: [
        (v) => !!v || 'จำเป็นต้องมี'
      ],
      postcodeRules: [
        (v) => !!v || 'จำเป็นต้องมี'
      ],
      telRules: [
        (v) => !!v || 'จำเป็นต้องมี',
        () => this.phoneObject.valid || 'เบอร์โทรศัพท์ไม่ถูกต้อง'
      ],
      emailRules: [
        (v) => !v || /.+@.+\..+/.test(v) || 'อีเมลไม่ถูกต้อง'
      ],
      form: {
        name: '',
        surname: '',
        additional: '',
        moo: '',
        tumbon: '',
        amphoe: '',
        province: '',
        zipcode: '',
        tel: '',
        email: ''
      },
      valid: false,
      phoneObject: {
        valid: false
      },
      amphoes: [],
      districts: [],
      provinces: []
    }
  },
  created () {
    this.debounceSuggestDistrict = this.$_.debounce(this.suggestDistrict, 150)
    this.debounceSuggestAmphoe = this.$_.debounce(this.suggestAmphoe, 150)
    this.debounceSuggestProvince = this.$_.debounce(this.suggestProvince, 150)
  },
  methods: {
    ...mapActions({
      addAddressList: 'salePage/addAddressList',
      setAddress: 'salePage/setAddress'
    }),
    validatePhoneObject (phoneObject) {
      this.phoneObject = phoneObject
    },
    suggestDistrict (value) {
      const newValue = value || ''
      const items = searchAddressByDistrict(newValue)
      this.districts = newValue ? [{ district: newValue }, ...items] : items
      this.form.tumbon = newValue
    },
    suggestAmphoe (value) {
      const newValue = value || ''
      const items = searchAddressByAmphoe(newValue)
      this.amphoes = newValue ? [{ amphoe: newValue }, ...items] : items
      this.form.amphoe = newValue
    },
    suggestProvince (value) {
      const newValue = value || ''
      const items = searchAddressByProvince(newValue)
      this.provinces = newValue ? [{ province: newValue }, ...items] : items
      this.form.province = newValue
    },
    selectDistrict (value) {
      if (value) {
        const { district, amphoe, province, zipcode } = value
        this.form.tumbon = district
        this.form.amphoe = amphoe
        this.suggestAmphoe(amphoe)
        this.form.province = province
        this.suggestProvince(province)
        this.form.zipcode = zipcode
      } else {
        this.form.tumbon = ''
      }
    },
    selectAmphoe (value) {
      if (value) {
        const { amphoe, province } = value
        this.form.amphoe = amphoe
        this.form.province = province
        this.suggestProvince(province)
      } else {
        this.form.amphoe = ''
      }
    },
    selectProvince (value) {
      if (value) {
        const { province } = value
        this.form.province = province
      } else {
        this.form.province = ''
      }
    },
    close () {
      this.$refs.form.reset()
      this.$refs.form.resetValidation()
      this.$emit('click:close')
    },
    submit () {
      const valid = this.$refs.form.validate()
      if (valid) {
        const name = `${this.form.name} ${this.form.surname}`
        const address = `${this.form.additional} ${this.form.moo} ${this.form.tumbon} ${this.form.amphoe} ${this.form.province}`
        const postcode = this.form.zipcode
        const tel = this.form.tel.replace(/\s+/g, '')
        const email = this.form.email
        this.addAddressList({
          address,
          name,
          postcode,
          tel,
          email
        })
        this.setAddress({
          address: `${address} ${this.form.zipcode}`,
          name,
          postcode,
          tel,
          email
        })
        this.close()
      }
    }
  },
  template: `
    <div class="snt-address-create">
      <snt-container class="snt-address-create__container">
        <div class="snt-address-create__title">
          <slot name="header">
            ที่อยู่จัดส่ง
          </slot>
        </div>
        <div class="snt-address-create__content">
          <v-form
            ref="form"
            v-model="valid"
            lazy-validation>
            <snt-row dense>
              <snt-col
                cols="12"
                sm="6">
                <div class="snt-address-create__label">
                  ชื่อ *
                </div>
                <snt-text-field
                  v-model="form.name"
                  :rules="nameRules"
                  :hide-details="false"
                  class="snt-address-create__input"
                  dense
                  outlined />
              </snt-col>
              <snt-col
                cols="12"
                sm="6">
                <div class="snt-address-create__label">
                  นามสกุล *
                </div>
                <snt-text-field
                  v-model="form.surname"
                  :rules="surNameRules"
                  :hide-details="false"
                  class="snt-address-create__input"
                  dense
                  outlined />
              </snt-col>
              <snt-col
                cols="12"
                sm="6">
                <div class="snt-address-create__label">
                  หมายเลข,ชื่ออาคาร *
                </div>
                <snt-text-field
                  v-model="form.additional"
                  :rules="additionalRules"
                  :hide-details="false"
                  class="snt-address-create__input"
                  dense
                  outlined />
              </snt-col>
              <snt-col
                cols="12"
                sm="6">
                <div class="snt-address-create__label">
                  หมู่ ,ซอย *
                </div>
                <snt-text-field
                  v-model="form.moo"
                  :rules="mooRules"
                  :hide-details="false"
                  class="snt-address-create__input"
                  dense
                  outlined />
              </snt-col>
              <snt-col
                cols="12"
                sm="6">
                <div class="snt-address-create__label">
                  แขวง /ตำบล *
                </div>
                <v-autocomplete
                  :value="form.tumbon"
                  :items="districts"
                  :rules="tumbonRules"
                  class="snt-address-create__input"
                  item-text="district"
                  item-value="district"
                  hide-no-data
                  hide-selected
                  auto-select-first
                  clearable
                  dense
                  outlined
                  return-object
                  @update:search-input="debounceSuggestDistrict($event)"
                  @input="selectDistrict($event)"
                />
              </snt-col>
              <snt-col
                cols="12"
                sm="6">
                <div class="snt-address-create__label">
                  เขต /อำเภอ *
                </div>
                <v-autocomplete
                  :value="form.amphoe"
                  :items="amphoes"
                  :rules="amphoeRules"
                  item-text="amphoe"
                  item-value="amphoe"
                  autocomplete="off"
                  class="snt-address-create__input"
                  hide-no-data
                  hide-selected
                  auto-select-first
                  clearable
                  dense
                  outlined
                  return-object
                  @update:search-input="debounceSuggestAmphoe($event)"
                  @input="selectAmphoe($event)" />
              </snt-col>
              <snt-col
                cols="12"
                sm="6">
                <div class="snt-address-create__label">
                  จังหวัด *
                </div>
                <v-autocomplete
                  :value="form.province"
                  :rules="provinceRules"
                  :items="provinces"
                  class="snt-address-create__input"
                  item-text="province"
                  item-value="province"
                  autocomplete="off"
                  hide-no-data
                  hide-selected
                  auto-select-first
                  clearable
                  dense
                  outlined
                  return-object
                  @update:search-input="debounceSuggestProvince($event)"
                  @input="selectProvince($event)" />
              </snt-col>
              <snt-col
                cols="12"
                sm="6">
                <div class="snt-address-create__label">
                  รหัสไปรษณีย์ *
                </div>
                <snt-text-field
                  v-model="form.zipcode"
                  :rules="postcodeRules"
                  :hide-details="false"
                  class="snt-address-create__input"
                  dense
                  outlined />
              </snt-col>
              <snt-col
                cols="12"
                sm="6">
                <div class="snt-address-create__label">
                  เบอร์โทรศัพท์ *
                </div>
                <telephone
                  v-model="form.tel"
                  :rules="telRules"
                  class="snt-address-create__input"
                  dense
                  outlined
                  @validate="validatePhoneObject($event)" />
              </snt-col>
              <snt-col
                cols="12"
                sm="6">
                <div class="snt-address-create__label">
                  อีเมล
                </div>
                <snt-text-field
                  v-model="form.email"
                  :rules="emailRules"
                  :hide-details="false"
                  class="snt-address-create__input"
                  dense
                  outlined />
              </snt-col>
            </snt-row>
          </v-form>
        </div>
        <div class="snt-address-create__action">
          <v-spacer />
          <snt-button
            class="snt-address-action__btn"
            color="primary"
            text
            @click="close()">
            ยกเลิก
          </snt-button>
          <snt-button
            :disabled="!valid"
            class="snt-address-action__btn"
            color="primary"
            depressed
            @click="submit()">
            อัปเดต
          </snt-button>
        </div>
      </snt-container>
    </div>
  `
})
