<template>
  <div>
    <tabset v-ref:tabs :close="false" style="height: 450px;">
      <tab header='基本信息'>
        <user-essential-info v-ref:useressential :baseinfo="data.baseinfo" :modify="modify" :old-address="oldAddress" @valid="essentialInfo = true" @invalid="essentialInfo = false"></user-essential-info>
        <!--<no-user-essential-info :baseinfo= "data.baseinfo" :modify="modify" v-if="nonUser" @valid="essentialInfo = true" @invalid="essentialInfo = false"></no-user-essential-info>-->
      </tab>
      <tab header='表具信息'>
        <!-- <user-meter-info :meterinfo="data.meterinfo" :usertype= "data.baseinfo.base.f_user_type"
        :gasproperties="data.baseinfo.base.f_gasproperties" @valid="meterInfo = true"
        @invalid="meterInfo = false"></user-meter-info> -->
        <!-- <user-meter-info :meterinfo="data.meterinfo" :usertype= "data.baseinfo.base.f_user_type"
        :gasproperties="data.baseinfo.base.f_gasproperties" @self-validator="isDisable()"></user-meter-info> -->
        <user-meter-info :meterinfo="data.meterinfo" :metervalid.sync="meterInfo" v-ref:meter :f_userinfo_id="data.baseinfo.base.f_userinfo_id"></user-meter-info>
      </tab>
      <tab header='设备信息'>
        <user-device-info :devicesinfo="data.devicesinfo" :userinfoid='data.baseinfo.base.f_userinfo_id'></user-device-info>
      </tab>
      <tab header='发票及其他信息'>
        <user-paper-info :baseinfo="data.baseinfo"></user-paper-info>
      </tab>
      <tab header='附件管理'>
        <upload :blodid="blodid" :reload-all="true"></upload>
      </tab>
    </tabset>
    <div class="form-horizontal auto">
      <div class="form-group">

        <div class="col-sm-offset-7 col-sm-3">
          <!-- || !meterInfo  -->
          <!-- <button type="button" class="btn btn-success" @click="confirm()" :disabled="!(essentialInfo && meterInfo)"> -->
          <button type="button" class="btn btn-success" @click="confirm()" title="演示系统暂不支持" :disabled="true">
            保&nbsp;&nbsp;&nbsp;存
          </button>
          <button type="button" class="btn btn-default" @click="cancel()" id='userfiles-useGenInf-取消'>
            取&nbsp;&nbsp;&nbsp;消
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

  let getFileGen = async function (self, data) {
    let result = await self.$resetpost('rs/logic/getFilesDetail', data, {resolveMsg: null, rejectMsg: '用户详细信息加载失败，请重新选择，如果多次失败，请检查系统是否正常！'})
    console.log('获取档案信息', result)
    self.data = result.data
    //更新地址
    // self.data.baseinfo.base.f_address = data.f_address
    //修改附件临时id为表档案id
    self.blodid = self.data.baseinfo.base.f_userinfo_id
    self.checkout()
    console.log('附件id', self.blodid)
  }

  let loadStreetAndResGen = async function (self) {
    // 获取区县
    let loc = self.$login.f.f_orgids.split('.')
    // 获取区县
    console.log('初始化查询区县')
    let condition = `f_type='区' and f_locationId = ${loc[loc.length-2]}`
    let res = await self.$resetpost('rs/sql/singleTable_OrderBy', {data: {items: 'id,f_name',tablename: 't_address',orderitem: 'f_name' ,condition: condition}},{resolveMsg: null, rejectMsg: '获取区县失败!'})
    let areas = []
    res.data.forEach((row)=>{
      areas.push({label:row.f_name, value:{id: row.id, name: row.f_name}})
      if (row.f_name === self.data.baseinfo.base.f_area) {
        self.data.baseinfo.base.f_area = {id: row.id, name: row.f_name}
        self.oldAddress.f_area_id = row.id
      }
    })
    self.$refs.useressential.areas = areas

    // 获取街道
    console.log('初始化查询街道', self.data.baseinfo.base)
    if (self.data.baseinfo.base.f_area.id) {
      let streetCondition = `f_type='街道' and f_parentId = ${self.data.baseinfo.base.f_area.id}`
      let getStreet = await self.$resetpost('rs/sql/singleTable_OrderBy', {data: {items: 'id,f_name',tablename: 't_address',orderitem: 'f_name' ,condition: streetCondition}},{resolveMsg: null, rejectMsg: '获取街道失败!'})
      let streets = []
      getStreet.data.forEach((row)=>{
        streets.push({label:row.f_name, value:{id: row.id, name: row.f_name}})
        if (row.f_name === self.data.baseinfo.base.f_street) {
          self.data.baseinfo.base.f_street = {id: row.id, name: row.f_name}
          self.oldAddress.f_street_id = row.id
        }
      })
      self.$refs.useressential.streets = streets
    } else {
      self.data.baseinfo.base.f_street = ''
    }

    // 获取小区
    console.log('初始化查询小区')
    if (self.data.baseinfo.base.f_street.id) {
      let resCondition = `f_type='小区' and f_parentId = ${self.data.baseinfo.base.f_street.id}`
      let getResCondition = await self.$resetpost('rs/sql/singleTable_OrderBy', {data: {items: 'id,f_name',tablename: 't_address',orderitem: 'f_name' ,condition: resCondition}},{resolveMsg: null, rejectMsg: '获取小区失败!'})
      let residentials = []
      getResCondition.data.forEach((row)=>{
        residentials.push({label:row.f_name, value:{id: row.id, name: row.f_name}})
        if (row.f_name === self.data.baseinfo.base.f_residential_area) {
          self.data.baseinfo.base.f_residential_area = {id: row.id, name: row.f_name}
          self.oldAddress.f_residential_area_id = row.id
        }
      })
      self.$refs.useressential.residentials = residentials
    } else {
      self.data.baseinfo.base.f_residential_area = ''
    }

  }

  export default {
    title: '综合信息',
    props: ['row', 'areainfo', 'nonUser', 'modify', 'userinfoid'],
    data () {
      return {
        data: {
          baseinfo: {
            base: {
              f_user_state: '',
              f_user_type: '',
              f_credentials: '',
              f_cost_type: '',
              f_gasproperties: '',
              f_paper_type: ''
            },
            bank: {
              f_bank_name: ''
            }
          },
          meterinfo: [],
          devicesinfo: []
        },
        essentialInfo: false,
        meterInfo: false,
        addressinit: false, //是否重新加载地址组件
        blodid: '', //附件的临时id

        areas: [],
        streets: [],
        residentials: [],

        oldAddress: {},
      }
    },
    ready () {
      this.blodid = '临时id'+Date.now()
      console.log('ready，，，', this.row, this.areainfo)
      if (this.row && !this.areainfo) { // 修改用户
        this.areaGen(this.row)
      } else if (!this.row && this.areainfo) { // 小区批量建档
        // 将小区信息转化为综合信息的格式
        this.areainfoInUser(this.areainfo)
      }
    },
    watch: {
      'row' (val) {
        console.log('观察row', val)
        if (val) {
          this.areaGen(val)
        } else {
          this.areainfoInUser(this.areainfo)
        }

      },
      'areainfo' (val) {
        console.log('小区观察。。', val)
        if (val) {
          this.$refs.meter.clearMeter()
          this.blodid = '临时id'+Date.now()
          this.areainfoInUser(val)
        }
      },
      'row || areainfo'(){
        this.addressinit = false
      }
      // 'nonUser' () {
      //   console.log('非民用建档观察...')
      //   this.nonUserGen()
      // }
    },
    methods: {
      confirm () {
        console.log('档案保存之前，。。。', this.data)
        let hasMachine = false
        for (let i = 0; i < this.data.meterinfo.length; i++) {
          if (this.data.meterinfo[i].gasbrand[0].f_meter_type === '机表') {
            hasMachine = true
            break
          }
        }
        this.$FileService.fileSave(this.data).then((res) => {
          // if (this.areainfo) {
          //   // 小区批量建档
          //   this.$dispatch('build-success', res.data.result[0])
          //   this.$refs.meter.clearMeter()
          //   this.areainfoInUser(this.areainfo)
          // } else if (this.nonUser) {
          //   this.$dispatch('success')
          // } else {
          // }
          this.$dispatch('success')
          // if (hasMachine) {
          //   this.userinfoid = res.data.result[0].f_userinfo_id
          //   this.show = true
          //   this.$refs.admiss.admiss.search(this.userinfoid)
          // }
          //刷新地址树
          // this.$dispatch('refreshtree',this.addressinit)

        }).catch((error) => {
          if (error.status === 603) {
            this.$error('重复提交')
            return
          }
          this.$dispatch('error', '档案保存', this.data, error)
        })
      },
      areaGen (data) {
        data.f_userinfo_id = data.f_userinfo_id + ''
        getFileGen(this, data)
      },
      nonUserGen () {
        this.data = {
          baseinfo: {
            base: {
              f_area: this.areainfo ? this.areainfo.f_area : '',
              f_slice_area: null,
              f_street: this.areainfo ? this.areainfo.f_street : '',
              f_address: this.areainfo ? this.areainfo.f_address : '',
              f_user_state: '正常',
              f_gasproperties: '',
              f_credentials: '',
              pricetype: '',
              pricename: '',
              f_adjustable: '',
              f_user_type: '非民用',
              f_cost_type: '现金缴费'
            },
            bank: {}
          },
          meterinfo: [{
            gasbrand: '',
            gasmodel: '',
            gasmodeltype: '',
            f_inputtor: '',
            f_position: '',
            f_meter_base: 0,
            f_aroundmeter: '左表',
            f_install_date: this.$login.toStandardTimeString(),
            f_gas_date: this.$login.toStandardTimeString()
          }],
          devicesinfo: []
        }
        // this.data.baseinfo.base.f_user_type = this.data.baseinfo.base.f_user_type ? [this.data.baseinfo.base.f_user_type] : ''
        this.checkout()
      },
      cancel () {
        this.$dispatch('clean', '取消档案修正', 'user-general-info', this.row)
      },
      checkout () {
        // 对收到的综合信息进行校验（主要目的是为了防止下拉框没有默认值）
        // 对综合用户基本信息进行校验

        // 将oldAddress 置为空，
        this.oldAddress = {}

        this.data.baseinfo.base.f_user_state = this.data.baseinfo.base.f_user_state ? [this.data.baseinfo.base.f_user_state] : ['正常']
        this.data.baseinfo.base.f_user_type = this.data.baseinfo.base.f_user_type ? [this.data.baseinfo.base.f_user_type] : ''
        this.data.baseinfo.base.f_credentials = this.data.baseinfo.base.f_credentials ? [this.data.baseinfo.base.f_credentials] : ['身份证']
        this.data.baseinfo.base.f_cost_type = this.data.baseinfo.base.f_cost_type ? [this.data.baseinfo.base.f_cost_type] : ['现金缴费']
        this.data.baseinfo.base.f_gasproperties = this.data.baseinfo.base.f_gasproperties ? [this.data.baseinfo.base.f_gasproperties] : ''
        this.data.baseinfo.base.f_paper_type = this.data.baseinfo.base.f_paper_type ? [this.data.baseinfo.base.f_paper_type] : ['国税发票']
        this.data.baseinfo.bank.f_bank_name = this.data.baseinfo.bank.f_bank_name ? [this.data.baseinfo.bank.f_bank_name] : ['中国银行']
        this.data.baseinfo.base.pricetype = this.data.baseinfo.base.pricetype ? [this.data.baseinfo.base.pricetype] : ''
        loadStreetAndResGen(this)
        if (this.data.baseinfo.base.pricename) {
          let names = this.getPricenames(this.data.baseinfo.base.f_user_type,
            this.data.baseinfo.base.f_gasproperties,
            this.data.baseinfo.base.pricetype)
          if (names.length > 0) {
            names.forEach((item) => {
              if (item.label === this.data.baseinfo.base.pricename) {
                this.data.baseinfo.base.pricename = [item.value]
              }
            })
          } else {
            this.data.baseinfo.base.pricename = ''
          }
        } else {
          this.data.baseinfo.base.pricename = ''
        }
        if (this.data.baseinfo.base.f_adjustable) {
          this.adjustables.forEach((item) => {
            if (item.label === this.data.baseinfo.base.f_adjustable) {
              this.data.baseinfo.base.f_adjustable = [item.value]
            }
          })
        } else {
          this.data.baseinfo.base.f_adjustable = ''
        }
        if (this.data.baseinfo.base.f_slice_area) {
          this.data.baseinfo.base.f_slice_area = [this.data.baseinfo.base.f_slice_area]
        } else {
          this.data.baseinfo.base.f_slice_area = ''
        }
        // 对表具信息进行校验
        this.data.meterinfo.forEach((row) => {
          if (row.gasbrand) {
          this.meterbrands.forEach((item) => {
            if (item.label === row.gasbrand) {
            row.gasbrand = [item.value]
          }
        })
        } else {
          row.gasbrand = ''
        }
        if (row.gasmodel && (row.gasbrand instanceof Array)) {
          row.gasbrand[0].gasmodel.forEach((item) => {
            if (item.label === row.gasmodel + row.gasmodeltype) {
            row.gasmodel = [item.value]
          }
        })
        } else {
          row.gasmodel = ''
        }
        if (row.f_fire_state === '1') {
          row.f_fire_state1 = true
        } else if (row.f_fire_state === '0') {
          row.f_fire_state1 = false
        }
        row.f_install_date = row.f_install_date ? row.f_install_date : ''
        row.f_gas_date = row.f_gas_date ? row.f_gas_date : ''
        row.f_changetube_date = row.f_changetube_date ? row.f_changetube_date : ''
        row.f_aroundmeter = row.f_aroundmeter ? [row.f_aroundmeter] : ''
        row.f_inputtor = row.f_inputtor ? [row.f_inputtor] : ''
        row.f_position = row.f_position ? [row.f_position] : ''
      })
        // console.log('5555555555', this.data.meterinfo)
        // 对设备进行校验
        this.data.devicesinfo.forEach((row) => {
          row.f_devices_type = row.f_devices_type ? [row.f_devices_type] : ''
        })
      },
      getPricenames (f_user_type, f_gasproperties, f_price_type) {
        let rs = []
        if (f_user_type.length === 1 && f_gasproperties.length === 1 && f_price_type.length === 1) {
          rs = this.$GetSaleParam.getPrice({f_user_type: f_user_type[0],
            f_gasproperties: f_gasproperties[0], f_price_type: f_price_type[0], filter: this.$login.f.f_fengongsi})
        }
        return rs
      },
      // 将小区信息转化为综合信息的格式
      areainfoInUser (areainfo) {
        // this.nextTick(() => {
        //
        // })
        this.data = {
          baseinfo: {
            base: {
              f_user_state: '正常',
              //区/县
              f_area: areainfo.f_area,
              //街道
              f_street: areainfo.f_street,
              f_slice_area: areainfo.f_slice_area, //片区
              //小区
              f_residential_area: areainfo.f_residential_area,
              //详细地址
              f_address: areainfo.f_address,
              //地址表id
              f_useraddress_id: areainfo.id,
              //单元,楼号,楼层,门牌号
              f_building: areainfo.f_building,
              f_unit: areainfo.f_unit,
              f_floor: areainfo.f_floor,
              f_room: areainfo.f_room,
              //小区id,有值代表是小区建档
              f_area_id: areainfo.f_area_id,
              //附件表临时id
              blodid: this.blodid,
              //用户姓名
              f_user_name: areainfo.f_user_name,
              //用户电话
              f_user_phone: areainfo.f_user_phone,
              //备用电话
              f_rent_phone: areainfo.f_rent_phone,
              pricetype: areainfo.f_price_type,//气价类型
              pricename: areainfo.f_price_name,//气价名称
              f_user_type: areainfo.f_user_type ? areainfo.f_user_type : '民用',//用户类型
              f_credentials: '',
              f_cost_type: '',
              f_gasproperties: areainfo.f_gasproperties, //用气性质
              f_adjustable: areainfo.f_adjustable_name //调压箱
            },
            bank: {}
          },
          meterinfo: [{
            //表号
            f_meternumber: areainfo.f_meternumber,
            //气表品牌
            gasbrand: areainfo.f_meter_brand,
            //气表型号
            gasmodel: areainfo.f_meter_style,
            //气表类型
            gasmodeltype: areainfo.f_type,
            f_inputtor: areainfo.f_inputtor,
            //安装位置
            f_position: areainfo.f_position,
            //左右表
            f_aroundmeter: areainfo.f_aroundmeter?areainfo.f_aroundmeter:'左表',
            f_meter_base: 0,
            f_install_date: this.$login.toStandardTimeString(),
            //通气日期
            f_gas_date: areainfo.f_gas_date?areainfo.f_gas_date:this.$login.toStandardTimeString(),
            //通气人
            f_gas_person: areainfo.f_gas_person
          }],
          devicesinfo: []
        }
        this.checkout()
      }
    },
    computed: {
      meterbrands () {
        return this.$GetSaleParam.getGasbrand()
      },
      adjustables () {
        return this.$GetSaleParam.getAdjustable()
      }
    }
  }
</script>
