<template>
  <div class="auto" style="overflow:auto;" id="ChangeMeter">
    <validator name='v'>
    <form novalidate class="form-horizontal">
      <div class="row auto" >
        <div class="col-sm-4 form-group">
          <label for="f_type" class=" font_normal_body">换表类型</label>
          <v-select id="f_type"
                    v-model="model.f_type"
                    title="参数:换表类型"
                    placeholder='请选择'
                    :value-single="true"
                    :value.sync="model.f_type"
                    :options='replacewatchtype'
                    @change="typeChange"
                    :disabled="!(row.f_meter_type.includes('卡表')||row.f_meter_type ==='物联网表')"
                    close-on-select clear-button>
          </v-select>
        </div>
        <div class="col-sm-4 form-group">
          <label for="f_change_operator" class=" font_normal_body">换&ensp;表&ensp;人</label>
          <input class="input_search" style="width:60%" type="text" v-model="model.f_change_operator" placeholder="换表人">
        </div>

        <div class="col-sm-4 form-group" :class="[$v.f_using_base_old.required || $v.f_using_base_old.dctest ? 'has-error' : 'has-success']">
          <label for="f_remanent_gas" class=" font_normal_body">旧表底数</label>
          <input class="input_search" style="width:60%" type="number"
                 v-model="model.f_using_base_old"
                 placeholder="请输入旧表底数"
                 v-validate:f_using_base_old='{required: true, dctest: [-1, ">" ] }'
                 @blur="pregasChange()">
        </div>
      </div>
      <!--<p class="bg-info text-center" v-if="!model.f_type.includes('清零')" style="padding: 8px;">新表信息</p>-->
      <meter-message v-if="!model.f_type.includes('清零') && !model.f_type.includes('换卡控流量计')" :f_userfiles_id="row.f_userfiles_id" :metermessage.sync="model.metermessage" @valid="meterinfo = true"
                     @invalid="meterinfo = false" @gasmodel="gasModelChange" v-ref:metermsg></meter-message>

      <div v-if="row.f_meter_type != '机表'">
        <div class="row auto" style="margin-top: 10px" v-if="changeType == 'gasToAmount' || changeType == 'amountToGas'">
          <!-- 气量转金额 || 金额转签气量 -->
          <div class="col-sm-4 form-group" :class="[$v.f_remanent_gas.required || $v.f_remanent_gas.dctest ? 'has-error' : 'has-success']">
            <label for="f_remanent_gas" class=" font_normal_body">补&ensp;气&ensp;量</label>
            <input class="input_search" style="width:60%" type="number"
                   v-model="model.f_remanent_gas"
                   placeholder="补气量"
                   v-validate:f_remanent_gas='{required: true, dctest: [-1, ">" ] }'>
          </div>
          <div class="col-sm-4 form-group">
            <label class=" font_normal_body">补气单价</label>
            <input class="input_search" style="width:60%" type="number"
                   v-model="model.f_remanent_price"
                   placeholder="补气单价" readonly>
          </div>
          <div class="col-sm-4 form-group"
               :class="[$v.f_remanent_money.required || $v.f_remanent_money.dctest ? 'has-error' : 'has-success']">
            <label for="f_remanent_money" class=" font_normal_body">补气金额</label>
            <input class="input_search" style="width:60%" type="number"
                   v-model="model.f_remanent_money"
                   placeholder="补气金额"
                   @blur="remanentChange"
                   v-validate:f_remanent_money='{required: true, dctest: [-1, ">" ] }'>
          </div>
        </div>
        <div class="row auto" v-if="changeType == 'gasToGas'">
          <!-- 气量转气量 -->
          <div class="col-sm-4 form-group" :class="[$v.f_remanent_gas.required || $v.f_remanent_gas.dctest ? 'has-error' : 'has-success']">
            <label for="f_remanent_gas" class=" font_normal_body">补&ensp;气&ensp;量</label>
            <input class="input_search" style="width:60%" type="number"
                   v-model="model.f_remanent_gas"
                   placeholder="补气量"
                   v-validate:f_remanent_gas='{required: true, dctest: [-1, ">" ] }'>
          </div>
        </div>

        <div class="row auto" v-if="changeType == 'amountToAmount'">
          <!-- 金额转金额 -->
          <div class="col-sm-4 form-group"
               :class="[$v.f_remanent_money.required || $v.f_remanent_money.dctest ? 'has-error' : 'has-success']">
            <label for="f_remanent_money" class=" font_normal_body">补气金额</label>
            <input class="input_search" style="width:60%" type="number"
                   v-model="model.f_remanent_money"
                   placeholder="补气金额"
                   v-validate:f_remanent_money='{required: true, dctest: [-1, ">" ] }'>
          </div>
        </div>
      </div>

      <div class="row auto" v-if="model.f_type.includes('换卡控流量计')">
        <div class="col-sm-4 form-group">
          <label class="font_normal_body" title="流量计表号">新流量计表号</label>
          <input type="text" class="input_search" style="width:60%" v-model="model.f_flowmeter_number"
                 placeholder='流量计表号'></input>
        </div>
        <div class="col-sm-4 form-group">
          <label class="font_normal_body" title="流量计通经">新流量计通经</label>
          <input type="text" class="input_search" style="width:60%" v-model="model.f_flowmeter_pass"
                 placeholder='流量计通经'></input>
        </div>
        <div class="col-sm-4 form-group" :class="[$v.f_meter_base.required ? 'has-error' : '']">
          <label class="font_normal_body">新表底数</label>
          <input type="number" class="input_search" style="width:60%" v-validate:f_meter_base='{required: true }' v-model="model.metermessage.f_meter_base" placeholder='表底数' >
        </div>

        <div class="col-sm-4 form-group">
          <label class="font_normal_body" title="流量计品牌">新流量计品牌</label>
          <v-select :value.sync="model.f_flowmeter_brand" :options='flowmeterbrands' value-single placeholder='流量计品牌' close-on-select
                    search v-model='model.f_flowmeter_brand'></v-select>
        </div>
        <div class="col-sm-4 form-group">
          <label class="font_normal_body" title="流量计型号">新流量计型号</label>
          <v-select :value.sync="model.f_flowmeter_model" :options='flowmetermodels(model.f_flowmeter_brand)' value-single placeholder='流量计型号' close-on-select
                    v-model='model.f_flowmeter_model' :disabled='model.f_flowmeter_brand.length === 0'></v-select>
        </div>
        <div class="col-sm-4 form-group">
          <label class="font_normal_body" title="流量计精准度">新流量计精准度</label>
          <input type="text" class="input_search" style="width:60%" v-model="model.f_flowmeter_accuracy"
                 placeholder='流量计精准度'></input>
        </div>
        <div class="col-sm-4 form-group">
          <label class="font_normal_body" title="流量计压力等级">新流量计压力等级</label>
          <input type="text" class="input_search" style="width:60%" v-model="model.f_flowmeter_mpa_level"
                 placeholder='流量计压力等级'></input>
        </div>
        <div class="col-sm-4 form-group">
          <label class="font_normal_body" title="流量计安装日期">新流量计安装日期</label>
          <datepicker style="width:60%" placeholder="流量计安装日期"
                      v-model="model.f_flowmeter_install_date"
                      :value.sync="model.f_flowmeter_install_date"
                      :format="'yyyy-MM-dd HH:mm:ss'"
          ></datepicker>
        </div>
        <div class="col-sm-4 form-group">
          <label class="font_normal_body">业务单号</label>
          <input class="input_search" style="width:60%"  type="text"
                 v-model="model.f_serial_number" placeholder="业务单号">
        </div>
      </div>


      <div class="row auto" >

        <div class="col-sm-4 form-group">
          <label for="f_changemeter_fee" class=" font_normal_body">换表金额</label>
          <input class="input_search" style="width:60%" type="number" v-model="model.f_changemeter_fee" placeholder="换表金额">
        </div>
        <div class="col-sm-4 form-group">
          <label for="f_paytype" class=" font_normal_body" title="参数名称：付款方式">收款方式</label>
          <v-select id="f_payment"
                    title="参数:付款方式"
                    v-model="f_payment"
                    placeholder='请选择'
                    :value-single="true"
                    :value.sync="model.f_payment"
                    :options='paytype'
                    close-on-select clear-button></v-select>
        </div>
        <div class="col-sm-4 form-group">
          <label for="f_print" class="font_normal_body">打印格式</label>
          <v-select id="print"
                    title="参数:打印格式"
                    v-model="f_print"
                    placeholder='请选择'
                    :multiple="mulPrint"
                    :value.sync="model.f_print"
                    :options='printstyle'
                    close-on-select clear-button></v-select>
        </div>
      </div>
      <div class="row" v-if="!model.f_type.includes('换卡控流量计')">
       <!-- <div class="col-sm-4 flex-row" >
          <label class="control-label">用户类型</label>
          <v-select :value.sync="newinfo.f_user_type"
                    :options='usertypes' placeholder='用户类型'
                    @change="userTypeChange()"
                    close-on-select></v-select>
        </div>
        <div class="col-sm-4 flex-row"
             :class="[$m.gas.required ? 'has-error' : '']">
          <label class="control-label">用气性质</label>
          <v-select :value.sync="newinfo.f_gasproperties" v-model="newinfo.f_gasproperties"
                    :options='gasproperties' placeholder='用气性质'
                    close-on-select v-ref:gas></v-select>
        </div>-->
        <div class="col-sm-4 form-group" :class="[$m.type.required ? 'has-error' : '']">
          <label class="font_normal_body">气价类型</label>
          <v-select :value.sync="newinfo.pricetype" v-model="newinfo.pricetype"
                    placeholder='气价类型' :options="pricetypes"
                    close-on-select v-ref:type>
          </v-select>
        </div>
        <div class="col-sm-4 form-group" :class="[$m.name.required ? 'has-error' : '']">
          <label class="font_normal_body">气价名称</label>
          <v-select :value.sync="newinfo.pricename" v-model="newinfo.pricename"
                    placeholder='气价名称' :options="getPricenames()"
                    close-on-select :disabled='newinfo.pricetype.length === 0 ' v-ref:name></v-select>
        </div>
        <div class="col-sm-4 form-group">
          <label class="font_normal_body">新抄表册</label>
          <v-select :value.sync="newinfo.f_meter_book" v-model="newinfo.f_meter_book"
                    placeholder='新抄表册' :options="meterbookoptions"
                    close-on-select></v-select>
        </div>

      </div>
      <div class="row auto" v-if="!model.f_type.includes('换卡控流量计')">
        <div class="col-sm-4 ">
          <label for="f_comments" class=" font_normal_body">业务单号</label>
          <input class="input_search" style="width:60%"  type="text"
                 v-model="model.f_serial_number" placeholder="业务单号">
        </div>
        <div class="col-sm-4 ">
          <label class=" font_normal_body">阶梯累计</label>
          <v-select id="f_ladder_sync"
                    v-model="f_payment"
                    placeholder='是否累计'
                    :search="false"
                    :value-single="true"
                    :value.sync="model.f_ladder_sync"
                    :options='ladder'
                    close-on-select clear-button></v-select>
        </div>
        <div class="col-sm-4"
             :class="[$v.f_stair_use.required || $v.f_stair_use.dctest ? 'has-error' : 'has-success']"
             v-if="row.f_meter_type.includes('卡表') && model.metermessage.gasbrand[0].f_meter_type ==='物联网表'&& model.f_ladder_sync !=='不同步'">
          <label class=" font_normal_body">阶梯用量</label>
          <input class="input_search" style="width:60%" type="number"
                 v-validate:f_stair_use='{required: true, dctest: [0, ">=" ] }'
                 v-model="model.f_stair_use" placeholder="旧表阶梯使用量">
        </div>
        <div class="col-sm-4 " v-if="model.metermessage.gasbrand[0].f_meter_type ==='物联网表' && model.metermessage.gasbrand[0].f_hascard ==='是'">
          <label class=" font_normal_body">开户方式</label>
          <v-select id="f_open_type"
                    v-model="f_payment"
                    placeholder='开户方式'
                    :search="false"
                    :value-single="true"
                    :value.sync="model.f_open_type"
                    :options='opentype'
                    close-on-select clear-button></v-select>
        </div>
        <div  class="col-sm-4 form-group" :class="[$v.f_newaroundmeter.required ? 'has-error' : '']">
          <label  class="font_normal_body">新表表向</label>
          <input type="text" v-show="false" v-model="$refs.f_newaroundmeter.selectedItems" v-validate:f_newaroundmeter='{required: true }'>
          <v-select :value.sync="model.f_newaroundmeter" :options='aroundmeters' placeholder='新表表向'
                    :value-single="true"
                    close-on-select
                    v-model='model.f_newaroundmeter' v-ref:f_newaroundmeter></v-select>
        </div>
      </div>
      <div class="row auto" >
        <div class="col-sm-12"
             v-if="!commitflag"
        >
          <label  class="font_normal_body ">备&emsp;&emsp;注</label>
          <textarea class="input_textarea" rows="3" style="width:87%;" v-model="model.f_comments"></textarea>
        </div>
        <div class="col-sm-12"
             :class="[$v.f_comments.required ? 'has-error' : 'has-success']"
             v-if="commitflag"
        >
          <label  class="font_normal_body ">备&emsp;&emsp;注</label>
          <textarea class="input_textarea" rows="3" style="width:87%;" v-model="model.f_comments"
                    v-validate:f_comments='{required: true}'
          ></textarea>
        </div>
      </div>
      <div style="text-align:right;height:auto;">
        <button class="button_search" type="button" @click="confirmbefore()" :disabled="(!meterinfo && !(model.f_type.includes('清零') || model.f_type.includes('换卡控流量计'))) || !$v.valid"
        >确认
        </button>
        <button class="button_clear" type="button" @click="clean()" >取消
        </button>
      </div>
      <!--<div style="height: auto;width: 100%">-->
        <!--<div style="height: 10%">-->
          <!--<img style="margin-top: -5px" src="../../../../../../static/images/lefticon/矩形1183.png">-->
          <!--<a style="font-size: 16px;font-weight: 500;color: #333;text-decoration: none;">附件信息</a>&nbsp;<a style="color: #999999"></a>-->
        <!--</div>-->
        <!--<upload :blodid="row.f_userinfo_id" isremark="true" fusetype="换表"></upload>-->
      <!--</div>-->
    </form>
    </validator>
  </div>
  <upload  v-if="config.showupload" :blodid="row.f_userinfo_id" isremark="true" fusetype="换表&清零"></upload>
</template>
<script>
/**
 *换表管理
 *组合界面，加载机表，物联网表，气量卡表，金额卡表旧表信息，以及控制显示换新表信息
 */
import { HttpResetClass } from 'vue-client'
let getPrice = async function (self) {
  await self.$LoadParams.loadParam(self.$login.f.orgid)
  await self.$getConfig(self, 'ChargeMeter')
  self.config.castInt = false
  self.model.f_open_type = self.config.open_way
  self.isGas = (self.row.f_collection_type == '按气量')

  let http = new HttpResetClass()
  let param = {
    tablename: 't_detailprice',
    condition: `f_price_name = '1' and f_stairprice_id = '${self.row.f_stairprice_id}'`
  }
  let res = await http.load('POST', 'rs/sql/saleSingleTable', {
    data: param
  }, {
    resolveMsg: null,
    rejectMsg: '获取一阶单价!!'
  })
  if (res.data.length > 0) {
    self.model.f_remanent_price = res.data[0].f_price
  }
  let temp = {
    tablename: 't_meter_book',
    condition: `f_book_state='有效' and f_filiale_id='${self.$login.f.orgid}'`
  }
  let meterbooks = await http.load('POST', 'rs/sql/saleSingleTable', {data: temp},
          {resolveMsg: null, rejectMsg: '获取抄表册信息失败！！'})
  if (meterbooks.data.length > 0) {
    let options = []
    for (let i = 0; i < meterbooks.data.length; i++) {
      let tmp = {label: meterbooks.data[i].f_book_name, value: `${meterbooks.data[i].id}`}
      options.push(tmp)
    }
    self.meterbookoptions = options
  }
  if (self.row.f_price_type === '固定气价') {
    self.model.f_stair_use = 0
  } else {
    let a = await http.load('POST', 'rs/logic/commonCal', {data: {model: self.row, isGasValue: 0, value: 0}}, {resolveMsg: null, rejectMsg: '获取阶梯使用情况出错'})
    self.model.f_stair_use = a.data.sumamount
  }
  self.newinfo.pricetype = [self.row.f_price_type]
  let params = {
    f_user_type: self.row.f_user_type,
    f_gasproperties: self.row.f_gasproperties,
    f_price_type: self.row.f_price_type,
    filter: self.$login.f.orgid
  }
  let rs = self.$GetSaleParam.getPrice(params)
  rs.forEach((val) => {
    if (val.label == self.row.f_price_name) {
      self.newinfo.pricename = [val.value]
    }
  })
  self.initData()
}
export default {
  title: '换表登记',
  data () {
    return {
      resid: [],  // 存放新增的f_files表中id
      model: {
        f_flowmeter_number: '',
        f_flowmeter_pass: '',
        f_flowmeter_brand: '',
        f_flowmeter_model: '',
        f_flowmeter_accuracy: '',
        f_flowmeter_mpa_level: '',
        f_flowmeter_install_date: this.$login.toStandardTimeString(),
        metermessage: {
          f_meter_type: '',
          gasbrand: '',
          gasmodel: '',
          f_meternumber: '',
          f_meter_base: '',
          f_metertitles: '',
          f_defendcard: '',
          f_defendcard_two: '',
          f_oldmeter_use_reference: 0 // 旧表使用量参考值
        },
        // 旧表底数
        f_ladder_sync: '同步',
        f_using_base_old: '',
        // 换表补气量
        f_remanent_gas: 0,
        // 换表补气单价
        f_remanent_price: 0,
        f_open_type: '',
        f_remanent_money: 0,
        f_type: '换新表',
        f_comments: '',
        f_othereason: '',
        f_stair_use: '',
        f_payment: '现金缴费',
        f_print: '普通收据',
        f_state: '有效',
        f_changemeter_date: this.$login.toStandardTimeString(),
        f_changemeter_fee: this.$appdata.getSingleValue('换表金额') ? this.$appdata.getSingleValue('换表金额') : 0
      },
      meterinfo: false,

      meterbookoptions: [],
      // 控制气量和金额的转换显示
      changeType: '',
      config: {
        open_way: '指令开户',
        showupload: true, //
        castInt: false,
        dispatch: false // 是否派工
      },
      // 控制气量金额的编辑
      isGas: false,
      replacewatchtype: this.$appdata.getParam('换表类型'),
      reason: this.$appdata.getParam('换表原因') ? this.$appdata.getParam('换表原因') : [],
      paytype: this.$appdata.getParam('付款方式'),
      printstyle: this.$appdata.getParam('打印格式'),
      gasproperties: [],
      addgasnum: 0,
      addgas: false,
      books: {
        data: []
      },
      audits: [],
      addbalance: false,
      newinfo: {
        f_user_type: '',
        f_gasproperties: '',
        pricetype: '',
        pricename: '',
        f_perform_date: this.$login.toStandardDateString() + ' 00:00:00' // 操作时间
      },
      ladder: [{label: '累计', value: '同步'}, {label: '不累计', value: '不同步'}],
      opentype: [{label: '指令开户', value: '指令开户'}, {label: '发卡开户', value: '发卡开户'}],
      usertypes: this.$appdata.getParam('用户类型') ? [{label: '全部', value: ''}, ...this.$appdata.getParam('用户类型')] : [],
      pricetypes: this.$appdata.getParam('气价类型') ? [{label: '全部', value: ''}, ...this.$appdata.getParam('气价类型')] : [],
      commitflag: false
    }
  },
  props: ['row'],
  ready () {
    getPrice(this)
  },
  events: {
    // 删除Resid数组元素
    'delResid' (val) {
      this.resid.$remove({id: val, f_biobid: ''})
      // this.resid.splice(this.resid.indexOf({id:val,f_biobid:''}),1);
    },
    // 增加Resid数组元素
    'resid' (val) {
      this.resid.push({id: val, f_biobid: ''})
    }
  },
  computed: {
    aroundmeters () {
      return this.$appdata.getParam('左右表')
    },
    flowmeterbrands () {
      let gasbrand = this.$GetSaleParam.getGasbrand()
      let flowmeterbrands = []
      for (let row of gasbrand) {
        flowmeterbrands.push({label: row.label, value: row.label})
      }
      return flowmeterbrands
    }
  },
  methods: {
    flowmetermodels (label) {
      let gasbrand = this.$GetSaleParam.getGasbrand()
      let flowmetermodels = []
      for (let row of gasbrand) {
        if (row.label == label) {
          for (let gasmodel of row.value.gasmodel) {
            flowmetermodels.push({label: gasmodel.label, value: gasmodel.label})
          }
          break
        }
      }
      return flowmetermodels
    },
    getPricenames () {
      console.log('气价。，。。', this.newinfo.pricetype)
      let rs = []
      if (this.row.f_user_type && this.row.f_gasproperties && this.newinfo.pricetype.length === 1) {
        let params = {
          f_user_type: this.row.f_user_type,
          f_gasproperties: this.row.f_gasproperties,
          f_price_type: this.newinfo.pricetype[0],
          filter: this.$login.f.orgid
        }
        rs = this.$GetSaleParam.getPrice(params)
      }
      if (rs.length === 0) {
        this.newinfo.f_price_name = ''
      }
      return rs
    },
    userTypeChange () {
      this.gasproperties = []
      if (this.newinfo.f_user_type.length === 1) {
        this.gasproperties = this.$appdata.getParam(this.newinfo.f_user_type[0])
      }
    },
    // 返回
    clean () {
      this.$dispatch('success', '换表', this.row)
    },
    async confirmbefore () {
      if (this.model.metermessage.f_meter_type[0] != '机表') {
        console.log('进来了')
        if (this.books.data.length > 0) {
          console.log('进来了2')
          if (this.books.data[0].f_whether_pay === '否') {
            this.$showAlert('该表有欠费，请到机表缴费界面进行缴费', 'warning', 3000)
            this.$dispatch('button-specifies', {name: '机表收费', value: 'machine-charge'}, this.row)
          } else {
            this.confirm()
          }
        } else {
          this.confirm()
        }
      } else {
        this.confirm()
      }
    },
    async confirm () {
      let msg = ''
      if (this.row.f_meter_type.includes('机表') || this.row.f_meter_type.includes('物联网表')) {
        let a = this.config.castInt ? parseInt(this.model.f_using_base_old) : this.model.f_using_base_old
        let b = this.config.castInt ? parseInt(this.row.f_meter_base) : this.row.f_meter_base
        console.log(a + '===========')
        console.log(b + '===========')
        if (a > b) {
          msg = (this.row.f_meter_type === '机表' ? '该用户表底数大于上次抄表底数，请确定是否继续生成欠费记录' : '该用户表底数大于上次抄表底数，请确定是否进行结算')
        } else if (this.row.f_capacity && this.row.f_capacity > 0 && (parseInt(this.model.f_using_base_old) < parseInt(this.row.f_meter_base))) {
          msg = '该用户表底数大于上次抄表底数，且已超越最大量程，请确定是否继续生成欠费记录'
        }
      }
      if ((this.row.f_meter_type.includes('机表') || this.row.f_meter_type.includes('物联网表')) && msg) {
        this.$showMessage(msg, ['confirm', 'cancel']).then((res) => {
          if (res === 'confirm') {
            debugger
            let url = this.row.f_meter_type.includes('物联网表') ? 'rs/logic/changeMeterWebHand' : 'rs/logic/changeMeterHand'
            let data = {
              downDate: this.$login.toStandardTimeString(),
              startDate: this.$login.toStandardDateString(),
              endDate: this.$login.toStandardDateString(),
              condition: `f_userfiles_id = '${this.row.f_userfiles_id}'`,
              f_operator: this.$login.f.name,
              f_operatorid: this.$login.f.id,
              f_meternumber: this.row.f_meternumber,
              f_userinfo_id: this.row.f_userinfo_id,
              f_userfiles_id: this.row.f_userfiles_id,
              f_serial_number: this.model.f_serial_number,
              f_meterbase: this.model.f_using_base_old,
              f_meter_brand: this.row.f_meter_brand,
              f_meter_classify: this.row.f_meter_type,
              f_price_id: this.row.f_price_id
            }
            this.$resetpost(url, {data: data}, {resolveMsg: '生成欠费成功', rejectMsg: '生成欠费失败'}).then((res) => {
              console.log('成功')
              if (this.model.metermessage.f_meter_type[0] != '机表') {
                this.$dispatch('refresh')
              } else {
                this.saveobj()
              }
            })
          } else {

          }
        })
      } else {
        if (this.row.f_meter_type.includes('气量卡表') && (this.model.f_using_base_old > (this.row.f_total_gas + this.row.f_initial_base + this.row.f_remanent_gas))) {
          await this.$showMessage(`该表可能存在超用，请确定是否继续进行换表操作！！！,或者取消进入超用收费！`, ['confirm', 'cancel']).then((res) => {
            if (res === 'confirm') {
              this.saveobj()
            } else {
            }
          })
        } else {
          this.saveobj()
        }
      }
    },
    async saveobj () {
      try {
        this.model.f_operator = this.$login.f.name
        this.model.f_operatorid = this.$login.f.id
        this.model.f_orgid = this.$login.f.orgid
        this.model.f_orgname = this.$login.f.orgs
        this.model.f_depid = this.$login.f.depids
        this.model.f_depname = this.$login.f.deps
        this.model.f_zoneid = this.$login.f.zoneid
        this.model.f_zones = this.$login.f.zones
        let data = {
          model: this.model,
          f_meter_book: this.newinfo.f_meter_book[0],
          old: this.row
        }
        let meterinfo = await this.$resetpost('rs/logic/changeMeter', data, {
          resolveMsg: null,
          rejectMsg: '换表失败！！！'
        })
        let param = []
        for (let row of this.resid) {
          param.push({id: row.id})
        }
        let data1 = {
          param: param,
          f_blobid: meterinfo.data.id
        }
        console.log('-------------------------->', data1)
        await this.$resetpost('rs/logic/updatefiles', data1)
        // 赋值【新表id】
        this.row.f_userfiles_id = meterinfo.data.new_userfiles_id

        if (this.newinfo.pricename.length > 0) {
          let param = {
            f_userinfo_id: this.row.f_userinfo_id,
            f_userfiles_id: this.row.f_userfiles_id,
            f_user_id: this.row.f_user_id,
            f_user_name: this.row.f_user_name,
            f_user_type: this.newinfo.f_user_type[0],
            f_gasproperties: this.newinfo.f_gasproperties[0],
            f_price_type: this.newinfo.pricetype[0],
            f_price_id: this.newinfo.pricename[0].f_price_id,
            f_filialeid: this.$login.f.orgid,
            f_operator: this.$login.f.name,
            f_operatorid: this.$login.f.id,
            f_orgid: this.$login.f.orgid,
            f_orgname: this.$login.f.orgs,
            f_depid: this.$login.f.depids,
            f_depname: this.$login.f.deps,
            f_perform_date: this.newinfo.f_perform_date,
            f_change_reason: ''
          }

          await this.$resetpost('rs/logic/user_pricechange', {data: param}, {resolveMsg: '更新气价成功', rejectMsg: '更新气价失败'})
        }
        let msg = await this.$showMessage('已成功换表，是否进入补气或购气界面', ['confirm', 'cancel'])
        if (msg == 'confirm') {
          this.$dispatch('get-new-row', this.row)
        } else {
          this.$dispatch('success')
        }
        if (this.config.dispatch) {
          await this.$showMessage(`是否添加派工单`, ['confirm', 'cancel']).then((res) => {
            if (res === 'confirm') {
              let batch = {
                sf_id: meterinfo.data.id,
                f_userinfo_code: this.row.f_userinfo_code,
                f_dispathch_name: this.row.f_user_name,
                f_phone: this.row.f_user_phone,
                f_dispathch_address: this.row.f_address,
                f_dispathch_type: '安装',
                f_source: '换表',
                f_remarks: this.model.f_comments,
                f_operator_date: this.$login.toStandardTimeString(),
                f_orgid: this.$login.f.orgid,
                f_dispathch_state: '待分配'
              }
              console.log('111:', batch)
              this.$resetpost('rs/logic/savePatch', batch).then((res1) => {
                // this.params.rows.splice(index, 1)
                console.log('更新成功！--------------------->', res1.data.id)
              })
            }
          })
        }
      } catch (error) {
        console.log('抛出的错误。。', error)
        let res = error.data.toString()
        this.$showAlert(res, 'danger', 2000)
        this.$dispatch('refresh')
      }
    },
    pregasChange () {
      this.commitflag = false
      // 每种表对应的计算方式都不一样
      if (this.row.f_meter_type === '气量卡表') {
        this.calGasCardRemanent()
      } else if (this.row.f_meter_type === '金额卡表') {
        // this.$showAlert('金额卡表换表尚在开发中，敬请期待！！', 'warning', 5000)
        // this.$dispatch('refresh')
        this.calMoneyCardRemanent()
      } else if (this.row.f_meter_type === '物联网表') {
        if ((parseInt(this.row.f_balance_amount) < (parseInt(this.model.f_using_base_old) - parseInt(this.row.f_meter_base)) * this.model.f_remanent_price)) {
          this.$showMessage('该表可能存在超用，请核实输入后进行换表操作！！', ['confirm', 'cancel']).then((res) => {
            if (res === 'confirm') {
              this.$dispatch('button-specifies', {name: '超用收费', value: 'over-use-charge'}, this.row)
            }
          })
        }
        this.Iotjisuan()
      }
      let msg = ''
      if (this.row.f_meter_type.includes('机表') || this.row.f_meter_type.includes('物联网表')) {
        console.log(this.config.castInt)
        let a = this.config.castInt ? parseInt(this.model.f_using_base_old) : this.model.f_using_base_old
        let b = this.config.castInt ? parseInt(this.row.f_meter_base) : this.row.f_meter_base
        console.log(a + '===========')
        console.log(b + '===========')
        if (a > b) {
          msg = (this.row.f_meter_type === '机表' ? '该用户表底数大于上次抄表底数，请确定是否继续生成欠费记录' : '该用户表底数大于上次抄表底数，请确定是否进行结算')
        } else if (this.row.f_capacity && this.row.f_capacity > 0 && (parseInt(this.model.f_using_base_old) < parseInt(this.row.f_meter_base))) {
          msg = '该用户表底数大于上次抄表底数，且已超越最大量程，请确定是否继续生成欠费记录'
        }
      }
      debugger
      if ((this.row.f_meter_type.includes('机表') || this.row.f_meter_type.includes('物联网表')) && msg) {
        this.$showMessage(msg, ['confirm', 'cancel']).then((res) => {
          if (res === 'confirm') {
            let url = this.row.f_meter_type.includes('物联网表') ? 'rs/logic/changeMeterWebHand' : 'rs/logic/changeMeterHand'
            let data = {
              downDate: this.$login.toStandardTimeString(),
              startDate: this.$login.toStandardDateString(),
              endDate: this.$login.toStandardDateString(),
              condition: `f_userfiles_id = '${this.row.f_userfiles_id}'`,
              f_operator: this.$login.f.name,
              f_operatorid: this.$login.f.id,
              f_meternumber: this.row.f_meternumber,
              f_userinfo_id: this.row.f_userinfo_id,
              f_userfiles_id: this.row.f_userfiles_id,
              f_serial_number: this.model.f_serial_number,
              f_meterbase: this.model.f_using_base_old,
              f_meter_brand: this.row.f_meter_brand,
              f_meter_classify: this.row.f_meter_type,
              f_price_id: this.row.f_price_id
            }
            this.$resetpost(url, {data: data}, {resolveMsg: '生成欠费成功', rejectMsg: '生成欠费失败'}).then((res) => {
              console.log('成功')
              if (this.row.f_meter_type.includes('物联网表')) {
                this.$dispatch('refresh')
              } else {
                this.$dispatch('button-specifies', {name: '机表收费', value: 'machine-charge'}, this.row)
              }
            })
          }
        })
      }
    },
    async Iotjisuan () {
      let f_remanent_gas
      let f_remanent_money
      if (this.row.f_collection_type == '按气量') {
        f_remanent_gas = (this.row.f_balance_gas - 0)
        if (this.row.f_remanent_type == 1) {
          f_remanent_gas += (this.row.f_remanent_gas - 0)
        }
      } else {
        f_remanent_money = (this.row.f_balance_amount - 0).toFixed(4)
        if (this.row.f_remanent_type == 1) {
          if (this.row.f_remanent_gas > 0) {
            f_remanent_money = (this.model.f_remanent_money - 0) + ((this.row.f_remanent_gas - 0) * (this.row.f_remanent_price - 0)).toFixed(4)
          } else if (this.row.f_remanent_money > 0) {
            f_remanent_money = (this.model.f_remanent_money - 0) + (this.row.f_remanent_money - 0)
          }
        }
      }
      let gas = (this.model.f_using_base_old - 0) - (this.row.f_meter_base - 0)
      let getAmount = await this.$CommonService.gasCalculate(this.row, gas)
      if (this.model.f_remanent_price > 0) {
        this.model.f_remanent_gas = (f_remanent_gas - gas).toFixed(4)
        this.model.f_remanent_money = (f_remanent_money - getAmount.data.chargenum).toFixed(4)
      }
    },
    typeChange () {
      if (this.model.f_type.includes('清零')) {
        let oldMeter = {
          f_meter_type: this.row.f_meter_type,
          f_collection_type: this.row.f_collection_type
        }
        let newMeter = {
          f_meter_type: this.row.f_meter_type,
          f_collection_type: this.row.f_collection_type
        }
        let res = this.$ChangeMeter.changeMeter(oldMeter, newMeter, this.row)
        console.log('看看新旧表的转换结果', res)
        this.changeType = res.name
      } else {
        this.changeType = ''
      }
    },

    initData () {
      this.commitflag = false
      if (this.row.f_meter_type == '物联网表') {
        // 判断是否需要结算
        // if (this.row.f_collection_type == '按气量') {
        //   this.calGasIOTRemanent()
        // } else {
        //   this.calMoneyIOTRemanent()
        // }
      } else if (this.row.f_meter_type == '机表') {
        this.validateOwe()
      } else {
        this.pregasChange()
      }
    },

    calGasCardRemanent () {
      // 拿到旧表底数 和【累计购气量+初始底数】比较  这里剩余气量如果是清零补气的就不加，如果是换表补气的就加
      let param = this.row.f_total_gas + this.row.f_initial_base

      if (this.row.f_remanent_type == 1) {
        param += this.row.f_remanent_gas
      }

      if (this.model.f_using_base_old > param) {
        this.$showAlert('该表可能存在超用，请核实输入后进行换表操作！！', 'warning', 5000)
        this.$dispatch('refresh')
      }
      if (this.model.f_remanent_price > 0) {
        this.model.f_remanent_gas = (param - (this.model.f_using_base_old - 0)).toFixed(4)
      }
    },

    calMoneyCardRemanent () {
      if (!this.model.f_remanent_money) {
        this.model.f_remanent_money = ''
      }
    },

    gasModelChange (val) {
      console.log('新表信息', val)
      if (val.length > 0) {
        this.commitflag = false
        // 新气表信息已选
        let oldMeter = {
          f_meter_type: this.row.f_meter_type,
          f_collection_type: this.row.f_collection_type
        }
        let newMeter = {
          f_meter_type: val[0].f_meter_type,
          f_collection_type: val[0].f_collection_type
        }
        let res = this.$ChangeMeter.changeMeter(oldMeter, newMeter, this.row)
        console.log('看看新旧表的转换结果', res)
        this.changeType = res.name
/*        if (this.addbalance) {
          this.addbalance = false
          this.model.f_remanent_money = (this.model.f_remanent_money - 0) - (this.row.f_balance - 0)
        }
        if (this.addgas) {
          this.addgas = false
          this.model.f_remanent_gas = (this.model.f_remanent_gas - 0) - (this.addgasnum - 0)
          this.addgasnum = 0
        }
        if (newMeter.f_meter_type == '物联网表' && newMeter.f_collection_type == '按金额' && (!this.addbalance)) {
          this.addbalance = true
          this.model.f_remanent_money = this.model.f_remanent_money ? (this.model.f_remanent_money - 0) + (this.row.f_balance - 0) : (this.row.f_balance - 0)
          if (!this.isGas) {
            this.addgas = true
          }
        }
        if (newMeter.f_meter_type == '物联网表' && newMeter.f_collection_type == '按气量' && (!this.addgas)) {
          this.addgas = true
          debugger
          this.addgasnum = ((this.row.f_balance - 0) / this.model.f_remanent_price).toFixed(4)
          this.model.f_remanent_gas = this.model.f_remanent_gas ? (this.model.f_remanent_gas - 0) + (this.addgasnum - 0) : this.addgasnum
          if (!this.isGas) {
            this.addbalance = true
            this.model.f_remanent_money = this.model.f_remanent_money ? (this.model.f_remanent_money - 0) + (this.row.f_balance - 0) : (this.row.f_balance - 0)
          }
        } */
      }
    },

    remanentChange () {
      this.commitflag = true
      // 气量转金额 或者 金额转气量的时候对气量和金额不做限制， 可以修改， 但是只变单价
      this.model.f_remanent_price = ((this.model.f_remanent_money) / (this.model.f_remanent_gas)).toFixed(4)
    },

    async validateOwe () {
      let http = new HttpResetClass()
      let audits = await http.load('POST', 'rs/sql/singleTable_OrderBy', {
        data: {
          items: 'id',
          tablename: 't_handplan',
          condition: ` f_user_id  = '${this.row.f_user_id}' and  f_hand_state = '有效' and f_meter_state = '待审核' `,
          orderitem: ' id desc'
        }
      }, {resolveMsg: null, rejectMsg: null}
      )
      console.log('获取到的待审核记录', audits.data)
      this.audits = audits.data
      if (this.audits.length > 0) {
        this.$showAlert('此用户还有待审核的抄表记录，请到抄表审核页面审核完成后再对用户进行换表操作', 'warning', 5000)
        this.$dispatch('refresh')
        return
      }
      let books = await http.load('POST', 'rs/sql/singleTable_OrderBy', {
        data: {
          items: 'f_whether_pay',
          tablename: 't_handplan',
          condition: ` f_user_id  = '${this.row.f_user_id}' and f_oughtfee > 0 and  f_hand_state = '有效' and f_meter_state='已抄表' `,
          orderitem: ' id desc'
        }
      }, {resolveMsg: null, rejectMsg: null}
      )
      console.log('获取到的欠费记录', books)
      this.books = books
      // 如果是机表验证是否有欠费
      if ((this.row.f_balance - 0) < 0) {
        this.$showAlert('该表有欠费，请到机表缴费界面进行缴费', 'warning', 3000)
        this.$dispatch('button-specifies', {name: '机表收费', value: 'machine-charge'}, this.row)
      }
    }
  },

  watch: {
    'row' () {
      console.log('-------------------------------')
      console.log(this.row)
    },
    'model.f_remanent_money' (val) {
      console.log('观察补气金额', val)
      if (!this.isGas) {
        this.model.f_remanent_gas = (val / this.model.f_remanent_price).toFixed(4)
      }
      if (this.model.f_using_base_old) {
        this.commitflag = true
      }
    },
    'model.f_remanent_gas' (val) {
      if (this.isGas) {
        this.model.f_remanent_money = (val * this.model.f_remanent_price).toFixed(4)
      }
      if (this.model.f_using_base_old) {
        this.commitflag = true
      }
    }
  }
}
</script>
<style lang="less">
  #ChangeMeter {
    .col-sm-4 {
      .font_normal_body {
        width: 73px;
        overflow: auto;
        white-space: nowrap;
        // 指滚动条两边的按钮
        &::-webkit-scrollbar-button {
          display: none;
        }
        // 滚动条的宽度
        &::-webkit-scrollbar {
          width: 5px !important;
          height: 5px !important;
        }
        // 滚动条的设置
        &::-webkit-scrollbar-thumb {
          background-color: #ddd;
          background-clip: padding-box;
        }
        &::-webkit-scrollbar-thumb:hover {
          background-color: #bbb;
        }
        &::-webkit-scrollbar-track {
          /*滚动条里面轨道*/
          box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
          background: #ededed;
        }
      }
    }
  }
</style>
