<template>
  <div class="flex-row auto">
    <div class="span auto" style="height: 98%;overflow-y: auto;">
      <validator name='v'>
        <form novalidate class="form-horizontal">
          <div class="flex-auto">
            <div style="height:550px;overflow-y: auto;">
            <div style="margin-top:10px;" class="auto row" v-for="row in model.gaslossdetail">
              <div class="panel panel-primary datapanel" style="background-color: #f4f6f8">
                  <div class="col-sm-4 form-group" :class="{'has-success':row.f_type,'has-error':!row.f_type}">
                    <label for="f_brand_spec" class="font_normal_body" title="参数名称：气损分类">气损分类</label>
                    <input v-show="false" v-model="row.f_type" v-validate:f_type='{required: true }'>
                    <v-select placeholder='气损分类'
                              v-model="row.f_type"
                              :value.sync="row.f_type"
                              :options='types'
                              :value-single="true"
                              close-on-select clear-button>
                    </v-select>
                  </div>
                  <div class="col-sm-4 form-group" :class="{'has-success':row.f_loss_type,'has-error':!row.f_loss_type}">
                    <label for="f_brand_spec" class="font_normal_body" title="参数名称：气损类型">气损类型</label>
                    <input v-show="false" v-model="row.f_loss_type" v-validate:f_loss_type='{required: true }'>
                    <v-select id="f_brand_spec"
                              placeholder='气损类型'
                              v-model="row.f_loss_type"
                              :value.sync="row.f_loss_type"
                              :options='row.f_type?this.$appdata.getParam(row.f_type):[]'
                              :value-single="true"
                              close-on-select clear-button>
                    </v-select>
                  </div>
                  <div class="col-sm-4 form-group" :class="{'has-success':row.f_unitprice,'has-error':!row.f_unitprice}">
                    <label style="" for="f_unitprice" class=" font_normal_body">单&emsp;&emsp;价</label>
                    <input class="input_search" style="width:60%" type="number" min="0"
                           v-validate:f_unitprice='{required: true, dctest: [0, ">" ] }'
                           @blur.prevent="getcollection()"
                           v-model="row.f_unitprice"
                           placeholder="单价" >
                  </div>
                  <div class="col-sm-4 form-group" :class="{'has-success':row.f_number,'has-error':!row.f_number}">
                    <label style="" for="f_number" class="font_normal_body">数&emsp;&emsp;量</label>
                    <input class="input_search"  style="width:60%" type="number" min='1' @blur.prevent="getcollection()"
                           v-validate:f_number='{required: true, dctest: [0, ">" ] }'
                           v-model="row.f_number"
                           placeholder="数量" >
                  </div>
                  <div class="form-group" style="display: flow-root;width: 60px">
                    <button type="button" class="glyphicon glyphicon-minus btn-danger" @click.stop="delthisdetail($index)"></button>
                    <button type="button" class="glyphicon glyphicon-plus btn-success" @click.stop="addadetail()"></button>
                  </div>
              </div>
            </div>
          </div>
          </div>
          <div class=" panel panel-primary datapanel" style="height:260px">
            <div class="row">
              <div class="col-sm-4 form-group">
                <label class=" font_normal_body">&emsp;客户编号</label>
                <input class="input_search" style="width:60%"
                       v-model="model.f_userinfo_code"
                       @blur="codeChange()"
                       placeholder="客户编号">
              </div>
              <div class="col-sm-4 form-group" :class="{'has-success':model.f_charge_person,'has-error':!model.f_charge_person}">
                <label class=" font_normal_body">&emsp;缴&nbsp;费&nbsp;人&nbsp;</label>
                <input class="input_search" style="width:60%"
                       v-validate:f_charge_person='{required: true }'
                       v-model="model.f_charge_person"
                       placeholder="缴费人">
              </div>
              <div class="col-sm-4 form-group" :class="{'has-success':model.f_charge_phone,'has-error':!model.f_charge_phone}">
                <label class=" font_normal_body">&emsp;联系电话</label>
                <input class="input_search" style="width:60%"
                       v-validate:f_charge_phone='{required: true }'
                       v-model="model.f_charge_phone"
                       placeholder="联系电话">
              </div>
              <div class="col-sm-12 form-group" :class="{'has-success':model.f_charge_address,'has-error':!model.f_charge_address}">
                <label class=" font_normal_body">缴费人地址</label>
                <input class="input_search" style="width:89%"
                       v-validate:f_charge_address='{required: true }'
                       v-model="model.f_charge_address"
                       placeholder="缴费人地址">
              </div>
              <div class="col-sm-4 form-group">
                <label for="f_paytype" class="font_normal_body" title="参数名称：付款方式">&emsp;收款方式</label>
                <v-select id="f_payment"
                          v-model="f_payment"
                          placeholder='请选择'
                          :value.sync="model.f_payment"
                          :value-single="true"
                          :options='paytype'
                          close-on-select clear-button>
                </v-select>
              </div>
              <div class="col-sm-4 form-group">
                <label for="f_print" class="font_normal_body">&emsp;打印格式</label>
                <v-select id="print"
                          v-model="model.f_print"
                          placeholder='请选择'
                          :value.sync="model.f_print"
                          :options='printstyle'
                          :value-single="true"
                          close-on-select clear-button>
                </v-select>
              </div>
              <div class="col-sm-4 auto">
                <label for="f_collection" style="text-align:right;"><font size="6px" style="font-weight:bold;color:darkred">收&emsp;款:{{model.f_collection}}</font></label>
              </div>
              <div class="col-sm-9 form-group">
                <label class=" font_normal_body">&emsp;备&emsp;&emsp;注</label>
                <input class="input_search" style="width:70%"
                       v-model="model.f_comments"
                       placeholder="备注">
              </div>
              <div style="text-align:right;height: 25%;">
                <button class="button_search btn-gn" type="button" @click="checkInvoiceMsg()" :disabled='!$v.valid || validateOk'>确认</button>
                <button class="button_clear btn-gn" type="button" @click="clean()">取消</button>
              </div>
              </div>
          </div>
        </form>
        <validate-bill v-if="hasValidateBill" :data="model" @validate-bill="validateBill"></validate-bill>
        <print-bill :show="print" :data='model' :bill-config='config' :bill-data='billData' v-on:toggle="close" @printok="printok" v-ref:printbill></print-bill>
        <ticket-print  :show="eticket_show" @toggle="eticket_toggle"  v-ref:eticketbill></ticket-print>
        <eticket-modal :show="eticket_msg" @closemodalshow="eticket_msg = false" :row="model" @confirm="confirm"></eticket-modal>
      </validator>
    </div>
    <payment-code v-ref:paymentcode :payment="model.f_payment"  :money="model.f_collection"></payment-code>
  </div>
</template>

<script>
  import {HttpResetClass} from 'vue-client'
  import Vue from 'vue'

  let gasLossGen = async function (self) {
    try {
      // 加入扫码盒付款码支付流水号
      self.model.f_serial_id = self.$refs.paymentcode.paymentCodeReturnData.f_out_trade_no
      self.model.f_bill_style = self.model.f_print
      let http = new HttpResetClass()
      self.model.f_describe = `${Vue.$login.f.name}对${self.model.f_charge_person}进行气损收费`
      let resid = await http.load('POST', 'rs/logic/gasLoss', self.model, {resolveMsg: '气损收费成功', rejectMsg: '气损收费失败'})
      console.log('f_print:', resid)
      if (self.model.f_print !== '电子发票') {
        if (self.config.hasBillManage) {
          self.model.id = resid.data
          self.model.f_bill_type = '其他费用'
          self.model.f_bill_style = self.model.f_print[0]
          self.print = true
        } else {
          self.model.id = resid.data
          self.print = true
        }
      } else if (self.model.f_print === '国税发票') {
        // TODO
        self.clean()
        self.$dispatch('refresh')
      } else if (self.model.f_print === '电子发票') {
        self.eticket_show = true
        await self.$refs.eticketbill.openETicket([resid.data], self.model, '气损收费')
      }
    } catch (error) {
      self.$showAlert(error, 'danger', 0)
      self.$dispatch('refresh')
    }
  }

  let asyncGasLoss = async function (self) {
    try {
      await self.$getConfig(self, 'gasLossCharge')
    } catch (error) {
      console.log('无配置文件')
    }
    self.model.f_print = self.config.printType
    self.model.f_payment = self.config.payment
    self.model.f_use_type = self.config.billType
    self.model.f_bill_type = self.config.f_print
    self.hasValidateBill = self.config.hasBillManage
  }
  export default {
    title: '气损收费',
    data () {
      return {
        config: {
          showupload: false,
          hasPrint: false,  // 默认打票
          hasBillManage: false,  // 默认不启用发票管理
          billType: '其他费用',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
          printType: '普通收据', // 收据/电子票/专用发票/国税发票
          payment: '现金缴费',  // 付款方式
          f_type: '', // 气损分类
          f_loss_type: '' // 气损类型
        },
        eticket_msg: false,
        eticket_show: false,
        invoice_is_pax: '征税',
        is_pax: [{label: '征税', value: '征税'}, {label: '不征税', value: '不征税'}],
        model: {
          f_userinfo_id: null,
          f_collection: 0,
          f_payment: '',
          f_bill_style: '',
          f_comments: '',
          f_charge_person: '',
          f_charge_phone: '',
          f_charge_address: '',
          f_state: '有效',
          f_operator: Vue.$login.f.name,
          f_operatorid: Vue.$login.f.id,
          f_orgid: Vue.$login.f.orgid,
          f_orgname: Vue.$login.f.orgs,
          f_depid: Vue.$login.f.depids,
          f_depname: Vue.$login.f.deps,
          f_operat_type: '气损收费',
          f_print: '',
          gaslossdetail: [{}],
          f_user_name: '',
          f_user_phone: '',
          f_address: '',
          f_paper_name: '',
          f_paper_account: '',
          f_idnumber: '',
          f_taxpayer_id: '',
          f_address_phone: ''
        },
        print: false,
        taxprint: false,
        billData: {
          url: 'rs/report/gasloss_bill',
          bill: ''
        },

        // 启用发票管理需要对票号进行验证
        hasValidateBill: false,
        validateOk: false,
        types: this.$appdata.getParam('气损分类'),
        printstyle: this.$appdata.getParam('打印格式'),
        paytype: this.$appdata.getParam('付款方式'),
        feetype: this.$appdata.getParam('其他费用'),
        services: this.$appdata.getParam('服务人员')
      }
    },
    ready () {
      asyncGasLoss(this)
    },

    methods: {
      checkInvoiceMsg () {
        if (this.model.f_print === '电子发票') {
          if (!this.model.f_taxpayer_id) {
            this.model.f_taxpayer_id = this.model.f_idnumber
          }
          if (!this.model.f_paper_name) {
            this.model.f_paper_name = this.model.f_user_name
          }
          if (!this.model.f_address_phone) {
            this.model.f_address_phone = this.model.f_address + ' ' + this.model.f_user_phone
          }
          this.eticket_msg = true
        } else {
          this.confirm()
        }
      },
      eticket_toggle () {
        this.eticket_show = false
        this.$dispatch('success')
      },
      async codeChange () {
        this.model.f_userinfo_code = this.model.f_userinfo_code.trim()
        if (this.model.f_userinfo_code) {
          let http = new HttpResetClass()
          let res = await http.load('POST', 'rs/sql/singleTable_OrderBy', {
            data: {
              items: 'u.f_userinfo_id,u.f_user_name,u.f_user_phone,a.f_address,u.f_paper_name,u.f_paper_account,u.f_idnumber,u.f_taxpayer_id,u.f_address_phone',
              tablename: 't_userinfo u  left join t_user_address a on u.f_userinfo_id = a.f_userinfo_id',
              condition: `u.f_userinfo_code = '${this.model.f_userinfo_code}' and u.f_user_state = '正常'`,
              orderitem: 'u.f_userinfo_id desc'
            }
          }, {resolveMsg: null, rejectMsg: '获取用户信息失败'})
          if (res.data.length == 0) {
            this.$showAlert('该客户编号不存在，请重新输入', 'warning', 3000)
            this.model.f_userinfo_code = null
          } else {
            this.model.f_userinfo_id = res.data[0].f_userinfo_id
            this.model.f_charge_person = res.data[0].f_user_name
            this.model.f_charge_phone = res.data[0].f_user_phone
            this.model.f_charge_address = res.data[0].f_address
            this.model.f_user_name = res.data[0].f_user_name
            this.model.f_user_phone = res.data[0].f_user_phone
            this.model.f_address = res.data[0].f_address
            this.model.f_paper_name = res.data[0].f_paper_name
            this.model.f_paper_account = res.data[0].f_paper_account
            this.model.f_idnumber = res.data[0].f_idnumber
            this.model.f_taxpayer_id = res.data[0].f_taxpayer_id
            this.model.f_address_phone = res.data[0].f_address_phone
          }
        }
      },
      async clean () {
        this.model = {}
        await this.$nextTick()
        this.model = {
          f_userinfo_id: null,
          f_collection: 0,
          f_payment: '',
          f_bill_style: '',
          f_comments: '',
          f_charge_person: '',
          f_charge_phone: '',
          f_charge_address: '',
          f_state: '有效',
          f_operator: Vue.$login.f.name,
          f_operatorid: Vue.$login.f.id,
          f_orgid: Vue.$login.f.orgid,
          f_orgname: Vue.$login.f.orgs,
          f_depid: Vue.$login.f.depids,
          f_depname: Vue.$login.f.deps,
          f_operat_type: '气损收费',
          f_print: '',
          gaslossdetail: [{}],
          f_user_name: '',
          f_user_phone: '',
          f_address: '',
          f_paper_name: '',
          f_paper_account: '',
          f_idnumber: '',
          f_taxpayer_id: '',
          f_address_phone: ''
        }
      },
      async confirm () {
        this.eticket_msg = false
        // // 先调用付款码支付组件流程
        let ss = await this.$refs.paymentcode.flowPath()
        this.$refs.paymentcode.paymentCodeShow = false
        console.log('付款码操作返回', ss)
        if (!ss.result) return
        gasLossGen(this)
      },
      close () {
        this.taxprint = false
        this.print = false
        this.clean()
      },
      printok () {
        this.$dispatch('success')
      },
      validateBill (val) {
        this.validateOk = !val.isOk
        this.billData.bill = val.bill
      },
      getcollection () {
        let money = 0
        this.model.gaslossdetail.forEach((item) => {
          if (item.f_unitprice && item.f_number) {
            money += ((item.f_unitprice - 0) * (item.f_number - 0)) - 0
          }
        })

        if (money != 0) {
          this.model.f_collection = money.toFixed(2)
        }
      },
      addadetail () {
        this.model.gaslossdetail.push({})
      },
      delthisdetail (index) {
        if (this.model.gaslossdetail.length > 1) {
          this.model.gaslossdetail.splice(index, 1)
          this.getcollection()
        }
      }
    },
    computed: {
    }
  }
</script>

<style>
</style>
