<template>
  <div class="basic-main"  style="height: 100%">
  <criteria-paged :model="model" :pager='false' v-ref:paged>
    <criteria partial='criteria' @condition-changed='$parent.selfSearch' v-ref:criteria>
        <p class="bg-info text-center" style="padding: 8px;">北方实业用气汇总</p>
      <div class="form-group" v-if="!$parent.$parent.data.f_files_path"></div>
        <div novalidate class="form-horizontal select-overspread container-fluid auto" partial >
        <div class="row">
            <div class="col-sm-2 form-group" >
              <label class="font_normal_body" for="startDate">开始日期:</label>
              <datepicker id="startDate" placeholder="开始日期" style="width: 60%"
                          v-model="model.startDate"
                          :value.sync="model.startDate"
                          :disabled-days-of-Week="[]"
                          :format="'yyyy-MM-dd HH:mm:ss'"
                          :show-reset-button="reset">
              </datepicker>
            </div>
            <div class="col-sm-2 form-group" >
              <label  class="font_normal_body" for="endDate">结束日期:</label>
              <datepicker id="endDate" placeholder="结束日期" style="width: 60%"
                          v-model="model.endDate"
                          :value.sync="model.endDate"
                          :disabled-days-of-Week="[]"
                          :format="'yyyy-MM-dd HH:mm:ss'"
                          :show-reset-button="reset">
              </datepicker>
            </div>
            <res-select-group
              :show-component="$parent.$parent.resshow"
              :selectin="true" :initres="$parent.$parent.initres"
              :cascade =true @re-res="$parent.$parent.getRes"
              v-ref:sel>
            </res-select-group>

        </div>
          <div class="span" style = "float:right;">
            <button class="button_search" @click="$parent.$parent.searchData()">查询</button>
             <report-print id='gasprice' top='3cm' left='0' width='100%' height='100%' :preview="true"></report-print>
             <report-excel id='gasprice'></report-excel>
            <div style="float: right"  class="button_spacing" :class="{'button_shrink_top':$parent.$parent.criteriaShow,
                  'button_shrink_bottom':!$parent.$parent.criteriaShow}"    @click="$parent.$parent.hidden()"></div>
          </div>
          <div class="row" v-show="$parent.$parent.criteriaShow">
            <div class="col-sm-2 form-group">
              <label class="font_normal_body">气价类型</label>
              <v-select :value.sync="model.pricetype" v-model="model.pricetype"
                        @change="$parent.$parent.pricetypechanged"
                        placeholder='气价类型' :options="$parent.$parent.pricetypes"
                        condition="sp.f_price_type = '{}'"
                        close-on-select v-ref:type>
              </v-select>
            </div>
            <div class="col-sm-2 form-group">
              <label class="font_normal_body">气价名称</label>
              <v-select :value.sync="model.f_price_name"
                        v-model="model.f_price_name"
                        multiple
                        :options="$parent.$parent.getPricenames"
                        condition="sp.f_price_name in {}"
              ></v-select>
            </div>
            <!--<div class="col-sm-2 form-group">-->
            <!--<label class="font_normal_body">收费状态</label>-->
            <!--<v-select :value.sync="$parent.$parent.f_state" multiple-->
            <!--v-model="$parent.$parent.f_state"-->
            <!--:options='$parent.$parent.charge_state' placeholder='请选择'-->
            <!--condition="f_state in {}"-->
            <!--close-on-select></v-select>-->
            <!--</div>-->
          </div>
        </div>
    </criteria>
    <div  partial='list' v-el:handcollect id='gasprice' style="overflow-y: scroll">
      <table class='tableprint' style="margin: 0px auto"  v-if="!$parent.data.f_files_path">
        <thead>
        <tr>
          <th colspan='9' style="font-weight: normal; text-align: left;">
            <h3 style="text-align: center">北方实业用气汇总</h3>
          </th>
        </tr>
        <tr>
          <th colspan='8' style="font-weight: normal; text-align: center;">
            开始时间：{{model.model.startDate}}&nbsp;&nbsp;&nbsp;
            结束时间：{{ model.model.endDate }}
          </th>
        </tr>
        <tr>
          <th colspan='8' style="font-weight: normal; text-align: center;">
            打印时间：{{{$parent.printTime}}}
          </th>
        </tr>
        <tr>
          <th colspan='8' style="font-weight: normal; text-align: center;">
            <div>
              <span v-show="$parent.orgname.trim()!=''">公司：{{$parent.orgname}}</span>
              <span v-show="$parent.depname.trim()!=''"> 部门：{{$parent.depname}}</span>
              <span v-show="$parent.operatorname.trim()!=''">人员：{{$parent.operatorname}}</span>
            </div>
          </th>
        </tr>
        </thead>
        <tr>
          <td colspan='12'>
            {{{ model.data.substring(26,model.data.length-8) }}}
          </td>
        </tr>
        <tfoot>
        <tr style="text-align: left">
          <th colspan='3'>财务审核：</th>
          <th colspan='3'>收款审核：</th>
          <th colspan='3'>收款员：</th>
        </tr>
        </tfoot>
      </table>
      {{{ $parent.reportStr}}}
    </div>
  </criteria-paged>
  <modal :show.sync="show" v-ref:modal small backdrop="false">
    <header slot="modal-header" class="modal-header">
      <h4 class="modal-title">输入文件名称</h4>
    </header>
    <article slot="modal-body" class="modal-body">
      <div class="form-group">
        <input  type="text" class="form-control" v-model="filename" placeholder='保存的文件名'>
      </div>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <button v-show="show" type="button" class="btn btn-default" @click='close'>取消</button>
      <button v-show="show" type="button" class="btn btn-success" @click='confirm(filename)'>确认</button>
    </footer>
  </modal>
  </div>
</template>

<script>
  import { DataModel } from 'vue-client'
  import co from 'co'

  let readySomething = async function (self) {
    self.$refs.paged.$refs.criteria.model.startDate = self.$login.toStandardDateString() + ' 00:00:00'
    self.$refs.paged.$refs.criteria.model.endDate = self.$login.toStandardDateString() + ' 23:59:59'
    console.log(self.$login.f)
    await self.$MagLoadParams.loadParam()
    self.initParams()
    self.$refs.paged.$refs.criteria.search()
  }
  let saveFile = function * (self) {
    // 线验证文件是否重名
    let count = yield self.$resetpost('api/af-revenue/sql/manageSingleTable',
      {data: {tablename: 't_report_record', condition: `f_files_name = '${self.filename}'`}},
      {resolveMsg: null, rejectMsg: null})
    if (count.data.length > 0) {
      self.$showAlert('无法保存，文件名重名', 'warning', 3000)
      return
    }
    let saveBack = yield self.$resetpost('api/af-revenue/logic/saveReport', {f_files_content: self.$refs.paged.$els.handcollect.innerHTML,
      f_files_name: self.filename, f_files_type: self.data.f_report_type, f_component_name: 'manage-bus-summary',
      f_operator: this.$login.f.name, f_query_month: `${self.model.model.startDate}-${self.model.model.endDate}`,
      f_outlets: this.$login.f.depname})
    if (saveBack.data.status === 'succeed') {
      self.show = false
      self.filename = ''
      // 后台保存完成，通知刷新
      self.$dispatch('save-success', self.filename)
    }
  }
  export default {
    title: '气价分组汇总表',
    props: ['data'],
    data () {
      return {
        printTime: this.$login.toStandardTimeString(),
        depresid: [],
        userresid: [],
        f_orgid: this.$login.f.orgid,
        f_depid: this.$login.f.depids,
        f_operatorid: this.$login.f.id,
        operatorid: [],
        depid: [],
        orgname: '',
        depname: '',
        operatorname: '',
        f_inputtor: [],
        f_user_type: '',
        criteriaShow: false,
        orgCondtionStr: '1=1',
        model: new DataModel('api/af-revenue/report/brandGasPriceGroup', {startDate: 'this.model.startDate', endDate: 'this.model.endDate',
          f_orgid: 'this.model.f_orgid'}),
        reportStr: null,
        resshow: ['company', 'department'],
        initres: {
          org: [this.$login.f.orgid],
          dep: [],
          user: []
        },
        f_filialeid: this.$login.f.orgid,
        show: false,
      }
    },
    ready () {
      readySomething(this).then(() => {
        this.$emit('ready')
      }).catch((error) => {
        this.$emit('error', error)
      })
    },
    methods: {
      initParams() {
        // 初始化气表品牌
        let brandArr = []
        this.$MagGetSaleParam.getGasbrand().forEach((item) => {
          let temp = {}
          temp.label = item.label
          temp.value = item.value.f_meter_brand
          brandArr.push(temp)
        })
        this.meterbrands = [{label: '全部', value: ''}, ...brandArr]
        //初始化气表价格
        this.prices = this.$MagGetSaleParam.getPrices()
      },
      hidden () {
        this.criteriaShow = !this.criteriaShow
      },
      searchData () {
        this.$refs.paged.$refs.criteria.search()
      },
      selfSearch (args) {
        let orgcondition = args.condition + this.orgCondtionStr

        this.$refs.paged.$refs.criteria.model.f_orgid = orgcondition
        this.$refs.paged.search(args)
      },
      async getRes(condition,obj) {
        this.orgCondtionStr = condition
        this.orgname = obj.orgnames[0]
        this.depname = obj.depnames[0]
      },
      // 根据文件路径获取储存的报表内容
      getFileContent (path) {
        this.$resetpost('api/af-revenue/logic/getReportFileContent', {f_files_path: path}, {resolveMsg: null, rejectMsg: null}).then((res) => {
          this.reportStr = res.data.filecontent
          this.model.state = '正确'
        })
      },
      confirm () {
        if (!this.filename || this.filename === '') {
          this.$showAlert('无法保存，文件名不能为空', 'warning', 3000)
        }
        let saveGen = saveFile(this)
        co(saveGen)
      },
      close () {
        this.show = false
      },
      pricetypechanged () {
        this.$refs.paged.$refs.criteria.model.f_price_name = []
      },
      // 将报表保存成文件
      confirmReport () {
        this.show = true
        this.filename = this.data.f_report_name + this.$login.toStandardDateString()
      }
    },
    watch: {
      'data' (val) {
        if (val.f_files_path) {
          this.getFileContent(val.f_files_path)
        } else {
          this.reportStr = null
        }
      }
    },
    computed: {
      getPricenames () {
        let pricetype = this.$refs.paged.$refs.criteria.model.pricetype
        if (this.$refs.paged.$refs.criteria.model !== null) {
          let rs = []
          let priceArr = []
          if (pricetype.length > 0) {
            let params = {
              f_price_type: pricetype[0],
              filter: this.f_filialeid,
              prices: this.prices
            }
            this.$MagGetSaleParam.getPrice(params).forEach((item) => {
              let temp = {}
              temp.label = item.label
              temp.value = item.value.f_price_name
              priceArr.push(temp)
            })
            if (priceArr.length == 0) {
              rs = [{label: '全部', value: ''}]
            } else {
              rs = [...priceArr]
            }
          }
          if (rs.length === 0) {
            console.log('rs读出来是空')
            this.$refs.paged.$refs.criteria.model.f_price_name = ''
          }
          return rs
        }
      },
      pricetypes () {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('气价类型')]
      },
      metertypes () {
        return [{label: ' 全部 ', value: ''}, ...this.$appdata.getParam('气表类型')]
      },
      payment () {
        return [...this.$appdata.getParam('付款方式查询')]
      }
    }
  }
</script>
<style scoped>
  .noborder{
    border: none;
  }
</style>
