<template>
  <div>
    <!--表具信息-->
    <validator name='v' :data.sync="data">
      <div class="auto select-overspread form-horizontal repair-bg">
        <div class="bq-parent">
          <blockquote class="blockquote">
            <p>表具信息</p>
          </blockquote>
        </div>
        <div class="panel panel-default auto repair-info-content">
          <div class="panel-body auto repair-info-content compatible">
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group" :class="[$v.f_meternumber.required ? 'has-error' : 'has-success']">
              <label for="f_meternumber" class="lb-left text-justify">表号</label>
              <input id="f_meternumber" v-model="userdata.userinfo.userfiles.f_meternumber" v-validate:f_meternumber="{required: true}" type="text" class="form-control"/>
              <button type="button" name="button" class="btn btn-primary" @click="scan">扫码</button>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group" :class="[$v.f_meter_brand.required ? 'has-error' : 'has-success']">
              <label for="f_meter_brand" class="lb-left text-justify">气表品牌</label>
              <input id="f_meter_brand" v-model="userdata.userinfo.userfiles.f_meter_brand" v-validate:f_meter_brand="{required: true}" type="text" class="form-control">
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group" :class="[$v.f_meter_style.required ? 'has-error' : 'has-success']">
              <label for="f_meter_style" class="lb-left text-justify">气表型号</label>
              <input id="f_meter_style" v-model="userdata.userinfo.userfiles.f_meter_style" v-validate:f_meter_style="{required: true}" type="text" class="form-control">
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group" :class="[$v.f_meter_type.required ? 'has-error' : 'has-success']">
              <label for="f_meter_type" class="lb-left text-justify">气表类型</label>
              <input id="f_meter_type" v-model="userdata.userinfo.userfiles.f_meter_type" v-validate:f_meter_type="{required: true}" type="text" class="form-control">
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group" :class="[$v.f_aroundmeter.required ? 'has-error' : 'has-success']">
              <label for="f_aroundmeter" class="lb-left text-justify">进气方向</label>
              <input type="text"
                     v-show="false"
                     v-model="userdata.userinfo.userfiles.f_aroundmeter"
                     v-validate:f_aroundmeter='{required: true}'>
              <v-select id="f_aroundmeter"
                        :value.sync="userdata.userinfo.userfiles.f_aroundmeter"
                        :value-single="true"
                        :options='aroundmeterlist'
                        placeholder='请选择'
                        close-on-select>
              </v-select>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group" :class="[$v.f_initial_base.required ? 'has-error' : 'has-success']">
              <label for="f_initial_base" class="lb-left text-justify">表基数</label>
              <input id="f_initial_base" v-model="userdata.userinfo.userfiles.f_initial_base" v-validate:f_initial_base="{required: true}" type="number" class="form-control">
            </div>
          </div>
        </div>
      </div>
      <div class="bq-parent">
        <blockquote class="blockquote">
          <input class="magic-checkbox" type="checkbox" id="isStay" v-model="isStay"/>
          <label for="isStay" style="width:150px;padding-bottom: 10px">用户是否入住</label>
        </blockquote>
      </div>
      <!--用户信息-->
      <div class="auto select-overspread form-horizontal repair-bg" v-show="isStay">
        <div class="bq-parent">
          <blockquote class="blockquote">
            <p>用户信息</p>
          </blockquote>
        </div>
        <div class="panel panel-default auto repair-info-content">
          <div class="panel-body auto repair-info-content compatible">
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group">
              <label for="f_user_name" class="lb-left text-justify">用户姓名</label>
              <input id="f_user_name" v-model="userdata.userinfo.f_user_name" type="text" class="form-control"/>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group">
              <label for="f_idnumber" class="lb-left text-justify">身份证号</label>
              <input id="f_idnumber" v-model="userdata.userinfo.f_idnumber" type="text" class="form-control">
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group" v-show="isNotIdNumber">
              <span style="font-size:10px;color: red">输入的身份证号长度不对，或者号码不符合规定！</span>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group">
              <label for="f_user_phone" class="lb-left text-justify">用户电话</label>
              <input id="f_user_phone" v-model="userdata.userinfo.f_user_phone" type="text" class="form-control">
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group">
              <label for="f_price_name" class="lb-left text-justify">住户类型</label>
              <v-select id="f_price_name"
                        :value.sync="userdata.userinfo.f_price_name"
                        :value-single="true"
                        :options='houseTypeOptions'
                        placeholder='请选择'
                        close-on-select>
              </v-select>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group">
              <label for="f_comments" class="lb-left text-justify">备注</label>
              <textarea id="f_comments" class="form-control" cols="30" rows="4" style="resize: vertical;" v-model="userdata.userinfo.f_comments"></textarea>
            </div>
          </div>
        </div>
      </div>
      <!--地址信息-->
      <div class="auto select-overspread form-horizontal repair-bg">
        <div class="bq-parent">
          <blockquote class="blockquote">
            <p>地址信息</p>
          </blockquote>
        </div>
        <div class="panel panel-default auto repair-info-content">
          <div class="panel-body auto repair-info-content compatible">
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group" :class="[$v.f_pcd_id.required ? 'has-error' : 'has-success']">
              <label for="f_pcd_id" class="lb-left text-justify">省市区</label>
              <input type="text"
                     v-show="false"
                     v-model="addressData.f_pcd_id"
                     v-validate:f_pcd_id='{required: true}'>
              <v-select id="f_pcd_id"
                        :value.sync="addressData.f_pcd_id"
                        :value-single="true"
                        :options='pcdslist'
                        placeholder='请选择'
                        close-on-select
                        search="true"
                        @change="pcdChange">
              </v-select>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group" :class="[$v.f_street_id.required ? 'has-error' : 'has-success']">
              <label for="f_street_id" class="lb-left text-justify">街道名称</label>
              <input type="text"
                     v-show="false"
                     v-model="addressData.f_street_id"
                     v-validate:f_street_id='{required: true}'>
              <v-select id="f_street_id"
                        :value.sync="addressData.f_street_id"
                        :value-single="true"
                        :options='streetslist'
                        placeholder='请选择'
                        close-on-select
                        search="true"
                        @change="streetChange">
              </v-select>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group" :class="[$v.f_residential_area_id.required ? 'has-error' : 'has-success']">
              <label for="f_residential_area_id" class="lb-left text-justify">小区名称</label>
              <input type="text"
                     v-show="false"
                     v-model="addressData.f_residential_area_id"
                     v-validate:f_residential_area_id='{required: true}'>
              <v-select id="f_residential_area_id"
                        :value.sync="addressData.f_residential_area_id"
                        :value-single="true"
                        :options='areaslist'
                        placeholder='请选择'
                        close-on-select
                        search="true"
                        @change="areaChange">
              </v-select>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group" :class="[$v.slice.required ? 'has-error' : 'has-success']">
              <label for="f_meter_type" class="lb-left text-justify">片区</label>
              <input type="text"
                     v-show="false"
                     v-model="$refs.slice.selectedItems"
                     v-validate:slice='{required: true}'>
              <v-select id="slice_area"
                        :value.sync="addressData.slice_area"
                        :options='sliceArea'
                        placeholder='片区/管理站'
                        filer-key="name"
                        close-on-select
                        v-ref:slice>
              </v-select>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group" :class="[$v.f_building.required ? 'has-error' : 'has-success']">
              <label for="f_building" class="lb-left text-justify">楼号</label>
              <input id="f_building" v-model="addressData.f_building" v-validate:f_building='{required: true}' type="text" class="form-control" style="width: 70%">
              <input id="f_building_suffix" v-model="addressData.f_building_suffix" type="text" class="form-control" style="width: 30%">
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group" :class="[$v.f_unit.required ? 'has-error' : 'has-success']">
              <label for="f_unit" class="lb-left text-justify">单元</label>
              <input id="f_unit" v-model="addressData.f_unit" v-validate:f_unit='{required: true}' type="text" class="form-control" style="width: 70%">
              <input id="f_unit_suffix" v-model="addressData.f_unit_suffix" type="text" class="form-control" style="width: 30%">
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group" :class="[$v.f_floor.required ? 'has-error' : 'has-success']">
              <label for="f_floor" class="lb-left text-justify">楼层</label>
              <input id="f_floor" v-model="addressData.f_floor" v-validate:f_floor='{required: true}' type="text" class="form-control" style="width: 70%">
              <input id="f_floor_suffix" v-model="addressData.f_floor_suffix" type="text" class="form-control" style="width: 30%">
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 form-input-group" :class="[$v.f_room.required ? 'has-error' : 'has-success']">
              <label for="f_room" class="lb-left text-justify">门牌号</label>
              <input id="f_room" type="text" v-model="addressData.f_room" v-validate:f_room='{required: true}' class="form-control" style="width: 70%">
              <input id="f_room_suffix" type="text" v-model="addressData.f_room_suffix" class="form-control" style="width: 30%">
            </div>
          </div>
        </div>
      </div>
    </validator>
    <!--提交-->
    <div class="panel panel-default auto repair-info-content" style="width: 100%;height: auto">
      <div style="margin: 0 auto;width: 25%">
        <button type="button" name="button" class="col-sm-3 btn btn-primary" :disabled='!$v.valid' @click='summit()'>
          上传档案
        </button>
      </div>
    </div>
    <work-busy :is-busy="isBusy"></work-busy>
  </div>
</template>

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

  export default {
    title: "ApplyOnline",
    data() {
      return {
        userdata: {
          address: {
            id: null
          },
          f_user_type: "民用",
          userinfo: {
            userfiles: {
              f_meternumber: null,
              f_meter_brand: null,
              f_meter_style: null,
              f_meter_type: null,
              f_aroundmeter: null,
              f_initial_base: null,
              f_table_state: "待开通"
            },
            f_price_name: null,
            f_rent_phone: null,
            f_user_phone: null,
            f_user_name: null,
            f_idnumber: null,
            f_comments: null
          },
          devices: [],
          f_operator: Vue.user.ename
        },
        // 是否入住
        isStay: false,
        addressData: {
          f_create_person: Vue.user.name,
          f_filialeid: Vue.user.orgid,
          f_operator: Vue.user.name,
          f_filiale: Vue.user.f_fengongsi,
          f_outlets: Vue.user.f_parentname,
          f_orgstr: Vue.user.orgpathstr,
          f_filialeids: Vue.user.f_orgids,
          f_operatorid: Vue.user.id,
          f_pcd: null,
          f_pcd_id: null,
          f_street: null,
          f_street_id: null,
          f_residential_area: null,
          f_residential_area_id: null,
          f_address: null,
          slice_area: null,
          f_slice_area: null,
          f_area_code: null,
          f_building: null,
          f_building_suffix: "栋",
          f_unit: null,
          f_unit_suffix: "单元",
          f_floor: null,
          f_floor_suffix: "层",
          f_room: null,
          f_room_suffix: "室",
          f_company: "",
          f_company_address: "",
          f_create_date: ''
        },
        //初始化省市区数据
        pcdslist: [],
        //初始化街道数据
        streetslist: [],
        //初始化街道数据
        areaslist: [],
        sliceArea: [],
        aroundmeterlist: [{label: '左表', value: '左表'}, {label: '右表', value: '右表'}],
        houseTypeOptions: [{label: '自有房', value: '自有房'}, {label: '租赁房', value: '租赁房'}],
        isNotIdNumber: false,
        isBusy: false
      }
    },
    async ready() {
      console.log('进入在线报装页面www')
      console.log('Vue.user ===> ' + JSON.stringify(Vue.user))
      await this.initpcds(` f_filialeids = '${Vue.user.f_orgids}'`)
      await this.initAreas(Vue.user.orgid)
      console.log('pcdslist ===> ' + JSON.stringify(this.pcdslist))
      console.log('sliceArea ===> ' + JSON.stringify(this.sliceArea))
    },
    methods: {
      scan() {
        HostApp.__this__ = this
        HostApp.scanCode({callback: "javascript:HostApp.__this__.scanCallback();"})
      },
      scanCallback() {
        let response = HostApp.getCode()
        console.log(`扫码返回值:${response}`)
        if (response.code == 200) {
          this.userdata.userinfo.userfiles.f_meternumber = response.data
        } else {
          this.$showMessage('无法识别该条形码，请调整手机聚焦重试。')
        }
      },
      // 初始化片区
      async initAreas(val) {
        let http = new HttpResetClass()
        let getAllArea = await http.load('POST', `${this.$androidUtil.getProxyUrl()}/rs/search`, {
          source: 'this.getParentByType($organization$).getChildByName($区$).getChildren()',
          userid: Vue.user.id
        }, {resolveMsg: null, rejectMsg: '获取片区出错！！！'})

        // let arr = getAllArea.data.filter((res) => {
        //   return res.parentid == val
        // })  
        let arr = getAllArea.data.filter((res) => {
          return true
        })
        console.log('过滤之后的片区:' + JSON.stringify(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', `${this.$androidUtil.getProxyUrl()}/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', `${this.$androidUtil.getProxyUrl()}/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.usertype) {
          pconditon = pconditon + ` and  f_special='1' `
        }
        this.areaslist = []
        let HttpReset = new HttpResetClass()
        let req = await HttpReset.load('POST', `${this.$androidUtil.getProxyUrl()}/rs/sql/address_singleTableOrderBy`, {
          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(`省/市/区变化 => ${JSON.stringify(val)} => ${JSON.stringify(this.addressData)}`)
        if (val) {
          //那就把[小区，街道]重新组织一下
          await this.initstreets(` f_filialeids = '${Vue.user.f_orgids}' and f_pcd_id ='${val}' `)
          if (this.addressData.f_street_id) {
            if (this.findbyid(this.streetslist, this.addressData.f_street_id)) {
              let pcd_id = this.findbyid(this.streetslist, this.addressData.f_street_id).f_pcd_id
              if (pcd_id != val) {
                this.addressData.f_street_id = ''
              }
            } else {
              this.addressData.f_street_id = ''
            }

            //那就把[小区，街道]重新组织一下
            if (this.addressData.f_street_id) {
              await this.initareas(` f_street_id ='${this.addressData.f_street_id}' `)
              if (this.addressData.f_residential_area_id) {
                if (this.findbyid(this.areaslist, this.addressData.f_residential_area_id)) {
                  let pcd_id = this.findbyid(this.areaslist, this.addressData.f_residential_area_id).f_pcd_id
                  if (pcd_id != val) {
                    this.addressData.f_residential_area_id = ''
                  }
                } else {
                  this.addressData.f_residential_area_id = ''
                }

              }
            }
          }
        }
        this.$resetValidation()
      },
      //小区变化
      areaChange(val) {
        console.log(`小区变化 => ${JSON.stringify(val)} => ${JSON.stringify(this.addressData)}`)
        if (val) {
          let getArea = this.areaslist.filter((res) => {
            return res.id = this.addressData.f_residential_area_id
          })
          if (getArea.length > 0) {
            console.log('获取小区数据', getArea[0].data)
            this.addressData.slice_area = [{name: getArea[0].data.f_slice_area, code: getArea[0].data.f_area_code}]
          }
        }
        this.$resetValidation()
      },
      //街道变化
      async streetChange(val) {
        console.log(`街道变化 => ${JSON.stringify(val)} => ${JSON.stringify(this.addressData)}`)
        if (this.streetslist[0]) {
          var street = ''
          this.streetslist.forEach((item) => {
            if (item.id === val) {
              street = item.label
            }
          })
          this.addressData.f_address = street
        }
        if (val) {
          //那就把[小区]重新组织一下
          await this.initareas(` f_street_id ='${val}' `)
          if (this.addressData.f_residential_area_id) {
            if (this.findbyid(this.areaslist, this.addressData.f_residential_area_id)) {
              let street_id = this.findbyid(this.areaslist, this.addressData.f_residential_area_id).f_street_id
              if (street_id != val) {
                this.addressData.f_residential_area_id = ''
              }
            } else {
              this.addressData.f_residential_area_id = ''
            }

          }
        }
        this.$resetValidation()
      },
      //根据名字找数据
      findbyid(list, name) {
        let result
        list.forEach((row, n) => {
          if (name == row.value) {
            result = row.data
          }
        })
        return result
      },
      getNowDate() {
        let now = new Date()
        let dateStr = ''
        dateStr += now.getFullYear()
        dateStr += '-' + (now.getMonth() + 1)
        dateStr += '-' + now.getDate()
        dateStr += ' ' + now.getHours()
        dateStr += ':' + now.getMinutes()
        dateStr += ':' + now.getSeconds()
        dateStr += '.' + now.getMilliseconds()
        return dateStr
      },
      async createAddress() {
        if (this.addressData.slice_area) {
          if (this.addressData.slice_area.length > 0) {
            this.addressData.f_slice_area = this.addressData.slice_area[0].name
            this.addressData.f_area_code = this.addressData.slice_area[0].code
          }
        }
        this.addressData.f_pcd = this.findbyid(this.pcdslist, this.addressData.f_pcd_id).f_pcd
        this.addressData.f_street = this.findbyid(this.streetslist, this.addressData.f_street_id).f_street
        this.addressData.f_residential_area = this.findbyid(this.areaslist, this.addressData.f_residential_area_id).f_residential_area
        this.addressData.f_address = this.addressData.f_street + this.addressData.f_residential_area + (this.addressData.f_building ? this.addressData.f_building + this.addressData.f_building_suffix : '') + (this.addressData.f_unit ? this.addressData.f_unit + this.addressData.f_unit_suffix : '') + (this.addressData.f_floor ? this.addressData.f_floor + this.addressData.f_floor_suffix : '') + this.addressData.f_room + this.addressData.f_room_suffix
        this.addressData.f_create_date = this.getNowDate()
          console.log("调用创建地址接口参数 ==> " + JSON.stringify(this.addressData))
        let http = new HttpResetClass()
        return await http.load('POST', `${this.$androidUtil.getProxyUrl()}/rs/logic/address_updateuseraddress`, this.addressData)
      },
      async createUserData() {
        let http = new HttpResetClass()
        return await http.load('POST',
          `${this.$androidUtil.getProxyUrl()}/rs/logic/sale_simple_userSave`,
          this.userdata
        )
      },
      async summit() {
        this.isBusy = true
        try {
          // 先创建地址信息
          console.log('创建地址')
          let response = await this.createAddress()
          console.log('createAddressResponse ===> ' + JSON.stringify(response))
          this.userdata.address.id = response.data.id
        } catch (e) {
          console.log('e ===> ' + JSON.stringify(e))
          // 如果地址已存在，使用存在的地址建档
          if (e.status && e.status == 635) {
            console.log('地址已存在，获取已存在地址id')
            let http = new HttpResetClass()
            let data = {
              data: {
                items: 'id',
                tablename: 't_user_address',
                condition: `f_address = '${this.addressData.f_address}'`
              }
            }
            let response = await http.load('POST', `${this.$androidUtil.getProxyUrl()}/rs/sql/querySingleTable`, data)
            console.log('searchAddressResponse ===> ' + JSON.stringify(response))
            if (response.data && response.data.length > 0) {
              this.userdata.address.id = response.data[0].id
            }
          } else {
            this.$showMessage('错误：' + JSON.stringify(e))
            this.isBusy = false
            return
          }
        }
        try {
          // 再建立档案
          console.log('创建档案')
          let response = await this.createUserData()
          console.log('createUserDataResponse ===> ' + JSON.stringify(response))
          if (response.data.status == 200) {
            this.$showMessage('档案创建成功！')
          } else {
            this.$showMessage('档案创建失败！' + JSON.stringify(response.data))
          }
          console.log('创建成功f_userinfo_id ===> ' + JSON.stringify(response.data.f_userinfo_id))
          // 上传成功，重新初始化数据
          Object.assign(this.$data, this.$options.data())
          await this.initpcds(` f_filialeids = '${Vue.user.f_orgids}'`)
          await this.initAreas(Vue.user.orgid)
        } catch (e) {
          console.log('e ===> ' + JSON.stringify(e))
          this.$showMessage('错误：' + JSON.stringify(e))
        }
        this.isBusy = false
      },
    },
    watch: {
      'userdata.userinfo.userfiles.f_meternumber': async function (newVal, oldVal) {
        console.log('newVal ===> ' + JSON.stringify(newVal))
        console.log('oldVal ===> ' + JSON.stringify(oldVal))
        // let response = await this.$resetpost(`${this.$androidUtil.getProxyUrl()}/rs/logic/xxxxxx`, {})
      },
      'userdata.userinfo.f_idnumber'(val) {
        if (val) {
          if (!(/^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/.test(val))) {
            // this.$showAlert('输入的身份证号长度不对，或者号码不符合规定！\n15位号码应全为数字，18位号码末位可以为数字或X。')
            this.isNotIdNumber = true
          } else {
            this.isNotIdNumber = false
          }
        } else {
          this.isNotIdNumber = false
        }
      }
    }
  }
</script>

<style scoped>

</style>