<template>
  <div class="auto">
    <validator name='v'>
      <form novalidate class="form-horizontal">
        <p class="bg-info text-center" style="padding: 8px;">{{special?'特殊地址管理':'地址管理'}}</p>
        <div class="auto select-overspread form-horizontal">
          <div v-bind:class="special?'col-sm-6':'col-sm-4'" class="form-group form-input-group" :class="[$v.f_area.required ? 'has-error' : 'has-success']">
            <label class="control-label">区/县</label>
            <input type="text" v-show="false" v-model="model.f_area" v-validate:f_area='{required: true }'>
            <v-select :value.sync="model.f_area" :value-single="true"
                      :options='farea' placeholder='请选择'
                      close-on-select search="true" @change="areaChange">
            </v-select>
          </div>
          <div v-bind:class="special?'col-sm-6':'col-sm-4'" class="form-group form-input-group" :class="[$v.f_street.required ? 'has-error' : 'has-success']">
            <label class="control-label">街道</label>
            <input type="text" v-show="false" v-model="model.f_street" v-validate:f_street='{required: true }'>
            <v-select :value.sync="model.f_street" :value-single="true"
                      :options='fstreet' placeholder='请选择'
                      close-on-select search="true" @change="streetChange">
            </v-select>
          </div>
          <div v-if="!special" class="col-sm-4 form-group form-input-group" :class="[$v.f_residential_area.required ? 'has-error' : 'has-success']">
            <label class="control-label">小区</label>
            <input type="text" v-show="false" v-model="model.f_residential_area" v-validate:f_residential_area='{required: true }'>
            <v-select :value.sync="model.f_residential_area" :value-single="true"
                      :options='fresidentialarea' placeholder='请选择'
                      close-on-select search="true">
            </v-select>
          </div>
          <div v-show="!special" class="col-sm-6 form-group form-input-group has-success">
            <label for="f_address" class="control-label">楼号</label>
            <input type="text" v-model="model.f_building" class="form-control" placeholder="楼号"/>
            <input type="text" v-show="!revise" v-model="initial.f_building" class="form-control" style="width: 30%;border-left: 0px;"/>
          </div>
          <div v-show="!special" class="col-sm-6 form-group form-input-group has-success">
            <label for="f_address" class="control-label">单元</label>
            <input type="text"  v-model="model.f_unit" class="form-control" placeholder="单元"/>
            <input type="text" v-show="!revise" v-model="initial.f_unit" class="form-control" style="width: 30%;border-left: 0px;"/>
          </div>
          <div v-show="!special" class="col-sm-6 form-group form-input-group has-success">
            <label for="f_address" class="control-label">楼层</label>
            <input type="text"  v-model="model.f_floor" class="form-control" placeholder="楼层"/>
            <input type="text" v-show="!revise" v-model="initial.f_floor" class="form-control" style="width: 30%;border-left: 0px;"/>
          </div>
          <div v-if="!special" class="col-sm-6 form-group form-input-group" :class="[$v.f_room.required ? 'has-error' : 'has-success']">
            <label for="f_address" class="control-label">门牌号</label>
            <input type="text"  v-model="model.f_room" class="form-control" placeholder="门牌号" v-validate:f_room='{required: true }'/>
            <input type="text" v-show="!revise" v-model="initial.f_room" class="form-control" style="width: 30%;border-left: 0px;"/>
          </div>
          <div v-if="special" class="col-sm-6 form-group form-input-group" :class="[$v.f_address.required ? 'has-error' : 'has-success']">
            <label for="f_address" class="control-label">详细地址</label>
            <input type="text"  v-model="model.f_address" class="form-control" placeholder="详细地址" v-validate:f_address='{required: true }'/>
          </div>
        </div>
      </form>
      <div style="text-align:right;margin-top:6px;margin-right:50px;" class="col-sm-12">
        <button class="btn btn-success" @click="confirm()"  :disabled='!$v.valid' id='components-comOpe-othCha-保存'>保&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;存</button>
        <button class="btn btn-success" @click="clear()"  id='components-comOpe-othCha-清空'>清&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;空</button>
        <button class="btn btn-success" @click="cancel()"  id='components-comOpe-othCha-清空'>取&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;消</button>
      </div>
    </validator>
  </div>
</template>

<script>
  import {HttpResetClass} from 'vue-client'
  export default {
    title: '用户地址管理',
    data () {
      return {
        model:{
          //id
          id: null,
          //小区id
          f_residential_area_id: '',

          f_street: '',
          f_residential_area: '',

          f_building: '',
          f_unit: '',
          f_floor: '',
          f_room: '',
          //详细地址
          f_address: ''
        },
        //下拉选数据
        area: [],
        street:[], //街道
        residentialArea:[], //小区

        //判断是否是修改地址
        revise: false,
        //判读是否是特殊地址
        special: false,
        //默认值
        initial:{
          f_building: '栋',
          f_unit: '单元',
          f_floor: '层',
          f_room: '室'
        },
      }
    },
    props: ['f_filialeids', 'row'],
    ready(){
      this.init()
    },
    methods:{
      //初始化--获取区/县数据
      init(){
        let loc = this.f_filialeids.split('.');
        console.log('获取区县，，。，', loc)
        this.getaddress(`f_type='区' and f_locationId = ${loc[loc.length-2]}`).then((data)=>{
          this.area = this.calculate(data.data)
        this.$emit('ready')
      }).catch((error) => {
          this.$emit('error', error)
      })
      },
      async getaddress(condition){
    let HttpReset = new HttpResetClass()
    var data =  await HttpReset.load('POST','rs/sql/address_singleTableOrderBy', {data: {items: 'id,f_name',tablename: 't_address',orderitem: 'f_name' ,condition: condition}},{resolveMsg: null, rejectMsg: '获取地址失败!'})
    return data
  },
  //把数据库查询数据转换为下拉数据
  calculate(rows){
    let data = []
    rows.forEach((row,n)=>{
      data[n] = {label:row.f_name, value:row.id}
    })
    return data
  },
  //根据id获取名字
  getname(data,id){
    if(!id){
      return ''
    }
    for(var i=0;i<data.length;i++){
      if(data[i].value === id){
        return data[i].label
      }
    }
  },
  //保存
  async confirm(){
    let data = {}
    if(!this.revise){
      //新增时
      let f_area = this.getname(this.area,this.model.f_area)
      let f_street = this.getname(this.street,this.model.f_street)
      let f_residential_area = this.getname(this.residentialArea,this.model.f_residential_area)
      data = {
        f_area: f_area,
        f_street: f_street,
        f_residential_area: f_residential_area,

        f_building: this.model.f_building,
        f_unit: this.model.f_unit,
        f_floor: this.model.f_floor,
        f_room: this.model.f_room,
        //小区id
        f_residential_area_id : this.model.f_residential_area,
        f_filialeids: this.f_filialeids,
        f_create_date: this.$login.toStandardTimeString()
      }
    }else{
      //选中修改时
      data = {
        //id
        id: this.model.id,
        f_area: this.getname(this.area,this.model.f_area),
        f_street: this.getname(this.street,this.model.f_street),
        f_residential_area: this.getname(this.residentialArea,this.model.f_residential_area),

        f_building: this.model.f_building,
        f_unit: this.model.f_unit,
        f_floor: this.model.f_floor,
        f_room: this.model.f_room,
        //小区id
        f_residential_area_id : this.model.f_residential_area_id,
        f_filialeids: this.f_filialeids,
        f_create_date: this.$login.toStandardTimeString()
      }
    }
    //防止小区id为空时后台报错
    if (!data.f_residential_area_id){
      data.f_residential_area_id = null
    }
    //把默认值加入
    //当是新增地址时加入默认值
    if(!this.revise){
      data.f_building = data.f_building?data.f_building+this.initial.f_building:''
      data.f_unit = data.f_unit?data.f_unit+this.initial.f_unit:''
      data.f_floor = data.f_floor?data.f_floor+this.initial.f_floor:''
      data.f_room = data.f_room?data.f_room+this.initial.f_room:''
    }else{
      data.f_building = data.f_building?data.f_building:''
      data.f_unit = data.f_unit?data.f_unit:''
      data.f_floor = data.f_floor?data.f_floor:''
      data.f_room = data.f_room?data.f_room:''
    }
    //防止出现null值在详细地址中
    data.f_area = data.f_area?data.f_area:''
    data.f_street = data.f_street?data.f_street:''
    data.f_residential_area = data.f_residential_area?data.f_residential_area:''
    //如果是新增特殊地址
    if(this.special){
      //特殊地址标识
      data.f_special = 1
      data.f_address = ''+data.f_area+data.f_street+this.model.f_address
    }else{
      data.f_address = ''+data.f_area+data.f_street+data.f_residential_area+data.f_building+data.f_unit+data.f_floor+data.f_room
    }
    //看看地址是否已存在
    var rs = await this.$resetpost('rs/sql/address_singleTable',{data: {items: 'id',tablename: 't_user_address',condition: `f_address='${data.f_address}'`}}, {resolveMsg: null, rejectMsg: null})
    console.log('保存地址',rs)
    if(rs.data.length>0){
      this.$showAlert('地址已存在', 'warning',900)
    }else{
      await this.$resetpost('rs/logic/address_adduseraddress', data, {resolveMsg: '保存成功', rejectMsg: '保存失败'})
      //修改状态保存后改为新增
      if(this.revise){
        //选择状态变为false
        this.revise = false
        //获取区/县数据
        this.init()
        //清空输入数据
        // this.partclear1()
      }
      this.partclear2()
      this.$dispatch('refresh')
    }
  },
  cancel(){
    this.$dispatch('cancel')
  },
  clear(){
    //当修改时不清空区/县,街道,小区
    if(!this.revise){
      this.partclear1()
    }
    this.partclear2()
  },
  partclear1(){
    this.model.f_area = ''
    this.model.f_street = ''
    this.model.f_residential_area = ''
  },
  partclear2(){
    this.model.f_building = ''
    this.model.f_unit = ''
    this.model.f_floor = ''
    this.model.f_room = ''
    this.model.f_address = ''
  },
  //区/县变化
  areaChange(val){
    //当是修改地址时不去获取了
    if (val !== this.row.f_area_id) {
      if (val) {
        console.log('我是组件变化发的街道请求')
        this.getaddress(`f_type='街道' AND f_parentId = ${val}`).then((data) => {
          this.street = this.calculate(data.data)
      })
      } else {
        this.street = []
      }
      //街道,小区设空
      this.model.f_street = ''
      this.model.f_residential_area = ''
      this.residentialArea = []
    }

    //验证器重置
    this.$resetValidation()
  },
  //街道变化
  streetChange(val) {
    //当是修改地址时不去获取了
    if (val !== this.row.f_street_id) {
      if (val) {
        console.log('我是组件变化发的小区请求')
        this.getaddress(`f_type='小区' AND f_parentId = ${val}`).then((data) => {
          this.residentialArea = this.calculate(data.data)
      })
      } else {
        this.residentialArea = []
      }
      this.model.f_residential_area = ''
    }
    //验证器重置
    this.$resetValidation()
  }
  },
  watch:{
    //分公司变化
    'f_filialeids'(){
      this.partclear1()
      this.init()
    }
  },
  computed:{
    farea(){
      return this.area
    },
    fstreet(){
      return this.street
    },
    fresidentialarea(){
      return this.residentialArea
    },
  },
  }
</script>
