import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'
import { CommonService } from '../common.service'

@Component({
  selector: 'app-page16',
  templateUrl: './page16.component.html',
  styleUrls: ['./page16.component.css']
})
export class Page16Component implements OnInit {
  @Input() curPageData: Array<any>
  //获取省份
  @Input() provinceList: Array<any>
  @Output() getAllAnswer = new EventEmitter<any>()
  isShow: boolean
  cityList: Array<any>
  provinceId: number
  provinceName: string
  //具体地址显示
  showAddress: boolean
  address: Object
  selectedProvinceObj: Object
  selectedCityObj: Object
  strAddress: string
  constructor(private commonService: CommonService) {}

  ngOnInit() {
    this.selectedProvinceObj = {}
    this.selectedCityObj = {}
    // console.log(this.curPageData)
    this.showAddress = false
    this.setOptionSelected()
  }

  showToast() {
    this.isShow = true
  }
  selectProvince(option) {
    if (!this.selectedProvinceObj['selected']) {
      this.selectedProvinceObj = option
      option['selected'] = true
    } else {
      if (this.selectedProvinceObj['provinceId'] != option.provinceId) {
        this.selectedProvinceObj['selected'] = false
        option['selected'] = true
        this.selectedProvinceObj = option
      }
    }
    // console.log(this.selectedProvinceObj)
    this.provinceName = option.provinceName
    this.provinceId = option.provinceId
    this.getCityqry()
  }
  closeToast() {
    this.isShow = false
  }

  getCityqry() {
    const param = {
      insurerId: 11,
      provinceId: this.provinceId
    }
    this.commonService.getCityqry(param).then(res => {
      if (res['success']) {
        this.cityList = res['data'].cityList
        // console.log(this.cityList)
      }
    })
  }

  selectCity(e) {
    this.showAddress = true
    this.strAddress = this.provinceName + e.cityName
    this.address = {
      customerInput: this.provinceName + ',' + e.cityName
    }
  }

  getAnswer(option) {
    if (!this.selectedCityObj['selected']) {
      this.selectedCityObj = option
      option['selected'] = true
    } else {
      if (this.selectedCityObj['optionId'] != option.optionId) {
        this.selectedCityObj['selected'] = false
        option['selected'] = true
        this.selectedCityObj = option
      }
    }
    const ret = {
      pageId: this.curPageData['pageId'],
      questions: [
        {
          ...this.curPageData['questions'][0],
          questionId: this.curPageData['questions'][0].questionId,
          options: [this.address]
        }
      ]
    }
    this.getAllAnswer.emit(ret)
  }

  setOptionSelected() {
    const options = this.provinceList
    // console.log(options)
    if (!options) {
      return
    }
    options.forEach(option => {
      if (option['selected']) {
        this.selectedProvinceObj = option;
        this.getAnswer(this.selectedProvinceObj);
      }
    })
    console.log(this.selectedProvinceObj)
  }

}
