<template>
  <div class="flex-row">
    <div class="span" style="overflow-y: auto;">
      <validator name='v'>
        <form novalidate class="form-horizontal">
          <p class="bg-info text-center" style="padding: 8px;">换表{{showGas ? '补气' : '补费'}}</p>

          <div class="row">
            <div class="col-sm-4" >
              <label for="f_pregas" class=" font_normal_body">剩余气量</label>
              <input class="input_search" style="width:60%" type="number"
                     v-model="model.f_fill_gas"
                     placeholder="剩余补气量" disabled>
              <!--<button type="button" class="btn button_new btn-lg" style="width:13%"-->
                      <!--@click="openExplain">-->
                <!--<span class="glyphicon glyphicon-question-sign"></span>-->
              <!--</button>-->
            </div>
            <div class="col-sm-4" >
              <label for="f_pregas" class=" font_normal_body">应补金额</label>
              <input class="input_search" style="width:60%" type="number"
                     :value="model.f_fill_money" disabled>
              <!--<button type="button" class="btn button_new btn-lg" style="width:13%"-->
                      <!--@click="openExplain">-->
                <!--<span class="glyphicon glyphicon-question-sign"></span>-->
              <!--</button>-->
            </div>
          </div>
          <div v-show="remanentfalg">
            <strong style="font-size: large" >【补气提示】:{{remanentstr}}</strong><br/>
          </div>
          <div v-show="false">
            <div class="row" style="margin-top:5px;">
              <div class="col-sm-4">
                <label class=" font_normal_body" title="参数名称：付款方式">收款方式</label>
                <v-select v-model="f_payment"
                          placeholder='请选择'
                          style="width:60%"
                          :value.sync="model.f_payment"
                          :options='paytype'
                          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='请选择'
                          style="width:60%"
                          :value.sync="model.f_print"
                          :options='printstyle'
                          close-on-select clear-button>
                </v-select>

              </div>
              <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" style="width:60%" v-model="model.f_voucher_number" placeholder="凭证号">
              </div>
            </div>

            <div class="row" style="margin-top:5px;">

              <div class="col-sm-4" v-if="(row.f_balance_gas - 0) < 0">
                <label for="f_balance_gas" class="font_normal_body">超用气量</label>
                <input type="text" class="input_search" style="width:60%" v-model="(0 - row.f_balance_gas)" disabled>
              </div>

              <div class="col-sm-4" v-if="(row.f_balance_amount - 0) < 0">
                <label for="f_balance_amount" class="font_normal_body">超用金额</label>
                <input type="text" class="input_search" style="width:60%" v-model="(0 - row.f_balance_amount)" disabled>
              </div>

              <div class="col-sm-4" v-if="showGas"
                   :class="[$v.f_pregas.required || $v.f_pregas.dctest ? 'has-error' : 'has-success']">
                <label for="f_pregas" class="font_normal_body">预购气量</label>
                <input id="f_pregas" class="input_search" style="width:60%" type="number" v-model="model.f_pregas"
                       @blur="pregas"
                       v-validate:f_pregas='{required: true, dctest: [(0 - row.f_balance_gas) < 0 ? 0 : (0 - row.f_balance_gas), ">=" ]}'
                       v-scale="[model.f_pregas, 4]">
              </div>

              <div class="col-sm-4" v-if="!showGas"
                   :class="[$v.f_preamount.required || $v.f_preamount.dctest ? 'has-error' : 'has-success']">
                <label for="f_preamount" class="font_normal_body">预购金额</label>
                <input id="f_preamount" class="input_search" style="width:60%" type="number" v-model="model.f_preamount"
                       @blur="remstrgas" v-validate:f_preamount='{required: true, dctest: [(0 - row.f_balance_amount) < 0 ? 0 : (0 - row.f_balance_amount) , ">" ]}'
                       v-scale="[model.f_preamount, 4]" :disabled="showGas">
              </div>

              <div class="col-sm-4" v-if="showGas">
                <label for="f_preamount" class="font_normal_body">预购金额</label>
                <input class="input_search" style="width:60%" type="number" v-model="model.f_preamount"
                       v-scale="[model.f_preamount, 4]" :disabled="showGas">
              </div>
            </div>
            <div class="row" style="margin-top:5px;">
              <div class="col-sm-12">
                <label for="f_curbalance" class="font_normal_body">&nbsp;&nbsp;&nbsp;备注&nbsp;&nbsp;&nbsp;</label>
                <input class="input_search" style="width:53.5%" v-model="model.f_comments">
              </div>
            </div>
          </div>
          <div v-if="paymentModel.length >1">
            <div class="row" style="margin-top:10px;" >
              <p class="col-sm-2 text-left" style="padding: 10px;"><img src="../../../../static/juxing.png"/><strong style="margin-left: 4%">付款明细</strong></p>
            </div>
            <div class="row" style="margin-top:10px;" >
              <div class="col-sm-4 " v-for="pay in paymentModel" >
                <label class="font_normal_body">{{pay.f_payment}}</label>
                <input id="f_money" type="text" class="input_search" style="width:60%" v-model="pay.f_money">
              </div>
              <div class="col-sm-4 ">
                <strong v-if="!islegal" style="color: red">所输入的金额必须等于收款金额</strong>
              </div>
            </div>
          </div>
        </form>
        <validate-bill v-if="hasValidateBill" :data="model" @validate-bill="validateBill"></validate-bill>
        <print-bill :show="print" :bill-data='billData' v-ref:printbill :bill-config='config'
                    @printok="printok" @toggle="printCancel" :data='row' ></print-bill>
        <div style="text-align:right;height: 25%;margin-top: 2%">
          <strong style="font-size: large" v-if="showGas">计算公式:{{calculatedetail ? calculatedetail : ' 暂无'}}</strong><br/>
          <button class="button_search btn-gn" @click="confirm()" :disabled='!$v.valid || validateOk || !islegal'>确认</button>
          <button class="button_clear btn-gn" @click="clean()">取消</button>
        </div>
      </validator>
    </div>
    <modal :show.sync="paymentCodeShow" backdrop="false">
      <header slot="modal-header" class="modal-header">
        <h4 class="modal-title">请扫描用户微信付款码</h4>
      </header>
      <article slot="modal-body" class="modal-body">
        <div class="form-horizontal" >
          <div class="form-group">
            <input type="text" class="form-control" @keyup.enter="ConfirmCode" @blur="paycodefocus"
                   v-model="paymentCode" placeholder="请扫描用户微信付款码" v-el:paycode>
          </div>
        </div>
      </article>
      <footer slot="modal-footer" class="modal-footer">
        <button type="button" class="btn btn-default" @click='closeCode'>取消</button>
      </footer>
    </modal>
  </div>
</template>
<script>
  /**
   *综合业务
   *物联网表收费组件
   */
  import XML from '../../../plugins/ObjTree'

  let asyncIOTMeterCenter = async function (self) {
    await self.$getConfig(self, 'IotChangeFill')
    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.model.f_use_type = self.config.billType
    self.model.f_bill_type = self.model.f_print
    self.hasValidateBill = self.config.hasBillManage
  }

  let pregasGen = async function (self) {
    if ((self.model.f_fill_gas - 0) < (self.model.f_pregas - 0)) {
      let calGas = 0
      if (self.row.f_isdecimal === '是') {
        calGas = ((self.model.f_pregas - 0) - (self.model.f_fill_gas - 0)).toFixed(4)
      } else {
        calGas = ((self.model.f_pregas - 0) - (self.model.f_fill_gas - 0)).toFixed(0)
      }
      self.model.f_user_id = self.row.f_user_id
      self.model.f_userfiles_id = self.row.f_userfiles_id
      let getAmount = await self.$CommonService.gasCalculate(self.model, calGas)
      self.model.f_preamount = getAmount.data.chargenum
      Object.assign(self.model, self.model, getAmount.data)
      self.model.chargeprice = getAmount.data.chargeprice
      self.calText(getAmount.data.chargeprice)
    } else {
      self.model.f_preamount = 0
    }
    self.remstrgas()
  }

  let IOTChargeGen = async function (self) {
    try {
      if (self.paymentModel.length === 0) {
        self.paymentModel = [{
          f_payment: self.model.f_payment[0],
          f_money: self.model.f_preamount
        }]
      }

      self.model.payments = self.paymentModel

      let ss
    // 如果是付款码支付则显示界面扫用户付款码收钱
      if (self.model.f_payment[0].indexOf('&') !== -1) {
        self.paymentCodeShow = true
        self.paycodefocus()
        ss = await self.paymentcodeawait()
        console.log('付款码操作返回', ss)
        if (ss.res != '支付完成') {
          return
        }
        self.paymentCodeShow = false
      }

      let param = {
        f_user_name: self.row.f_user_name,
        f_user_type: self.row.f_user_type,
        f_meter_type: self.row.f_meter_type,
        f_gasproperties: self.row.f_gasproperties,
        f_userinfo_id: self.row.f_userinfo_id,
        f_address: self.row.f_address,
        f_meter_brand: self.row.f_meter_brand,

        f_old_total_gas: self.row.f_total_gas,
        f_old_total_fee: self.row.f_total_fee,

        f_fill_gas: self.model.f_fill_gas ? self.model.f_fill_gas : 0,
        f_fill_money: self.model.f_fill_money ? self.model.f_fill_money : 0,

        f_remanent_gas: self.row.f_remanent_gas,
        f_remanent_price: self.row.f_remanent_price,
        f_remanent_money: self.row.f_remanent_money,
        f_remanent_type: self.row.f_remanent_type,

        f_user_id: self.row.f_user_id,
        f_userfiles_id: self.row.f_userfiles_id,
        f_pregas: self.model.f_fill_gas - 0,
        f_balance: self.row.f_balance,
        f_balance_gas: self.row.f_balance_gas,
        f_balance_amount: self.row.f_balance_amount,
        f_preamount: self.model.f_fill_money - 0,
        f_payment: self.model.f_payment.toString(),
        payments: self.model.payments,
        f_print: self.model.f_print.toString(),
        f_voucher_number: self.model.f_voucher_number,
        userinfo_version: self.row.userinfo_version,
        version: self.row.version,
        f_operator: self.$login.f.name,
        f_operatorid: self.$login.f.id,
        f_orgid: self.$login.f.orgid,
        f_orgname: self.$login.f.orgs,
        f_depid: self.$login.f.depids,
        f_depname: self.$login.f.deps,
        f_comments: self.model.f_comments,
        times: self.row.f_iot_times,
        // 额外判断
        f_collection_type: self.row.f_collection_type,
        f_calculation: self.row.f_calculation
      }

      if (self.row.f_remanent_type == 1) {
        // 换新表
        param.f_total_gas = (self.row.f_total_gas - 0) + (self.model.f_pregas - 0)
        param.f_total_fee = (self.row.f_total_fee - 0) + (self.model.f_preamount - 0)
      } else {
        // 清零换表 （不考虑，物联网不存在清零换表）
        if (self.model.f_fill_gas > 0 && !self.showGas) {
          param.f_total_fee = (self.row.f_total_fee - 0) + (self.model.f_preamount - 0) - (self.model.f_fill_money - 0)
        } else {
          param.f_total_gas = (self.row.f_total_gas - 0) + (self.model.f_pregas - self.model.f_fill_gas)
          param.f_total_fee = (self.row.f_total_fee - 0) + (self.model.f_preamount - 0)
        }
      }

      let res = await self.$resetpost('rs/logic/sale_iotRemanentGas', {data: param}, {
        warnMsg: `确定对客户${self.row.f_user_name}进行物联网表缴费吗？`,
        resolveMsg: '物联网收费成功！！',
        rejectMsg: '物联网收费出错!!!'
      })

      console.log('物联网收费返回。。。', res)

      if (self.model.f_payment[0].indexOf('&') !== -1) {
        self.sellinggasId = res.data.id
        await self.updateSellinggas(ss.orderNumber)
      }
      // 开始打票
      console.log('开始打票', self.config)
      if (self.config.hasPrint) {
        console.log('self.config.printType', self.config.printType)
        if (self.config.printType != '电子发票') {
          console.log('self.config.hasBillManage', self.config.hasBillManage)
          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.print = true
          } else {
            self.row.id = res.data.id
            self.print = true
          }
        } else if (self.config.printType === '国税发票') {
          // TODO
        } else if (self.config.printType === '电子发票') {
          // TODO
        }
      } else {
        self.$dispatch('success')
      }
    } catch (error) {
      if (error.status === 301) {
        self.$dispatch('refresh')
      } else {
        if (error) {
          self.$showAlert(error, 'danger', 0)
        }
      }

      self.$dispatch('refresh')
    }
  }

  export default {
    title: '物联网表收费',
    data () {
      return {
        config: {
          hasPrint: false,  // 默认打票
          hasBillManage: false,  // 默认不启用发票管理
          billType: '燃气费',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
          printType: '普通收据', // 收据/电子票/专用发票/国税发票
          payment: '现金缴费'
        },
        model: {
          f_payment: ['现金缴费'],
          f_pregas: null,
          f_preamount: null,
          f_print: [],
          f_fill_gas: 0,
          f_fill_money: 0,
          f_comments: ''
        },
        showGas: false,
        calculatedetail: '',

        print: false,
        billData: {
          url: 'rs/report/iot_sell',
          bill: ''
        },

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

        paymentModel: [],

        // 补气提示控制
        remanentfalg: false,
        remanentstr: '',

        // 下拉框值
        paytype: this.$appdata.getParam('付款方式'),
        printstyle: this.$appdata.getParam('打印格式'),

        // 付款码弹框显示
        paymentCodeShow: false,
        // 付款码值
        paymentCode: null,
        // 付款码流程控制
        paycoderesolve: null,
        // 定时器
        timer: null,
        // 收费成功id
        sellinggasId: null,
        // xml解析对象
        xotree: new XML.ObjTree()
      }
    },
    props: ['row'],
    ready () {
      // this.showGas = (this.row.f_collection_type === '按气量')
      this.calRemanentMoney()
      asyncIOTMeterCenter(this)
      console.log('看看row', this.row)
    },
    watch: {
      'model.f_payment.length' (val) {
        console.log('付款方式多选。。', val)
        if (val > 1 && !this.model.f_preamount) {
          this.model.f_payment = ['现金缴费']
          this.$showAlert('请先计算付款金额', 'warning', 2000)
        } else {
          this.paymentModel = []

          this.model.f_payment.forEach((res) => {
            let temp = {
              f_payment: res,
              f_money: 0
            }
            this.paymentModel.push(temp)
          })
          this.$resetValidation()
        }
      }
    },
    methods: {

      // 付款码框获得焦点
      paycodefocus () {
        this.$nextTick(() => {
          this.$els.paycode.focus()
        })
      },
      // 付款码流程控制
      paymentcodeawait () {
        return new Promise((resolve) => {
          this.paycoderesolve = resolve
        })
      },
      // 付款码支付流程
      async ConfirmCode () {
        // 分公司

        let data = {
          // 收费id用于查看日志对应账单
          filiale: this.$login.f.orgid,
          f_userinfo_id: this.row.f_userinfo_id,
          f_user_id: this.row.f_user_id,
          money: this.model.f_collection,
          auth_code: this.paymentCode,
          body: this.$login.f.orgs,
          f_payment: this.model.f_payment[0]
        }
        let res = await this.$resetpost('rs/logic/WeiXinPay', data, {resolveMsg: null, rejectMsg: '服务器内部出错,'})
        res = res.data
        if (res.result_msg == '支付确认成功') {
          this.paycoderesolve({res: '支付完成', orderNumber: res.orderNumber})
        } else if (res.result_msg == '支付状态待查询') {
          // 支付结果未知, 根据商户订单号继续查询
          this.$showAlert(`正在查询用户付款状态,请勿进行任何操作,耐心等待,如长时间未响应可手动取消`, 'warning')
          let self = this
          // 启动定时器之前先关闭定时器,防止之前的定时器未关闭
          if (this.timer) {
            this.closeTimer()
          }
          this.timer = setInterval(async () => {
            let res1 = await self.$resetpost('rs/logic/WeiXinPayStatus', res, {resolveMsg: null, rejectMsg: '付款码支付查询出错,'})
            res1 = res1.data
          // 支付成功关闭定时器
            if (res1.trade_state == 'Y') {
              self.paycoderesolve({res: '支付完成', orderNumber: res.orderNumber})
              self.closeTimer()
              return
            }
          // 确定失败关闭定时器
            if (res1.trade_state == 'N') {
              self.$showAlert(`付款失败, 请重新扫描用户付款码`, 'danger')
              self.closeTimer()
              return
            }
            if (res1.times > 5) {
              self.$showAlert(`多次查询未成功，请重新扫描用户付款码`, 'danger')
              self.closeTimer()
            }
          }, 5000)
        } else {
          this.$showAlert(`${res.result_msg}, 请重新扫描用户付款码`, 'danger')
        }
        // 清空付款码
        this.paymentCode = ''
      },
      // 付款成功更新收费记录订单号

      async updateSellinggas (transaction_id) {
        let sqldata = `update t_sellinggas set f_serial_id = '${transaction_id}' where id = '${this.sellinggasId}'`
        await this.$resetpost('rs/logic/runSQL', {data: {sql: sqldata}}, {resolveMsg: null, rejectMsg: '更新收费记录订单号失败'})
      },
      // 关闭定时器
      closeTimer () {
        console.log('关闭定时器')
        clearInterval(this.timer)
        this.timer = null
      },
      closeCode () {
        this.$showMessage('取消后无法继续收款,确定取消吗?', ['confirm', 'cancel']).then((res) => {
          if (res == 'confirm') {
            this.paymentCodeShow = false
            this.$closeAlert()
            this.paycoderesolve({res: '支付取消'})
            this.closeTimer()
          }
        })
      },
      confirm () {
        this.model.f_userinfo_id = this.row.f_userinfo_id
        this.model.f_userfiles_id = this.row.f_userfiles_id
        this.model.f_user_id = this.row.f_user_id
        this.model.userinfo_version = this.row.userinfo_version
        this.model.version = this.row.version

        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

        IOTChargeGen(this)
      },
      clean () {
        this.$info('取消操作')
        this.$dispatch('refresh', this.row)
      },
      close () {
        this.print = false
        this.clean()
      },
      printok () {
        this.$dispatch('success')
      },
      validateBill (val) {
        this.validateOk = !val.isOk
        this.billData.bill = val.bill
      },
      printCancel () {
        this.$dispatch('refresh')
      },
      calRemanentMoney () {
        // 计算 应补金额
        // 计算 应补金额
        if (this.row.f_remanent_gas > 0 && this.row.f_remanent_money > 0) {
          this.$showAlert('旧表剩余量有问题！！请联系开发人员处理！！', 'warning', 3000)
          return
        }
        let temp = 0
        let temp2 = 0
          // 验证是否支持小数
        if (this.row.f_remanent_money > 0 && (this.row.f_remanent_gas - 0) == 0) {
          temp = ((this.row.f_remanent_money - 0) / (this.row.f_remanent_price - 0)).toFixed(this.row.f_isdecimal == '否' ? 0 : 4)
        } else {
          temp = this.row.f_remanent_gas.toFixed(this.row.f_isdecimal == '否' ? 0 : 4)
        }

        if (this.row.f_remanent_gas > 0 && (this.row.f_remanent_money - 0) == 0) {
          temp2 = (this.row.f_remanent_gas * this.row.f_remanent_price).toFixed(4)
        } else {
          temp2 = this.row.f_remanent_money
        }
        this.model.f_pregas = this.model.f_fill_gas = temp
        this.model.f_preamount = this.model.f_fill_money = temp2
        console.log('temp', temp, 'temp2', temp2)
      },
      openExplain () {

      },
      pregas () {
        if (this.model.f_pregas && this.model.f_pregas > 0 && this.model.f_pregas - (0 - this.row.f_balance_gas) >= 0) {
          try {
            pregasGen(this)
          } catch (error) {
            this.$showAlert(`发卡售气划价错误，错误类型：${error}`, 'danger', 0)
            this.$dispatch('error', '发卡售气', this.model, error)
          }
        } else {
          this.model.f_pregas = null
        }
      },
      remstrgas () {
        if (this.row.f_collection_type == '按气量') {
          if (this.model.f_fill_gas > this.model.f_pregas && this.model.f_pregas > 0) {
            this.remanentstr = '您已经成功抵扣' + this.model.f_pregas + '补气量！！，该气量不会产生任何费用'
            this.remanentfalg = true
          } else if (this.model.f_fill_gas < this.model.f_pregas) {
            this.remanentstr = '您已经成功抵扣' + this.model.f_fill_gas + '补气量！！！，该气量不会产生任何费用,并且超出购买' + (this.model.f_pregas - this.model.f_fill_gas) +
            '方气量，超出部分产生费用!'
            this.remanentfalg = true
          } else {
            this.remanentfalg = false
            this.remanentstr = ''
          }
        } else {
          let temp = (this.model.f_fill_money - 0)

          if (temp > (this.model.f_preamount - 0) && (this.model.f_preamount - 0) > 0) {
            this.remanentstr = '您已经成功抵扣' + this.model.f_preamount + '元！！！，本次不收取费用！！'
            this.remanentfalg = true
          } else if (temp < (this.model.f_preamount - 0)) {
            this.remanentstr = '您已经成功抵扣' + temp + '元！！！，本次将收取' + (this.model.f_preamount - temp) + '元！！！'
            this.remanentfalg = true
          } else {
            this.remanentfalg = false
            this.remanentstr = ''
          }
        }
      },
      calText (val) {
        let str = ''
        val.forEach((item) => {
          str = str + item.f_price + ' x ' + item.f_gas + '+'
        })
        str = str.slice(0, str.length - 1)
        this.calculatedetail = str
      }
    },
    computed: {
      'islegal' () {
        if (this.paymentModel.length > 1 && this.model.f_preamount) {
          let sum = 0
          this.paymentModel.forEach((res) => {
            sum += (res.f_money - 0)
          })

          return (this.model.f_preamount - 0) === (sum - 0)
        } else {
          return true
        }
      }
    }
  }
</script>
