<template>
  <div>
    <div class="form-group" style="height: auto;position: relative;padding-bottom: 30px; ">
      <div class="col-sm-3">
        <input type="text" class="form-control" v-model="f_name" condition="f_name='{}'" placeholder='地址名称' >
      </div>
      <div class="col-sm-3">
        <v-select :value.sync="f_type" :options='address_type' placeholder='地址类型' close-on-select
                  v-model='f_type' v-ref:f_adjustable></v-select>
      </div>
      <div class="col-sm-3">
        <button style="position: absolute;left: 3px;" class="btn btn-success" @click="query">查询</button>
      </div>
    </div>
    <span v-if="!show">
      <dropdown class="auto" id="vc-chooser">
        <button type="button" class="btn btn-default dropdown-toggle auto" style="position: fixed;z-index: 1000;width: 93%;top: 65px;" data-toggle="dropdown" :id="'vc-chooser-button-'+attach">
          <span>{{ textContent }}</span>
          <span class="caret"></span>
        </button>
        <tree-grid :model='model' :is-click="false" slot="dropdown-menu" class="auto" style="width: auto;" role="menu" url="rs/path/address_getChild">
          <template partial='body'>
            <td>{{row.data.f_type}}</td>
            <td>
              <tree-grid-item :row="row" :iconsize="$parent.$parent.$parent.iconsize">
                <span partial>
                  <span v-if="row.data.f_type=='门牌号' && (!row.data.idstr || row.data.idstr<=0)" style="color: green" @click.stop="$parent.$parent.$parent.selectclick(row)">{{row.data.f_name}}</span>
                  <span v-else>{{row.data.f_type=='门牌号'?row.data.f_name+'(此地址已有档案)':row.data.f_name}}</span>
                  <span v-show="row.size">({{ row.size }})</span>
                </span>
              </tree-grid-item>
            </td>
          </template>
        </tree-grid>
      </dropdown>
    </span>

    <div v-if="show">
      <tree-grid :model='model' :is-click="false" url="rs/path/address_getChild" id="vc-chooser" v-ref:tree>
        <template partial='head'>
          <tr>
            <th>类型</th>
            <th>内容</th>
          </tr>
        </template>
        <template partial='body'>
          <td>{{row.data.f_type=='区'?'区/县':row.data.f_type}}</td>
          <td>
            <tree-grid-item :row="row" :iconsize="$parent.$parent.iconsize">
              <span partial>
                <span>{{row.data.f_name}}</span>
                <span v-show="row.size">({{ row.size }})</span>
                <button v-if="row.data.f_type=='门牌号' && row.data.idstr>0" class="btn btn-info btn-xs" @click="$parent.$parent.selectclick(row)">修正</button>
                <button v-if="row.data.f_type=='门牌号' && (!row.data.idstr || row.data.idstr<=0)" class="btn btn-info btn-xs" @click="$parent.$parent.selectclick(row)">建档</button>
              </span>
            </tree-grid-item>
          </td>
        </template>
      </tree-grid>
    </div>
  </div>
</template>

<script>
  import * as ldapHelper from '../util/LdapHelper'
  import { HttpResetClass } from 'vue-client'
  import  Vue from 'vue'

  //  获取根地址
  let asyncGetRoot = async function(self) {
    let condition = ""
    if(self.f_location) {
      condition = `f_locationId=${self.f_location.f_locationId} and f_locationType='${self.f_location.f_locationType}'`
    } else {
      condition = " 1=1 "
    }
    console.log(`条件condition是 ${condition}`)
    let http = new HttpResetClass()
    await http.load('POST', 'rs/path/address_getRoot', {data: {f_parentId: null, condition: condition}},{resolveMsg: null}).then((data)=>{
      self.model = data.data
    })
  }
  //查询地址
  let asyncQuery = async function(self, condition, login) {
    let result = await self.$resetpost(`rs/logic/address_query`, {data: {condition: condition, login: login}},{resolveMsg: null})
    return result
  }

  export default {
    name: "AddressSelect",
    props: {
      //位置
      f_location: {
        type: Object
      },
      // 默认显示地址
      value:{
        type: Object
      },
      // 下拉选择 || 树选择
      show: {
        type: Boolean,
        default: false
      }
    },
    data () {
      return {
        model: [],
        textContent: '请选择',
        contentId: '',
        attach: 'name',
        // 查询条件
        f_name: '',
        f_type: ['小区'],
        // 选中的节点
        treeRow: {},
        // 参数类, 用于修改tree组件的类
        category: {
          rootClass: {
            add: ['tree well'], //  'tree well'
            remove: ['list-group']
          },
          child: {
            add: [], //  'tree well'
            remove: ['list-group-item', 'item-text-color']
          },
        },
        iconsize: '18px'
      }
    },
    computed : {
      address_type() {
        return this.$appdata.getParam('地址类型')
      }
    },
    methods: {
      // 初始化
      init() {
        return asyncGetRoot(this).then(() => {
          this.$emit('ready')
        }).catch((error) => {
          this.$emit('error', error)
        })
      },
      updataTree () {
        let index = this.$refs.tree.toNode.indexOf(this.treeRow)
        console.log("updataTree=",this.$refs.tree.toNode[index])
        this.$refs.tree.toNode[index].data.idstr = 1
      },
      //点击分公司方法
      selectclick (row) {
        console.log('看看row',row)
        let newobj={
          "rows": ldapHelper.getFullNameType(row, 'f_name', 'f_type'),
          "id": ldapHelper.getFullName(row, 'id')
        }
        let address = ''
        newobj.rows.forEach((item)=>{
          address += item.name
        })
        this.textContent = address
        this.contentId = row.id
        this.treeRow = row
        //返回,  需要修改
        console.log('返回数据',newobj,address)
        this.$emit('re-ref', newobj,address)
      },
      // 当外面传入的选中对象发生变化时调用
      valueChange () {
        this.textContent = this.value.address
        let arr = this.value.lastId.split('.')
        this.contentId = arr[arr.length-1]
      },
      //检查是否显示对勾
      isInStr(val) {
        if(this.contentId == val){
          return true
        }else{
          return false
        }
      },
      // 查询
      async query() {
        console.log(this.f_type)
        if(this.f_name==="") {
          await this.init()
        } else if(this.f_type.length <= 0) {
          alert("请输入地址类型");
        } else {
          let condition ={
            name: this.f_name,
            type: this.f_type[0]
          }
          let login = {
            id: this.f_location.f_locationId+"",
            type: this.f_location.f_locationType
          }
          let res = await asyncQuery(this, condition, login)
          this.model = res.data
          await new Promise(resolve => {
            this.$nextTick(() => {
              resolve()
            })
          })
          // 展开所有子
          this.$refs.tree.openAll()
          this.$emit('ready')
        }
      }
    },
    //初始化参数
    ready () {
      if(this.f_location.f_locationId && this.f_location.f_locationType){
        this.init()
      }
      if(this.value){
        this.valueChange()
      }
    },
    // 参数变化触发
    watch: {
      'f_location'(val) {
        if(val.f_locationId && val.f_locationType){
          this.init()
        }
      },
      'value' (val) {
        if(val){
          this.valueChange()
        }
      },
    },
  }
</script>

<style lang="less">
  #vc-chooser {
    .list-group-item {
      background-color: #FFF;
      color: #000;
    }
  }
  #vc-chooser .list-group {
    width: 300px;
  }
  .query {
    display: inline-block;
    width: 100%;
    height: 40px;
    line-height: 25px;
  }
</style>
