<template>
  <div class="container">
    <div class="block">
      <van-cell title="头像" required>
        <template>
          <van-image width="37" height="37" :src="userInfo.headImgUrl" round />
        </template>
      </van-cell>
      <van-field label="姓名"  v-model="surName" placeholder="请输入" />
      <van-cell title="性别">
        <van-radio-group class="gender" v-model="gender">
          <van-radio :name="0">男</van-radio>
          <van-radio :name="1" style="margin-left: 50px">女</van-radio>
        </van-radio-group>
      </van-cell>
      <van-field label="身份证号码"  v-model="idNum" placeholder="请输入" />
      <template>
        <van-field label="手机号"  v-model="mobile" placeholder="请输入" />
        <van-field label="验证码"  v-model="smsCode" placeholder="请输入" v-if="type !== 'edit'">
          <template #button>
            <van-button size="mini" round type="info" v-if="time === 60" @click="getCode">获取验证码</van-button>
            <van-button size="mini" round type="info" v-else disabled>{{ time }}s后重试</van-button>
          </template>
        </van-field>
      </template>
      <!--    </div>
    <div class="block">-->
      <Picker
        required
        label="所在街道"
        placeholder="请选择"
        v-model="streetId"
        :items="streetOptions"
        @change="e => setVal('street', e, 'getChildAgencyByPid')"
      />
      <Picker
        required
        label="所在社区"
        placeholder="请选择"
        v-model="communityId"
        :items="communityOptions"
        @change="e => setVal('community', e, 'getQuartersForCommunity')"
      />
      <!--      <Picker
        required
        label="小区"
        placeholder="请选择"
        v-model="quarterId"
        :items="quarterOptions"
        @change="e => setVal('quarter', e, 'buildingoption')"
      />
      <Picker
        required
        label="楼栋"
        placeholder="请选择"
        v-model="buildingId"
        :items="buildingOptions"
        @change="e => setVal('building', e, 'unitoption')"
      />
      <Picker
        required
        label="单元号"
        placeholder="请选择"
        v-model="unitId"
        :items="unitOptions"
        @change="e => setVal('unit', e, 'houseoption')"
      />
      <Picker
        required
        label="门牌号"
        placeholder="请选择"
        v-model="houseNumberId"
        :items="houseOptions"
        @change="e => setVal('houseNumber', e)"
      />-->
    </div>
    <Perfect v-if="type === 'edit'" />
    <van-button round block @click="submit" color="linear-gradient(to right, #81B5FB, #3E92FF)">提交</van-button>
  </div>
</template>

<script>
import Picker from '@/components/Picker'
import Perfect from '@/components/Perfect'
import {
  buildingoption,
  getAllAgencyStreet,
  getChildAgencyByPid,
  getQuartersForCommunity,
  editUser,
  houseoption,
  register,
  sendsmscode,
  unitoption
} from '@/api/user'
var leftTime
export default {
  name: 'userInfo',
  components: { Picker, Perfect },
  data() {
    return {
      form: {},
      jiedaoOptions: [],
      time: 60,
      userInfo: {},
      mobile: '',
      smsCode: '',
      surName: '',
      gender: '',
      userId: '',
      streetId: '',
      communityId: '',
      quarterId: '',
      buildingId: '',
      unitId: '',
      houseNumberId: '',
      gridId: '',
      customerId: '',
      homeId: '',
      streetOptions: [],
      communityOptions: [],
      quarterOptions: [],
      buildingOptions: [],
      unitOptions: [],
      houseOptions: [],
      type: '',
      city: '',
      street:"",
      district:"",
      idNum:""
    }
  },

  mounted() {
    this.init()
  },
  destroyed() {
    clearInterval(leftTime)
  },
  watch: {
    '$route.params.type'() {
      this.init()
    }
  },
  methods: {
   async init() {
      this.type = this.$route.params.type ? this.$route.params.type : ''
      document.title = this.$route.params.type === 'edit' ? '编辑' : '注册'
      this.userInfo = this.$store.state.app.userInfo
      if (this.type === 'edit') {
        this.surName = this.userInfo.realName;
        this.gender = this.userInfo.sex;
        let streetId = this.userInfo.orgIdPath.split(':');
        this.streetId = streetId[streetId.length - 2]
        await this.getChildAgencyByPid()
        this.customerId = this.userInfo.customerId;
        this.communityId = this.userInfo.agencyId;
        this.idNum = this.userInfo.idNum;
        this.mobile = this.userInfo.mobile;
        this.$nextTick(() => {
          this.getAllAgencyStreet()
          this.getChildAgencyByPid()
          console.log(this.streetId, 'this.streetId')
        })
  

        /*        this.quarterId = this.userInfo.quarterId
        this.buildingId = this.userInfo.buildingId
        this.unitId = this.userInfo.unitId
        this.houseNumberId = this.userInfo.houseNumberId
        this.homeId = this.userInfo.homeId
        this.gridId = this.userInfo.gridId
        this.getQuartersForCommunity()
        this.buildingoption()
        this.unitoption()
        this.houseoption()*/
      } else {
        // 初始化腾讯地图
        this.geolocation = new qq.maps.Geolocation('LWBBZ-TIGC3-VFP3L-YNMWH-FJB7T-JFBLO', 'myapp')
        // 获取定位
        this.getMyLocation()
      }
    },
    // 获取当前位置
    getMyLocation() {
      this.geolocation.getLocation(this.showPosition, this.errorPosition) //开启定位
    },
    // 定位成功
    showPosition(position) {
      this.longitude = position.lng
      this.latitude = position.lat
      this.address = position.city + position.addr
      this.city = position.city
      this.getAllAgencyStreet()
    },
    errorPosition() {
      console.log('定位失败，再次进行定位')
    },
    submit() {
      console.log(this.gender);
      let params = {
        ...this.userInfo
      }
      params.agencyId = this.communityId;
      params.gender = this.gender;
      params.realName = this.surName;
      params.idNum = this.idNum;
      params.mobile = this.mobile;
      if (this.type !== 'edit') {
        params.mobile = this.mobile
        params.smsCode = this.smsCode
        params.surName = this.surName
        if (!params.realName) {
          this.$toast.fail('请输入姓名')
          return
        }
        if (!params.mobile) {
          this.$toast.fail('请输入手机号')
          return
        }
        if (!params.smsCode) {
          this.$toast.fail('请输入验证码')
          return
        }
      } else {
        params.realName = this.surName
        if (!params.realName) {
          this.$toast.fail('请输入姓名')
          return
        }
      }
      if (!this.street) {
        this.$toast.fail('请选择所在街道')
        return
      }
      if (!this.district) {
        this.$toast.fail('请选择所在社区')
        return
      }
      /* if (!params.quarterId) {
        this.$toast.fail('请选择小区')
        return
      }
      if (!params.buildingId) {
        this.$toast.fail('请选择楼栋')
        return
      }
      if (!params.unitId) {
        this.$toast.fail('请选择单元号')
        return
      }
      if (!params.houseNumberId) {
        this.$toast.fail('请选择门牌号')
        return
      }*/
      if (this.type !== 'edit') {
        register(params).then(res => {
          localStorage.setItem('token', res.token)
          this.$toast.success('提交成功')
          this.$router.back()
        })
      } else {
        editUser(params).then(() => {
          this.$toast.success('修改成功')
          this.$router.back()
        })
      }
    },
    getCode() {
      if (!this.mobile) {
        this.$toast.fail('请输入手机号')
        return false
      }
      if (!/1[3456789]\d{9}/.test(this.mobile)) {
        this.$toast.fail('手机号格式错误')
        return false
      }
      sendsmscode({
        mobile: this.mobile
      }).then(() => {
        leftTime = setInterval(() => {
          if (this.time > 0) {
            this.time--
          } else {
            this.time = 60
            clearInterval(leftTime)
          }
        }, 1000)
      })
    },
    setVal(key, val, method) {
      console.log(key, val, method,"url");
   
      console.log(this.street, 'street');
      if (key === 'street') {
        this.communityId = ''
        this.customerId = val.customerId
        this.street=val.label;
        this.communityOptions = []
        this.quarterOptions = []
        this.buildingOptions = []
        this.unitOptions = []
        this.houseOptions = []
      }

      if (key === 'community') {
        this.quarterId = ''
        this.gridId = ''
        this.district=val.label
        console.log(this.district, 'district');
        this.quarterOptions = []
        this.buildingOptions = []
        this.unitOptions = []
        this.houseOptions = []
      }
      if (key === 'quarter') {
        this.gridId = val.gridId
        this.buildingId = ''
        this.buildingOptions = []
        this.unitOptions = []
        this.houseOptions = []
      }
      if (key === 'building') {
        this.unitId = ''
        this.unitOptions = []
        this.houseOptions = []
      }
      if (key === 'unit') {
        this.houseNumberId = ''
        this.houseOptions = []
      }
      if (key === 'houseNumber') {
        this.houseNumberId = val.label
        this.homeId = val.value
        this.houseOptions = []
      } else {
        this[key + 'Id'] = val.value
      }

      if (method) {
        this[`${method}`]()
      }
    },
    // 获取街道
    getAllAgencyStreet() {
      getAllAgencyStreet({}).then(res => {
    
        this.streetOptions = res
          ? res.map(item => {
            return {
              label: item.organizationName,
              value: item.id,
              customerId: item.customerId
            }
          })
          : []
          console.log(this.streetOptions, 'resresres')
        this.communityOptions = []
        console.log(this.city)
        if (this.city === '青岛市') {
          this.streetOptions.forEach(item => {
            if (item.label === '海伦路街道') {
              this.streetId = item.value
              this.customerId = item.customerId
              console.log(item)
            }
          })
          console.log(this.streetOptions,"wrf ");
          this.getChildAgencyByPid()
        }
      })
    },
    // 获取社区
    getChildAgencyByPid() {
      getChildAgencyByPid({
        pid: this.streetId
      }).then(res => {
        this.communityOptions = res
          ? res.map(item => {
            return {
              label: item.organizationName,
              value: item.id
            }
          })
          : []
        // this.quarterOptions = []
      })
    },
    // 获取小区
    getQuartersForCommunity() {
      getQuartersForCommunity({
        agencyId: this.communityId
      }).then(res => {
        this.quarterOptions = res
          ? res.map(item => {
            return {
              label: item.label,
              value: item.value,
              gridId: item.pid
            }
          })
          : []
        // this.buildingOptions = []
      })
    },
    // 获取楼栋
    buildingoption() {
      buildingoption({
        quartersId: this.quarterId
      }).then(res => {
        this.buildingOptions = res
          ? res.map(item => {
            return {
              label: item.label,
              value: item.value
            }
          })
          : []
        // this.unitOptions = []
      })
    },
    // 获取单元
    unitoption() {
      unitoption({
        buildingId: this.buildingId
      }).then(res => {
        this.unitOptions = res
          ? res.map(item => {
            return {
              label: item.label,
              value: item.value
            }
          })
          : []
        // this.houseOptions = []
      })
    },
    // 获取房号
    houseoption() {
      houseoption({
        unitId: this.unitId
      }).then(res => {
        this.houseOptions = res
          ? res.map(item => {
            return {
              label: item.label,
              value: item.value
            }
          })
          : []
      })
    }
  }
}
</script>

<style scoped lang="less">
@import './index';
</style>
