<template>
  <div>
    <div class="border">
      <div v-if="!isquery" class="form-group" style="height: auto;position: relative;">
        <div class="col-sm-2">
          <input type="text" class="form-control col-sm-2" v-model="f_name" condition="f_name='{}'" placeholder='地址名称' >
        </div>
        <v-select class="col-sm-2" style="margin-left: 5px" :value.sync="f_type" :options='address_type' placeholder='地址类型'
                  close-on-select v-model='f_type' v-ref:f_adjustable></v-select>
        <button class="btn btn-info" @click="query">查询</button>
        <button class="btn btn-info" @click="addRoot">添加区(县)</button>
        <button class="btn btn-success" @click="importAddress">导入地址</button>
      </div>
      <div v-if="isquery" class="form-group row" style="height: auto;position: relative;">
        <div class="col-sm-2 paddingLeft">
          <right-tree :userid.sync='userid' :source.sync='source'  @re-res="getRes" > </right-tree>
        </div>
        <div class="col-sm-2 paddingLeft">
          <input type="text" class="form-control" v-model="name_x"
                 condition="f_name='{}'" :placeholder='config.querys[0]'>
        </div>
        <div class="col-sm-2 paddingLeft">
          <input type="text" class="form-control" v-model="name_l"
                 condition="f_name='{}'" :placeholder='config.querys[1]'>
        </div>
        <div class="col-sm-2 paddingLeft">
          <input type="text" class="form-control" v-model="name_d"
                 condition="f_name='{}'" :placeholder='config.querys[2]'>
        </div>
        <!--<div class="col-sm-2 paddingLeft">-->
          <!--<input type="text" class="form-control" v-model="name_c" @keyup.enter="search(name_c, config.querys[3])"-->
                 <!--condition="f_name='{}'" :placeholder='config.querys[3]'>-->
        <!--</div>-->
        <!--<div class="col-sm-2 paddingLeft">-->
          <!--<input type="text" class="form-control" v-model="name_m" @keyup.enter="search(name_m, config.querys[4])"-->
                 <!--condition="f_name='{}'" :placeholder='config.querys[4]'>-->
        <!--</div>-->
        <button class="btn btn-info" @click="search">查询</button>
        <button class="btn btn-info" @click="clear">清空</button>
        <button class="btn btn-info" @click="addRoot">添加区(县)</button>
        <button v-if="isbasch" class="btn btn-success" @click="importAddress">导入地址</button>
      </div>
      <tree-grid class="treeList" :model="model" v-ref:tree :is-Click="true" isEdit="true" @select-changed='selectclick' url='rs/path/address_getChild' id="vc-chooser">
        <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="18px">
              <span partial>
                <span v-if="$parent.$parent.isinspect">
                  <span v-if="row.data.f_type=='门牌号' && (!row.data.idstr || row.data.idstr<=0)" style="color: green">{{row.data.f_name}}</span>
                  <span v-else>{{row.data.f_type=='门牌号'?row.data.f_name+'(此地址已有档案)':row.data.f_name}}</span>
                </span>
                <span v-if="!$parent.$parent.isinspect">
                  <span>{{row.data.f_name}}</span>
                </span>
                <span>({{row.size>0?row.size:0}})</span>
                <span v-if="$parent.isSelected(row)">
                  <!--添加地址-->
                  <button class="btn btn-info btn-sm" v-for="type in $parent.$parent.config.types[row.data.f_type]" @click="$parent.$parent.$parent.addType(row, type)">
                    <span class="glyphicon glyphicon-plus-sign">{{type}}</span>
                  </button>
                  <!--修改地址-->
                  <button class="btn btn-success btn-sm" @click="$parent.$parent.updateType(row, 1)">修改名称</button>

                  <!--删除地址-->
                  <button  v-if="row.size<=0" class="btn btn-success btn-sm" @click="$parent.$parent.deleteType(row)">删除</button>
                </span>
              </span>
            </tree-grid-item>
          </td>
        </template>
      </tree-grid>
    </div>
    <div class="rightDiv" v-show="showAddress" >
      <address-add style="flex: 1.5;width: 85%" :isbasch="isbasch" :row="item" :f_parentid="parentid" :type="type" :f_location="location" :isarea="isarea"
                   @add-child-node="addChildNode" @updata-child-node="updataChildNode" v-ref:addressadd ></address-add>
    </div>
    <modal :show.sync="showFile" v-ref:modal backdrop="true">
      <header slot="modal-header" class="modal-header">
        <button type="button" class="close" @click="closeFile"><span>&times;</span></button>
        <h4 class="modal-title">文件导入</h4>
      </header>
      <article slot="modal-body" class="modal-body">
        <div class="form-group">
          <file-upload class="my-file-uploader" name="addressUploadFile" action="rs/file/uploadFile" tagname="文件导入" :headers="headers" multiple v-ref:file></file-upload>
        </div>
      </article>
      <footer slot="modal-footer" class="modal-footer"></footer>
    </modal>
  </div>
</template>

<script>
  import addressAdd from '../components/AddressAddAddress'
  import * as ldapHelper from '../util/LdapHelper'
  import Vue from 'vue'

  export default {
    name: "AddressTreeManage",
    components: {
      addressAdd,
    },
    title: '地址管理',
    props: {
      //位置
      f_location: {
        default: {
          f_locationId: '1535',
          f_locationType: 't_organization',
        },
        type: Object,
      },
      // 查询格式
      isquery: {
        type: Boolean,
        default : false,
      },
      // 是否显示小区信息
      isarea: {
        type: Boolean,
        default: false,
      },
      // 是否显示批量添加
      isbasch: {
        type: Boolean,
        default: true,
      },
      // 是否检查用户建档
      isinspect: {
        type: Boolean,
        default: false,
      }
    },

    data () {
      return {
        config: {
          // 类型定义
          types: {
            '区': ['街道'],
            '街道': ['小区','门牌号'],
            '小区': ['楼号', '单元'],
            '楼号': ['单元', '楼层', '门牌号'],
            '单元': ['楼层', '门牌号'],
            '楼层': ['门牌号']
          },
          // 查询类型
          querys: ['小区', '楼号', '单元', '楼层', '门牌号'],
        },
        model: [],
        showAddress: false,
        //当前更改
        item: null,
        parentid: null,
        location: null,
        showFile: false,
        headers: {'username': '', 'blodid': '','f_usetype':'','f_remarks':''},
        login: {id: '1535',type: 't_organization'},
        type: '',
        // 参数类, 用于修改tree组件的类
        category: {
          child: {
            add: [], //  ''
            remove: []
          },
          span: {
            add: ['glyphicon glyphicon-minus-sign','glyphicon glyphicon-plus-sign'],
            remove: ['glyphicon glyphicon-chevron-down','glyphicon glyphicon-chevron-right']
          }
        },
        // 选中的节点
        treeRow: null,
        selectItem: null, // 选择的参数
        userid: this.$login.f.id,
        source:`tool.getFullTree(this.getRights().where(row.getType() == $organization$))`,
        f_type: ['小区'],
        f_name: '',
        name_x: '',
        name_l: '',
        name_d: '',
        name_c: '',
        name_m: '',
      }
    },
    ready() {
      if(Vue.$login.f.parent && Vue.$login.f.parent.parentid) {
        this.f_location.f_locationId = Vue.$login.f.parent.parentid
        this.login.id = Vue.$login.f.parent.parentid+""
      }
      if(this.f_location.f_locationId && this.f_location.f_locationType) {
        this.init()
      }
    },
    watch: {
      'f_location' (val) {
        this.showAddress = false
        if(val.f_locationId && val.f_locationType) {
          this.init()
        }
      },
      'f_location.f_locationId' () {
        this.showAddress = false
        if(this.f_location.f_locationId && this.f_location.f_locationType) {
          this.init()
        }
      }
    },
    computed : {
      address_type() {
        return this.$appdata.getParam('地址类型')
      }
    },
    methods: {
      // 参数初始化
      init() {
        return asyncGetRoot(this).then(() => {
          this.$emit('ready')
        }).catch((error) => {
          this.$emit('error', error)
        })
      },
      //添加根地址
      addRoot() {
        this.type = '区'
        this.item = null
        this.location = Object.assign({}, this.location, this.f_location)
        this.parentid = null
        this.treeRow = null
        this.isarea = false
        this.showAddress = true
      },
      //添加子地址
      addType(row, type) {
        this.type = type
        this.item = null
        this.location = Object.assign({}, this.location, this.f_location)
        this.parentid = row.data.id
        this.treeRow = row
        this.isarea = false
        this.showAddress = true
      },
      //修改地址
      updateType(row, type) {
        console.log('xiugai ......', row, type)
        if(type == 1){
          this.isarea = false
        } else {
          this.isarea = true
        }
        this.type = row.data.f_type
        this.parentid = null
        this.location = null
        this.item = Object.assign({}, this.item, row.data)
        this.treeRow = row
        this.showAddress = true
      },
      //删除地址
      deleteType(row) {
        console.log(row)
        let self = this
        let id = row.data.id
        return asyncDelete(this, row, row.data.f_type).then((res) => {
          console.log(res.data.status + "    " + res.data.msg)
          if(res.data.status == 200) {
            console.log(row.parent)
            if(row.parent) {
              // 父节点刷新
              this.$refs.tree.refreshChild(row.parent)
            } else {
              this.init()
            }
          } else {
            alert(res.data.msg)
          }
          this.showAddress = false
        })
      },
      //导入地址
      importAddress() {
        this.showFile = true
      },
      // 关闭文件上传对话框
      closeFile() {
        this.showFile = false
        // 将选的文件清空
        // this.$showMessage(this.$refs.file.$el.querySelector('input').value)
        this.$refs.file.$el.querySelector('input').value = ''
      },
      // 父组件更新子组件属性 , 传入登陆信息
      updateData(val) {
        if(val.headers){
          this.headers = val.headers
        }
        if(val.login){
          this.login = val.login
        }
      },
      // 添加子节点
      addChildNode(data) {
        if(this.treeRow) {
          // 刷新当前节点
          this.$refs.tree.refreshChild(this.treeRow)
        } else {
          this.init()
        }
      },
      // 修改
      updataChildNode(data) {
        if(this.treeRow.parent){
          this.$refs.tree.refreshChild(this.treeRow.parent)
        } else {
          this.init()
        }
      },
      filterParams (param,filialeCodeStr) {
        this.selectItem = null
        if(param){
          this.model.rows = this.allParams.filter((item) => {
            return filialeCodeStr==(item.f_orgstr)  && item.name.includes(param)
          })
        }else{
          this.model.rows = this.allParams.filter((item) => {
            return filialeCodeStr==(item.f_orgstr)
          })
        }
      },
      async query() {
        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')
        }
      },
      // 地址搜索
      async search() {
        let condition ={
          f_area: this.name_x,
          f_building: this.name_l,
          f_unit: this.name_d
        }
        let login = {
          id: this.f_location.f_locationId+"",
          type: this.f_location.f_locationType
        }
        let res = await this.$resetpost(`rs/logic/address_search`, {data: {condition: condition, login: login}},{resolveMsg: null})
        this.model = res.data
        //刷新dom
        await new Promise(resolve => {
          this.$nextTick(() => {
            resolve()
          })
        })
        // 展开所有子
        this.$refs.tree.openAll()
      },
      // 清空
      clear() {
        this.name_x = ''
        this.name_l = ''
        this.name_d = ''
        this.name_c = ''
        this.name_m = ''
        this.init()
      },
      selectclick (obj) {
        let row = obj.val
        if(this.isinspect){
          //如果选择地址已有档案则不返回事件,并把选中状态改为未选中
          if(row.data.idstr > 0) {
            this.$refs.tree.selectStore.selected = null
            return
          }
        }
        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.$dispatch('re-ref', newobj,address)
      },
      getRes (obj) {
        let loc = obj.resids.split('.');
        this.f_location.f_locationId = loc[loc.length-2];
      }
    },
    events: {
      onFileUpload: function (file, res) {
        console.log("上传完毕"+JSON.stringify(res))
        let data = {
          filepath: res.f_downloadpath,
          login: this.login
        }
        console.log("filepath="+JSON.stringify(data))
        return asyncImport(this, data).then(() => {
          this.closeFile()
          this.init()
        }).catch((error) => {
          this.$emit('error', error)
        })
      },
      'onFileError'(error) {
        this.$showAlert(error, 'warning', 2000)
      }
    },
  }
  // 导入地址
  let asyncImport = async function (self, data) {
    let result = await self.$resetpost(`rs/logic/address_import`,data, {resolveMsg: '导入成功', rejectMsg: '导入失败', silent: true}, 0)
    return result
  }
  //  获取根地址
  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 "
    }
    let that = self
    // console.log(`condition=${condition}`)
    let result = await self.$resetpost('rs/path/address_getRoot',{data: {f_parentId: null, condition: condition}},{resolveMsg: null})
    // console.log(JSON.stringify(result.data))
    self.model = result.data
    return result
  }
  // 删除地址
  let asyncDelete = async function(self, row, type) {
    let result = await self.$resetpost(`rs/logic/address_deleteAddress`, {childId: `${row.data.id}`}, {resolveMsg: null})
    if(type == '小区') {
      await self.$resetpost(`rs/logic/address_deleteArea`,{areaId: `${row.data.id}`}, {resolveMsg: null})
    }
    return result
  }
  //查询地址
  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
  }

</script>

<style lang="less" scoped>
  .btn{
    margin-left: 7px;
    border-radius: 4px;
  }
  .border{
    max-width: 50%;
    /*overflow-y: auto;*/
    float: left;
  }
  .rightDiv{
    width: 50%;
    /*margin-left: 200px;*/
    float: left;
  }
  .treeList {
    overflow-y: auto;
    max-height: 90%;
  }
  .paddingLeft {
    padding-left: 10px;
    width: 15%;
  }
</style>
