<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:10px;">-->
          <!--            -->
          <!--          </div>-->
          <div class="panel-body">
            <data-grid :model="detail" partial='list' class="list_area table_sy" v-ref:grid>
              <template partial='head'>
                <tr>
                  <th><nobr>收费类型</nobr></th>
                  <th><nobr>品名规格</nobr></th>
                  <th><nobr>型号</nobr></th>
                  <th><nobr>单价</nobr></th>
                  <th><nobr>数量</nobr></th>
                </tr>
              </template>
              <template partial='body'>
                <tr>
                  <td style="text-align: center">{{row.f_brand_spec}}</td>
                  <td style="text-align: center">{{row.f_typename}}</td>
                  <td style="text-align: center"><nobr>{{row.f_typenumber}}</nobr></td>
                  <td style="text-align: center">{{row.f_unitprice}}</td>
                  <td style="text-align: center">{{row.f_number}}</td>
                </tr>
              </template>
            </data-grid>
          </div>


          <div class="row" style="margin-top:10px;">
            <div class="col-sm-4">
              <label for="f_paytype" class="font_normal_body" title="参数名称：付款方式">收款方式</label>
              <v-select id="f_payment"
                        v-model="f_payment"
                        placeholder='请选择'
                        :value.sync="model.f_payment"
                        :options='paytype'
                        close-on-select clear-button>
              </v-select>
            </div>
            <div class="col-sm-4">
              <label for="f_print" class="font_normal_body">&nbsp;打印格式</label>
              <v-select id="print"
                        v-model="f_print"
                        placeholder='请选择'
                        :value.sync="model.f_print"
                        :options='printstyle'
                        close-on-select clear-button>
              </v-select>
            </div>
            <div class="col-sm-4">
              <label for="f_collection" class="font_normal_body">&nbsp;收&emsp;&emsp;款</label>
              <label for="f_collection" class="font_normal_body">{{model.f_collection}}</label>
            </div>
          </div>
          <div class="row" style="margin-top:10px;" v-if="model.f_payment[0].includes('POS')">
            <div class="col-sm-4">
              <label for="f_voucher_number" class="font_normal_body">&nbsp;&nbsp;&nbsp;凭证号</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:10px;">
            <div class="col-sm-4">
              <label for="f_voucher_number" class="font_normal_body">服务人员</label>
              <v-select v-model="model.f_service_person"
                        placeholder='请选择'
                        :value.sync="model.f_service_person"
                        :options='services'
                        close-on-select clear-button>
              </v-select>
            </div>
            <div class="col-sm-8">
              <label for="f_comments" class=" font_normal_body">&nbsp;备&emsp;&emsp;注</label>
              <input type="text" class="input_search" style="width:80%" v-model="model.f_comments" rows="1"
                     placeholder="备注">
            </div>
          </div>
        </form>
        <validate-bill v-if="hasValidateBill" :data="model" @validate-bill="validateBill"></validate-bill>
        <print-bill :show="print" :data='row' :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>
        <modal :show.sync="eticket_msg" v-ref:modal large backdrop="false" :width="900">
          <header slot="modal-header" class="modal-header">
            <button type="button" class="close" @click="eticket_msg = false"><span>&times;</span></button>
            <h4 class="modal-title">发票信息</h4>
          </header>
          <article slot="modal-body" class="modal-body">
            <div class="auto select-overspread form-horizontal">
              <div class="row auto">
                <div class="col-sm-6 form-group form-input-group" :class="[!row.f_paper_name ? 'has-error' : '']">
                  <label class="control-label">开票名称:</label>
                  <input class="form-control col-sm-2"
                         v-model="row.f_paper_name" placeholder="开票名称">
                </div>
                <div class="col-sm-6 form-group form-input-group">
                  <nobr class="col-sm-4"><label class="control-label">是否征税:</label></nobr>
                  <v-select v-model="invoice_is_pax"
                            placeholder='请选择'
                            :value.sync="invoice_is_pax"
                            close-on-select
                            :width="60"
                            :value-single="true"
                            :search="false"
                            disabled
                            :options='is_pax' clear-button>
                  </v-select>
                </div>
                <div class="col-sm-12 form-group form-input-group">
                  <label class="control-label">开户行及账号:</label>
                  <input class="form-control col-sm-2"
                         v-model="row.f_paper_account" placeholder="购方开户行及账号">
                </div>
                <div class="col-sm-12 form-group form-input-group" :class="[!row.f_taxpayer_id ? 'has-error' : '']">
                  <label class="control-label">纳税人识别号:</label>
                  <input class="form-control col-sm-2"
                         v-model="row.f_taxpayer_id" placeholder="纳税人识别号">
                </div>
                <div class="col-sm-12 form-group form-input-group" :class="[!row.f_address_phone ? 'has-error' : '']">
                  <label class="control-label">开票地址电话:</label>
                  <input class="form-control col-sm-2"
                         v-model="row.f_address_phone" placeholder="开票地址">
                </div>
              </div>
            </div>
          </article>
          <footer slot="modal-footer" class="modal-footer">
            <button type="button" class="btn button_search"
                    :disabled="!(row.f_taxpayer_id&&row.f_paper_name&&row.f_address_phone)"
                    @click='confirm'>确认收费
            </button>
          </footer>
        </modal>
        <!-- <print-other-charge-bill :show="print" v-ref:printbill :row='row' :logic='model' v-on:success="close" v-on:toggle="close"></print-other-charge-bill> -->
        <!-- <tax-other-bill :show="taxprint"  v-ref:taxprintbill :row='row' :logic='model' v-on:success="close" v-on:toggle="close"></tax-other-bill> -->
        <div style="text-align:right;height: 25%;">
          <button v-if="config.modificationList" class="button_search" @click="confirm(true)"
                  :disabled='!$v.valid || validateOk'>确认并转单
          </button>
          <payment-code-button :clickable="!$v.valid || validateOk"
                               :payment.sync="model.f_payment" :payment-data="paytype"
                               @confirm-payment="confirm()">
          </payment-code-button>
          <button class="button_search btn-gn" @click="checkInvoiceMsg()" :disabled='!$v.valid || validateOk'>确认</button>
          <button class="button_clear btn-gn" @click="clean()">取消</button>
        </div>
      </validator>

    </div>
    <payment-code v-ref:paymentcode :payment="model.f_payment" :row="row" :money="model.f_collection"></payment-code>
  </div>
</template>
<script>
  let otherChargeGen = async function (self, parameter) {
    try {
      // 加入扫码盒付款码支付流水号
      self.model.f_serial_id = self.$refs.paymentcode.paymentCodeReturnData.f_out_trade_no
      console.log('11111', self.model)
      let resid = await self.$LogicService.otherChargeByPay(self.model, self.row)
      console.log('其他收费返回id', resid, self.config.hasPrint, self.$login.r.includes('不打印发票'))
      if (self.config.dispatch) {
        await self.$showMessage(`是否添加派工单`, ['confirm', 'cancel']).then((res) => {
          if (res === 'confirm') {
            console.log('其他收费xinxi', self.model)
            console.log('其他收费xinxi', self.row)
            let batch = {
              sf_id: resid.data,
              f_userinfo_code: self.row.f_userinfo_code,
              f_dispathch_name: self.row.f_user_name,
              f_phone: self.row.f_user_phone,
              f_dispathch_address: self.row.f_address,
              f_meternumber: self.row.f_meternumber,
              f_dispathch_type: '安装',
              f_source: '其他收费',
              f_money: self.model.f_collection,
              f_remarks: self.model.f_comments,
              f_operator_date: self.$login.toStandardTimeString(),
              f_orgid: self.$login.f.orgid,
              f_dispathch_state: '待分配'
            }
            console.log('111:', batch)
            self.$resetpost('rs/logic/savePatch', batch).then((res1) => {
              // this.params.rows.splice(index, 1)
              console.log('更新成功！', res1.data.id)
            })
          }
        })
      }
      let localeSustainMoney = window.localStorage.getItem('sustainMoney')
      if (localeSustainMoney != null) {
        localeSustainMoney = (localeSustainMoney - 0) + (self.model.f_collection - 0)
        window.localStorage.setItem('sustainMoney', localeSustainMoney)
      }
      // // 转燃气改装工程单
      // if (self.config.modificationList && parameter) {
      //   let printSheet = {
      //     f_userinfo_id: self.row.f_userinfo_id,
      //     f_charge_id: resid.data,
      //     f_state: '有效',
      //     f_print_state: '未打印',
      //     f_type: '改装单',
      //     f_orgid: self.$login.f.orgid ? self.$login.f.orgid : '',
      //     f_orgname: self.$login.f.orgs ? self.$login.f.orgs : '',
      //     f_depid: self.$login.f.depids ? self.$login.f.depids : '',
      //     f_depname: self.$login.f.deps ? self.$login.f.deps : '',
      //     f_operator: self.$login.f.name,
      //     f_operatorid: self.$login.f.id
      //   }
      //   await self.$resetpost('rs/logic/savePrintSheet', {data: {printData: printSheet}}, {
      //     resolveMsg: '',
      //     rejectMsg: '转单失败, 请重试'
      //   })
      // }
      if (self.config.hasPrint && !self.$login.r.includes('不打印发票')) {
        if (self.model.f_print[0] != '电子发票') {
          if (self.config.hasBillManage) {
            self.row.id = resid.data
            self.row.f_bill_type = '其他收费'
            self.row.f_bill_style = self.model.f_print[0]
            self.print = true
          } else {
            self.row.id = resid.data
            self.print = true
          }
        } else if (self.model.f_print[0] === '国税发票') {
          // TODO
          self.$dispatch('success')
        } else if (self.model.f_print[0] === '电子发票') {
          self.eticket_show = true
          await self.$refs.eticketbill.openETicket([resid.data], self.row, '是', self.invoice_is_pax, '其他收费')
          // self.$CommonService.openEticket(resid.data, '其他收费')
          // self.$dispatch('success')
        }
      } else {
        self.$dispatch('success')
      }
    } catch (error) {
      console.log(error)
      self.$showAlert(error, 'danger', 0)
      self.$dispatch('refresh')
    }
  }

  let asyncOtherCharge = async function (self) {
    await self.$getConfig(self, 'OtherCharge')
    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_brand_spec = [self.config.brandspec]

    self.model.f_use_type = self.config.billType
    self.model.f_bill_type = self.model.f_print
    self.hasValidateBill = self.config.hasBillManage
    let res = await self.$resetpost('rs/sql/saleSingleTable', {
      data: {
        tablename: 't_othercharge_nopay',
        condition: `f_userfiles_id = '${self.row.f_userfiles_id}' and f_is_pay='否' and f_state='有效'`
      }
    }, {resolveMsg: null, rejectMsg: '获取其他欠费时出错！！！'})
    let ids = []
    res.data.forEach((val) => {
      self.model.f_collection = (self.model.f_collection - 0) + (val.f_collection - 0)
      ids.push(val.id)
    })
    self.model.f_collection = self.model.f_collection.toFixed(2) - 0
    ids = self.$login.convertToIn(ids)
    self.model.f_print = [res.data[0].f_bill_style]
    self.model.f_payment = [res.data[0].f_payment]
    self.model.f_service_person = [res.data[0].f_service_person]
    self.model.f_voucher_number = res.data[0].f_voucher_number
    self.model.nopay_id = ids
    let detail = await self.$resetpost('rs/sql/saleSingleTable', {
      data: {
        tablename: 't_othercharge_detail_nopay',
        condition: `f_othercharge_id in ${ids}`
      }
    }, {resolveMsg: null, rejectMsg: '获取其他欠费明细时出错！！！'})
    self.detail.rows = detail.data
    self.model.otherdetail = detail.data
  }
  export default {
    title: '其他收费',
    data () {
      return {
        config: {
          modificationList: true,
          dispatch: false,
          hasPrint: true,  // 默认打票
          hasBillManage: false,  // 默认不启用发票管理
          billType: '其他费用',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
          printType: '普通收据', // 收据/电子票/专用发票/国税发票
          payment: '现金缴费',  // 付款方式
          brandspec: '材料费' // 收费类型
        },
        model: {
          f_print: [],
          f_payment: '现金缴费',
          f_number: 0,
          f_unitprice: 0,
          f_collection: 0,
          f_comments: '',
          f_voucher_number: '',
          f_service_person: '',
          // 用户其他费用信息
          t_userfees: '',
          f_fee_type: [],
          f_fee_time: ['12'],
          otherdetail: [{f_brand_spec: ['材料费'], f_unitprice: '', f_number: ''}]
        },
        eticket_msg: false,
        eticket_show: false,
        invoice_is_pax: '征税',
        is_pax: [{label: '征税', value: '征税'}, {label: '不征税', value: '不征税'}],
        print: false,
        taxprint: false,
        billData: {
          url: 'rs/report/otherCharge_bill',
          bill: ''
        },
        detail: {
          rows: []
        },
        // 启用发票管理需要对票号进行验证
        hasValidateBill: false,
        validateOk: false,
        f_typenumber: '',
        typeNameList: [],
        typenumberList: [],
        brandspec: this.$appdata.getParam('品名及规格'),
        printstyle: this.$appdata.getParam('打印格式'),
        paytype: this.$appdata.getParam('付款方式'),
        feetype: this.$appdata.getParam('其他费用'),
        services: this.$appdata.getParam('服务人员')
      }
    },
    props: ['row'],
    ready () {
      // this.model.f_unitprice = this.$appdata.getSingleValue('置换气费')
      asyncOtherCharge(this)
    },
    watch: {
      'model.otherdetail' (val) {
      },
      'model.f_fee_type' (val) {
        if (val[0]) {
          this.userfees(this.row.f_userinfo_id, val[0])
        }
      }
    },
    methods: {
      setTypeprice (val) {
        console.log('f_typenumber', this.f_typenumber)
        if (this.f_typenumber !== ' ') {
          let unitprice = this.$appdata.getSingleValue(val)
          console.log('unitprice', unitprice)
          if (unitprice !== undefined) {
            this.row.f_unitprice = this.$appdata.getSingleValue(val)
          }
        }
      },
      // 校验发票信息
      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.eticket_msg = true
        } else {
          this.confirm()
        }
      },
      eticket_toggle () {
        this.eticket_show = false
        this.$dispatch('success')
      },
      async setTypename (val) {
        this.f_typenumber = ''
        this.f_unitprice = ''
        this.typeNameList = this.$appdata.getParam(val)
        if (val == '开卡费') {
          if (this.$appdata.getSingleValue('开卡费')) {
            let money = this.$appdata.getSingleValue('开卡费')
            await this.model.otherdetail.forEach(function (item) {
              if (item.f_brand_spec[0] == '开卡费') {
                item.f_unitprice = money
                item.f_number = 1
              }
            })
            this.getcollection()
          }
        }
      },
      setTypenumber (val) {
        this.typenumberList = this.$appdata.getParam(val)
      },
      async confirm (parameter) {
        this.eticket_msg = false
        // 先调用付款码支付组件流程
        let ss = await this.$refs.paymentcode.flowPath()
        this.$refs.paymentcode.paymentCodeShow = false
        console.log('付款码操作返回', ss)
        if (!ss.result) return
        otherChargeGen(this, parameter)
      },
      clean () {
        this.$dispatch('refresh', this.row)
      },
      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.otherdetail.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.otherdetail.push({f_brand_spec: ['材料费']})
      },
      delthisdetail (index) {
        if (this.model.otherdetail.length > 1) {
          this.model.otherdetail.splice(index, 1)
          this.getcollection()
        }
      },
      async userfees (userinfoid, feetype) {
        this.model.t_userfees = await this.$resetpost('rs/sql/saleSingleTable', {
          data: {
            tablename: 't_userfees',
            condition: `f_userinfo_id=${userinfoid} and f_fee_type='${feetype}'`
          }
        }, {resolveMsg: null, rejectMsg: '查询客户其他费用失败!'})
      }
    },
    computed: {
      feetime () {
        return [{label: '一个月', value: '1'}, {label: '三个月', value: '3'}, {label: '六个月', value: '6'}, {
          label: '一年',
          value: '12'
        }]
      },
      gettypename () {
        return this.typeNameList
      },
      gettypenumber () {
        return this.typenumberList
      }
    }
  }
</script>

<style>
</style>
