<template>
  <div class="auto" style="height:80%">
    <validator name='d' @valid="$emit('address-valid')" @invalid="$emit('address-valid')">
      <p class="bg-info text-center" style="padding: 8px;">{{is_pecial ? '特殊地址管理' : '民用地址管理'}}</p>
      <form class="auto select-overspread form-horizontal">
        <div class="row">

          <div class="col-sm-6 form-group "
               :class="[$v.f_pcd_id.required ? 'has-error' : 'has-success']">
            <label class="font_normal_body">省&ensp;市&ensp;区</label>
            <input type="text" style="width:41%" v-show="false" v-model="model.f_pcd_id"
                   v-validate:f_pcd_id='{required: true }'>
            <v-select :value.sync="model.f_pcd_id" :value-single="true"
                      :options='pcdslist' placeholder='请选择'
                      close-on-select search="true" @change="pcdChange">
            </v-select>
          </div>

          <div class="col-sm-6 form-group "
               :class="[$v.f_street_id.required ? 'has-error' : 'has-success']">
            <label class="font_normal_body">街道名称</label>
            <input type="text" style="width:41%" v-show="false" v-model="model.f_street_id"
                   v-validate:f_street_id='{required: true }'>
            <v-select :value.sync="model.f_street_id" :value-single="true"
                      :options='streetslist' placeholder='请选择'
                      close-on-select search="true" @change="streetChange">
            </v-select>
          </div>
          <div v-if="!is_pecial" class="col-sm-6 form-group "
               :class="[$v.f_residential_area_id.required ? 'has-error' : 'has-success']">
            <label class="font_normal_body">小区名称</label>
            <input type="text" style="width:41%" v-show="false" v-model="model.f_residential_area_id"
                   v-validate:f_residential_area_id='{required: true }'>
            <v-select :value.sync="model.f_residential_area_id" :value-single="true"
                      :options='areaslist' placeholder='请选择'
                      @change="areaChange"
                      close-on-select search="true">
            </v-select>
          </div>
          <div class="col-sm-6 form-group " :class="[$v.slice.required ? 'has-error' : 'has-success']">
            <label class="font_normal_body">片&emsp;&emsp;区</label>
            <input type="text" style="width:60%" class="input_search" v-show="false" v-model="$refs.slice.selectedItems"
                   v-validate:slice='{required: true }'>
            <v-select :value.sync="model.slice_area" v-model="model.slice_area"
                      :options='sliceArea' placeholder='片区/管理站' filer-key="name"
                      close-on-select v-ref:slice>
            </v-select>
          </div>
          <div v-if="!is_pecial" class="col-sm-6 form-group ">
            <label for="f_address" class="font_normal_body">楼&emsp;&emsp;号</label>
            <input type="text" style="width:40%" v-model="model.f_building" class="input_search"
                   placeholder="楼号"/>
            <input type="text" style="width:20%" v-model="model.f_building_suffix" class="input_search"
            />

          </div>
          <div v-if="!is_pecial" class="col-sm-6 form-group ">
            <label for="f_address" class="font_normal_body">单&emsp;&emsp;元</label>
            <input type="text" style="width:40%" v-model="model.f_unit" class="input_search" placeholder="单元"/>
            <input type="text" style="width:20%" v-model="model.f_unit_suffix" class="input_search"
            />
          </div>
          <div v-if="!is_pecial" class="col-sm-6 form-group ">
            <label for="f_address" class="font_normal_body">楼&emsp;&emsp;层</label>
            <input type="text" style="width:40%" v-model="model.f_floor" class="input_search"
                   placeholder="楼层" />
            <input type="text" style="width:20%" v-model="model.f_floor_suffix" class="input_search"
            />
          </div>
          <div v-if="!is_pecial" class="col-sm-6 form-group "
               :class="[$v.f_room.required ? 'has-error' : 'has-success']">
            <label for="f_address" class="font_normal_body">门&ensp;牌&ensp;号</label>
            <input type="text" style="width:40%" v-model="model.f_room" class="input_search" placeholder="门牌号"
                   v-validate:f_room='{required: true }'/>
            <input type="text" style="width:20%" v-model="model.f_room_suffix" class="input_search"
            />
          </div>
          <div v-if="is_pecial" class="col-sm-6 form-group "
               :class="[$v.f_address.required ? 'has-error' : 'has-success']">
            <label for="f_address" class="font_normal_body">详细地址</label>
            <input type="text" style="width:60%" v-model="model.f_address" class="input_search" placeholder="详细地址"
                   v-validate:f_address='{required: true }'/>
          </div>
          <div class="col-sm-12 form-group" style="margin: 8px 0">
            <label  class="font_normal_body " >备&emsp;&emsp;注</label>
            <textarea class="input_textarea" rows="3" style="width:80%;height: auto !important;" v-model="model.f_comments"></textarea>
          </div>
          <div  class="col-sm-12 form-group button-range">
            <button class="button_search button_spacing" type="button" @click="confirm()" :disabled='!$v.valid'>保存</button>
            <button class="button_clear button_spacing" type="button" @click="cancel()">取消</button>
          </div>

        </div>
      </form>
    </validator>
  </div>
</template>

<script>
  import {HttpResetClass} from 'vue-client'

  let getAreaConfig = async function (self) {
      // 获取气价里面的配置
    await self.$getConfig(self, 'UserAddress')
    console.log('查看地址的配置获取', self.config)
    Object.assign(self.model, self.model, self.config)
  }

  export default {
    title: '用户地址添加',
    data () {
      return {
        // 初始化省市区数据
        pcdslist: [],
        // 初始化街道数据
        streetslist: [],
        // 初始化街道数据
        areaslist: [],
        config: {
          f_building_suffix: '号楼',
          f_unit_suffix: '单元',
          f_floor_suffix: '层',
          f_room_suffix: '室'
        },
        model: {
          f_pcd_id: '',
          f_street_id: '',
          f_comments: '',
          f_residential_area_id: '',
          f_pcd: '',
          f_street: '',
          f_residential_area: '',
          f_slice_area: '',
          f_building: '',
          f_building_start: '',
          f_building_end: '',
          f_building_suffix: '',
          f_unit: '',
          f_unit_start: '',
          f_unit_end: '',
          f_unit_suffix: '',
          f_floor: '',
          f_floor_start: '',
          f_floor_end: '',
          f_floor_suffix: '',
          f_room: '',
          f_room_start: '',
          f_room_end: '',
          f_room_suffix: '',
          // 详细地址
          f_address: '',
          // 单位名称
          f_company: '',
          // 单位地址
          f_company_address: ''
        },
        // 选中所有地址
        addresslist: [],
        is_pecial: false,

        // 公司信息
        curorgid: [this.$login.f.orgid],

        f_orgid: '',

        sliceArea: []
      }
    },
    props: ['f_filialeids', 'is_pecial', 'isSelect', 'row'],
    ready () {
      this.initdata()
      getAreaConfig(this)
    },
    methods: {
      async initdata () {
        this.initAreas(this.f_filialeids)
        await this.initpcds(` f_filialeid = '${this.f_filialeids}'`)
        this.initModel()
      },

      // 初始化片区
      async initAreas (val) {
        if (val) {
          let http = new HttpResetClass()

          let getAllArea = await http.load('POST', '/rs/search', {
            source: 'this.getParentByType($organization$).getAllChildrens().where(row.getType() == $zone$)',
            userid: this.$login.f.id
          }, {resolveMsg: null, rejectMsg: '获取片区出错！！！'})

          let arr = getAllArea.data.filter((res) => {
            return res.parentid == val
          })
          console.log('过滤之后的片区', arr)
          this.sliceArea = []
          arr.forEach((res) => {
            this.sliceArea.push({label: res.name, value: {name: res.name, code: res.number}})
          })
        }
      },

      // 初始化省市区,添加街道
      async initpcds (pconditon) {
        this.pcdslist = []
        let HttpReset = new HttpResetClass()
        let req = await HttpReset.load('POST', 'rs/sql/address_singleTableOrderBy', {
          data: {
            items: '*',
            tablename: 't_pcd',
            orderitem: 'id',
            condition: pconditon
          }
        }, {resolveMsg: null, rejectMsg: '获取地址失败!'})
        let redata = []
        req.data.forEach((row, n) => {
          redata[n] = {
            label: row.f_pcd,
            value: row.id,
            data: row,
            id: row.id
          }
        })
        this.pcdslist = redata
      },
      // 初始化街道 添加小区
      async initstreets (pconditon) {
        this.streetslist = []
        let HttpReset = new HttpResetClass()
        let req = await HttpReset.load('POST', 'rs/sql/address_singleTableOrderBy', {
          data: {
            items: '*',
            tablename: 't_street',
            orderitem: 'id',
            condition: pconditon
          }
        }, {resolveMsg: null, rejectMsg: '获取地址失败!'})
        let redata = []
        req.data.forEach((row, n) => {
          redata[n] = {
            label: row.f_street,
            value: row.id,
            data: row,
            id: row.id
          }
        })
        this.streetslist = redata
      },
      // 初始化小区添加小区
      async initareas (pconditon) {
        if (this.is_pecial) {
          pconditon = pconditon + ` and  f_special='1' `
        }
        this.areaslist = []
        let HttpReset = new HttpResetClass()
        let req = await HttpReset.load('POST', 'rs/sql/address_singleTableOrderBy?pageNo=1&pageSize=9999999', {
          data: {
            items: '*',
            tablename: 't_area',
            orderitem: 'id',
            condition: pconditon
          }
        }, {resolveMsg: null, rejectMsg: '获取地址失败!'})
        let redata = []
        req.data.forEach((row) => {
          redata.push({
            label: row.f_residential_area,
            value: row.id,
            data: row,
            id: row.id
          })
        })
        this.areaslist = redata
      },
      // 省/市/区变化
      async pcdChange (val) {
        console.log('省/市/区变化', val)
        if (val) {
          // 那就把[小区，街道]重新组织一下
          await this.initstreets(` f_filialeid = '${this.f_filialeids}' and f_pcd_id ='${val}' `)
          if (this.model.f_street_id) {
            if (this.findbyid(this.streetslist, this.model.f_street_id)) {
              let pcd_id = this.findbyid(this.streetslist, this.model.f_street_id).f_pcd_id
              if (pcd_id != val) {
                this.model.f_street_id = ''
              }
            } else {
              this.model.f_street_id = ''
            }

            // 那就把[小区，街道]重新组织一下
            if (this.model.f_street_id) {
              await this.initareas(` f_street_id ='${this.model.f_street_id}' `)
              if (this.model.f_residential_area_id) {
                if (this.findbyid(this.areaslist, this.model.f_residential_area_id)) {
                  let pcd_id = this.findbyid(this.areaslist, this.model.f_residential_area_id).f_pcd_id
                  if (pcd_id != val) {
                    this.model.f_residential_area_id = ''
                  }
                } else {
                  this.model.f_residential_area_id = ''
                }
              }
            }
          }
        }
        this.$resetValidation()
      },
      // 小区变化
      areaChange (val) {
        console.log('小区变化', val, this.model)
        if (val) {
          let getArea = this.areaslist.filter((res) => {
            return res.id = this.model.f_residential_area_id
          })
          if (getArea.length > 0) {
            console.log('获取小区数据', getArea[0].data)
            this.model.slice_area = [{name: getArea[0].data.f_slice_area, code: getArea[0].data.f_area_code}]
          }
        }
        this.$resetValidation()
      },

      // 街道变化
      async streetChange (val) {
        console.log('街道变化', val)
        if (this.streetslist[0]) {
          var street = ''
          this.streetslist.forEach((item) => {
            if (item.id === val) {
              street = item.label
            }
          })
          this.model.f_address = street
        }
        if (val) {
          // 那就把[小区]重新组织一下
          await this.initareas(` f_street_id ='${val}' `)
          if (this.model.f_residential_area_id) {
            if (this.findbyid(this.areaslist, this.model.f_residential_area_id)) {
              let street_id = this.findbyid(this.areaslist, this.model.f_residential_area_id).f_street_id
              if (street_id != val) {
                this.model.f_residential_area_id = ''
              }
            } else {
              this.model.f_residential_area_id = ''
            }
          }
        }
        this.$resetValidation()
      },

      getorg (val) {
        this.f_orgid = val[0]
      },

      initModel () {
        if (this.row) {
          this.cleardata()
          this.model = Object.assign({}, this.model, this.row)
          // 处理片区代码
          this.model.slice_area = [{
            name: this.model.f_slice_area,
            code: this.model.f_area_code
          }]
        }
      },
      // 保存
      async confirm () {
        let res = await this.saveonedata()
        console.log('地址保存数据', res)
        if (!this.isSelect) {
          this.model.id = res.data.id
          // let condition = `id = '${res.data.id}'`
          // let getAddress = await this.$resetpost('rs/sql/address_files', {data: {condition: condition,orderitem: 'f_create_date desc'}}, {resolveMsg:null, rejectMsg: '获取地址详情出错'})
          // console.log('获取详细地址信息', getAddress)
          this.$dispatch('confirmaddress', this.model)
        }
        this.cleardata()
        this.$dispatch('confirm')
      },
      // 保存一户信息
      async saveonedata () {
        this.model.f_create_person = this.$login.f.name
        this.model.f_filialeid = this.f_filialeids
        this.model.f_operator = this.$login.f.name
        this.model.f_operatorid = this.$login.f.id
        this.model.f_orgid = this.$login.f.orgid
        this.model.f_orgname = this.$login.f.orgs
        this.model.f_depid = this.$login.f.depids
        this.model.f_depname = this.$login.f.deps
        if (this.model.slice_area) {
          if (this.model.slice_area.length > 0) {
            this.model.f_slice_area = this.model.slice_area[0].name
            this.model.f_area_code = this.model.slice_area[0].code
          }
        }
        if (this.is_pecial) {
          // 非民用
          this.model.f_special = '1'
          this.model.f_building_suffix = ''
          this.model.f_unit_suffix = ''
          this.model.f_floor_suffix = ''
          this.model.f_room_suffix = ''
          this.model.f_pcd = this.findbyid(this.pcdslist, this.model.f_pcd_id).f_pcd
          this.model.f_street = this.findbyid(this.streetslist, this.model.f_street_id).f_street
        } else {
          // 民用
          this.model.f_pcd = this.findbyid(this.pcdslist, this.model.f_pcd_id).f_pcd
          this.model.f_street = this.findbyid(this.streetslist, this.model.f_street_id).f_street
          this.model.f_residential_area = this.findbyid(this.areaslist, this.model.f_residential_area_id).f_residential_area
          this.model.f_address = this.model.f_residential_area + (this.model.f_building ? this.model.f_building + this.model.f_building_suffix : '') + (this.model.f_unit ? this.model.f_unit + this.model.f_unit_suffix : '') + (this.model.f_floor ? this.model.f_floor + this.model.f_floor_suffix : '') + this.model.f_room + this.model.f_room_suffix
        }
        return await this.$resetpost('rs/logic/address_updateuseraddress', this.model)
      },
      cancel () {
        if (!this.isSelect) {
          this.$dispatch('confirmaddress', this.model)
        }
        this.cleardata()
        this.$dispatch('cancel')
      },
      cleardata () {
        this.model = {
          f_pcd_id: '',
          f_street_id: '',
          f_residential_area_id: '',
          f_pcd: '',
          f_comments: '',
          f_street: '',
          f_residential_area: '',
          f_slice_area: '',
          f_building: '',
          f_building_start: '',
          f_building_end: '',
          f_building_suffix: this.config.f_building_suffix,
          f_unit: '',
          f_unit_start: '',
          f_unit_end: '',
          f_unit_suffix: this.config.f_unit_suffix,
          f_floor: '',
          f_floor_start: '',
          f_floor_end: '',
          f_floor_suffix: this.config.f_floor_suffix,
          f_room: '',
          f_room_start: '',
          f_room_end: '',
          f_room_suffix: this.config.f_room_suffix,
          // 详细地址
          f_address: '',
          // 单位名称
          f_company: '',
          // 单位地址
          f_company_address: ''
        }
      },

      // 根据名字找数据
      findbyid (list, name) {
        var result
        list.forEach((row, n) => {
          if (name == row.value) {
            result = row.data
          }
        })
        return result
      }
    },
    watch: {
      // 分公司变化
      'f_filialeids' () {
        if (this.model.f_filialeid) {
          if (this.model.f_filialeid != this.f_filialeids) {
            this.$dispatch('cancel')
          }
        }
        this.cleardata()
        this.initdata()
      },
      'row' () {
        this.initdata()
      }
    }
  }
</script>
