<template>
  <div class="flex-row">
    <div class="span" style="overflow-y: auto;">
      <validator name='v'>
        <form novalidate class="form-horizontal">
          <div class="row" style="margin-top:5px;">
            <div class="col-sm-4">
              <label class=" font_normal_body">付款方式</label>

                <v-select v-model="f_payment"
                          placeholder='请选择'
                          style="width:60%"
                          :value.sync="model.f_payment"
                          :multiple="true"
                          :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, 2]">
            </div>

            <div class="col-sm-4"
                 :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"
                     v-validate:f_preamount='{required: true, dctest: [(0 - row.f_balance_amount) < 0 ? 0 : (0 - row.f_balance_amount) , ">" ]}'
                     v-scale="[model.f_preamount, 2]" :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 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" @click="confirm()" :disabled='!$v.valid || validateOk || !islegal'>确认</button>
          <button class="button_clear" @click="clean()">取消</button>
        </div>
      </validator>
    </div>
  </div>
</template>
<script>
  /**
   *综合业务
   *物联网表收费组件
   */

  let asyncIOTMeterCenter = async function (self) {
    await self.$getConfig(self,'IOTMeterCenter')
    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.row.f_isdecimal === '是') {
      self.model.f_pregas = (self.model.f_pregas - 0).toFixed(2)
    } else {
      self.model.f_pregas = (self.model.f_pregas - 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, self.model.f_pregas)
    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)
  }

  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 param = Object.assign({}, {}, self.model)
      param.f_payment = self.model.f_payment.toString()
      param.f_print = self.model.f_print.toString()
      let res = await self.$resetpost('rs/logic/sale_IOTCharge_logic', {data: param}, {
        warnMsg: `确定对客户${self.row.f_user_name}进行物联网表缴费吗？`,
        resolveMsg: '物联网收费成功！！',
        rejectMsg: '物联网收费出错!!!'
      })

      console.log('物联网收费返回。。。', res)
      // 开始打票
      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: 0,
          f_preamount: 0,
          f_print: [],
          f_comments: ''
        },
        showGas: false,
        calculatedetail: '',

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

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

        paymentModel: [],

        // 下拉框值
        paytype: this.$appdata.getParam('付款方式'),
        printstyle: this.$appdata.getParam('打印格式')
      }
    },
    props: ['row'],
    ready () {
      this.showGas = (this.row.f_collection_type === '按气量')
      asyncIOTMeterCenter(this)
    },
    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: {
      confirm () {
        console.log('model and row', this.model, this.row)
        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_total_fee=(this.row.f_total_fee - 0)+(this.model.f_preamount - 0)
        this.model.f_total_gas=(this.row.f_total_gas - 0)+(this.model.f_pregas - 0)
        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')
      },
      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)
          }
        }
      },

      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>
