<template>
  <div class="auto basic-main" style="height:95%">
    <criteria-paged :model="model" v-ref:paged @sort="sort">
      <criteria partial='criteria' @condition-changed='$parent.selfSearch' v-ref:cri>
        <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
          <div class="row">
            <div class="form-group col-sm-2">
              <label class="font_normal_body">客户编号</label>
              <input type="text" class="form-control" v-model="model.f_userinfo_code" style="width:60%"
                     condition="f_userinfo_code = '{}' " placeholder="客户编号"
              >
            </div>
            <div class="form-group col-sm-2">
              <label class="font_normal_body">用户姓名</label>
              <input type="text" class="form-control" v-model="model.f_user_name" style="width:60%"
                     condition="f_user_name like '%{}%'" placeholder="用户姓名"
              >
            </div>
            <div class="form-group col-sm-2">
              <label class="font_normal_body">客户地址</label>
              <input type="text" class="form-control" v-model="model.f_buy_address_phone" style="width:60%"
                     condition="f_buy_address_phone like '%{}%'" placeholder="客户地址"
              >
            </div>
            <div class="form-group col-sm-2">
              <label class="font_normal_body">票据状态</label>
              <v-select id="f_bill_state"
                        style="width:60%"
                        v-model="model.f_bill_state"
                        placeholder='票据状态'
                        condition="f_bill_state ='{}'"
                        :value.sync="model.f_bill_state"
                        :options='$parent.$parent.eticktypes'
                        :search="false"
                        close-on-select clear-button>
              </v-select>
            </div>
            <div style="float: right">
              <button class="button_search" @click="$parent.$parent.resetStatus()">认证重置</button>
              <button class="button_search" @click="search()">查 询</button>
              <button class="button_clear button_spacing" @click="$parent.$parent.clear()">清空</button>
              <export-excel :data="$parent.$parent.getCondition"
                            :field="$parent.$parent.fields"
                            sqlurl="rs/logic/saleExport" sql-name="eticket_query"
                            template-name='发票记录导出'
                            :choose-col="true">
              </export-excel>
              <div
                :class="{'button_shrink_top':$parent.$parent.criteriaShow,'button_shrink_bottom':!$parent.$parent.criteriaShow}"
                @click="$parent.$parent.criteriaShow=!$parent.$parent.criteriaShow"
                class="button_spacing"
                style="float: right"></div>
            </div>
          </div>
          <div class="row" v-show="$parent.$parent.criteriaShow">
            <res-select-group :show-component="['company','department', 'operator']" :initres="$parent.$parent.initres"
                 @re-res="$parent.$parent.getRes" v-ref:sel></res-select-group>
            <div class="form-group col-sm-2">
              <label class="font_normal_body">开票日期</label>
              <datepicker id="f_operate_datestarthate" placeholder="开始日期"
                          v-model="model.f_operate_datestarthate"
                          :value.sync="model.f_operate_datestarthate"
                          format="yyyy-MM-dd 00:00:00"
                          condition="f_operate_date >= '{}'"
                          style="width:60%">
              </datepicker>
            </div>
            <div class="form-group col-sm-2">
              <label class="font_normal_body">&nbsp;&nbsp;至&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
              <datepicker id="f_operate_dateendDate" placeholder="结束日期"
                          v-model="model.f_operate_dateendDate"
                          :value.sync="model.f_operate_dateendDate"
                          format="yyyy-MM-dd 23:59:59"
                          condition=" f_operate_date <= '{}'"
                          style="width:60%">
              </datepicker>
            </div>
            <div class="col-sm-2 form-group  flex-row" style="white-space: nowrap">
              <label class="font_normal_body">发票金额</label>
              <div class="row">
                <input type="text" style="width:27%" class="input_search" v-model="model.f_collection_small"
                       condition="f_total_money >= {} " placeholder="">
                <label class="font_normal_body"> ≤ x ≤ </label>
                <input type="text" style="width:27%" class="input_search" v-model="model.f_collection_big"
                       condition="f_total_money <= {} " placeholder="">
              </div>
            </div>
            <div class="form-group col-sm-2">
              <label class="font_normal_body">开票人&nbsp;&nbsp;</label>
              <input type="text" class="form-control" v-model="model.f_operator" style="width:60%"
                     condition="f_operator = '{}' " placeholder="开票人"
              >
            </div>
            <!--<div class="form-group col-sm-2">-->
            <!--  <label class="font_normal_body">收款人&nbsp;&nbsp;</label>-->
            <!--  <input type="text" class="form-control" v-model="model.sell_operator" style="width:60%"-->
            <!--         condition="sell_operator = '{}'" placeholder="收款人"-->
            <!--  >-->
            <!--</div>-->
            <div  class="col-sm-2 form-group">
              <label class="font_normal_body">用户类型</label>
              <v-select :value.sync="model.f_user_type"
                        :options='$parent.$parent.usertypes'
                        placeholder='请选择' v-model="model.f_user_type"
                        condition="(s.f_user_type = '{}' OR (s.f_user_type IS NULL AND uf.f_user_type = '{}'))"
                        close-on-select></v-select>
            </div>
          </div>
        </div>
      </criteria>
      <data-grid :model="model" 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>
              <data-order field="f_total_money" name="实收金额"
                          :order.sync="$parent.$parent.$parent.orderFields.f_collection"></data-order>
            </th>
            <th>
              <data-order field="f_total_money" name="开票金额"
                          :order.sync="$parent.$parent.$parent.orderFields.f_total_money"></data-order>
            </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>
            <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' :model="model">
          <tr>
            <th style="text-align:center">{{ row.f_userinfo_code }}</th>
            <th style="text-align:center">{{ row.f_user_name }}</th>
            <th style="text-align:center">{{ row.f_buy_address_phone }}</th>
            <th style="text-align:center">{{ row.f_user_type }}</th>
            <th style="text-align:center">{{ row.f_collection }}</th>
            <th style="text-align:center">{{ row.f_total_money }}</th>
            <th style="text-align:center">{{ row.f_tax_money }}</th>
            <th style="text-align:center">{{ row.f_invoice_type === '0' ? '蓝票' : '红票'}}</th>
            <th style="text-align:center">{{ row.f_bill_code }}</th>
            <th style="text-align:center">{{ row.f_fpqqlsh }}</th>
            <th style="text-align:center">{{ row.f_bill_number }}</th>
            <th style="text-align:center">{{ row.f_bill_state }}</th>
            <th style="text-align:center">{{ row.f_remessage }}</th>
            <th style="text-align:center">{{ row.f_charge_type }}</th>
            <th style="text-align:center">{{ row.f_sign_result }}</th>
            <th style="text-align:center">{{ row.sell_operate_date }}</th>
            <th style="text-align:center">{{ row.f_operate_date }}</th>
            <th style="text-align:center">{{ row.f_operator }}</th>
            <th style="text-align:center">{{ row.sell_operator }}</th>
            <th style="text-align:center">
              <button class="btn btn-link" v-if="row.f_bill_url"
                      @click="$parent.$parent.$parent.watch_ch(row.f_bill_url)">
                查看发票
              </button>
            </th>
            <th style="text-align:center">
              <template v-if="row.f_invoice_source !== '外部录入'">
                <button class="btn btn-link" v-if="row.f_bill_state==='开票成功' && row.f_invoice_type === '0'"
                        @click="$parent.$parent.$parent.fp_ch(row)">发票冲红
                </button>
                <button class="btn btn-link" v-if="row.f_bill_state==='待开票'"
                        @click="$parent.$parent.$parent.kp(row)">开票
                </button>
                <button class="btn btn-link" v-if="row.f_bill_state==='开票失败'"
                        @click="$parent.$parent.$parent.kp(row, true)">重新开票
                </button>
                <!--                <button class="btn btn-link" v-if="['查询失败','等待查询'].includes(row.f_bill_state)"-->
                <!--                        @click="$parent.$parent.$parent.fp_search(row)">电票查询-->
                <!--                </button>-->
              </template>
            </th>
          </tr>
        </template>
      </data-grid>
    </criteria-paged>
  </div>
  <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;font-weight: bold">
        开票金额合计:&emsp;{{sumsmodel.f_total_money}}
      </td>
    </tr>
  </table>
  <modal v-if="show" :show.sync="show" v-ref:modal backdrop="false">
    <header slot="modal-header" class="modal-header">
      <h4 class="modal-title">撤销原因</h4>
    </header>
    <article slot="modal-body" class="modal-body">
      <validator name='v'>
        <form class="form-horizontal select-overspread">
          <div class="form-group" :class="[$v.f_cancel_reason.required ? 'has-error' : 'has-success']">
            <label class=" col-sm-3 control-label">冲红备注:</label>
            <div class="col-sm-8">
                    <textarea class="form-control" v-model="bz" rows="3"
                              placeholder="请填写冲红备注" v-validate:bz='{required: true}'></textarea>
            </div>
          </div>
        </form>
      </validator>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <button v-show="show" type="button" class="button_search" @click='confirm()' :disabled="!$v.valid ">确认</button>
      <button v-show="show" type="button" class="button_clear" @click='close'>取消</button>
    </footer>
  </modal>
  <ticket-print :show="eticket_show" @toggle="eticket_toggle" v-ref:eticketbill></ticket-print>
</template>
<script>

import {PagedList} from 'vue-client'
import axios from "axios";

export default {
  title: '发票管理',
  data () {
    return {
      model: new PagedList('rs/sql/eticket_query', 20, {orderitem: this.orderitem ? '"' + this.orderitem + ' "' : `'f_operate_date desc'`}, {
        f_total_money: 0
      }),
      criteriaShow: false,
      eticket_show: false,
      orgCondtionStr: '',
      showsum_show: false,
      invoiceTypes: [{label: '专用发票', value: '专用发票'}, {label: '普通发票', value: '普通发票'}, {label: '国税发票', value: '国税发票'}],
      eticktypes: [{label: '开票成功', value: '开票成功'}, {label: '等待查询', value: '等待查询'}, {
        label: '开票失败',
        value: '开票失败'
      }, {
        label: '冲红失败',
        value: '冲红失败'
      }, {label: '冲红', value: '冲红'}, {label: '撤销', value: '撤销'}],
      show: false,
      bz: '',
      row: {},
      orderFields: {
        f_operate_date: 'desc',
        f_collection: 'no',
        f_total_money: 'no'
      },
      sumsmodel: {},
      other: [],
      footer: [],
      // 排序
      orderitem: ' f_operate_date desc ',
      fields: {
        'f_userinfo_code': '客户编号',
        'f_user_name': '客户姓名',
        'f_buy_address_phone': '用户地址',
        'f_user_type': '用户类型',
        'f_gasproperties': '用气性质',
        'f_collection': '实收金额',
        'f_total_money': '开票金额',
        'f_tax_money': '不含税金额',
        'f_invoice_type': '发票类型',
        'f_bill_code': '发票代码',
        'f_fpqqlsh': '发票流水号',
        'f_bill_number': '发票号码',
        'f_bill_state': '发票状态',
        'f_charge_type': '发票类型',
        'sell_operate_date': '收费时间',
        'f_operate_date': '开票时间',
        'f_operator': '开票人',
        'sell_operator': '收款人'
      },
      install_show: false,
      initres: {
        org: [this.$login.f.orgid],
        dep: [this.$login.f.depids],
        user: [this.$login.f.id]
      }
    }
  },
  ready () {
    this.sumsmodel = this.$refs.paged.$refs.grid.model.sums
    this.$refs.paged.$refs.cri.model.f_operate_datestarthate = this.$login.toStandardDateString() + ' 00:00:00'
    this.$refs.paged.$refs.cri.model.f_operate_dateendDate = this.$login.toStandardDateString() + ' 23:59:59'
  },
  methods: {
    getotherfooter () {
      // this.$refs.paged.$refs.cri.$refs.exports.otherData=[];
      // this.$refs.paged.$refs.cri.$refs.exports.footerData=[];
      this.other = []
      this.footer = []
      let otherInData = []
      otherInData.push(`导出时间: ${this.$login.toStandardTimeString()}`)
      let footerData = []
      let exportfield = this.fields
      footerData.push('合计')
      let self = this
      for (var field in self.sumsmodel) {
        footerData.push(`${exportfield[field]}合计:${self.sumsmodel[field]}`)
      }
      this.footer.push(footerData)
      this.other.push(otherInData)
    },
    getRes (obj) {
      this.orgCondtionStr = obj
    },
    search () {
      this.$refs.paged.$refs.cri.search()
    },
    resetStatus () {
      console.log('>>> 发票状态重置， 登录信息：', this.$login.f)
      let condition = ''
      if (this.$login.f.orgid) {
        condition = `${condition} and f_orgid = '${this.$login.f.orgid}'`
      }
      if (this.$login.f.depids) {
        condition = `${condition} and f_depid = '${this.$login.f.depids}'`
      }
      axios.post('/invoice/rs/logic/resetStatus', { condition: condition }, {
        resolveMsg: null,
        rejectMsg: '发票状态重置失败!'
      }).then(res => {
        this.$showAlert('本月因未认证导致开票失败的记录状态已重置！', 'success', 5000)
      }).catch(error => {
        this.$showAlert('操作失败！', 'error', 5000)
        console.error('>>> 发票状态重置失败：', error)
      })
    },
    selfSearch (args) {
      if (!this.orgCondtionStr) {
        args.condition = `${args.condition}` + ` and s.f_orgid = '${this.$login.f.orgid}'`
      } else {
        args.condition = `${args.condition}` + this.orgCondtionStr
      }
      this.model.search(args.condition, args.model)
      this.sumsmodel = this.$refs.paged.$refs.grid.model.sums
    },
    sort (field, rule) {
      // 将所有排序方式设为不排序，实现相互排斥
      for (let key in this.orderFields) {
        if (key === field) {
          this.orderFields[key] = rule
        } else {
          this.orderFields[key] = 'no'
        }
      }
      // 如果新规则不排序，还原为默认排序
      if (rule === 'no') {
        this.model.paramSource.orderitem = `'${this.orderitem}'`
      } else {
        this.model.paramSource.orderitem = `'${field} ${rule}'`
      }
      this.search()
    },
    async confirm () {
      this.eticket_show = true
      await this.$refs.eticketbill.rushRedInvoice({id: this.row.f_sell_id, eticket_id: this.row.id, bz: this.bz})
    },
    async fp_search (row) {
      this.eticket_show = true
      await this.$refs.eticketbill.fp_search(row, row.id)
    },
    watch_ch (src) {
      this.eticket_show = true
      this.$refs.eticketbill.watch_ch(src)
    },
    fp_ch (row) {
      this.row = row
      this.show = true
      this.bz = `对应正数发票代码:${row.f_bill_code}，号码:${row.f_bill_number}。`
    },
    close () {
      this.show = false
      this.install_show = false
    },
    kp (row, retry = false) {
      this.eticket_show = true
      this.$refs.eticketbill.openETicket(row.f_sell_id, row, row.f_charge_type, retry, row.f_invoice_category)
    },
    eticket_toggle () {
      this.eticket_show = false
      this.show = false
      this.row = {}
      this.bz = ''
    }
  },
  computed: {
    usertypes () {
      return [{label: ' 全部 ', value: ''}, ...this.$appdata.getParam('用户类型')]
    },
    getCondition () {
      return {
        condition: `${this.$refs.paged.$refs.cri.condition}` + this.orgCondtionStr,
        orderitem: this.orderitem ? `${this.orderitem}` : ' f_operate_date desc'
      }
    }
  },
  events: {
    'search' () {
      this.search()
    }
  },
  watch: {
    sumsmodel: {
      handler: function (val) {
        this.getotherfooter()
      },
      deep: true
    }
  }
}
</script>
<style scoped>
th {
  text-align: center;
  padding: 2px;
}

td {
  text-align: center;
  padding: 2px;
}
</style>
