<template>
  <div class="auto">
    <validator name='m'>
      <meter-message :metermessage.sync="model.metermessage" @valid="meterinfo = true"
                     @invalid="meterinfo = false" @gasmodel="gasModelChange" v-ref:metermsg></meter-message>
      <form novalidate class="form-horizontal">

        <!-- 相关补气量组件 -->

        <!-- 气量 -> 气量 -->
        <div class="row" style="margin-top:10px;" v-if="changeType.name === 'gasToGas' && row.f_newremanent_gas > 0">
          <div class="col-sm-4 form-input-group">
            <label for="f_remanent_gas" class=" col-sm-2 control-label">剩余补气量:</label>
            <div class="col-sm-2">
              <input class="form-control" type="text" v-model="row.f_newremanent_gas" disabled>
            </div>
          </div>
          <div class="col-sm-4 form-input-group" v-if="!this.model.metermessage.gasbrand[0].f_meter_type.includes('机表')">
            <label for="f_pregas" class=" col-sm-2 control-label">本次补气量:</label>
            <div class="col-sm-2">
              <input class="form-control" type="number" v-model="model.f_pregas" placeholder="本次补气量" :disabled="changeType.all" @blur="pregasChange()">
            </div>
          </div>
          <div class="col-sm-4 form-input-group" v-else>
              <strong>注: 剩余气量将在下次抄表时进行扣减</strong>
          </div>
          <div class="col-sm-4 form-input-group" v-if="!changeType.all">
            <label for="f_remanent_gas" class=" col-sm-2 control-label">剩余补气量:</label>
            <div class="col-sm-2">
              <input class="form-control" type="text" v-model="f_remanent_gas" disabled>
            </div>
          </div>
        </div>

        <!-- 气量 -> 金额 -->
        <div class="row" style="margin-top:10px;" v-if="changeType.name === 'gasToAmount' && row.f_newremanent_gas > 0">
          <div class="col-sm-4 form-input-group">
            <label for="f_remanent_gas" class=" col-sm-2 control-label">剩余补气量:</label>
            <div class="col-sm-2">
              <input class="form-control" type="text" v-model="row.f_newremanent_gas.toFixed(2)" disabled>
            </div>
          </div>
          <div class="col-sm-4 form-input-group">
            <label for="f_pregas" class=" col-sm-2 control-label">单价:</label>
            <div class="col-sm-2">
              <input class="form-control" type="number" v-model="model.f_price" placeholder="单价">
            </div>
          </div>
          <div class="col-sm-4 form-input-group">
            <label for="f_remanent_gas" class=" col-sm-2 control-label">本次充值金额:</label>
            <div class="col-sm-2">
              <input class="form-control" type="text" v-model="f_cal_amount" disabled>
            </div>
          </div>
        </div>

        <!-- 金额 -> 气量 -->
        <div class="row" style="margin-top:10px;" v-if="changeType.name === 'amountToGas' && row.f_newremanent_amount > 0">
          <div class="col-sm-4 form-input-group">
            <label for="f_newremanent_amount" class=" col-sm-2 control-label">剩余金额:</label>
            <div class="col-sm-2">
              <input class="form-control" type="text" v-model="row.f_newremanent_amount.toFixed(2)" disabled>
            </div>
          </div>
          <div class="col-sm-4 form-input-group">
            <label for="f_pregas" class=" col-sm-2 control-label">单价:</label>
            <div class="col-sm-2">
              <input class="form-control" type="number" v-model="model.f_price" placeholder="单价">
            </div>
          </div>
          <div class="col-sm-4 form-input-group">
            <label for="f_remanent_gas" class=" col-sm-2 control-label">本次补气量:</label>
            <div class="col-sm-2">
              <input class="form-control" type="text" v-model="f_cal_gas" disabled>
            </div>
          </div>
        </div>

        <!-- 金额 -> 金额 -->
        <div class="row" style="margin-top:10px;" v-if="changeType.name === 'amountToAmount' && row.f_newremanent_amount > 0">
          <div class="col-sm-4 form-input-group">
            <label for="f_newremanent_amount" class=" col-sm-2 control-label">剩余金额:</label>
            <div class="col-sm-2">
              <input class="form-control" type="text" v-model="row.f_newremanent_amount.toFixed(2)" disabled>
            </div>
          </div>
          <div class="col-sm-4 form-input-group" v-if="!this.model.metermessage.gasbrand[0].f_meter_type.includes('机表')">
            <label for="f_remanent_gas" class=" col-sm-2 control-label">本次充值金额:</label>
            <div class="col-sm-2">
              <input class="form-control" type="text" v-model="model.f_preamount" disabled>
            </div>
          </div>
          <div class="col-sm-4 form-input-group" v-else>
            <strong>注: 剩余金额将累计至账户余额中</strong>
          </div>
        </div>


        <div class="row" style="margin-top:10px;">
          <div class="col-sm-4 form-input-group">
            <label for="f_changemeter_type" class=" col-sm-2 control-label">换表类型:</label>
            <div class="col-sm-2">
              <v-select id="f_changemeter_type"
                        v-model="model.f_changemeter_type"
                        placeholder='请选择'
                        :value.sync="model.f_changemeter_type"
                        :options='replacewatchtype'
                        close-on-select clear-button>
              </v-select>
            </div>
          </div>
          <div class="col-sm-4 form-input-group">
            <label for="f_changemeter_fee" class=" col-sm-2 control-label">换表金额:</label>
            <div class="col-sm-2">
              <input class="form-control" type="number" v-model="model.f_changemeter_fee" placeholder="换表金额">
            </div>
          </div>

          <div class="col-sm-4 form-input-group">
            <label for="f_change_operator" class=" col-sm-2 control-label">换表人:</label>
            <div class="col-sm-2">
              <!-- <input class="form-control" 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"
                        :options='changepersons'
                        close-on-select></v-select>
            </div>
          </div>

        </div>

        <div class="row" style="margin-top:10px;">
          <div class="form-group form-input-group col-sm-4">
            <label for="f_paytype" class=" col-sm-2 control-label">付款方式:</label>
            <div class="col-sm-2">
              <v-select id="f_payment"
                        v-model="f_payment"
                        placeholder='请选择'
                        :value.sync="model.f_payment"
                        :options='paytype'
                        close-on-select clear-button></v-select>
            </div>
          </div>
          <div class="form-group form-input-group col-sm-4">
            <label for="f_print" class="control-label col-sm-2">打印格式:</label>
            <div class="col-sm-2">
              <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>
          <div class="col-sm-4 form-input-group">
            <label for="f_changemeter_date" class=" col-sm-2 control-label">换表时间:</label>
            <div class="col-sm-2">
              <datepicker placeholder="换表时间"
                          v-model="model.f_changemeter_date"
                          :value.sync="model.f_changemeter_date"
                          :format="'yyyy-MM-dd HH:mm:ss'"
              ></datepicker>
            </div>
          </div>
        </div>
        <div class="row" style="margin-top:10px;">
          <div class="form-group form-input-group col-sm-4" v-if="model.f_payment[0].includes('POS')">
            <label for="f_voucher_number" class="control-label col-sm-2">凭证号:</label>
            <input type="text" class="form-control col-sm-2" v-model="model.f_voucher_number" placeholder="凭证号">
          </div>
          <div class="col-sm-4 form-input-group">
            <label for="f_reason" class=" col-sm-2 control-label">换表原因:</label>
            <div class="form-group col-sm-2 ">
              <v-select id="f_reason"
                        v-model="model.f_reason"
                        placeholder='换表原因'
                        :value.sync="model.f_reason"
                        :options='reason'
                        close-on-select></v-select>
            </div>
          </div>
        </div>
        <div class="row" style="margin-top:10px;" v-if="model.f_reason[0] ==='其他'">
          <div class="col-sm-12 form-input-group">
            <label for="f_reason" class=" col-sm-2 control-label">换表原因:</label>
            <textarea class="col-sm-10 form-control" rows="3" v-model="model.f_othereason" placeholder="请填写换表原因"></textarea>
          </div>
        </div>
      </form>
      <print-bill :show="print" :bill-manager='config.hasBillManage' v-ref:printbill :bill-url='billUrl' v-on:toggle="close" :data='row' @printok="printok" ></print-bill>
    </validator>
    <div style="text-align:right;height:auto;margin-top:10px;">
      <button class="btn btn-success" @click="changeAndPlus()"
              v-if="(model.f_pregas - 0) > 0 || (model.f_preamount - 0) > 0"
              :disabled='!(meterinfo && $m.valid)' >换表并补气
      </button>
      <button class="btn btn-success" @click="confirm()" title="演示系统暂不支持" :disabled="true"
              v-if="(model.f_pregas - 0) === 0 && (model.f_preamount - 0) === 0">确认
      </button>
      <button class="btn btn-default" @click="clean()" >取消
      </button>
    </div>
    <upload :blodid="blodid"></upload>
  </div>
</template>
<script>
  /**
   *换表管理
   *换新表信息
   */
  import co from 'co'
  import Vue from 'vue'

  let getPriceGen = async function (self) {
    await self.$getConfig(self,'ChangeNewMeter')
    console.log('换表config', self.config)
    self.model.f_print = self.config.printType instanceof Array ? self.config.printType : [self.config.printType]
    self.model.f_payment = [self.config.payment]
    self.mulPrint = self.config.printType instanceof Array
    let getPrices = await self.$resetpost('rs/sql/getFirstPrice', {data: {f_price_id: self.row.f_price_id, f_filialeids: self.$login.f.f_orgids}}, {
      resolveMsg: null,
      rejectMsg: null
    })
    self.model.f_price = getPrices.data[0].f_price
  }

  let changeMeterGen = async function (self) {
    try {
      let res = await self.$ChangeMeterService.changeNewMeter(self.model, self.row)
      console.log('换表返回', res, self.model)
      // 开始打票
      if (self.config.hasPrint) {
        if (self.model.f_print.indexOf('普通收据') !== -1) {
          if (self.config.hasBillManage) {
            // 启用发票管理，获取票据管理中的票号并存储记录
            self.row.id = res.data.id
            self.row.f_bill_type = '换表'
            self.row.f_bill_style = self.model.f_print[0]
            self.row.f_collection = self.model.f_changemeter_fee
            self.billUrl = 'rs/report/changemeter_bill'
            self.print = true
          } else {
            self.row.id = res.data.id
            self.billUrl = 'rs/report/changemeter_bill'
            self.print = true
          }
        } else {
          if (self.model.f_print[0] === '电子发票') {
            self.$CommonService.openEticket(res, '换表费')
            self.$dispatch('success')
          }
        }
      } else {
        self.$dispatch('success')
      }
    } catch (error) {
      self.$showAlert(error, 'danger', 0)
      self.$dispatch('refresh')
    }
  }

  export default {
    data() {
      return {
        config: {
          hasPrint : false,  //默认打票
          hasBillManage :false,  //默认不启用发票管理
          printType: '普通收据', // 收据/电子票/专用发票/国税发票
          payment: '现金缴费'
        },
        model: {
          metermessage: {
            gasbrand: '',
            gasmodel: '',
            f_meter_base: 0,
            f_metertitles: ''
          },
          f_changemeter_type: '换新表',
          f_reason: '控制器坏',
          f_payment: '现金缴费',
          f_print: [],
          f_changemeter_date: this.$login.toStandardTimeString(),
          f_changemeter_fee: this.$appdata.getSingleValue('换表金额'),
          isCardMeter: false,
          isfillgas: false,
          f_pregas: 0,
          f_preamount: 0,
          f_price: 0,
          f_balance: 0,
          f_real_balance: 0,
          f_balance_gas: 0,
          f_balance_amount: 0,
          f_remanent_gas: 0
        },
        changeType: {
          name: '',
          all: false
        },
        meterinfo: false,
        money: true,
        gasTogas: false,
        gasToAmount: false,
        amountinfo: false,
        amountToAmount: false,
        viewsee: false,

        // 票据
        print: false,
        billUrl: '',
        mulPrint: false,

        f_remanent_gas: 0,  // 本次气量补不完，计算剩余的气量
        f_cal_gas: 0, // 金额转气量 按照一阶价格计算的气量
        f_cal_amount: 0, // 气量转金额时将按照一阶单价计算的金额

        blodid: '',

        replacewatchtype: this.$appdata.getParam('换表类型'),
        reason: this.$appdata.getParam('换表原因'),
        paytype: this.$appdata.getParam('付款方式'),
        printstyle: this.$appdata.getParam('打印格式')
      }
    },
    props: ['row'],
    ready() {
      this.model.f_print = [this.config.printType]
      this.blodid = this.row.f_userinfo_id
      this.getFirstPrice()
    },
    methods: {
      changeAndPlus () {
        this.model.f_remanent_gas = this.f_remanent_gas
        if (this.model.metermessage.gasbrand[0].f_meter_type.includes('卡表')) {
          //新表为卡表需要判断是否卡
          this.$showMessage(`请确保你已经插入了${this.model.metermessage.gasbrand[0].f_meter_brand}的卡？`, ['confirm', 'cancel']).then((res) => {
            if (res === 'confirm') {
              this.model.isfillgas  = true
              console.log('开始换表补气。。。', this.model, this.row)
              changeMeterGen(this)
            }
          })
        } else {
          console.log('开始物联网表换表补气。。。', this.model, this.row)
          changeMeterGen(this)
        }
      },
      confirm() {
        this.row.f_coding = this.model.metermessage.gasmodel[0].f_coding

        // 机表换其他表必须先清欠
        if (!this.model.metermessage.gasbrand[0].f_meter_type.includes('机表')) {
          if (this.row.f_meter_type === '机表' && this.row.isHasOwe === true) {
            this.$showMessage('之前机表有欠费, 换表之后欠费记录将无法缴纳，请先对之前的机表进行清欠!!', ['confirm', 'cancel']).then((res) => {
                this.$dispatch('refresh')
            })
          }
        }
        if (this.model.metermessage.gasbrand[0].f_meter_type.includes('卡表')) {
          this.$showMessage(`请确保你已经插入了${this.model.metermessage.gasbrand[0].f_meter_brand}的卡？`, ['confirm', 'cancel']).then((res) => {
              if (res === 'confirm') {
              this.model.isfillgas  = true
              changeMeterGen(this)
            }
          })
        } else {
          this.model.f_remanent_gas = this.row.f_newremanent_gas ? (this.row.f_newremanent_gas - 0) : 0
          console.log('换表。。。', this.model, this.row)
          changeMeterGen(this)
        }
      },
      clean() {
        this.$dispatch('success', '换表', this.row)
      },
      printok () {
        // 收据打完，判断是否还有其他票据进行请求
        for (let i = 0; i < this.model.f_print.length; i++) {
          if (this.model.f_print[i] === '电子发票') {
            this.$CommonService.openEticket(this.row.id, '换表费')
          }
        }
        this.$dispatch('success')
      },
      getFirstPrice() {
        getPriceGen(this)
      },
      gasModelChange (val) {
        if (val.length > 0) {
          // 新气表信息已选
          let oldMeter = {
            f_meter_type: this.row.f_meter_type
          }
          if (this.row.f_meter_type === '物联网表') {
            oldMeter.f_billing = this.row.f_billing
            oldMeter.f_calculation = this.row.f_calculation
          }

          let newMeter = {
            f_meter_type: val[0].f_meter_type
          }
          if (val[0].f_meter_type === '物联网表') {
            newMeter.f_billing = val[0].gasmodel[0].value.f_billing
            newMeter.f_calculation = val[0].gasmodel[0].value.f_calculation
          }
          let res = this.$ChangeMeter.changeMeter(oldMeter, newMeter, this.row)
          this.model = Object.assign({}, this.model, res)
          console.log('表具转换之后获取的值', res, this.model)
          this.changeType = Object.assign({}, this.changeType, res.changeType)
        }
      },
      pregasChange (val) {
        console.log('本次购气量。。。', this.row, this.model, val)
        if (this.row.f_isdecimal === '是') {
          this.model.f_pregas = (this.model.f_pregas - 0).toFixed(2)
        } else {
          this.model.f_pregas = (this.model.f_pregas - 0).toFixed(0)
        }
      }
    },
    computed: {
      'f_remanent_gas' () {
        console.log('计算剩余气量。。', this.model.f_pregas, this.row.f_newremanent_gas, this.model.f_pregas && this.row.f_newremanent_gas > 0)
        if (this.model.f_pregas && this.row.f_newremanent_gas > 0) {
          return (this.row.f_newremanent_gas - 0) - (this.model.f_pregas - 0)
        } else {
          return 0
        }

      },
      'f_cal_gas' () {
        if (this.changeType.name && (this.row.f_newremanent_amount - 0) > 0) {
          if (this.model.metermessage.gasbrand[0].f_meter_type === '气量卡表') {
            // 涉及表上是否支持小数问题
            if (this.row.f_isdecimal === '是') {
              this.model.f_pregas = ((this.row.f_newremanent_amount - 0) / (this.model.f_price)).toFixed(2)
            } else {
              this.model.f_pregas = (this.row.f_newremanent_amount - 0) / (this.model.f_price).toFixed(0)
            }
            return this.model.f_pregas
          } else {
            return this.model.f_pregas = this.model.f_balance_gas = ((this.row.f_newremanent_amount - 0) / (this.model.f_price)).toFixed(2)
          }
        }
      },
      'f_cal_amount' () {
        if (this.changeType.name === 'gasToAmount' && this.row.f_newremanent_gas > 0) {
          // 计算本次充值金额
          console.log('计算本次充值金额', this.model.metermessage.gasbrand[0], this.model)
          if (this.changeType.name && (this.row.f_newremanent_gas - 0) > 0) {
            if (this.model.metermessage.gasbrand[0].f_meter_type === '金额卡表') {
              // 换为金额卡表时，f_balance_amount = 0
              return this.model.f_preamount = ((this.row.f_newremanent_gas - 0) * (this.model.f_price)).toFixed(2)
            } else if (this.model.metermessage.gasbrand[0].gasmodel[0].value.f_calculation === '后付费'){
              this.model.f_preamount = ((this.row.f_newremanent_gas - 0) * (this.model.f_price)).toFixed(2)
              return this.model.f_real_balance = this.model.f_balance = (this.row.f_real_balance - 0) + (((this.row.f_newremanent_gas - 0) * (this.model.f_price)).toFixed(2) - 0)
            } else {
              console.log('计算本次充值金额2', this.model)
              return this.model.f_preamount = this.model.f_balance_amount = ((this.row.f_newremanent_gas - 0) * (this.model.f_price)).toFixed(2)
            }
          }
        }
      },
      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>
