<template>
  <div class="auto" style="overflow:auto;">
    <validator name='v'>
    <form novalidate class="form-horizontal">
      <p class="bg-info text-center" style="padding: 8px;">换表计算</p>
      <div class="row auto" >
        <div class="col-sm-4">
          <label for="f_type" class=" font_normal_body">换表类型</label>
          <v-select id="f_type"
                    v-model="model.f_type"
                    placeholder='请选择'
                    :value-single="true"
                    :value.sync="model.f_type"
                    :options='replacewatchtype'
                    :disabled="!row.f_meter_type.includes('卡表')"
                    close-on-select clear-button>
          </v-select>
        </div>
        <div class="col-sm-4">
          <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" :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>
      <div class="row auto" >

        <div class="col-sm-4" :class="[$v.f_remanent_gas.required || $v.f_remanent_gas.dctest ? 'has-error' : 'has-success']">
          <label for="f_remanent_gas" class=" font_normal_body">&nbsp;&nbsp;&nbsp;补气量</label>
          <input class="input_search" style="width:60%" type="number"
                 v-model="model.f_remanent_gas"
                 placeholder="补气量"
                 :disabled="!isGas"
                 v-validate:f_remanent_gas='{required: true, dctest: [-1, ">" ] }'>
        </div>
        <div class="col-sm-4">
          <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"
             :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="补气金额"
                 :disabled="isGas"
                 v-validate:f_remanent_money='{required: true, dctest: [-1, ">" ] }'>
        </div>
      </div>
      <div class="row auto" >
        <div class="col-sm-4">
          <label for="f_change_operator" class=" font_normal_body">&nbsp;&nbsp;&nbsp;换表人</label>
          <!-- <input class="input_search" style="width:60%" type="text" v-model="model.f_change_operator" placeholder="换表人"> -->
          <v-select id="f_change_operator"
                    v-model="model.f_change_operator"
                    placeholder='换表人'
                    :value.sync="model.f_change_operator"
                    :value-single="true"
                    :options='changepersons'
                    close-on-select></v-select>
        </div>
        <div class="col-sm-4">
          <label for="f_paytype" class=" font_normal_body">付款方式</label>
          <v-select id="f_payment"
                    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">
          <label for="f_print" class="font_normal_body">打印格式</label>
          <v-select id="print"
                    v-model="f_print"
                    placeholder='请选择'
                    :multiple="mulPrint"
                    :value.sync="model.f_print"
                    :options='printstyle'
                    close-on-select clear-button></v-select>
        </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('清零')" :metermessage.sync="model.metermessage" @valid="meterinfo = true"
                     @invalid="meterinfo = false" v-ref:metermsg></meter-message>
      <div class="row auto" style="margin-top:5px;">
        <div class="col-sm-4">
          <label for="f_othereason" class="font_normal_body">换表原因</label>
          <input class="input_search" style="width:60%" v-model="model.f_othereason" placeholder="请填写换表原因"/>
        </div>
        <div class="col-sm-8">
          <label for="f_comments" class="font_normal_body">&nbsp;&nbsp;&nbsp;备注&nbsp;&nbsp;&nbsp;</label>
          <input class="input_search" style="width:80%" v-model="model.f_comments" placeholder="备注"/>
        </div>
      </div>
      <div style="text-align:right;height:auto;">
        <button class="button_search" type="button" @click="confirm()" :disabled="(!meterinfo&& !model.f_type.includes('清零'))||!$v.valid"
        >确认
        </button>
        <button class="button_clear" type="button" @click="clean()" >取消
        </button>
      </div>
    </form>
    </validator>
  </div>
</template>
<script>
/**
 *换表管理
 *组合界面，加载机表，物联网表，气量卡表，金额卡表旧表信息，以及控制显示换新表信息
 */
import { HttpResetClass } from 'vue-client'
let getPrice = async function (self) {

  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
  }
  self.initData()
}
export default {
  title: '换表登记',
  data () {
    return {
      model: {
        metermessage: {
          f_meter_type: '',
          gasbrand: '',
          gasmodel: '',
          f_meternumber: '',
          f_meter_base: 0,
          f_metertitles: '',
          f_oldmeter_use_reference: 0 // 旧表使用量参考值
        },
        //旧表底数
        f_using_base_old: '',
        //换表补气量
        f_remanent_gas: 0,
        //换表补气单价
        f_remanent_price: 0,
        f_remanent_money: 0,
        f_type: '换新表',
        f_comments: '',
        f_othereason: '',
        f_payment: '现金缴费',
        f_print: '普通收据',
        f_state:'有效',
        f_changemeter_date: this.$login.toStandardTimeString(),
        f_changemeter_fee: this.$appdata.getSingleValue('换表金额') ? this.$appdata.getSingleValue('换表金额') : 0,
      },
      meterinfo: false,

      // 控制气量金额的编辑
      isGas: false,

      replacewatchtype: this.$appdata.getParam('换表类型'),
      reason: this.$appdata.getParam('换表原因') ? this.$appdata.getParam('换表原因') : [],
      paytype: this.$appdata.getParam('付款方式'),
      printstyle: this.$appdata.getParam('打印格式')
    }
  },
  props: ['row'],
  ready () {
    getPrice(this)
  },
  methods: {
    //返回
    clean() {
      this.$dispatch('success', '换表', this.row)
    },
    async confirm() {
      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
        let data={
          model:this.model,
          old:this.row,
        }
        let meterinfo = await this.$resetpost('rs/logic/changeMeter', data, {
          resolveMsg: null,
          rejectMsg: '换表失败！！！'
        })
        //赋值【新表id】
        this.row.f_userfiles_id=meterinfo.data.new_userfiles_id
        let msg = await this.$showMessage('已成功换表，是否进入补气或购气界面', ['confirm', 'cancel'])
        if (msg == 'confirm') {
          this.$dispatch('get-new-row', this.row)
        } else {
          this.$dispatch('success')
        }
      } catch (error) {
        console.log('抛出的错误。。', error)
          this.$showAlert(error, 'danger', 200)
          this.$dispatch('refresh')
      }
    },
    pregasChange () {
      // 每种表对应的计算方式都不一样
      if (this.row.f_meter_type == '气量卡表') {
        this.calGasCardRemanent()
      } else if (this.row.f_meter_type == '金额卡表') {
        // this.$showAlert('金额卡表换表尚在开发中，敬请期待！！', 'warning', 5000)
        // this.$dispatch('refresh')
        this.calMoneyCardRemanent()
      }
    },

    initData () {
      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 = ''
      }
    },

    calGasIOTRemanent () {
      this.model.f_remanent_gas = (this.row.f_balance_gas - 0)
      if (this.row.f_remanent_type == 1) {
        this.model.f_remanent_gas += (this.row.f_remanent_gas - 0)
      }
    },
    calMoneyIOTRemanent () {
      this.model.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) {
          this.model.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) {
          this.model.f_remanent_money = (this.model.f_remanent_money - 0) + (this.row.f_remanent_money - 0)
        }
      }
    },

    validateOwe () {
      // 如果是机表验证是否有欠费
      if ((this.row.f_balance - 0) <0) {
        this.$showAlert('该表有欠费，请到机表缴费界面进行缴费', 'warning', 3000)
        this.$dispatch('button-specifies', {name:'机表收费', value: 'machine-charge'}, this.row)
      }
    }
  },

  watch: {
    'model.f_remanent_money' (val) {
      console.log('观察补气金额', val)
      if (!this.isGas) {
        return this.model.f_remanent_gas = (val/this.model.f_remanent_price).toFixed(4)
      }
    },
    'model.f_remanent_gas' (val) {
      if (this.isGas) {
        return this.model.f_remanent_money = (val * this.model.f_remanent_price).toFixed(4)
      }
    },
  },

  computed: {
    changepersons () {
      let rs = new Array()
      for (let i = 0; i < this.$login.f.f_changemeterman.length; i++) {
        let temp = {
          label: this.$login.f.f_changemeterman[i].name,
          value: this.$login.f.f_changemeterman[i].name
        }
        rs.push(temp)
      }
      return rs
    }
  }
}
</script>
