<template>
  <div class="auto" style="height: auto">
    <div class="flex">
      <criteria-paged :model="model" v-ref:paged>
        <criteria partial='criteria' @condition-changed='$parent.selfSearch' v-ref:cri>
          <div novalidate class="form-inline" partial>
          </div>
        </criteria>
        <data-grid :model="model" partial='list' v-ref:grid>
          <template partial='head'>
            <tr>
              <th>
                <input type="checkbox"  @click="$parent.$parent.$parent.addOrRemove($parent.$parent.$parent.selectAll)" :checked="$parent.$parent.$parent.selectAll">
              </th>
              <th>
                <nobr>表编号</nobr>
              </th>
              <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">
                <input type="checkbox" v-model="$parent.$parent.$parent.selecteds" :value="row">
              </td>
              <td style="text-align:center">{{row.f_user_id}}</td>
              <td style="text-align:center">{{row.f_last_tablebase}}</td>
              <td style="text-align:center">{{row.f_tablebase}}</td>
              <td style="text-align:center">{{row.totalgas}}</td>
              <td style="text-align:center">{{row.totalfee}}</td>
              <td style="text-align:center">{{row.f_hand_month}}</td>
            </tr>
          </template>
          <template partial='foot'></template>
        </data-grid>
      </criteria-paged>
    </div>
    <div class="span" v-if="selecteds.length > 0">
      <form class="form-horizontal">
        <div class="row">
          <div class="form-group form-input-group col-sm-4">
            <label class="control-label col-sm-2">总气量:</label>
            <input type="text" class="form-control col-sm-2" v-model="eticket.totalGas" placeholder="总气量" disabled>
          </div>
          <div class="form-group form-input-group col-sm-4">
            <label class="control-label col-sm-2">总金额:</label>
            <input type="text" class="form-control col-sm-2" v-model="eticket.totalFee" placeholder="总金额" disabled>
        </div>
      </div>
      </form>
      <div class="form-group" style="float: left">
        <validate-bill v-if="hasValidateBill" :data="model" @validate-bill="validateBill"></validate-bill>
      </div>
      <div class="form-group" style="float: right">
        <print-bill :show="print" :bill-config='config' :bill-data='billData' v-on:toggle="close" :data='data' @printok="printok" v-ref:printbill></print-bill>
        <button class="btn btn-success" @click="confirm()">开票</button>
      </div>
    </div>
  </div>
</template>

<script>
  import {PagedList} from 'vue-client'

  let liquidationManage = async function (self) {
    await self.$getConfig(self, 'liquidationManage')
    console.log('liquidationManage', 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
  }

  export default {
    title: '未开记录',
    data () {
      return {
        model: new PagedList('rs/sql/sale_getliquidation', 10),
        eticket: {
          totalGas: 0,
          totalFee: 0,
          hand_months: []
        },
        selecteds: [],
        selectAll: false,
        data: '',
        billData: {
          url: 'rs/report/meter_liquidation',
          bill: '',
          f_meter_classify: '机表'
        },
        print: false,
        flag: false,
        hasValidateBill: true,
        config: {
          hasBillManage: true,  // 默认不启用发票管理
          billType: '燃气费',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
          payment: '现金缴费',
          printType: '普通收据' // 收据/电子票/专用发票/国税发票
        }
      }
    },
    props: ['row'],
    ready () {
      liquidationManage(this)
      console.log('给起止时间赋值', this.$refs.paged.$refs.cri)
      this.search()
    },
    methods: {
      search () {
        this.$refs.paged.$refs.cri.search()
      },
      selfSearch (args) {
        if (this.row) {
          args.condition = `${args.condition} and m.f_userinfo_id = '${this.row.f_userinfo_id}'`
        }
        this.model.search(args.condition, args.model)
      },
      addOrRemove (is) {
        this.selecteds = []
        if (!is) { // 添加本页所有数据到ids中
          this.model.rows.forEach((row) => {
            this.selecteds.push(row)
          })
          this.selectAll = true
        } else { // 从ids中取消所有的数据
          this.selecteds = []
          this.selectAll = false
        }
      },
      async confirm () {
        await this.$showMessage('确认开收据吗?', ['cancel', 'confirm']).then(
          (response) => {
            if (response === 'confirm') {
              this.flag = true
            } else if (response === 'cancel') {
              this.flag = false
            }
          })
        if (this.flag) {
          let ids = '-1'// 拼接选中的表编号
          for (var i = 0; i < this.selecteds.length; i++) {
            ids += ',' + this.selecteds[i].f_user_id
          }
          let liquidation = {// 组装数据
            f_user_name: this.row.f_user_name,
            f_bill_id: this.billData.bill.id,
            f_bill_number: this.billData.bill.number,
            f_bill_type: this.model.f_bill_type[0],
            f_userinfo_id: this.selecteds[0].f_userinfo_id,
            f_user_id: ids,
            f_operator: this.$login.f.name,
            f_hand_month: this.eticket.hand_months,
            f_paid_money: this.eticket.totalFee,
            f_gas: this.eticket.totalGas,
            f_filiale: this.$login.f.f_fengongsi,
            f_outlets: this.$login.f.f_parentname,
            f_orgstr: this.$login.f.orgpathstr,
            f_filialeids: this.$login.f.f_orgids
          }
          let id = await this.$CommonService.saveLiquidation(liquidation)
          this.data = {
            id: id.data,
            f_bill_type: '清算单',
            f_bill_style: '普通收据',
            f_userinfo_id: this.selecteds[0].f_userinfo_id,
            totalGas: this.eticket.totalGas,
            totalFee: this.eticket.totalFee
          }
          this.print = true
        }
      },
      printok () {
        this.$refs.paged.$refs.cri.search()
        this.print = false
        this.selecteds = []
        this.$dispatch('success')
      },
      close () {
        this.$refs.paged.$refs.cri.search()
        this.print = false
      },
      validateBill (val) {
        console.log(val, '+++++++++++++==val')
        this.billData.bill = val.bill
      }
    },
    watch: {
      'selecteds.length' (val) {
        console.log('观察选中的数据', val, this.selecteds)
        this.selectAll = val === this.model.rows.length
        if (val > 0) {
          this.eticket.totalGas = 0
          this.eticket.totalFee = 0
          this.eticket.hand_months = []
          for (let i = 0; i < this.selecteds.length; i++) {
            this.eticket.totalGas = (this.eticket.totalGas - 0) + (this.selecteds[i].totalgas - 0)
            this.eticket.totalFee = (this.eticket.totalFee - 0) + (this.selecteds[i].totalfee - 0)
            this.eticket.hand_months.push(this.selecteds[i].f_hand_month)
          }
        }
      }
    }
  }
</script>
