<template>
  <div>
    <div style="overflow-y: scroll;height: 92%">
      <div style="height: auto;width: 100%">
        <div style="margin-bottom: 2%; margin-top: 2%">
          <img style="margin-top: -5px" src="../../../../../static/images/lefticon/矩形1183.png">
          <a style="font-size: 20px;font-weight: 500;">基本    信息</a>&nbsp;<a style="color: #999999;text-decoration: none"></a>
          <button class="button_search" style="width: max-content" @click="uploadFiles()">上传附件</button>
          <button class="button_search" style="width: max-content" @click="uploadPictures()">拍照</button>
        </div>
        <file-user-essential-info-new :baseinfo="data.baseinfo" :addressinfo="data.addressinfo" @valid="essentialInfo = true"
                                      :f_filialeid="f_filialeid"    @invalid="essentialInfo = false" v-ref:useressential :isedit="isedit"></file-user-essential-info-new>
      </div>

      <div style="height: auto;width: 100%">
        <file-user-meter-info-new :meterinfo="data.meterinfo" :f_filialeid="f_filialeid" :metervalid.sync="meterInfo"
                         :f_userinfo_id="data.baseinfo.base.f_userinfo_id" v-ref:meter></file-user-meter-info-new>
      </div>

      <div style="height: auto;width: 100%">
        <div style="margin-bottom: 2%; margin-top: 2%">
          <img style="margin-top: -5px" src="../../../../../static/images/lefticon/矩形1183.png">
          <a style="font-size: 20px;font-weight: 500;">发票信息</a>&nbsp;<a style="color: #999999"></a>
        </div>
        <user-paper-info-test :baseinfo="data.baseinfo"></user-paper-info-test>
      </div>

      <!--<div style="height: auto;width: 100%">-->
        <!--<div style="margin-bottom: 2%; margin-top: 2%">-->
          <!--<img style="margin-top: -5px" src="../../../static/images/lefticon/矩形1183.png">-->
          <!--<a style="font-size: 20px;font-weight: 500;">附件信息</a>&nbsp;<a style="color: #999999"></a>-->
        <!--</div>-->
        <!--<upload :blodid="blodid" isremark="true" fusetype="档案"></upload>-->
      <!--</div>-->
    </div>

    <div class="form-horizontal auto">
      <div class="form-group">
        <div style="text-align:right;">
<!--          <button class="button_search" v-show="row.f_print_state === null" @click="ignitionSheet()">生成点火单</button>-->
<!--          <button class="button_search" v-show="row.f_print_state === null" @click="schedule()">生成流程单</button>-->
          <button v-if="config.meter_required" class="button_search" @click="confirm()" :disabled="!(essentialInfo && meterInfo )">确认
          </button>
          <button v-if="!config.meter_required" class="button_search" @click="confirm()" :disabled="!essentialInfo">确认
          </button>
          <button class="button_search" style="width: max-content" v-if="haslimit" @click="limitClick">限购配置</button>
          <button class="button_clear" @click="cancel()">取消</button>
        </div>
      </div>
    </div>
    <limit-gas :show.sync="limitShow" :f_userinfo_id="data.baseinfo.base.f_userinfo_id"
               @limit="getLimitGas"></limit-gas>
    <modal :show.sync="showfiles" width="80%" style="width:auto;"  v-ref:modal middle backdrop="false">
      <article slot="modal-body">
                <upload-idcard :blodid="blodid" isremark="true" @getidinfo="confirmIdCard" style="width:auto" fusetype="档案信息"></upload-idcard>
      </article>
      <footer slot="modal-footer" class="modal-footer">
      </footer>
    </modal>
  <high-meter-idcard :show.sync="highmetershow" v-if="highmetershow"  @photo-finish="newPhoto" v-on:confirminfo="confirmIdCard"></high-meter-idcard>
  <user-flow-sheet :show="printflag" :bill-config='configs' :bill-data='billData' :data='newdata' v-on:toggle="close" @printok="printok" v-ref:printbill></user-flow-sheet>


  </div>



</template>

<script>
import UserPaperInfoTest from './../../../../components/FilesManageNew/UserPaperInfoTest'
import {HttpResetClass} from 'vue-client'
import * as Util from '../../../../Util'

let getFileGen = async function (self, data) {
  let http = new HttpResetClass()
  let result = await http.load('POST', 'rs/logic/filemanage_getFilesDetail', data, {
    resolveMsg: null,
    rejectMsg: '用户详细信息加载失败，请重新选择，如果多次失败，请检查系统是否正常！'
  })
  if (result.data.meterinfo.length === 0) {
    // 预备户可以不填表具信息 所以修正时如果没有表具信息 则初始化一个
    result.data.meterinfo.push({
      f_meternumber: '', f_metertitles: '', f_area_code: '', gasbrand: '', gasmodel: '', gasmodeltype: '',
      pricetype: '', pricename: '', f_user_type: '', f_gasproperties: '', f_inputtor: '', f_position: '',
      f_userfiles_address: '', f_usetype: '', f_usestate: '', f_aroundmeter: '', f_garbage_fee: '否', f_meter_base: '',
      f_initial_base: '', f_gas_person: '', f_adjustable: '', f_detailprice: '', devicesinfo: []
    })
  }

  self.data = result.data
    // 更新地址
    // 修改附件临时id为表档案id
  self.blodid = self.data.baseinfo.base.f_userinfo_id
  console.log('获取档案信息', self.data)
  self.checkout()
  console.log('附件id', self.blodid)
}

export default {
  title: '综合信息',
  props: ['f_filialeid', 'row', 'areainfo', 'haslimit', 'isedit', 'configs'],
  components: {UserPaperInfoTest},
  data () {
    return {
      config: {
        adddevices: false,
        // 预备户表具信息是否必填
        meter_required: true,
        f_building_suffix: '栋',
        f_unit_suffix: '单元',
        f_floor_suffix: '层',
        f_room_suffix: '室'
      },
      headers: {'username': this.$login.f.name, 'blodid': '', 'fremarks': '', 'defname': '', 'fusetype': '档案信息'},
      data: {
        baseinfo: {
          base: {
            f_user_state: '',
            f_print_dh: '否',
            f_print_lc: '点火单',
            f_credentials: '',
            f_cost_type: '',
            f_paper_type: '',
            f_idnumber: ''
          },
          bank: {
            f_bank_name: ''
          }
        },
        addressinfo: {
          id: '',
          f_address: '',
          f_address_state: ''
        },
        meterinfo: [{
          f_user_type: '',
          f_gasproperties: '',
          devicesinfo: []
        }],
        devicesinfo: [],
        address: {
          id: '',
          f_address: ''
        }
      },
      printSheet: {
        f_state: '有效',
        f_print_state: '未打印',
        f_type: '点火单',
        f_orgid: this.$login.f.orgid ? this.$login.f.orgid : '',
        f_orgname: this.$login.f.orgs ? this.$login.f.orgs : '',
        f_depid: this.$login.f.depids ? this.$login.f.depids : '',
        f_depname: this.$login.f.deps ? this.$login.f.deps : '',
        f_operator: this.$login.f.name,
        f_operatorid: this.$login.f.id
      }, // 插入打印的模型
      billData: {
        url: 'rs/report/userignition',
        bill: ''
      },
      oldAddress: {},
      newdata: {},
      highmetershow: false, // 高拍仪组件控制
      showfiles: false,
        // 子组件验证
      essentialInfo: false,
      meterInfo: false,
      printflag: false,
        // 地址相关属性
      params: {
        areas: [],
        f_street: [],
        f_residential_area: []
      },

        // 限购相关属性
      limitShow: false,
      limit_gas: null,
      peopleNum: this.$appdata.getSingleValue('默认人口'),
      blodid: '', // 附件的临时id
      defaultMeterInfo: ''  // 默认的表具信息
    }
  },
  async ready () {
    this.blodid = '临时id' + Date.now()
    console.log('ready，，，', this.row)
    console.log('f_filialeid111，，，', this.f_filialeid)
    try {
      await this.$getConfig(this, 'FilesDetail')
    } catch (error) {
      console.log('捕获到异常', error)
    }
    console.log('FilesDetail的config:' + this.config)
    if (this.row) { // 修改用户
      await this.areaGen(this.row)
    } else if (!this.row) { // 小区批量建档
            // 将小区信息转化为综合信息的格式
      await this.areainfoInUser(this.areainfo)
    }
  },
  watch: {
    async 'row' (val) {
      console.log('观察row', val)
      if (val) {
        await this.areaGen(val)
      } else {
        await this.areainfoInUser(this.areainfo)
      }
    },
    'areainfo' (val) {
      console.log('小区观察。。', val)
      if (val) {
        this.$refs.meter.clearMeter()
        this.blodid = '临时id' + Date.now()
        this.areainfoInUser(val)
      }
    },
    'essentialInfo' (val) {
      console.log('观察到验证变化', val)
    }
  },
  methods: {
    close () {
      this.printflag = false
    },
    printok () {
      console.log('======================')
      this.confirm()
    },
    downFiles (index) {
      console.log('xxxxxxxxxxxxxxxxxxxxx')
        // 下载不同文件
      if (index == 0) {
        let url = 'rs/report/userinstall'
        this.billData.url = url
        this.data.baseinfo.base.f_print_lc = '是'
      } else {
        let url = 'rs/report/userignition'
        this.billData.url = url
        this.data.baseinfo.base.f_print_dh = '是'
      }
      this.newdata = this.row
      this.printflag = true
    },
    confirmIdCard (IdCardInfo) {
      this.uploadPictures()
      this.data.baseinfo.base.f_user_name = IdCardInfo.strName
      this.data.baseinfo.base.f_idnumber = IdCardInfo.strID
    },
    uploadFiles () {
      this.showfiles = !this.showfiles
    },

    uploadPictures () {
      this.highmetershow = !this.highmetershow
    },
    savePrintSheet (res) {
      console.log('保存单子:' + this.data.baseinfo.base.f_print_dh_stats)
      if (!this.data.baseinfo.base.f_print_dh_stats) {
        console.log('单子类型', this.data.baseinfo.base.f_print_dh)
        this.printSheet.f_userinfo_id = res.f_userinfo_id
        if (this.data.baseinfo.base.f_print_dh == '点火单') {
          this.ignitionSheet()
        }
        if (this.data.baseinfo.base.f_print_dh == '流程单') {
          this.schedule()
        }
      }
    },
    ignitionSheet () { // 点火单
      this.printSheet.f_type = '点火单'
      this.saveTablePrintSheet()
    },
    schedule () { // 流程单
      this.printSheet.f_type = '流程单'
      this.saveTablePrintSheet()
    },
    async saveTablePrintSheet () {
      console.log(this.printSheet)
      let check = await this.$resetpost('rs/logic/checkPrintUser', {data: {f_userinfo_id: this.printSheet.f_userinfo_id}}, {resolveMsg: '', rejectMsg: ''})
      if (check.data.length === 0) {
        await this.$resetpost('rs/logic/savePrintSheet', {data: {printData: this.printSheet}}, {resolveMsg: '', rejectMsg: ''})
      }
        // let check = await this.$resetpost('rs/logic/checkPrintUser', {data:{f_userinfo_id: this.printSheet.f_userinfo_id}}, {resolveMsg: '', rejectMsg: ''})
        // if (check.data.length !== 0){
        //     if(check.data[0].num !== 0){
        //         // let msg = "您已生成了 \""+check.data[0].type+"\" ,请前往 [ 综合业务 ] --> [ 打印数据 ]页面查看";
        //         // this.$showMessage(msg);
        //         return ;
        //     }
        // }
        // let expiration = await this.$resetpost('rs/logic/savePrintSheet', {
        //     data:{printData:this.printSheet}
        // }, {resolveMsg: '', rejectMsg: ''})
        // console.log(expiration);
        // if(expiration.data === 200){
        //     this.$showMessage("您已成功生成 \""+this.printSheet.f_type+"\" ,请前往 [ 综合业务 ] --> [ 打印数据 ]页面查看")
        // }
    },
    confirm () {
      this.data.addressinfo.f_address = this.$refs.useressential.addressinfo.f_address
      this.data.addressinfo.id = this.$refs.useressential.addressinfo.id
      this.data.oldaddressinfo = this.oldAddress
      this.data.inputcode = this.$refs.useressential.inputcode ? this.$refs.useressential.inputcode : '否'
      this.data.limit_gas = this.limit_gas
      if (this.f_filialeid && this.f_filialeid != '') {
        this.data.f_filialeid = this.f_filialeid
      } else {
        this.data.f_filialeid = this.$login.f.orgid
      }
      if (this.row) {
        this.data.baseinfo.base.version = this.row.version
      }
      this.data.baseinfo.base.f_user_name = Util.removerUnnecessary(this.data.baseinfo.base.f_user_name)
      this.data.baseinfo.base.f_user_phone = Util.removerUnnecessary(this.data.baseinfo.base.f_user_phone)
      this.data.meterinfo.forEach((item) => {
        item.f_meternumber = Util.removerUnnecessary(item.f_meternumber)
      })
      this.$FileManageService.fileSave(this.$FileManageService.fileSaveBefore(this.data)).then((res) => {
        this.savePrintSheet(res.data.result[0])
        this.$dispatch('success')
      }).catch((error) => {
        if (error.status === 603) {
          this.$error('重复提交')
          return
        }
        this.$dispatch('error', '档案保存', this.data, error)
      })
    },
    convertBase64ToBlob (base64String) {
        // 将base64解码
      var bytes = atob(base64String)
        // var bytes = base64;
      var bytesCode = new ArrayBuffer(bytes.length)
        // 转换为类型化数组
      var byteArray = new Uint8Array(bytesCode)

        // 将base64转换为ascii码
      for (var i = 0; i < bytes.length; i++) {
        byteArray[i] = bytes.charCodeAt(i)
      }
        // 生成Blob对象（文件对象）
      return new Blob([bytesCode], {type: 'image/jpeg'})
    },
    newPhoto (Imgbase64) {
      //console.log('imgbase----->',Imgbase64)
      let form = new FormData()
      let xhr = new XMLHttpRequest()
      let formDataBoundary = '----WebkitFormBoundary' + 'GaoPaiYi'
      form.append('Content-Type', 'multipart/form-data;boundary=' + formDataBoundary)
      form.append('file', this.convertBase64ToBlob(Imgbase64), 'GaoPaiYi.jpg')
      xhr.open('POST', 'rs/file/uploadFile')

      if (this.headers) {
        console.log('this.blodid----->',this.blodid)
        this.headers.blodid = this.blodid
        for (var header in this.headers) {
          xhr.setRequestHeader(header, encodeURIComponent(this.headers[header]))
        }
      }
      xhr.send(form)
      setTimeout(() => {
        this.load(this)
      }, 5000)
    },
    async areaGen (data) {
      data.f_user_id = data.f_user_id + ''
      await getFileGen(this, data)
    },
    cancel () {
      this.$dispatch('clean', '取消档案修正', 'user-general-info', this.row)
    },
    checkout (val) {
          // 对收到的综合信息进行校验（主要目的是为了防止下拉框没有默认值）
          // 对综合用户基本信息进行校验

          // 将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_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_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.f_people_num = this.data.baseinfo.base.f_people_num ? this.data.baseinfo.base.f_people_num : (this.peopleNum ? this.peopleNum : 0)

      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.oldAddress.f_address = this.data.addressinfo.f_address
      this.oldAddress.id = this.data.addressinfo.id

          // 地址信息
          // loadStreetAndResGen(this)

          // 对表具信息进行校验
      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 === (val === 'area' ? row.gasmodel : 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 : null
        row.f_gas_date = row.f_gas_date ? row.f_gas_date : null
        row.f_changetube_date = row.f_changetube_date ? row.f_changetube_date : null
        row.f_aroundmeter = row.f_aroundmeter ? [row.f_aroundmeter] : ''
        row.f_garbage_fee = row.f_garbage_fee ? [row.f_garbage_fee] : '否'
        row.f_valve_state = row.f_valve_state ? [row.f_valve_state] : '开阀'
        row.f_inputtor = row.f_inputtor ? [row.f_inputtor] : ''
        row.f_position = row.f_position ? row.f_position : ''

        row.f_user_type = row.f_user_type ? [row.f_user_type] : ''
        row.f_gasproperties = row.f_gasproperties ? [row.f_gasproperties] : ''
        row.pricetype = row.pricetype ? [row.pricetype] : ''

        if (row.pricename) {
          let names = this.getPricenames(row.f_user_type,
                    row.f_gasproperties,
                    row.pricetype)
          if (names.length > 0) {
            names.forEach((item) => {
              if (item.label === row.pricename) {
                row.pricename = [item.value]
                row.f_detailprice = this.$CommonService.getShowPriceDetail(item.value.detailprice)
              }
            })
          } else {
            row.pricename = ''
          }
        } else {
          row.pricename = ''
        }

        if (row.f_adjustable) {
          this.adjustables.forEach((item) => {
            if (item.label === row.f_adjustable) {
              row.f_adjustable = [item.value]
            }
          })
        } else {
          row.f_adjustable = ''
        }
      })
          // 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.f_filialeid
        })
      }
      return rs
    },
        // 将小区信息转化为综合信息的格式
    async areainfoInUser (areainfo) {
            // this.nextTick(() => {
            //
            // })
            // await this.$getConfig(this, 'UserAddress')
      this.data = {
        baseinfo: {
          base: {
            f_user_state: '预备',
            f_print_dh: '',
            f_print_lc: '否',
            f_is_mgq: '',
            f_slice_area: '', // 片区
                  // 附件表临时id
            blodid: this.blodid,
                  // 用户姓名
            f_user_name: '',
                  // 用户电话
            f_user_phone: '',
            f_people_num: 0,
                  // 备用电话
            f_rent_phone: '',
            f_credentials: '身份证',
            f_cost_type: '',
            f_address: '',
            addressid: '',
            f_idnumber: ''
          },
          bank: {}
        },
        addressinfo: {
                // 详细地址
          f_address: '',
          id: ''
        },
        meterinfo: [{
                // 表号
          f_meternumber: '',
          f_metertitles: '',
          f_area_code: '',
                // 气表品牌
          gasbrand: '',
                // 气表型号
          gasmodel: '',
                // 气表类型
          gasmodeltype: '',
          pricetype: '', // 气价类型
          pricename: '', // 气价名称
          f_user_type: '', // 用户类型
          f_gasproperties: '', // 用气性质
          f_inputtor: '',
                // 安装位置
          f_position: '',
                // 安装地址
          f_userfiles_address: '',
                // 使用类型
          f_usetype: '',
                // 使用状态
          f_usestate: '',
                // 左右表
          f_aroundmeter: '',
          f_garbage_fee: '否',
          f_meter_base: '',
          f_initial_base: '',
                // 通气人
          f_gas_person: '',
          f_adjustable: '', // 调压箱
          f_detailprice: '',  // 价格详情显示
          devicesinfo: [] // 设备信息
        }],
        devicesinfo: []
      }
            // 若有id，则表示该地址是更新操作
            /* if (areainfo.id) {
                this.data.addressinfo.id = areainfo.id
            }
            // 改地址是 只有表没有户信息
            if (areainfo.meter) {
                Object.assign(this.data.meterinfo[0], this.data.meterinfo[0], areainfo.meter)
            }
            if (areainfo.user) {
                Object.assign(this.data.baseinfo.base, this.data.baseinfo.base, areainfo.user)
            } */

      this.checkout('area')
    },
    limitClick () {
      this.limitShow = true
    },
    getLimitGas (val) {
      this.limit_gas = val
    },
    clearinfo () {
      this.blodid = '临时id' + Date.now()
      this.areainfoInUser(this.areainfo)
    }
  },
  computed: {
    meterbrands () {
      return this.$GetSaleParam.getGasbrand()
    },
    adjustables () {
      return this.$GetSaleParam.getAdjustable()
    },
    getMeterBooks () {
      return this.$GetSaleParam.getMeterBooks()
    }
  },
  events: {
      // 设置表具气价等默认值
    defaultOtheret (row) {
      if (!this.isedit) {
        let temp = {
          gasmodel: row.f_meter_style,
          gasbrand: row.f_meter_brand,
          gasmodeltype: row.f_meter_style,
          pricetype: row.f_price_type,
          pricename: row.f_price_name,
          f_user_type: row.f_user_type,
          f_gasproperties: row.f_gasproperties,
          f_position: row.f_position,
          f_inputtor: row.f_inputtor,
          f_meter_book_num: row.f_meter_book,
          f_adjustable: row.f_adjustable_id,
          f_hand_month: [row.f_hand_month]
        }
        if (!(temp.f_position instanceof Array)) {
          temp.f_position = [temp.f_position]
        }
        Object.assign(this.data.meterinfo[0], this.data.meterinfo[0], temp)

        this.checkout('area')
      }
    }
  }
}
</script>
<style scoped>


</style>
