<template>
    <div class="auto">
        <validator name='v'>
            <form novalidate class="form-horizontal">
                <div class="row">
                    <div class="col-sm-4 form-group">
                        <label class="font_normal_body">用户编号</label>
                        <input class="input_search" style="width:60%" type="text" placeholder='目标用户编号'
                               v-model="model.f_userinfo_code" @blur="getuser(model.f_userinfo_code)">
                    </div>
                    <div class="col-sm-4 form-group" >
                        <label for="f_user_name" class="font_normal_body">用户姓名</label>
                        <input class="input_search" style="width:60%" type="text" placeholder='目标用户姓名'
                               v-model="model.f_user_name" readonly >
                    </div>

                    <div class="col-sm-4 form-group" >
                        <label class="font_normal_body">气表类型</label>
                        <input class="input_search" style="width:60%" type="text" placeholder='目标用户气表类型'
                               v-model="model.f_meter_type" readonly >
                    </div>
                </div>
                <div class="row">

                    <div class="col-sm-4 form-group" v-if="row.f_meter_type =='机表'" >
                        <label class="font_normal_body">当前余额</label>
                        <input class="input_search" style="width:60%" type="text" placeholder='当前余额'
                               v-model="row.f_balance" readonly >
                    </div>
                    <div class="col-sm-4 form-group" v-if="row.f_meter_type =='物联网表'" >
                        <label class="font_normal_body">当前余额</label>
                        <input class="input_search" style="width:60%" type="text" placeholder='当前余额'
                               v-model="row.f_balance_amount" readonly >
                    </div>
                    <div class="col-sm-4 form-group" v-if="row.f_meter_type == '气量卡表' || row.f_meter_type == '金额卡表'"
                         :class="[$v.f_meter_base.required || $v.f_meter_base.dctest ? 'has-error' : 'has-success']">
                        <label class="font_normal_body">当前底数</label>
                        <input class="input_search" style="width:60%" type="text" placeholder='当前表已用气量'
                               @blur="meterBaseChange()"
                               v-validate:f_meter_base='{required: true}'  v-model="model.f_meter_base" >
                    </div>
                    <div class="col-sm-4 form-group" v-if="model.f_meter_type!='' && model.f_meter_type!='气量卡表'"
                         :class="[$v.f_move_fee.required || $v.f_move_fee.dctest ? 'has-error' : 'has-success']">
                        <label class="font_normal_body">转气金额</label>
                        <input class="input_search" style="width:60%" type="number" v-model="model.f_move_fee"
                                @blur="preamount()"
                               v-validate:f_move_fee='{required: true}' placeholder="转气金额">
                    </div>
                    <div class="col-sm-4 form-group" v-if="model.f_meter_type!='' && model.f_meter_type=='气量卡表'"
                         :class="[$v.f_move_fee.required || $v.f_move_fee.dctest ? 'has-error' : 'has-success']">
                        <label class="font_normal_body">转气金额</label>
                        <input class="input_search" style="width:60%" type="number" v-model="model.f_move_fee"

                               v-validate:f_move_fee='{required: true}' placeholder="转气金额">
                    </div>
                    <div class="col-sm-4 form-group" v-if="model.f_meter_type!='' && model.f_meter_type=='气量卡表'"
                         :class="[$v.f_move_gas.required || $v.f_move_gas.dctest ? 'has-error' : 'has-success']">
                        <label class="font_normal_body">转气气量</label>
                        <input class="input_search" style="width:60%" type="number" v-model="model.f_move_gas"
                               @blur="pregas()"
                               v-validate:f_move_gas='{required: true}' placeholder="转气气量">
                    </div>
                    <div class="col-sm-4 form-group" v-if="model.f_meter_type!='' && model.f_meter_type!='气量卡表'"
                         :class="[$v.f_move_gas.required || $v.f_move_gas.dctest ? 'has-error' : 'has-success']">
                        <label class="font_normal_body">转气气量</label>
                        <input class="input_search" style="width:60%" type="number" v-model="model.f_move_gas"
                               v-validate:f_move_gas='{required: true}' placeholder="转气气量">
                    </div>
                </div>

                <div class="row">
                    <div class="col-sm-8">
                        <label for="f_paper_account" class="font_normal_body ">&nbsp;&nbsp;&nbsp;备注&nbsp;&nbsp;&nbsp;</label>
                        <input class="input_search" style="width:80%"  v-model="model.f_comments">
                    </div>

                </div>
            </form>
            <div style="text-align:right;">
                <button class="button_search btn-gn" @click="confirm()" :disabled='!$v.valid'>确认</button>
                <button class="button_clear btn-gn" @click="clean()">取消</button>
            </div>
        </validator>
      <print-bill :show="print" :bill-config='config' :bill-data='billData' :data='row' @toggle="close"
                  @printok="printok" v-ref:printbill></print-bill>
    </div>
</template>


<script>
    let preamountGen = async function (self) {
      let calFee = self.model.f_move_fee
      let getGas = await self.$CommonService.feeCalculate(self.model, calFee)
      if (getGas.data.gas) {
        self.model.f_move_gas = (getGas.data.gas - 0).toFixed(2)
      }
    }
    let pregasGen = async function (self) {
      self.model.f_move_gas = (self.model.f_move_gas - 0).toFixed(2)
      self.model.f_reverse = self.model.f_move_gas
      let getAmount = await self.$CommonService.gasCalculate(self.model, self.model.f_move_gas)
      self.model.f_move_fee = getAmount.data.chargenum
    }
    let readyGen = async function (self) {
      await self.$getConfig(self, 'gasMove')
      console.log('转气转出config', self.config)
    }
    export default {
      title: '转气',
      data () {
        return {
          model: {
            f_refund_fee: '',
            f_comments: '',
            f_meter_type: '',
            f_user_name: '',
            f_userfiles_id: '',
            f_move_fee: 0,
            f_move_gas: 0
          },

          config: {
            hasBillManage: false,
            hasPrint: true
          },
          blodid: '',
          hasValidateBill: false,
          validateOk: false,

          printModel: {},
          print: false,
          billUrl: '',
          billData: {
            // 只打印转入的票据
            url: 'rs/report/gas_transfer_into',
            billnumber: ''
          },

                // 下拉框值
          paytype: this.$appdata.getParam('付款方式'),
          printstyle: this.$appdata.getParam('打印格式')
        }
      },
      props: ['row'],
      ready () {
        readyGen(this)
      },
      methods: {
        meterBaseChange () {
          if (this.model.f_meter_base && this.model.f_meter_base > 0 && this.model.f_meter_base <= this.row.f_total_gas) {
            this.model.f_move_gas = (this.row.f_total_gas - this.model.f_meter_base).toFixed(2)
          }
          if (this.model.f_meter_base > this.row.f_total_gas) {
            this.$showAlert('转气底数不能大于总购气量', 'warning', 1500)
            this.model.f_meter_base = ''
            return
          }
          if (this.model.f_move_gas && this.model.f_move_gas > 0) {
            try {
              pregasGen(this)
            } catch (error) {
              this.$showAlert(`划价错误，错误类型：${error}`, 'danger', 0)
            }
          } else {
            this.model.f_move_gas = 0
          }
        },
        preamount () {
          try {
            preamountGen(this)
          } catch (error) {
            this.$showAlert(`发卡售气划价错误，错误类型：${error}`, 'danger', 0)
          }
        },
        pregas () {
          if (this.model.f_move_gas && this.model.f_move_gas > 0) {
            try {
              pregasGen(this)
            } catch (error) {
              this.$showAlert(`划价错误，错误类型：${error}`, 'danger', 0)
            }
          } else {
            this.model.f_move_gas = 0
          }
        },
        async getuser (val) {
          if (val == this.row.f_userinfo_code) {
            this.$showAlert('不能给自己转气', 'warning', 1500)
            return
          }
          let res = await this.$resetpost('rs/sql/sale_getUser',
                    {data: {condition: `i.f_userinfo_code='${val}' and i.f_orgid='${this.$login.f.orgid}'`}}, {resolveMsg: null, rejectMsg: null})
          console.log(res.data)
          if (res.data.length > 0) {
            this.model.f_user_name = res.data[0].f_user_name
            this.model.f_meter_type = res.data[0].f_meter_type
            this.model.f_userfiles_id = res.data[0].f_userfiles_id
          } else {
            this.$showAlert('输入的用户编号不正确', 'warning', 1500)
          }
        },
        async confirm () {
          if (this.model.f_move_fee <= 0) {
            this.$showAlert('转气金额和气量不能为0或小于0', 'warning', 1500)
            return
          }
          if (this.row.f_meter_type == '机表' && this.row.f_balance < this.model.f_move_fee) {
            this.$showAlert('转气金额不能大于余额', 'warning', 1500)
            return
          }
          if (this.row.f_meter_type == '物联网表' && this.row.f_balance_amount < this.model.f_move_fee) {
            this.$showAlert('转气金额不能大于余额', 'warning', 1500)
            return
          }
          if (!this.model.f_meter_type) {
            this.$showAlert('请先输入目标用户信息', 'warning', 1500)
            return
          }

          let param = {
            f_user_id: this.row.f_user_id,
            f_userfiles_id: this.row.f_userfiles_id,
            userfilesid: this.model.f_userfiles_id,
            version: this.row.version,
            f_move_fee: this.model.f_move_fee,
            f_meter_base: this.model.f_meter_base,
            f_move_gas: this.model.f_move_gas,
            f_comments: this.model.f_comments,
            f_billing: this.row.f_billing,
            f_userinfo_code: this.model.f_userinfo_code,
            f_price_id: this.row.f_price_id,
            f_orgid: this.$login.f.orgid,
            f_stairprice_id: this.row.f_stairprice_id,
            operInfo: {
              f_operator: this.$login.f.name,
              f_operatorid: this.$login.f.id,
              f_orgid: this.$login.f.orgid,
              f_orgname: this.$login.f.orgs,
              f_depid: this.$login.f.depids,
              f_depname: this.$login.f.deps
            }
          }

          this.$resetpost('rs/logic/movegas', {data: param}, {warnMsg: `确定要进行转气吗？`, resolveMsg: '转气成功！！', rejectMsg: '转气失败！！请重试！！'}).then((res) => {
            console.log(res)
            if (this.config.hasPrint) {
              if (this.config.hasBillManage) {
                // 启用发票管理，获取票据管理中的票号并存储记录
                this.row.id = res.data.id
                this.row.f_bill_type = '转气'
                this.row.f_bill_style = this.model.f_print[0]
                this.print = true
              } else {
                this.row.id = res.data.id
                this.print = true
              }
            } else {
              this.$dispatch('success', '转气', this.row)
            }
          })
        },
        close () {
          this.print = false
          this.clean()
        },
        clean () {
          this.$dispatch('refresh')
        },
        printok () {
          this.$dispatch('success')
        },
        validateBill (val) {
          this.validateOk = !val.isOk
          this.billData.bill = val.bill
        }
      }
    }
</script>
