<template>
  <div class="auto">
    <validator name='m'>
      <form novalidate class="form-horizontal">

        <div class="row" style="margin-top:10px;">
          <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.sync="model.f_type"
                      :options='replacewatchtype'
                      @change="typeChange"
                      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">
            <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"
                      :options='changepersons'
                      close-on-select></v-select>
          </div>

        </div>

        <meter-message :metermessage.sync="model.metermessage" @valid="meterinfo = true"
                     @invalid="meterinfo = false" @gasmodel="gasModelChange" v-ref:metermsg></meter-message>

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

        <!-- 气量 -> 气量 -->
        <div class="row" style="margin-top:10px;" v-if="changeType.name === 'gasToGas' && row.f_newremanent_gas > 0">
          <div class="col-sm-4">
            <label for="f_remanent_gas" class=" font_normal_body">剩余补气</label>
              <input class="input_search" style="width:60%" type="text" v-model="row.f_newremanent_gas" disabled>
          </div>
          <div v-if="!this.model.metermessage.gasbrand[0].f_meter_type.includes('机表')">
            <div class="col-sm-4" :class="[$m.f_pregas.dctest ? 'has-error' : 'has-success']">
              <label for="f_pregas" class=" font_normal_body">本次补气</label>
                <input class="input_search" style="width:60%" type="number" v-model="model.f_pregas" v-validate:f_pregas='{dctest: [row.f_newremanent_gas, "<=" ] }'
                       placeholder="本次补气量" :disabled="changeType.all" @blur="pregasChange()">
            </div>
          </div>
          <div class="col-sm-4" v-else>
            <strong>注: 剩余气量将在下次抄表时进行扣减</strong>
          </div>
          <div class="col-sm-4" v-if="!changeType.all">
            <label for="f_remanent_gas" class=" font_normal_body">剩余补气</label>
              <input class="input_search" style="width:60%" type="text" v-model="f_remanent_gas" disabled>
          </div>
        </div>

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

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

        <!-- 金额 -> 金额 -->
        <div class="row" style="margin-top:10px;" v-if="changeType.name === 'amountToAmount' && row.f_newremanent_amount > 0">
          <div class="col-sm-4">
            <label for="f_newremanent_amount" class=" font_normal_body">剩余金额</label>
              <input class="input_search" style="width:60%" type="text" v-model="row.f_newremanent_amount.toFixed(4)" disabled>
          </div>
          <div class="col-sm-4" v-if="model.metermessage.gasbrand[0].f_meter_type.includes('金额卡表') || model.metermessage.gasbrand[0].f_meter_type.includes('物联网')">
            <label class=" font_normal_body">充值金额</label>
              <input class="input_search" style="width:60%" type="text" v-model="model.f_preamount" disabled>
          </div>
          <div class="col-sm-4" v-else>
            <strong>注: 剩余金额将累计至账户余额中</strong>
          </div>
        </div>


        <div class="row" style="margin-top:10px;">
          <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.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 class="col-sm-4">
            <label for="f_changemeter_date" class=" font_normal_body">换表时间</label>
              <datepicker placeholder="换表时间" style="width:60%"
                          v-model="model.f_changemeter_date"
                          :value.sync="model.f_changemeter_date"
                          :format="'yyyy-MM-dd HH:mm:ss'"
              ></datepicker>
          </div>
        </div>
        <div class="row" style="margin-top:10px;">
          <div class="col-sm-4" v-if="model.f_payment[0].includes('POS')">
            <label for="f_voucher_number" class="font_normal_body">凭证号</label>
            <input type="text" class="input_search col-sm-2" v-model="model.f_voucher_number" placeholder="凭证号">
          </div>
          <div class="col-sm-4">
            <label for="f_reason" class=" font_normal_body">换表原因</label>
              <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 class="row" style="margin-top:10px;" v-if="model.f_reason[0] ==='其他'">
          <div class="col-sm-12">
            <label for="f_reason" class=" font_normal_body">换表原因</label>
            <textarea class="col-sm-10 input_search" rows="1" v-model="model.f_othereason" placeholder="请填写换表原因"></textarea>
          </div>
        </div>
      </form>
      <accept-bill :show="acceptprint" :bill-url='acceptUrl' v-on:toggle="close" :data='row' :billdata="printData" v-ref:acceptbill @closeaccept="closeAccept"></accept-bill>
      <validate-bill v-if="hasValidateBill" :data="model" @validate-bill="validateBill"></validate-bill>
      <print-bill :show="print" :bill-config='config' :bill-data='billData' v-ref:printbill v-on:toggle="close" :data='row' @printok="printok" ></print-bill>
    </validator>
    <div style="text-align:right;height:auto;margin-top:10px;">
      <button class="button_search" @click="accept()" v-if="config.hasAcceptance" :disabled="!meterinfo || validateOk">受理单</button>
      <button class="button_search" style="width: max-content"  @click="changeAndPlus()"
              v-if="(model.f_pregas - 0) > 0 || (model.f_preamount - 0) > 0"
              :disabled='!(meterinfo && $m.valid) || validateOk' >换表并补气
      </button>
      <button class="button_search" @click="confirm()" :disabled="!meterinfo || validateOk"
              v-if="(model.f_pregas - 0) === 0 && (model.f_preamount - 0) === 0">确认
      </button>
      <button class="button_clear" @click="clean()" >取消
      </button>
    </div>
    <upload :blodid="blodid"  isremark="true" fusetype="换表"></upload>
  </div>
</template>
<script>
  /**
   *换表管理
   *换新表信息
   */

  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

    self.model.f_use_type = self.config.billType
    self.model.f_bill_type = self.model.f_print
    self.hasValidateBill = self.config.hasBillManage

    let getPrices = await self.$resetpost('rs/sql/getFirstPrice', {data: {f_price_id: self.row.f_price_id, f_filialeids: self.$login.f.orgid}}, {
      resolveMsg: null,
      rejectMsg: null
    })
    if (getPrices.data.length > 0) {
      self.model.f_price = getPrices.data[0].f_price
    }
    // 获取旧表使用量
    let param = {
      f_user_id: self.row.f_user_id
    }
    let getOldUsed = await self.$CommonService.feeCalculate(param, 0)
    console.log('获取旧表使用量', getOldUsed.data.sumamount)
    self.model.f_sumamount = (getOldUsed.data.sumamount - 0).toFixed(4)
  }

  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
            self.row.f_bill_type = '换表'
            self.row.f_bill_style = self.model.f_print[0]
            self.print = true
          } else {
            self.row.id = res
            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,  //默认不启用发票管理
          billType: '其他费用',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
          printType: '普通收据', // 收据/电子票/专用发票/国税发票
          payment: '现金缴费',
          hasAcceptance: false // 是否需要打印受理单
        },
        model: {
          metermessage: {
            gasbrand: '',
            gasmodel: '',
            f_meternumber: '',
            f_meter_base: 0,
            f_metertitles: '',
            f_oldmeter_use: 0,
            f_oldmeter_use_reference: 0 // 旧表使用量参考值
          },
          f_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,
          f_sumamount: 0 // 当前累购量
        },
        changeType: {
          name: '',
          all: false
        },
        meterinfo: false,
        money: true,
        gasTogas: false,
        gasToAmount: false,
        amountinfo: false,
        amountToAmount: false,
        viewsee: false,

        // 票据
        print: false,
        billData: {
          url: 'rs/report/change_meter',
          bill: ''
        },
        mulPrint: false,

        // 启用发票管理需要对票号进行验证
        hasValidateBill: false,
        validateOk: false,

        // 受理单
        acceptprint: false,
        acceptUrl: '',
        printData:{
          reason: '',
          totals: '',
          oldMeterBase:'',
          newMeterBase:'',
          fillgas:''
        },

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

        isChargeprice: false, // 当预结算转为后结算时并有气量转金额，需要核减气量的价格明细，为划价时使用

        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.$dispatch('no-button')
        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.isCardMeter = true
              console.log('开始换表补气。。。', this.model, this.row)
              changeMeterGen(this)
            }
          })
        } else {
          // 当预结算转为后结算时并有气量转金额，需要核减气量的价格明细，为划价时使用
          this.row.isChargeprice = this.changeType.name === 'gasToAmount' && this.model.metermessage.gasbrand[0].f_meter_type.includes('物联网')
          console.log('开始物联网表换表补气。。。', this.model, this.row)
          changeMeterGen(this)
        }
      },
      confirm() {
        this.model.f_remanent_gas = this.f_remanent_gas
        this.row.f_coding = this.model.metermessage.gasmodel[0].f_coding
        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.isCardMeter = true
                changeMeterGen(this)
              }
          })
        } else {
          this.model.f_pregas = this.model.f_remanent_gas = this.row.f_newremanent_gas ? (this.row.f_newremanent_gas - 0) : 0
          changeMeterGen(this)
        }
      },

      typeChange () {
        if (this.model.f_type.length > 0) {
          if (this.model.f_type[0].includes('清零')) {
            this.model.metermessage.f_meternumber = this.row.f_meternumber
            this.$GetSaleParam.getGasbrand().forEach((item) => {
              if (item.value.id == this.row.f_gasbrand_id) {
                this.model.metermessage.gasbrand = [item.value]
                item.value.gasmodel.forEach((val) => {
                  if (val.value.id == this.row.f_gasmodel_id) {
                    this.model.metermessage.gasmodel = [val.value]
                  }
                })
              }
            })
            this.$refs.metermsg.resetValidate()
          }
        }
      },

      clean() {
        this.$dispatch('success', '换表', this.row)
      },
      validateBill (val) {
        this.validateOk = !val.isOk
        this.billData.bill = val.bill
      },
      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')
      },
      close () {
        this.print = false
        this.acceptprint = false
        this.clean()
      },
      getFirstPrice() {
        getPriceGen(this)
      },
      gasModelChange (val) {
        if (val.length > 0) {
          // 计算旧表使用量
          console.log('计算旧表使用量', this.row.f_newremanent_gas, this.model.f_sumamount , (this.model.f_sumamount - 0) - this.row.f_newremanent_gas ? (this.row.f_newremanent_gas - 0) : 0)
          let temp = (this.model.f_sumamount - 0) - (this.row.f_newremanent_gas ? (this.row.f_newremanent_gas - 0) : 0)
          if (temp >= 0) {
            this.model.metermessage.f_oldmeter_use_reference = this.model.metermessage.f_oldmeter_use = (temp).toFixed(4)
          }
          // 机表换其他表必须先清欠
          if (!this.model.metermessage.gasbrand[0].f_meter_type.includes('机表')) {
            if (this.row.f_meter_type === '机表' && this.row.isHasOwe === true) {
              this.$showMessage('之前机表有欠费, 换表之后欠费记录将无法缴纳，请先对之前的机表进行清欠!!', ['confirm']).then((res) => {
                this.$dispatch('refresh')
              })
            }
          }
          // 新气表信息已选
          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(4)
        } else {
          this.model.f_pregas = (this.model.f_pregas - 0).toFixed(0)
        }
      },
      accept () {
        // 打印受理单
        console.log('受累单中model',this.model)
        console.log('受累单中row',this.row)
        if (this.model.f_othereason || this.model.f_reason[0] ==='其他') {
          this.printData.reason = `'${this.model.f_othereason}'`
        }else {
          this.printData.reason = this.model.f_comments? `'${this.model.f_reason[0]}'` : ''+  `'${this.model.f_reason}'`
        }
        this.printData.totals = `'${this.row.f_total_gas}'`
        this.printData.oldMeterBase = `'${this.row.f_tablebase}'`
        this.printData.newMeterBase = `'${this.model.metermessage.f_meter_base}'`
        this.printData.fillgas = `'${this.model.f_pregas}'`
        console.log('受累单中printData',this.printData)
        this.acceptUrl = 'rs/report/acceptChangeMeter_bill'
        this.gasModelChange = true
      },
      closeAccept () {
        this.acceptprint = false
      }
    },
    watch: {
      'changeType.name' (val) {
        console.log('观察到换表类型。。。', val)
        if (val === 'gasToAmount' && this.row.f_newremanent_gas > 0) {
          // 计算本次充值金额
          console.log('计算本次充值金额', this.model.metermessage.gasbrand[0], this.model)
          if (this.model.metermessage.gasbrand[0].f_meter_type === '金额卡表') {
            // 换为金额卡表时，f_balance_amount = 0
            this.model.f_preamount = ((this.row.f_newremanent_gas - 0) * (this.model.f_price)).toFixed(4)
          } 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(4)
            this.model.f_balance = ((this.row.f_newremanent_gas - 0) * (this.model.f_price)).toFixed(4)
          } else {
            console.log('计算本次充值金额2', this.model)
            this.model.f_preamount = this.model.f_balance_amount = ((this.row.f_balance - 0) + (this.row.f_newremanent_gas - 0) * (this.model.f_price)).toFixed(4)
          }
        }
      }
    },
    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(4)
            } 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(4)
          }
        }
      },
      '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.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(4)
        //   } 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(4)
        //     return this.model.f_balance = ((this.row.f_newremanent_gas - 0) * (this.model.f_price)).toFixed(4)
        //   } else {
        //     console.log('计算本次充值金额2', this.model)
        //     return this.model.f_preamount = this.model.f_balance_amount = ((this.row.f_balance - 0) + (this.row.f_newremanent_gas - 0) * (this.model.f_price)).toFixed(4)
        //   }
        // }
      },
      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>
