<template>
  <div class="span" style="overflow-y: auto !important;">
    <validator name='v'>
      <form class="form-horizontal">
        <div class="row" style="padding-top: 0.5em;">
          <div class="col-sm-4 form-group" :class="[$v.payment.required ? 'has-error select-error' : '']">
            <label for="f_paytype" class=" font_normal_body" title="参数名称：付款方式">收款方式</label>
            <input type="text" v-show="false" v-model="$refs.payment.selectedItems" v-validate:payment='{required: true }'>
            <v-select id="f_payment"
                      v-model="f_payment"
                      style="width:60%"
                      placeholder='请选择'
                      :value.sync="data.f_payment"
                      :options='paytype'
                      v-ref:payment
                      close-on-select clear-button>
            </v-select>

          </div>
          <div class="col-sm-4 form-group">
            <label for="f_print" class="font_normal_body">打印格式</label>

            <v-select id="print"
                      v-model="data.f_print"
                      placeholder='请选择'
                      style="width:60%"
                      :value.sync="data.f_print"
                      :options='printstyle'
                      close-on-select clear-button>
            </v-select>
          </div>
          <div class="col-sm-4 form-group">
            <label for="f_balance"  class="font_normal_body">上期结余</label>
            <input class="input_search" style="width:60%"  type="number" v-model="data.f_balance"
                   v-scale="[data.f_balance,4]" placeholder="上期结余" disabled>
          </div>
        </div>
        <div class="row" style="padding-top: 0.5em;">
          <div class="col-sm-4 form-group">
            <label for="f_overdue" class="font_normal_body">本期结余</label>
            <input class="input_search" style="width:60%"  type="number" v-model="data.f_curbalance" disabled>
          </div>
          <div  class="col-sm-4 form-group" :class="[$v.f_collection.required || $v.f_collection.dctest ? 'has-error select-error' : '']">
            <label for="f_collection" class="font_normal_body">收&emsp;&emsp;款</label>
            <input id="f_collection" class="input_search" style="width:60%" type="number" v-model="data.f_collection"
                   @blur="collectionmoney"
                   v-validate:f_collection='{required: true, dctest: [0, ">=" ]}'  v-scale = "[data.f_collection, 2]"
                   @mousewheel.native.prevent @keyup.enter="confirm()">
          </div>
          <div class="col-sm-4 form-group" v-if="!mjshow" >
            <label for="f_serial_number" class="font_normal_body">&nbsp;业务单号</label>
            <input class="input_search" style="width:60%"  type="text"
                   v-model="data.f_serial_number" placeholder="业务单号">
          </div>
          <div class="col-sm-4 form-group" v-if="mjshow" :class="[$v.f_serial_number.required || $v.f_serial_number.dctest ? 'has-error' : 'has-success']">
            <label for="f_serial_number" class="font_normal_body">&nbsp;业务单号</label>
            <input class="input_search" style="width:60%"  type="text" v-validate:f_serial_number='{required: true }'
                   v-model="data.f_serial_number" placeholder="业务单号">
          </div>
        </div>

        <div class="row" style="padding-top: 0.5em;">
          <div class="col-sm-12">
            <label for="f_comments" class="font_normal_body">备&emsp;&emsp;注</label>
            <input class="input_search" style="width:87%" v-model="data.f_comments" placeholder="备注">
          </div>
        </div>
      </form>
      <validate-bill v-if="hasValidateBill" :data="data" @validate-bill="validateBill"></validate-bill>
      <print-bill :show="print" :bill-config='config' :bill-data='billData' v-on:toggle="close" :data='data' @printok="printok" v-ref:printbill></print-bill>
      <div class="text-right" style="margin-top: 1%">
        <button class="button_search btn-gn" @click="checkInvoiceMsg()"  :disabled='!$v.valid || validateOk'>确认</button>
        <button class="button_clear btn-gn" @click="clean()">取消</button>
      </div>
    </validator>
    <payment-code v-ref:paymentcode :payment="data.f_payment" :row="row" :money="data.f_collection"></payment-code>
    <!--文件上传按钮-->
    <eticket-modal :show="eticket_msg" :row="row" @confirm="confirm"></eticket-modal>
    <eticket-print-async  :show="eticket_show" @toggle="eticket_toggle"  v-ref:asynceticket></eticket-print-async>

  </div>
</template>
<script>
  import XML from '../../plugins/ObjTree'

  /**
   *预存收费
   *预存收费组件
   */
  let loadGen = async function (self) {
    // await self.$getConfig(self,'MachineCharge')
    // let http = new HttpResetClass()
    // let res = await http.load('POST', 'rs/logic/sale_getOwe', {data: {f_userinfo_id: self.row.f_userinfo_id}}, {resolveMsg: null, rejectMsg: '获取欠费出错！！'})
    // self.list = res.data

    // let owes = []
    // for (let i = 0; i < res.data.length; i++) {
    //  for(let j = 0; j < res.data[i].rows.length; j++) {
    //    owes.push(res.data[i].rows[j])
    //  }
    // }
    self.refreshCenter()
  }

  let asyncMachineMeterCenter = async function (self) {
    await self.$getConfig(self, 'DepositCharge')
    if(self.row.f_paper_type){
      self.data.f_print=self.row.f_paper_type instanceof Array  ? self.row.f_paper_type : [self.row.f_paper_type ]
      console.log(" this.model.f_print", this.model.f_print)
    }else{
      self.data.f_print = self.config.printType instanceof Array  ? self.config.printType : [self.config.printType]
    }
    // self.data.f_print = self.config.printType instanceof Array ? self.config.printType : [self.config.printType]
    self.data.f_payment = [self.config.payment]
    self.data.f_use_type = self.config.billType
    self.data.f_bill_type = self.data.f_print
    self.hasValidateBill = self.config.hasBillManage
  }

  let machineChargeGen = async function (self) {
    try {
      // 加入扫码盒付款码支付流水号
      self.data.f_serial_id = self.$refs.paymentcode.paymentCodeReturnData.f_out_trade_no
      let res = await self.$MachineChargeService.depositCharge(self.data, self.row, self.floor)
      console.log('res:+++====', res)
      // 开始打票
      if (self.config.hasPrint && !self.$login.r.includes('不打印发票')) {
        if (self.data.f_print.indexOf('电子发票') == -1) {
          if (self.config.hasBillManage) {
            // 启用发票管理，获取票据管理中的票号并存储记录
            self.data.id = res.data
            self.data.f_bill_type = '机表收费'
            self.data.f_bill_style = self.data.f_print[0]
            self.print = true
          } else {
            // 如果不欠费就用下边的预存收据
            self.billData.url = 'rs/report/pre_sell'
            // 获取选中的handplan的id
          // self.data.handid = ""
          // self.$parent.$children[0].selecteds.forEach((row,index)=>{
          //   self.data.handid = self.data.handid+"','"+row.handplan_id
          // })
            self.data.id = res.data
            self.print = true
          }
        } else if (self.data.f_print[0] === '国税发票') {
          // TODO
        } else if (self.data.f_print[0] === '电子发票') {
          // TODO
          self.eticket_show=true
          await self.$refs.asynceticket.openEticket(res.data, self.row,'预存收费')
        }
      } else {
        self.$dispatch('success')
      }
    } catch (error) {
      self.$showAlert(error, 'danger', 0)
      self.$dispatch('refresh')
    }
  }

  export default {
    title: '收费',
    data () {
      return {
        //发票相关
        eticket_msg:false,
        eticket_show: false,
        config: {
          hasPrint: true,  // 默认打票
          hasBillManage: false,  // 默认不启用发票管理
          billType: '燃气费',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
          printType: '普通收据', // 收据/电子票/专用发票/国税发票
          payment: '现金缴费'
        },
        overdueModal: {
          f_old_overdue: 0,
          f_new_overdue: ''
        },
        newOverdue: 0,
        isBreakOverdue: false,
        breakOverdue: {},

        showErrorMsg: false,
        print: false,
        isConfirm: true,
        show: false,
        count: 0,
        billData: {
          url: 'rs/report/machine_bill',
          bill: ''
        },

        // 启用发票管理需要对票号进行验证
        hasValidateBill: false,
        validateOk: false,
        handid: '',
        showOverdueModal: false,
        editOverdue: this.$login.r.includes('违约金修改'),
        paytype: this.$appdata.getParam('付款方式') ? this.$appdata.getParam('付款方式') : [],
        printstyle: this.$appdata.getParam('打印格式') ? this.$appdata.getParam('打印格式') : [],
        privilegeList: [{label: '无优惠', value: '0'}],
        // 在向下取整时,保存所有的应交金额
        totalcost: 0,
        data: [],
        floor: false, // 是否向下取整
        model: [],
        mjshow: false
      }
    },
    props: ['row'],
    ready () {
      // this.calOverdue()
      this.newOverdue = this.overdueModal.f_old_overdue = this.data.f_overdue
      if (this.floor) {
        this.totalcost = this.data.f_totalcost
      }
      asyncMachineMeterCenter(this)
      loadGen(this)
  },
    methods: {
      checkInvoiceMsg () {
        if (this.model.f_print[0] === '电子发票') {
          if (!this.row.f_taxpayer_id) {
            this.row.f_taxpayer_id = this.row.f_idnumber
          }
          if (!this.row.f_paper_name) {
            this.row.f_paper_name = this.row.f_user_name
          }
          if (!this.row.f_address_phone) {
            this.row.f_address_phone = this.row.f_address + ' ' + this.row.f_user_phone
          }
          this.confirm()
        } else {
          this.confirm()
        }
      },
      eticket_toggle () {
        this.eticket_show = false
        this.$dispatch('success')
      },
      collectionmoney () {
        this.data.f_curbalance = parseFloat(this.data.f_collection) + parseFloat(this.data.f_balance)
        this.data.f_curbalance = this.data.f_curbalance.toFixed(2)
      },
      refreshCenter () {
        this.initData(this.row)
      },
      initData (row) {
        let temp = {
          f_payment: ['现金缴费'],
          f_user_id: row.f_user_id,
          f_userinfo_id: row.f_userinfo_id,
          f_userfiles_id: row.f_userfiles_id,
          f_balance: row.f_balance,
          otherprice: '',
          f_pregas: 0,
          f_preamount: 0,
          f_totalcost: 0,
          f_curbalance: 0,
          f_collection: '',
          f_garbage_fee: 0,
          f_overdue: 0,
          f_lowest: 0,
          f_print: ['普通收据'],
          f_privilege_id: 0,
          f_privilege_money: 0,
          f_after_discount: 0
        }
        this.model = Object.assign({}, this.model, temp)
        this.data = this.model
      },
      closeCode () {
        this.$showMessage('取消后无法继续收款,确定取消吗?', ['confirm', 'cancel']).then((res) => {
          if (res == 'confirm'
        ) {
            this.paymentCodeShow = false
            this.$closeAlert()
            this.paycoderesolve({res: '支付取消'})
            this.closeTimer()
          }
        })
      },
      modefiy () {
        this.overdueModal.f_new_overdue = ''
        this.showOverdueModal = true
      },
      confirmOverdue () {
        this.breakOverdue = {
          f_user_id: this.data.f_user_id,
          f_userfiles_id: this.data.f_userfiles_id,
          f_userinfo_id: this.data.f_userinfo_id,
          f_old_overdue: this.overdueModal.f_old_overdue,
          f_new_overdue: this.overdueModal.f_new_overdue,
          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,
          f_zoneid: this.$login.f.zoneid,
          f_zones: this.$login.f.zones
        }
        this.showOverdueModal = false
        this.newOverdue = this.overdueModal.f_new_overdue
        this.isBreakOverdue = (this.overdueModal.f_new_overdue - this.overdueModal.f_old_overdue != 0)
      },
      closeOverdue () {
        this.showOverdueModal = false
        this.editOverdue = null
        this.showErrorMsg = false
      },
      confirm () {
        this.eticket_msg=false
        // 如果有变更原因说明有变更
        if (this.data.f_collection < 0) {
          this.$showMessage('收款金额不能小于零！！')
          return
        }

        this.data.f_overdue = this.newOverdue
        this.data.isBreakOverdue = this.isBreakOverdue
        if (this.isBreakOverdue) {
          this.data.breakOverdue = this.breakOverdue
        }

        this.$showMessage(`确定对用户${this.row.f_user_name}进行预存缴费吗？`, ['confirm', 'cancel']).then(async (res) => {
          if (res === 'confirm') {
          // 先调用付款码支付组件流程
            let ss = await this.$refs.paymentcode.flowPath()
            this.$refs.paymentcode.paymentCodeShow = false
            console.log('付款码操作返回', ss)
            if (!ss.result) return
            machineChargeGen(this)
          }
        })
      },
      calOverdue () {
        this.data.f_totalcost = this.data.f_totalcost - (this.data.f_overdue - this.newOverdue)
        this.data.f_overdue = this.newOverdue
      },

      clean () {
        this.$dispatch('success', '机表收费', this.data)
        this.$info('取消操作')
      },

      validateBill (val) {
        this.validateOk = !val.isOk
        this.billData.bill = val.bill
      },

      printok () {
        console.log('成功')
        this.$dispatch('success')
      },
      close () {
        this.print = false
        this.clean()
      }
    },
    watch: {
      'data.f_payment' (val) {
        // 根据付款方式增加业务单号
        if (val == '免交') {
          this.mjshow = true
        } else {
          this.mjshow = false
        }
      }
    }
  }
</script>
