<template>
  <div class="auto select-overspread">
    <validator name='v'>
      <ul class="nav nav-tabs">
        <li role="presentation" class="active"><a href="#">结算信息</a></li>
      </ul>
      <form class="form-horizontal" style="margin-top:20px;flex: 1;">
        <div class="row">
          <div class="col-sm-4 form-group form-input-group">
            <label for="f_area" class="control-label">用户编号</label>
            <input type="text" v-model="model.f_userinfo_code" :disabled="true"
                   class="form-control" placeholder="用户编号">
          </div>
          <div class="col-sm-4 form-group form-input-group">
            <label for="f_area" class="control-label">用户姓名</label>
            <input type="text" v-model="model.f_user_name" :disabled="true"
                   class="form-control" placeholder="用户姓名">
          </div>
        </div>
        <div class="row">
          <div class="col-sm-4 form-group form-input-group">
            <label class="control-label">结算日期:</label>
            <datepicker placeholder="开始日期"
                        v-model="model.f_account_start_date"
                        v-el:date :disabled="true"
                        :value.sync="model.f_account_start_date"
                        :format="'yyyy-MM-dd'"
            ></datepicker>
          </div>
          <div class="col-sm-4 form-group form-input-group">
            <label class="control-label">至:</label>
            <datepicker placeholder="结束日期"
                        v-model="model.f_account_end_date"
                        v-el:date :disabled="true"
                        :value.sync="model.f_account_end_date"
                        :format="'yyyy-MM-dd'"
            ></datepicker>
          </div>
          <div class="col-sm-4 form-group form-input-group">
            <label for="f_area" class="control-label">上期结余</label>
            <input type="text" v-model="model.f_last_balance" :disabled="true"
                   class="form-control" v-scale="[model.f_last_balance, 2]" placeholder="0">
          </div>
        </div>
      </form>
      <data-grid :model="model" class="list_area table_sy" partial='list' 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>
            <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_meternumber }}</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.f_hand_date }}</td>
            <td style="text-align:center">{{ row.f_stair_num }}</td>
            <td style="text-align:center">{{ row.f_pregas }}</td>
            <td style="text-align:center">{{ row.f_price }}</td>
            <td style="text-align:center">{{ row.f_preamount }}</td>
          </tr>
        </template>
        <template partial='foot'></template>
      </data-grid>
      <table class="table-hover">
        <tr style="position: relative" class="table-bordered">
          <td
            style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px;color: #5CB95C;font-weight: bold">
            汇总信息
          </td>
          <td style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px">
            气量合计:&emsp;{{ model.f_pregas_sum }}
          </td>
          <td style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px">
            气费合计:&emsp;{{ model.f_preamount_sum.toFixed(2) }}
          </td>
        </tr>
      </table>
      <div style="text-align:right;height:auto;margin-top:30px;margin-right:50px;">
        <div class="row" v-if="buttonshow">
          <div class="form-group form-input-group col-sm-4">
            <label for="f_comments" class="col-sm-2 control-label">备注:</label>
            <textarea class="form-control" v-model="model.bz" rows="1" placeholder="备注"></textarea>
          </div>
          <div class="form-group form-input-group col-sm-4">
            <label for="f_print" class="col-sm-2 control-label">打印格式:</label>
            <v-select id="print"
                      v-model="f_print"
                      placeholder='请选择'
                      :value.sync="model.f_print"
                      :options='printstyle'
                      close-on-select clear-button>
            </v-select>
            <br>
            <span v-if="model.f_print[0] === '数电专票'"
                  style="color: red; font-size: 12px">您当前选择的票据格式是数电专票，请确认</span>
          </div>
          <div class="form-group form-input-group col-sm-4">
            <label class="control-label col-sm-2">是否出票</label>
            <v-select id="f_isprint"
                      v-model="f_isprint"
                      placeholder='请选择'
                      :value.sync="f_isprint"
                      :options='isprint'
                      close-on-select clear-button>
            </v-select>
          </div>
        </div>
        <button class="button_search" @click="confirm()" v-if="buttonshow" style="width:80px;margin-left:20px;"
                id="userfiles-adjTabBox-确认">结&nbsp;&nbsp;&nbsp;算
        </button>
        <button class="button_clear" @click="cancel()" style="width:80px;margin-left:20px;"
                id="userfiles-adjTabBox-取消">取&nbsp;&nbsp;&nbsp;消
        </button>
      </div>
      <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>
      </div>
      <div class="form-group" style="float: right">
        <paper-ticket-bill :show="paperticket" :data='data' @toggle="closeticket"></paper-ticket-bill>
      </div>
    </validator>
  </div>
</template>

<script>
/**
 *阶梯气价相关信息组件
 */
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.config.printType
  self.hasValidateBill = self.config.hasBillManage
  console.log('开始没调？？？111')
  await self.getUpdate()
}
export default {
  props: ['data', 'parentData'],
  data () {
    return {
      buttonshow: false,
      model: {
        rows: [],
        f_userinfo_id: this.data.f_userinfo_id,
        f_user_name: this.data.f_user_name,
        f_userinfo_code: this.data.f_userinfo_code,
        f_user_type: this.data.f_user_type,
        f_address: this.data.f_address,
        f_account_start_date: this.data.f_account_start_date,
        f_account_end_date: this.data.f_account_end_date,
        f_last_balance: this.data.f_last_balance,
        f_balance: 0,
        f_collection: this.data.f_collection,
        f_operatorid: '',
        f_operator: '',
        f_orgid: '',
        f_orgname: '',
        f_depid: '',
        f_depname: '',
        f_pregas_sum: 0,
        f_preamount_sum: 0,
        f_bill_type: ['普通收据'],
        f_use_type: '燃气费'
      },
      billData: {
        url: 'rs/report/webmeter_liquidation',
        bill: '',
        f_meter_classify: '物联网表'
      },
      f_isprint: [false],
      isprint: [{label: '是', value: true}, {label: '否', value: false}],
      print: false,
      flag: false,
      hasValidateBill: true,
      config: {
        hasBillManage: false,  // 默认不启用发票管理
        billType: '燃气费',   // 票据类型（燃气费，其他费用，调用的发票代码不同）
        payment: '现金缴费',
        printType: ['普通收据'] // 收据/电子票/专用发票/国税发票
      },
      printstyle: this.$appdata.getParam('打印格式'),
      paperticket: false,
      row: {},
      f_bill_url: ''
    }
  },
  watch: {
    'row': {
      handler (val) {
        console.log('观察到用户发生变化', val, this.model)
        this.f_user_id = this.data.f_user_id
        this.model.f_bill_type = this.config.printType
        this.model.f_use_type = this.config.billType
        this.getUpdate()
      },
      deep: true
    }
  },
  ready () {
    liquidationManage(this).then(() => {
      this.$emit('ready')
    }).catch((error) => {
      this.$emit('error', error)
    })
    this.f_user_id = this.data.f_user_id
  },
  methods: {
    closeticket () {
      this.paperticket = false
      this.$dispatch('search')
    },
    printok () {
      this.$dispatch('search')
    },
    async confirm () {
      // this.model.f_hand_account_date=this.$login.toStandardTimeString()
      if (this.model.f_pregas_sum <= 0) {
        await this.$showMessage('结算气量等于0，是否继续进行结算', ['confirm', 'cancel']).then((res) => {
          if (res == 'cancel') {
            return
          }
        })
      }
      this.model.f_user_type = this.data.f_user_type
      this.model.f_meter_classify = this.data.f_meter_classify
      this.model.f_operator_date = this.$login.toStandardTimeString()
      this.model.f_operator = this.$login.f.name
      this.model.f_operatorid = this.$login.f.id
      this.model.f_orgid = this.$login.f.orgid
      this.model.f_orgname = this.$login.f.orgs
      this.model.f_depid = this.$login.f.depids
      this.model.f_depname = this.$login.f.deps
      this.model.f_bill_style = this.model.f_print[0]
      console.log('结算数据', this.model)
      let res = await this.$resetpost('rs/logic/saveHandAccount', this.model, {resolveMsg: '结算成功', rejectMsg: null})
      console.log('结算返回', res.data.id, this.model.f_print[0])
      if (this.f_isprint[0]) {
        if (this.model.f_print[0] === '普通收据') {
          // 启用发票管理，获取票据管理中的票号并存储记录
          this.data.id = res.data.id
          this.data.f_bill_type = '物联网表结算'
          this.print = true
        }
        // else if (this.model.f_print[0] === '纸质普票') {
        //   let param = {
        //     f_print: this.model.f_print[0],
        //     bz: this.model.bz,
        //     id: res.data.id
        //   }
        //   await
        //     this.$CommonService.openEticket(param, '结算收费')
        //   this.data.id = res.data.id
        //   this.paperticket = true
        // } else if (this.model.f_print[0] === '纸质专票') {
        //   // TODO
        //   let param = {
        //     f_print: this.model.f_print[0],
        //     bz: this.model.bz,
        //     id: res.data.id
        //   }
        //   await
        //     this.$CommonService.openEticket(param, '结算收费')
        //   this.data.id = res.data.id
        //   this.paperticket = true
        // } else if (this.model.f_print[0] === '电子发票') {
        //   // TODO
        //   let param = {
        //     f_print: this.model.f_print[0],
        //     id: res.data.id,
        //     bz: this.model.bz
        //   }
        //   let temp = await
        //   this.$CommonService.openEticket(param, '结算收费')
        //   console.log('temp', temp.data.f_bill_url)
        //   this.f_bill_url = temp.data.f_bill_url
        //   window.open(this.f_bill_url)
        //   this.$dispatch('search')
        // }
      } else {
        this.$dispatch('search')
      }
    },
    validateBill (val) {
      this.billData.bill = val.bill
    },
    cancel () {
      this.$dispatch('close')
    },
    async getUpdate () {
      this.buttonshow = false
      let res = null
      if (this.data.f_meter_classify === '物联网表') {
        res = await this.$resetpost('rs/sql/gethandfiles', {
          data: {
            f_userinfo_id: this.data.f_userinfo_id,
            f_start_date: this.data.f_account_start_date,
            f_end_date: this.data.f_account_end_date,
            f_orgid: this.model.f_orgid
          }
        }, {rejectMsg: '获取表底数出错', resolveMsg: null})
      } else {
        res = await this.$resetpost('rs/sql/getmachinehandfiles', {
          data: {
            f_userinfo_id: this.data.f_userinfo_id,
            f_start_date: this.data.f_account_start_date,
            f_end_date: this.data.f_account_end_date,
            f_orgid: this.model.f_orgid
          }
        }, {rejectMsg: '获取表底数出错', resolveMsg: null})
      }
      this.model.f_userinfo_id = this.data.f_userinfo_id
      this.model.f_userinfo_code = this.data.f_userinfo_code
      this.model.f_user_name = this.data.f_user_name
      this.model.f_user_type = this.data.f_user_type
      this.model.f_address = this.data.f_address
      this.model.f_account_start_date = this.data.f_account_start_date
      this.model.f_account_end_date = this.data.f_account_end_date
      this.model.f_last_balance = this.data.f_last_balance
      this.model.f_balance = 0
      this.model.f_collection = this.data.f_collection
      this.model.f_pregas_sum = 0
      this.model.f_preamount_sum = 0

      this.model.rows = res.data

      var f_pregas_sum = 0
      var f_preamount_sum = 0
      for (var i = 0; i < this.model.rows.length; i++) {
        f_pregas_sum = parseInt(f_pregas_sum) + parseInt(this.model.rows[i].f_pregas)
        f_preamount_sum = f_preamount_sum + this.model.rows[i].f_preamount
      }

      if (this.model.rows.length > 0) {
        this.buttonshow = true
      }

      if (!(isNaN(parseInt(this.data.f_last_balance)) && isNaN(parseInt(this.data.f_collection)))) {
        this.model.f_balance = this.model.f_last_balance + this.model.f_collection - f_preamount_sum
        this.model.f_preamount_sum = f_preamount_sum
        this.model.f_pregas_sum = f_pregas_sum
      } else {
        this.model.f_balance = !isNaN(this.data.f_last_balance) ? this.model.f_last_balance : 0
      }
    }
  }
}
</script>
<style>

</style>
