<template>
  <div class="auto content">
    <div class="col-sm-12">
      <label v-if="!model.id" class="add">添加{{type=='区'?'区/县':type}}</label>
      <label v-if="model.id  && !isarea" class="fs24">修改{{type=='区'?'区/县':type}}</label>
<!--      <label v-if="model.id && isarea" class="fs24">修改 {{model.f_name}} 默认表具</label>-->
    </div>
    <div class="col-sm-12" role="group">
      <center v-if="!(type=='区'||type=='街道'||type=='小区') && !model.id && isbasch">
        <button class="btn" :class="isselected ? 'btn-info':'btn-default'" @click="changetosingle">单个添加</button>
        <button class="btn" :class="isselected ? 'btn-default':'btn-info'" @click="changetobatch">批量添加</button>
      </center>
      <div class="auto col-sm-12 margintop" v-show="parent.f_name!='' && parent.f_type!='' && !isarea">
        <span class="shangji">上级名称：<label class="name">{{parent.f_name}}</label></span>
        <span class="shangji">上级类型：<label class="name">{{parent.f_type=='区'?'区/县':parent.f_type}}</label></span>
      </div>

      <div v-if="isselected && !isarea" class="form-group col-sm-12" style="margin-bottom: 20px; margin-top: 30px">
        <span class="col-sm-2 control-label shangji">{{model.f_type=='区'?'区/县':model.f_type}}名称：</span>
        <input type="text"  v-model="model.f_name" class="col-sm-10 input" placeholder="请输入" >
      </div>

      <div v-if="!isselected && !(type=='小区') && isbasch">
        <div class="form-group col-sm-12" v-show="type=='楼号'">
          <span class="col-sm-2 control-label name">楼号：</span>
          <input v-model="name_l" class="col-sm-6" />
          <span class="col-sm-2 control-label name">名称：</span>
          <input v-model="name_l_t" class="col-sm-2" />
        </div>
        <div class="form-group remark" v-show="type=='楼号'">备注：例如1-5,10-18</div>
        <div class="form-group col-sm-12" v-show="type=='楼号'||type=='单元'">
          <span class="col-sm-2 control-label name">单元：</span>
          <input class="col-sm-6" v-model="name_d"/>
          <span class="col-sm-2 control-label name">名称：</span>
          <input class="col-sm-2" v-model="name_d_t"/>
        </div>
        <div class="form-group remark" v-show="type=='楼号'||type=='单元'">备注：例如1-4</div>
        <div class="form-group col-sm-12" v-show="type=='楼号'||type=='单元'||type=='楼层'">
          <span class="col-sm-2 control-label name">楼层：</span>
          <input class="col-sm-6" v-model="name_c" />
          <span class="col-sm-2 control-label name">名称：</span>
          <input class="col-sm-2" v-model="name_c_t" />
        </div>
        <div class="form-group remark" v-show="type=='楼号'||type=='单元'||type=='楼层'">备注：例如1-5,8-10</div>
        <div class="form-group col-sm-12">
          <span class="col-sm-2 control-label name">门牌号：</span>
          <input v-model="name_m" class="col-sm-6"/>
          <span class="col-sm-2 control-label name">名称：</span>
          <input v-model="name_m_t" class="col-sm-2"/>
        </div>
        <div class="form-group remark">备注：例如1-4,门牌号规则：单元+楼层+门牌号</div>
      </div>
<!--      <div class="form-group auto" v-show="isarea">-->
<!--        <new-address-info v-ref:newaddressinfo v-if="type=='小区'" :areatype="areatype" :row="areaData" @addchild="addChild" @signout="signOut"></new-address-info>-->
<!--      </div>-->
      <div  class="form-group col-sm-12" v-show="!(type=='小区') || !isarea">
        <button type="button" class="btn btn-success" @click="addChild" >保存</button>
        <button type="button" class="btn btn-info" @click="signOut">取消</button>
      </div>
    </div>
  </div>
</template>

<script>
  // import NewAddressInfo from './NewAddressInfo'
  import {HttpResetClass} from 'vue-client'
  // 提交地址
  let asyncAddChild = async function(self, val) {
    console.log('33333333333333333',val)
    let result = null
    let data = null
    //新增 || 修改
    if(val.id != null) {
      console.log("asyncAddChild=" , val)
      result = await self.$resetpost(`rs/logic/address_addAddress`, val, {resolveMsg: null})
      // 添加小区 t_area
      if(val.f_type=='小区') {
        let parent = await self.$resetpost(`rs/logic/address_parent`, {id: val.id + ""}, {resolveMsg: null})
        await self.$refs.newaddressinfo.confirm(result.data.id, parent.data)
      }
    } else {
      // 子地址 || 根地址
      if(val.f_parentId == null) {
        data = {data: {f_parentId: null, condition: `f_locationId=${val.f_locationId} and f_locationType='${val.f_locationType}' and f_name='${val.f_name}'`}}
      } else {
        data = {data: {f_parentId: val.f_parentId.id, condition: `f_name='${val.f_name}'`}}
      }
      console.log('444444444444444',data)
      result = await self.$resetpost('rs/path/address_getRoot', data, {resolveMsg: null})
      console.log('55555555555555',result)
      // 查询改地址是否已存在
      console.log('666666666666666',result.data.length)
      if(result.data.length > 0) {
        alert("该地址已存在")
        throw err = new Error( '该地址已存在' )
      } else {
        console.log("调剂的速度val: ", val)
        result = await self.$resetpost(`rs/logic/address_addAddress`, val, {resolveMsg: null})
        // 添加小区 t_area
        console.log("result=" , result)
        if(result.data && val.f_type=='小区') {
          let parent = await self.$resetpost(`rs/logic/address_parent`, {id: result.data.id+""}, {resolveMsg: null})
          await self.$refs.newaddressinfo.confirm(result.data.id, parent.data)
        }
      }
    }
    return result
  }
  // 获取地址
  let asyncGetAddress = async function(self,num) {
    let data = {data: {f_parentId: null, condition: `id='${self.f_parentid}'`}}
    let result
    if(num == 1){ //添加
      result = await self.$resetpost('rs/sql/address_getSelf', {data: {id: self.f_parentid}}, {resolveMsg: null})
    } else { //修改
      result = await self.$resetpost('rs/sql/address_getParent', {data: {id: self.model.id}}, {resolveMsg: null})
    }
    if(result.data.length > 0) {
      self.parent = result.data[0]
    } else {
      self.parent = {}
    }
    return result
  }

  export default {
    name: "AddressAddAddress",
    // components: {NewAddressInfo},
    props: {
      // 主键 id
      row: {
        type: Object,
      },
      // 父节点id
      f_parentid: {
        type: Number,
      },
      //位置
      f_location: {
        type: Object,
      },
      // 地址类型
      type: {
        type: String,
      },
      // 是否显示小区信息
      isarea: {
        type: Boolean,
        default: false,
      },
      // 是否显示批量添加
      isbasch: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        model: {
          id: null,      //地址id
          f_locationId: null, //位置id
          f_locationType: null,//位置类型
          f_parentId: null,//上级地址id
          f_name: '', //地址名称
          f_type: '',   //地址类型
        },
        // 上级地址
        parent: {},
        // 小区信息
        areaData: null,
        // 小区 的 区名称
        areatype: '',
        isselected:true,
        // 楼号
        name_l: '',
        name_l_t: '',
        // 单元
        name_d: '',
        name_d_t: '',
        // 楼层
        name_c: '',
        name_c_t: '',
        // 门牌号
        name_m: '',
        name_m_t: '',
      }
    },
    ready () {
      if(this.row) {
        this.model = Object.assign({}, this.model, this.row)
      }
      if(this.f_parentid) {
        this.model.f_parentId = {id: this.f_parentid}
        return this.init()
      }
      if(this.f_location) {
        this.model.f_locationId = this.f_location.f_locationId
        this.model.f_locationType = this.f_location.f_locationType
      }
      if(this.type!='') {
        this.model.f_type = this.type
      }
    },
    watch: {
      'f_location' (val) {
        this.isselected = true
        if(val) {
          this.model.f_locationId = val.f_locationId
          this.model.f_locationType = val.f_locationType
        } else {
          this.model.f_locationId = null
          this.model.f_locationType = null
        }
      },
      'f_parentid' (val) {
        this.isselected = true
        // 添加
        if(val) {
          this.model.f_parentId = {id: val}
          this.addinit(val)
        } else {
          this.model.f_parentId = null
          this.parent = {}
        }
      },
      'type' (val) {
        console.log("asdasd safffgg456756val", val)
        this.isselected = true
        if(val!='') {
          this.model.f_type = val
        }
      },
      'row' (val) {
        console.log("val", val)
        this.isselected = true
        if(val) {
          this.getParent(val)
        } else {
          this.addArea()
        }
      }
    },
    methods: {

      // 添加
      async addinit(val){
        let http = new HttpResetClass()
        let res = await http.load('POST', 'rs/sql/address_getSelf', {data: {id: this.f_parentid}}, {resolveMsg: null})
        this.parent = res.data.length > 0 ? res.data[0]: {}
        let parent = await http.load('POST', `rs/logic/address_parent`, {id: val+""}, {resolveMsg: null, rejectMsg:'请求address_parent报错！！'})
        this.areatype = parent.data.f_area
      },
      // 初始化
      async init(num) {
        let data = {data: {f_parentId: null, condition: `id='${this.f_parentid}'`}}
        let result
        if(num == 1){ //添加
          result = await this.$resetpost('rs/sql/address_getSelf', {data: {id: this.f_parentid}}, {resolveMsg: null})
        } else { //修改
          result = await this.$resetpost('rs/sql/address_getParent', {data: {id: this.model.id}}, {resolveMsg: null})
        }
        if(result.data.length > 0) {
          this.parent = result.data[0]
        } else {
          this.parent = {}
        }
        return result
      },
      //提交地址
      addChild() {
        // 判断是否是批量添加
        if(!this.isselected && !(this.type=='小区') && this.isbasch) {
          console.log("批量添加,上级id: ", this.model.f_parentId)
          return this.baschAdd(this.model.f_parentId)
        } else {
          console.log('11111111111111111111',this.model)
          let data = Object.assign({}, data, this.model)
          console.log('2222222222222222',data)
          let id = this.model.id
          if(this.model.f_name != '') {
            return asyncAddChild(this, data).then((res) => {
              let result = data
              result.id = res.data.id
              this.model.f_name = ''
              this.model.idstr = null
              this.model.size = null
              this.isselected = true
              this.$parent.showAddress = !this.$parent.showAddress
              this.initModel()
              console.log("addChild", result)
              if(id != null) { // 修改
                this.$emit('updata-child-node', result)
              } else { //新增
                this.$emit('add-child-node', result)
              }
            }).catch((error) => {
              this.$emit('error', error)
            })
          } else {
            alert("名称和类型不能为空")
          }
        }
      },
      //返回
      signOut() {
        if (this.type === '小区') {
          this.$refs.newaddressinfo.initModel()
        }
        this.model.f_name = ''
        this.model.id = null
        this.isselected = true
        this.initModel()
        this.$parent.showAddress = !this.$parent.showAddress
      },
      async baschAdd(id) {
        if(!this.isselected) {
          let batchs = new Array()
          if(this.name_l != '') {
            if(this.name_l_t == ''){
              this.name_l_t = '号楼'
            }
            batchs.push({type: '楼号', names: this.name_l, n_type: this.name_l_t})
          }
          if(this.name_d != '') {
            if(this.name_d_t == ''){
              this.name_d_t = '单元'
            }
            batchs.push({type: '单元', names: this.name_d, n_type: this.name_d_t})
          }
          if(this.name_c != '') {
            if(this.name_c_t == ''){
              this.name_c_t = '层'
            }
            batchs.push({type: '楼层', names: this.name_c, n_type: this.name_c_t})
          }
          if(this.name_m != '') {
            if(this.name_m_t == ''){
              this.name_m_t = '号'
            }
            batchs.push({type: '门牌号', names: this.name_m, n_type: this.name_m_t})
          }
          console.log("批量添加baschAdd: ",batchs, "  ",  id)
          this.$showMessage('将会占用几分钟！！', ['confirm', 'cancel']).then((res) => {
            if (res === 'confirm') {
              this.isselected = true
              this.$parent.showAddress = !this.$parent.showAddress
              let http = new HttpResetClass()
              http.load('POST', 'rs/logic/address_batch', {id: id.id+"", json: batchs}, {rejectMsg:'批量上传出错', resolveMsg: '地址导入完成'}, 0).then(() => {
                this.$showMessage('导入完成。。！', ['confirm']).then((res) => {
                  if (res === 'confirm') {
                    this.initModel()
                    this.$emit('add-child-node')
                  }
                })
              })
            }
          })
          // let http = new HttpResetClass()
          // await http.load('POST', `rs/logic/address_batch`, {id: id.id+"", json: batchs})
          // this.isselected = true
          // this.initModel()
          // this.$parent.showAddress = !this.$parent.showAddress
          // this.$emit('add-child-node')
        }
      },
      // 新增
      addArea() {
        this.model.id = null
        this.parent = {}
        this.model.f_name = ''
        if(this.type=='') {
          this.model.f_type = ''
        }
        if(!this.f_location) {
          this.model.f_locationId = null
          this.model.f_locationType = null
        }
        if(!this.f_parentid){
          this.model.f_parentId = null
        }
        this.areaData = null
      },
      //
      async getParent(val) {
        let http = new HttpResetClass()
        let parent = await http.load('POST', `rs/logic/address_parent`, {id: val.id+""}, {resolveMsg: null, rejectMsg:'请求address_parent报错！！'})
        this.areatype = parent.data.f_area

        this.model = Object.assign({}, this.model, val)

        let res = await http.load('POST', 'rs/sql/address_getParent', {data: {id: this.model.id}}, {resolveMsg: null, rejectMsg:'请求address_getParent报错！！'})
        if(res.data.length > 0) {
          this.parent = res.data[0]
        } else {
          this.parent = {}
        }

        if(val.id != null && this.type=='小区') {
          let result = await http.load('POST','rs/path/address_getArea', {data: {id: val.id}}, {resolveMsg: null})
          if(result.data.length > 0) {
            this.areaData = result.data[0]
          } else {
            this.areaData = null
          }
        } else {
          this.areaData = null
        }
      },

      changetosingle(){
        this.isselected = true
      },
      changetobatch(){
        this.isselected = false
      },
      // 初始化参数
      initModel() {
        this.name_l = ''
        this.name_l_t = ''
        // 单元
        this.name_d = ''
        this.name_d_t = ''
        // 楼层
        this.name_c = ''
        this.name_c_t = ''
        // 门牌号
        this.name_m = ''
        this.name_m_t = ''
      }
    },
  }
</script>

<style type="text/css" scoped>
  *{
    margin: 0 auto;
    text-align: center;
  }
  div {
    margin-top: 10px;
  }
  .btngroup{
    height: 32px;
    width: 92px;
  }
  .btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle){
    border-radius: 4px;
    border-bottom-right-radius: 0;
    border-top-right-radius: 0;
  }
  .add{
    font-family: PingFangSC-Medium;
    font-size: 24px;
    color: #333333;
  }
  .shangji{
    font-family: PingFangSC-Medium;
    font-size: 16px;
    color: #666666;
  }
  .name{
    font-family: PingFangSC-Bold;
    font-size: 16px;
    color: #333333;
  }
  .margintop{
    margin-top: 20px;
  }
  .input{
    background-color: #FFFFFF;
    border: 1px solid #999999;
  }
  .remark{
    font-family: PingFangSC-Medium;
    font-size: 14px;
    color: #666666;
  }

</style>
