<template>
  <div style="flex:1;" class="flex">
    <button class="btn btn-xs" v-show="!this.criteriaShow" @click="this.show()">
      <span class="glyphicon glyphicon-chevron-down" style="color: #000;"></span>
    </button>
    <criteria-paged :model="model" v-ref:paged>
      <criteria partial='criteria' @condition-changed='$parent.selfSearch' v-ref:cri v-show="$parent.criteriaShow">
        <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
          <div class="row">
            <div class="col-sm-2 form-group form-input-group" >
              <label class="control-label">用户编号</label>
              <input  type="text" class="form-control" v-model="model.f_userinfo_code"
                      condition="f_userinfo_code = '{}' " placeholder="用户编号">
            </div>
            <div class="col-sm-2 form-group form-input-group" >
              <label class="control-label">用户姓名</label>
              <input  type="text" class="form-control" v-model="model.f_user_name"
                      condition="f_user_name like '%{}%'" placeholder="用户姓名">
            </div>
            <div class="col-sm-2 form-group form-input-group" >
              <label class="control-label">用户地址</label>
              <input  type="text" class="form-control" v-model="model.f_address"
                      condition="f_address like '%{}%'" placeholder='用户地址'>
            </div>
            <div class="col-sm-2 form-group form-input-group" >
              <label class="control-label">所属表(表号)</label>
              <input  type="text" class="form-control" v-model="model.f_meternumber"
                      condition="f_meternumber like '%{}%'" placeholder='所属表(表号)'>
            </div>

            <div class="col-sm-2 form-group form-input-group" >
              <label class="control-label">设备类型</label>
              <v-select :value.sync="model.f_devices_type"
                        v-model="model.f_devices_type"
                        :options='$parent.$parent.deviceTypes' placeholder='请选择'
                        condition1="f_devices_type = '{}'"
                        ></v-select>
            </div>
            <div class="col-sm-2 form-group form-input-group" >
              <label for="startDate" class="control-label">开始日期</label>
              <datepicker id="startDate" placeholder="开始日期" width='100%'
                          v-model="model.startDate"
                          :value.sync="model.startDate"
                          :format="'yyyy-MM-dd'"
                          :show-reset-button="true"
                          condition="f_operate_date >= '{} 00:00:00'">
              </datepicker>
            </div>
            <div class="col-sm-2 form-group form-input-group" >
              <label for="endDate" class="control-label">结束日期</label>
              <datepicker id="endDate" placeholder="结束日期" width='100%'
                          v-model="model.endDate"
                          :value.sync="model.endDate"
                          :format="'yyyy-MM-dd'"
                          :show-reset-button="true"
                          condition="f_operate_date <= '{} 23:59:59'">
              </datepicker>
            </div>

            <div class="col-sm-2 form-group form-input-group" >
              <label for="endDate" class="control-label">组织机构</label>
              <right-tree :userid.sync='$parent.$parent.userid'
                          :source.sync='$parent.$parent.source'
                          :multiple="true"
                          @re-res="$parent.$parent.getRes"></right-tree>
            </div>

          </div>
          <div class="row">
            <div class="span" style = "float:right;margin-top:10px">
              <button class="btn btn-success" @click="search()">查询</button>
              <button class="btn btn-success" @click="$parent.$parent.clear()">清空</button>
              <!--<button class="btn btn-default" @click="$parent.$parent.stamp()">打印</button>-->

              <export-excel :data="$parent.$parent.getCondition"
                            :field="$parent.$parent.getExportField"
                            sqlurl="rs/logic/exportfile" sql-name="userDeviceQuery" template-name='用户设备查询导出'  :choose-col="true"></export-excel>

              <button class="btn" @click="$parent.$parent.hidden()" style="margin-left: 10px">
                <span class="glyphicon glyphicon-chevron-up"></span>
              </button>
            </div>
          </div>
        </div>
      </criteria>

      <data-grid  :model="model" 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>
          </tr>
        </template>
        <template partial='body'>
          <td style="text-align: center;"><nobr>{{row.f_userinfo_code}}</nobr></td>
          <td style="text-align: center;"><nobr>{{row.f_user_name}}</nobr></td>
          <td style="text-align: center;"><nobr>{{row.f_address}}</nobr></td>
          <td style="text-align: center;"><nobr>{{row.f_meternumber}}</nobr></td>
          <td style="text-align: center;"><nobr>{{row.f_devices_type}}</nobr></td>
          <td style="text-align: center;"><nobr>{{row.f_pregas_total}}</nobr></td>
        </template>
        <template partial='foot'>

        </template>
      </data-grid>
    </criteria-paged>

    <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;{{sumsmodel.f_column}}</td>
        <td style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px">用气量汇总:&emsp;{{sumsmodel.f_pregas_total}}</td>
      </tr>
    </table>

    <modal :show.sync="printshow" v-ref:modal backdrop="false">
      <header slot="modal-header" class="modal-header text-center">
        <h4 class="modal-title">打印列选择</h4>
        <input type="checkbox" class="" id="f_generations" v-model="all">
        <label for="f_generations" class="font-size">全选</label>
      </header>
      <article slot="modal-body">
        <div class="auto col-sm-11 col-md-offset-1"  style="margin-top: 10px;">
          <div class="col-sm-3" v-for="f in fields">
            <input type="checkbox" class="" :id="'water-owe-details-'+$index" v-model="modelval" :value="$key">
            <label :for="'water-owe-details-'+$index" class="font-size">{{f}}</label>
          </div>
        </div>
      </article>
      <footer slot="modal-footer" class="modal-footer">
        <center>
          <button v-show="printshow" type="button" class="btn btn-default" @click='close()'>取消</button>
          <button v-show="printshow" type="button" class="btn btn-success" @click='print()'>打印</button>
          <print-table :model='model' v-show="false" v-ref:print
                       :top='40' :left='60' :right='40' :bottom='60'
                       :thead="thead" :tfoot='tfoot' :attach="yangsen"
                       :fields="modelval" :printpage="true">
          </print-table>
        </center>
      </footer>
    </modal>
  </div>
</template>

<script>
  import { PagedList } from 'vue-client'
  import defaultPrint from '../config/DefaultPrint'
  import exportConfig from '../config/exportConfig'

  let readySomething = async function (self) {
    self.$refs.paged.$refs.cri.model.startDate = self.$login.toStandardDateString()
    self.$refs.paged.$refs.cri.model.endDate = self.$login.toStandardDateString()

    await self.$refs.paged.$refs.cri.search()
  }
  export default {
    data() {
      return {
        model: new PagedList('rs/sql/userDeviceQuery', 20,{},{f_column: 0,f_pregas_total: 0}),
        criteriaShow: true,

        filialeNameStr: null,
        filialeCodeStr: this.$login.f.f_orgids,
        userid: this.$login.f.id,
        source:`tool.getFullTree(this.getRights().where(row.getType() != $zone$).where(row.getType() != $role$))`,

        modelval: [],
        printshow: false,
        all: false,
        fields: {},
        thead: '',
        tfoot: '',

        // 下拉框参数
        deviceTypes: this.$appdata.getParam('设备类型') ? [{label: '全部', value: ''}, ...this.$appdata.getParam('设备类型')] : [],
        brand: this.$appdata.getParam('设备品牌') ? [{label: '全部', value: ''}, ...this.$appdata.getParam('设备品牌')] : [],

        // 合计数据
        sumsmodel: {}
      }
    },
    ready(){
      readySomething(this).then(() => {
        this.$emit('ready')
      }).catch((error) => {
        this.$emit('error', error)
      })
    },
    methods: {
      selfSearch (args) {
        const rawOrg = this.filialeCodeStr
        let codes = []
        if (Array.isArray(rawOrg)) {
          codes = rawOrg
        } else if (typeof rawOrg === 'string') {
          codes = rawOrg.split(',').map(item => item.trim()).filter(item => item)
        }
        let orgCondition = ''
        if (codes.length === 1) {
          orgCondition = ` and f_filialeids like '${codes[0]}%'`
        } else if (codes.length > 1) {
          const parts = codes.map(code => `f_filialeids like '${code}%'`)
          orgCondition = ' and (' + parts.join(' or ') + ')'
        }
        args.condition = `${args.condition}${orgCondition}`

        if (this.$refs.paged.$refs.cri.model.f_devices_type != '') {
          this.$refs.paged.model.params.condition1 = `f_devices_type = '${this.$refs.paged.$refs.cri.model.f_devices_type[0]}'`
        } else {
          this.$refs.paged.model.params.condition1 = `1=1`
        }
        this.model.search(args.condition, args.model)

        this.sumsmodel = this.$refs.paged.$refs.grid.model.sums
        console.log('合计字段', this.sumsmodel)
      },
      clear(){
        Object.keys(this.$refs.paged.$refs.cri.model).forEach((key) => {
          this.$refs.paged.$refs.cri.model[key] = ''
        })
      },
      show(){
        this.criteriaShow = true
      },
      hidden(){
        this.criteriaShow = false
      },
      getRes(obj) {
        this.filialeNameStr = obj.res
        this.filialeCodeStr = obj.resids
      },
      stamp () {
        this.all = false
        //默认选择要打印的列
        this.modelval = defaultPrint.config
        this.fields = this.getfield
        console.log('所有打印字段',this.fields)
        this.printshow = true
        this.put()
      },
      put () {
        // 对Modelval进行排序
        this.sortModelval()
        this.thead = `<tr><th colspan=${this.modelval.length}>设备查询统计报表</th></tr><tr>`
        for (let key of this.modelval) {
          this.thead += '<th>' + this.fields[key] + '</th>'
        }
        this.thead += '</tr>'
      },
      print () {
        this.$refs.print.PrintAsFile()
        this.printshow = false
      },
      close () {
        this.printshow = false
        this.all = false
      },
      // 对选择的列进行排序
      sortModelval () {
        let sortModel = []
        Object.keys(this.fields).forEach((key) => {
          if (this.modelval.includes(key)) {
            sortModel.push(key)
          }
        })
        this.modelval = sortModel
        console.log('选择的打印的字段', this.modelval)
      }
    },
    watch:{
      'all' (val) {
        if (val) {
          this.modelval = this.bodyData
        } else {
          this.modelval = defaultPrint.config
          this.put()
        }
      },
      'modelval.length' () {
        this.put()
      },
    },
    computed:{
      getCondition(){
        const rawOrg = this.filialeCodeStr
        let codes = []
        if (Array.isArray(rawOrg)) {
          codes = rawOrg
        } else if (typeof rawOrg === 'string') {
          codes = rawOrg.split(',').map(item => item.trim()).filter(item => item)
        }
        let orgCondition = ''
        if (codes.length === 1) {
          orgCondition = `  and f_filialeids like '${codes[0]}%'`
        } else if (codes.length > 1) {
          const parts = codes.map(code => `f_filialeids like '${code}%'`)
          orgCondition = '  and (' + parts.join(' or ') + ')'
        }
        return {condition: `${this.$refs.paged.$refs.cri.condition}${orgCondition}`, condition1: this.$refs.paged.model.params.condition1}
      },
      getfield(){
        let data = {}
        this.bodyData.forEach((value, index)=>{
          data[this.bodyData[index]] = this.headData[index]
        })
        //合计字段打印
        this.tfoot = `<tr><th colspan=${this.modelval.length}>全表汇总信息: `
        if(this.sumsmodel){
          Object.keys(this.sumsmodel).forEach((key) => {
            this.tfoot += this.fields[key] + '合计: ' + `<font color="blue">${this.sumsmodel[key]} </font>`
          })
        }else{
          this.tfoot += '暂无'
        }
        this.tfoot += '</th></tr>'
        return data
      },
      getExportField() {
        return exportConfig.userDeviceConfig
      }
    }
  }
</script>
