<template>
  <div class="auto">
    <validator name='v' >
      <div class="auto">
        <div class="flex-row lb"><label style="margin-left: 6px">小区信息</label></div>
        <div class="flex-row auto box">
          <div class="addresstitle"><label>小区默认表具信息</label></div>
          <div class="addressbody">
            <form class="form-horizontal" style="flex: 1;">
              <div class="form-group auto">
                <div class="col-sm-3 average" :class="[$v.type.required ? 'select-error' : '']">
                  <input type="text" v-show="false" v-model="$refs.type.selectedItems" v-validate:type='{required: true }'>
                  <v-select :value.sync="model.f_user_type" v-model="model.f_user_type" :value-single="true"
                            :options='usertypes' placeholder='用户类型' close-on-select v-ref:type></v-select>
                </div>
                <div class="col-sm-3 average" :class="[$v.nature.required ? 'select-error' : '']">
                  <input type="text" v-show="false" v-model="$refs.nature.selectedItems" v-validate:nature='{required: true }'>
                  <v-select :value.sync="model.f_gasproperties" v-model="model.f_gasproperties"  :value-single="true"
                            :options='gasproperties' placeholder='用气性质'
                            close-on-select v-ref:nature></v-select>
                </div>
                <div class="col-sm-3 average" :class="[$v.f_brand.required ? 'select-error' : '']" >
                  <input type="text" v-show="false" v-model="$refs.f_brand.selectedItems" v-validate:f_brand='{required: true }'>
                  <v-select :value.sync="model.f_meter_brand" :options='meterbrands' placeholder='气表品牌' close-on-select  :value-single="true"
                            v-model='model.f_meter_brand' v-ref:f_brand></v-select>
                </div>
                <div class="col-sm-3 average" :class="[$v.f_style.required ? 'select-error' : '']">
                  <input type="text" v-show="false" v-model="$refs.f_style.selectedItems" v-validate:f_style='{required: true }'>
                  <v-select :value.sync="model.f_meter_style" :options='meterstyle' placeholder='气表型号' close-on-select  :value-single="true" v-model='model.f_meter_style' v-ref:f_style></v-select>
                </div>
                <div class="col-sm-3 average" :class="[$v.pricetype.required ? 'select-error' : '']">
                  <input type="text" v-show="false" v-model="$refs.pricetype.selectedItems" v-validate:pricetype='{required: true }'>
                  <v-select :value.sync="model.f_price_type" v-model="model.f_price_type"  :value-single="true"
                            :options='f_price_types' placeholder='气价类型'
                            close-on-select v-ref:pricetype></v-select>
                </div>
              </div>
              <div class="form-group auto">
                <div class="col-sm-3 average" :class="[$v.pricename.required ? 'select-error' : '']">
                  <input type="text" v-show="false" v-model="$refs.pricename.selectedItems" v-validate:pricename='{required: true }'>
                  <v-select :value.sync="model.f_price_name" v-model="model.f_price_name"  :value-single="true"
                            :options='pricenames' placeholder='气价名称'
                            close-on-select v-ref:pricename></v-select>
                </div>
                <div class="col-sm-3 average" >
                  <v-select :value.sync="model.f_position" v-model="model.f_position"  :value-single="true" :options='positions'
                            placeholder='安装位置' close-on-select ></v-select>
                </div>
                <div class=" col-sm-3 average" >
                  <v-select :value.sync="model.f_inputtor" v-model="model.f_inputtor"  :value-single="true"
                            :options='inputtores' placeholder='　抄表员' close-on-select ></v-select>
                </div>
                <div class="col-sm-3 average" >
                  <v-select :value.sync="model.f_adjustable_id" :options='adjustables' placeholder='　调压箱' close-on-select :value-single="true" v-model='model.f_adjustable_id'  :search='true' ></v-select>
                </div>
                <div class="col-sm-3 average" >
                  <v-select :value.sync="model.f_slice_area" v-model="model.f_slice_area"  :value-single="true"
                            :options='sliceArea' placeholder='片区/管理站' close-on-select></v-select>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </validator>
    <div  class="form-group auto button" style="overflow: auto">
      <button type="button" class="btn btn-success" :disabled="!$v.valid" @click="this.$emit('addchild')" >保存</button>
      <button type="button" class="btn btn-info" @click="this.$emit('signout')" >取消</button>
    </div>
  </div>
</template>

<script>
  import co from 'co'

  let getMeterType = function * (self) {
    if (self.row) {
      let result = yield self.$resetpost('rs/sql/querySingleTable', {data: {items: 'f_meter_type', tablename: 't_gasbrand', condition: `f_meter_brand = '${self.row.f_meter_brand}'`}}, {resolveMsg: null, rejectMsg: null})
      if (result && result.data.length > 0) {
        console.log('数据格式是神马样子的', result)
        if (result.data[0].f_meter_type === '物联网表') {
          self.viewsee = true
        } else {
          self.viewsee = false
        }
      }
    }
  }

  let areaGen =async function  (self, areaid, parent) {
    let data = {}
    console.log("小区信息parent的值: ", parent)
    console.log("小区信息model的值: ", self.model)
    data.f_area = parent.f_area  //区
    // data.f_slice_area = parent.f_slice_area  //片区
    data.f_slice_area = self.model.f_slice_area  //片区
    data.f_street = parent.f_street //街道
    data.f_residential_area = parent.f_residential_area //小区名称
    data.f_area_address = parent.f_area_address  //详细地址
    data.f_area_id =  areaid  // 地址id
    data.f_areastr = parent.f_areastr  //地址id串
    // 如果数据中有id，不校验小区是存在
    if (self.model.id) {
      data.id = self.model.id
    } else {
      let tablename = 't_area'
      let condition = `f_area_id='${data.f_area_id}'`
      console.log('做小区验证了，，，，condition，', condition)
      let areaRes = await self.$SqlService.singleTable(tablename, condition)
      if (areaRes.data.length > 0) {
        // self.$showAlert('小区已存在, 请重新输入', 'danger', 2000)
        self.model.f_area = ''
        self.model.f_street = ''
        self.model.f_residential_area = ''
        return
      }
    }
    data.f_filiale = self.model.f_filiale ? self.model.f_filiale : self.$login.f.f_fengongsi
    data.f_filialeids = self.model.f_filialeids ? self.model.f_filialeids : self.$login.f.f_orgids
    data.f_orgstr = self.model.f_orgstr ? self.model.f_orgstr : self.$login.f.orgpathstr
    data.f_outlets = self.$login.f.f_parentname
    data.f_show_way = self.model.f_show_way
    data.f_adjustable_id = self.model.f_adjustable_id!=''?self.model.f_adjustable_id:null
    data.f_price_type = self.model.f_price_type // 气价类型
    data.f_price_name = self.model.f_price_name // 气价名称
    data.f_user_type = self.model.f_user_type // 用户类型
    data.f_gasproperties = self.model.f_gasproperties// 用气性质
    data.f_meter_brand = self.model.f_meter_brand // 气表品牌
    data.f_meter_style = self.model.f_meter_style?self.model.f_meter_style.f_meter_style:'' // 气表型号
    data.f_type = self.model.f_meter_style?self.model.f_meter_style.f_type:''  // 气表型号类型
    data.f_position = self.model.f_position// 表安装位置
    data.f_inputtor = self.model.f_inputtor // 抄表员
    data.f_operator = self.$login.f.name // 操作人
    data.f_operate_date = self.$login.toStandardTimeString() // 操作时间
    // 父表record中插入
    data.f_operat_type = '新建小区'
    data.f_operat_type = `新建${self.model.f_residential_area}`
    data.f_state = '有效'
    data.f_delaypay = 0
    console.log("数据参数附属："+JSON.stringify(data))
    let result = await self.$resetpost('rs/entity/t_area', data)
    // self.$dispatch('success', '新建小区成功', 'new-area-info', data)
    console.log("result=", result.data)
    self.initModel()
    return result
  }

  let validateAddressGen = function * (self) {
    let areaRes = yield self.$resetpost('rs/sql/saleSingleTable', {data: {tablename: 't_area', condition: `f_residential_area = '${self.model.f_residential_area}' and f_street = '${self.model.f_street}'`}}, {resolveMsg: null, rejectMsg: '验证小区，查询出错！！！！'})
    console.log('查询出的小区,,,', areaRes)
    if (areaRes.data.length > 0) {
      self.$showAlert('小区已存在, 请重新输入', 'danger', 0)
      self.model.f_street = ''
      self.model.f_residential_area = ''
    }
  }

  export default {
    title: '新建小区',
    data () {
      return {
        viewsee: false,
        model: {
          f_area: '',
          f_adjustable_id: '',
          f_user_type: '',
          f_meter_brand: '',
          f_show_way: '',
          f_meter_style: '',
          f_inputtor: '',
          f_position: '',
          f_price_type: '',           // 气价表中，气价类型
          f_price_name: '',           // 气价表中，气价名称
          f_gasproperties: ''         // 气价表中，用气性质
        },
        imgdefault: '/images/mainicon/biaopan.png',
      }
    },
    props: ['row','areatype'],
    ready () {
      return co(getMeterType(this)).then(() => {
        if(this.areatype) {
          this.model.f_area = this.areatype
        }
        if (this.row) {
          this.init()
        }
      })
    },
    watch: {
      // 'model.f_meter_brand' (val) {
      //   console.log('val里面是神马', val)
      //   if (val && val.length > 0) {
      //     this.$resetpost('rs/sql/querySingleTable', {data: {items: 'f_meter_type', tablename: 't_gasbrand', condition: `f_meter_brand = '${val[0].f_meter_brand}'`}}, {resolveMsg: null, rejectMsg: null}).then((res) => {
      //       console.log('res是神马呀', res)
      //       if (res.data[0].f_meter_type === '物联网表') {
      //         this.viewsee = true
      //       } else {
      //         this.viewsee = false
      //       }
      //     }).catch((error) => {
      //       console.log('异常提示:' + error)
      //     })
      //   }
      // },
      'row' (val) {
        if (val) {
          this.init() // 初始化区，和片区
        } else {
          this.initModel() // 清空数据
        }
      },
      'areatype' (val) {
        if(val) {
          this.model.f_area =val  // 初始化 区
        } else {
          this.model.f_area = null //清除 区
        }
      },
      'model.f_slice_area' (val) {
        console.log("model.f_slice_area = ", val)
      }
    },
    methods: {
      confirm (areaid, parent) {
        return areaGen(this, areaid, parent).then(() => {
          this.$emit('ready')
        }).catch((error) => {
          this.$emit('error', error)
        })
      },
      cancel () {
        this.$dispatch('clean', '取消新建小区', 'new-area-info')
      },
      validateAddress () {
        console.log('开始地址验证..', this.model.f_street, this.model.f_residential_area)
        if (this.model.f_street && this.model.f_residential_area) {
          co(validateAddressGen(this))
        }
      },
      // 小区初始化
      init() {
        this.model = Object.assign({}, this.model, this.row)
        // 初始化 气表型号
        if(this.model.f_meter_brand) {
          console.log("2222: ", this.model.f_meter_brand)
          this.$GetSaleParam.getGasbrand().forEach((item, index) => {
            // 根据气表品牌 查找气表型号
            if(this.model.f_meter_brand == item.value.f_meter_brand) {
              item.value.gasmodel.forEach((iten, inde) => {
                // 用 f_type 和 f_meter_style 去匹配 气表型号
                if(this.row.f_meter_style==iten.value.f_meter_style && this.row.f_type==iten.value.f_type) {
                  console.log("11111: ",iten, "  ", this.row)
                  this.model.f_meter_style = iten.value
                }
              })
            }
          })
        }
        console.log("初始化 气表型号: ", this.model.f_meter_style)
      },
      initModel () {
        this.model = {
          f_adjustable_id: '',
          f_user_type: '',
          f_meter_brand: '',
          f_show_way: '',
          f_meter_style: '',
          f_inputtor: '',
          f_position: '',
          f_price_type: '',           // 气价表中，气价类型
          f_price_name: '',           // 气价表中，气价名称
          f_gasproperties: ''         // 气价表中，用气性质
        }
      }
    },
    computed: {
      usertypes () {
        console.log('获取用户类型。，。。', this.$appdata.getParam('用户类型'))
        return this.$appdata.getParam('用户类型')
      },
      f_price_types () {
        return this.$appdata.getParam('气价类型')
      },
      viewstyle () {
        return this.$appdata.getParam('显示类型')
      },
      gasproperties () {
        let rs = []
        if (this.model.f_user_type) {
          rs = this.$appdata.getParam(this.model.f_user_type)
        }
        console.log("用气性质: ", rs)
        return rs
      },
      positions () {
        let ret = this.$appdata.getParam('安装位置')
        console.log("安装位置: ", ret)
        return ret
      },
      inputtores () {
        // 获取抄表员
        console.log('获取抄表员', this.$login.f)
        let rs = new Array()
        if (this.$login.f.f_gasman.length > 0) {
          for (let i = 0; i < this.$login.f.f_gasman.length; i++) {
            let temp = {
              label: this.$login.f.f_gasman[i].name,
              value: this.$login.f.f_gasman[i].name
            }
            rs.push(temp)
          }
        }
        // let rs = this.$appdata.getParam('抄表员')
        return rs
      },
      sliceArea () {
        let rs = new Array()
        for (let i = 0; i < this.$login.f.f_allArea.length; i++) {
          let temp = {
            label: this.$login.f.f_allArea[i].label,
            value: this.$login.f.f_allArea[i].label
          }
          rs.push(temp)
        }
        return rs
      },
      meterbrands () {
        let ret = this.$GetSaleParam.getGasbrand()
        let rs = new Array()
        ret.forEach((item, index) =>{
          rs.push({label: item.label, value: item.value.f_meter_brand})
        })
        console.log("气表品牌: ", rs)
        return rs
      },
      meterstyle() {
        let ret = this.$GetSaleParam.getGasbrand()
        console.log("气表型号ret: ", ret)
        let rs = new Array()
        if(this.model.f_meter_brand) {
          ret.forEach((item, index) => {
            if(this.model.f_meter_brand == item.value.f_meter_brand) {
              rs = item.value.gasmodel
              // item.value.gasmodel.forEach((item1, index1) => {
              //   rs.push({label: item1.label, value: item1.value.f_meter_style})
              // })
            }
          })
        }
        console.log("气表型号rs: ", rs)
        return rs
      },
      adjustables () {
        let filter = this.$login.f.f_orgids
        let ret = this.$GetSaleParam.getAdjustable(filter)
        let arr = new Array()
        ret.forEach((item, index) => {
          arr.push({label: `[${item.value.f_adjustable_id}]-${item.label}`, value: item.value.id})
          // arr[index].label = `[${item.value.f_adjustable_id}]-${item.label}`
          // arr[index].value = item.value.id
        })
        return [{label: '全部', value: ''}, ...arr]
      },
      pricenames () {
        let rs = new Array()
        if (this.model.f_user_type && this.model.f_gasproperties && this.model.f_price_type) {
          let params = {
            f_user_type: this.model.f_user_type,
            f_gasproperties: this.model.f_gasproperties,
            f_price_type: this.model.f_price_type,
            filter: this.$login.f.f_fengongsi
          }
          console.log('气价参数。，。。', params)
          let ret = this.$GetSaleParam.getPrice(params)
          ret.forEach((item, index) => {
            rs.push({label: item.label, value: item.value.f_price_name})
            // rs[index].value = item.value.f_price_name
          })
        }
        return rs
      }
    }
  }
</script>
<style lang="less" scoped>
  .average{
    width: 20%;
  }
  v-select{
    width: 110px;
    height: 30px;
    border-radius: 2px;
    border: 1px solid #d0d0d0;
    background-color: #ffffff;
  }
  .box {
    width: 727px;
    height: 175px;
    border-radius: 2px;
    background-color: #fafafa;
    border: 1px solid #999999;
    margin-top: 13px;
  }
  .addresstitle{
    width: 100%;
    height: 20%;
    font-family: PingFangSC-Bold;
    font-size: 16px;
    color: #666666;
    margin-top: 20px;
    margin-left: 20px;
    text-align: left;
  }
  .addressbody{
    margin-top: 60px;
    width: 100%;
    height: auto;
    position: absolute;
  }
  .lb{
    width: 100%;
    padding-left: 8px;
    border: none;
    border-left: 4px solid #3db6ef;
    font-size: 16px;
    font-family: PingFangSC-Bold;
    color: #666666;
    text-align: left;
  }
  .button{
    margin-top: 20px;
  }
</style>
