  <template>
  <div id="unit" class="flex-row">
    <div class="basic-main" @keyup.enter="search">
      <div class="flex" v-if="!show">

        <criteria-paged :model="model" v-ref:paged>
          <criteria partial='criteria' @condition-changed='$parent.selfSearch' v-ref:cri>
            <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
              <div class="row">
                <res-select-group :initres="$parent.$parent.initres"  @re-res="$parent.$parent.getRes" v-ref:sel></res-select-group>
                <div class="span" style="float:right;">
                  <button class="button_search button_spacing" @click="search()">查询</button>
                  <button class="button_clear button_spacing" @click="$parent.$parent.clear()">清空</button>

                  <export-excel :data="$parent.$parent.getCondition"
                                :field="$parent.$parent.getfield"
                                :footer="$parent.$parent.footer"
                                :header="$parent.$parent.other"
                                sqlurl="api/af-revenue/logic/openapi/exportfile"
                                sql-name="BalanceStatistical"
                                template-name='余额统计查询导出'
                                :choose-col="true"></export-excel>
                  <print-data :model="$parent.model" :field="$parent.$parent.getfield"
                              :defaultfield="$parent.$parent.defaultfield" print-name="余额查询打印"
                              :sumsmodel="$parent.$parent.sumsmodel"></print-data>

                  <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>
              <div class="row" v-show="$parent.$parent.criteriaShow">
                <div class="col-sm-2 form-group">
                  <label for="startDate" class="font_normal_body">开始日期</label>
                  <datepicker id="startDate" placeholder="开始日期" style="width:60%"
                              v-model="model.startDate"
                              :value.sync="model.startDate"
                              :format="'yyyy-MM-dd HH:mm:ss'"
                              :show-reset-button="true">
                  </datepicker>
                </div>
                <div class="col-sm-2 form-group">
                  <label for="endDate" class="font_normal_body">结束日期</label>
                  <datepicker id="endDate" placeholder="结束日期" style="width:60%"
                              v-model="model.endDate"
                              :value.sync="model.endDate"
                              :format="'yyyy-MM-dd HH:mm:ss'"
                              :show-reset-button="true">
                  </datepicker>
                </div>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">客户编号</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.f_userinfo_code"
                         condition="f_userinfo_code = '{}' " placeholder="客户编号">
                </div>

                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">客户名称</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.f_user_name"
                         condition="f_user_name like '%{}%'" placeholder="客户名称">
                </div>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">客户地址</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.f_address"
                         condition="f_address like '%{}%'" placeholder='客户地址'>
                </div>

                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">客户类型</label>
                  <v-select :value.sync="model.f_user_type"
                            @change="$parent.$parent.userTypeChange()"
                            :options='$parent.$parent.usertypes' placeholder='请选择' v-model="model.f_user_type"
                            condition="f_user_type = '{}'"
                            close-on-select></v-select>
                </div>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">用气性质</label>
                  <v-select :value.sync="model.f_gasproperties" v-model="model.f_gasproperties"
                            :options='$parent.$parent.gasproperties' placeholder='请选择'
                            condition="f_gasproperties = '{}'"
                            close-on-select></v-select>
                </div>
<!--                <div class="col-sm-2 form-group">-->
<!--                  <label class="font_normal_body">气价类型</label>-->
<!--                  <v-select :value.sync="model.pricetype" v-model="model.pricetype"-->
<!--                            placeholder='气价类型' :options="$parent.$parent.pricetypes"-->
<!--                            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"-->
<!--                            :options="$parent.$parent.getPricenames"-->
<!--                            condition="f_price_name = '{}'"-->
<!--                            close-on-select></v-select>-->
<!--                </div>-->
<!--                <div class="col-sm-2 form-group">-->
<!--                  <label class="font_normal_body">&ensp;壁挂炉&ensp;</label>-->
<!--                  <v-select :value.sync="model.f_bgl"-->
<!--                            v-model="model.f_bgl"-->
<!--                            :options='$parent.$parent.bgl' placeholder='请选择'-->
<!--                            condition="f_bgl = '{}'"-->
<!--                            close-on-select></v-select>-->
<!--                </div>-->
<!--                <div class="col-sm-2 form-group">-->
<!--                  <label class="font_normal_body">回收率小于</label>-->
<!--                  <input type="number" style="width:60%" class="input_search" v-model="model.recovery_rate"-->
<!--                         condition="recovery_rate < {}" placeholder='回收率'>-->
<!--                </div>-->
<!--                <div class="col-sm-2 form-group">-->
<!--                  <label class="font_normal_body">&nbsp;&nbsp;&nbsp;抄表员</label>-->
<!--                  <v-select :value.sync="model.f_inputtor"-->
<!--                            v-model="model.f_inputtor" condition="f_inputtor = '{}'"-->
<!--                            :options='$parent.$parent.inputtor' placeholder='请选择'-->
<!--                            multiple = "true"-->
<!--                            close-on-select></v-select>-->
<!--                </div>-->
             </div>
            </div>
          </criteria>

          <data-grid :model="model" partial='list' class="list_area table_sy"  v-ref:grid :classname="$parent.classname">
            <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>
              </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_balance}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_oughtfee}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_preamount}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_curbalance}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_user_balance}}</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;font-weight: bold">
              期初余额合计:&emsp;{{sumsmodel.f_balance}}
            </td>
            <td style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px;font-weight: bold">
              期间应收合计:&emsp;{{sumsmodel.f_oughtfee}}
            </td>
            <td style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px;font-weight: bold">
              期间已缴合计:&emsp;{{sumsmodel.f_preamount}}
            </td>
            <td style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px;font-weight: bold">
              期末余额合计:&emsp;{{sumsmodel.f_curbalance}}
            </td>
            <td style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px;font-weight: bold">
              最新余额合计:&emsp;{{sumsmodel.f_user_balance}}
            </td>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
  import {PagedList, HttpResetClass} 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() + ' 00:00:00'
    self.$refs.paged.$refs.cri.model.endDate = self.$login.toStandardDateString() + ' 23:59:59'
    // await self.$refs.paged.$refs.cri.search()
    await self.$getConfig(self, 'HandplanQuery')
    console.log('抄表查询获取默认配置', self.config)
    self.defaultfield = [...self.defaultfield, ...self.config.defaultPrint]
    console.log('开始初始化参数', self.defaultfield)
    await self.$MagLoadParams.loadParam()
    // await self.$MagLoadParams.loadParam()
    // self.initParams()
    console.log('开始查询')
    self.sumsmodel = self.$refs.paged.$refs.grid.model.sums
  }
  export default {
    data() {
      return {
        data: {},
        other: [],
        footer: [],
        model: new PagedList('api/af-revenue/sql/BalanceStatistical', 20, {startDate: 'this.model.startDate', endDate: 'this.model.endDate'},{
          f_balance: 0,
          f_oughtfee: 0,
          f_preamount: 0,
          f_curbalance: 0,
          f_user_balance: 0
        }),
        initres: {
          org:[this.$login.f.orgid],
          dep:[],
          user:[],
        },
        show:false,
        rowdata:{},
        criteriaShow: false,
        residentialArea: [],
        orgCondtionStr: '',
        modelval: [],
        inputtouPerson: [],
        printshow: false,
        bgl:[{label: '全部', value: ''},{label: '有', value: '1'},{label: '无', value: '0'}],
        all: false,
        fields: {},
        thead: '',
        tfoot: '',

        // 下拉框

        //合计数据
        sumsmodel: {},
        defaultfield: [],
        config: {
          defaultPrint: ['f_userinfo_code', 'f_address', 'f_user_name', 'f_meternumber']
        },
        batchmoneyShow:false,
        gasproperties:[]
      }
    },
    ready() {
      readySomething(this).then(() => {
        this.$emit('ready')
      }).catch((error) => {
        this.$emit('error', error)
      })
    },
    methods: {
      userTypeChange () {
        this.gasproperties=[]
        if(this.$refs.paged.$refs.cri.model !==null) {
          this.$refs.paged.$refs.cri.model.f_gasproperties=''
          this.gasproperties = this.$appdata.getParam(this.$refs.paged.$refs.cri.model.f_user_type[0])
        }
        else{
          this.gasproperties =[{label: '全部', value: ''}]
        }
      },
      getotherfooter() {
        // this.$refs.paged.$refs.cri.$refs.exports.otherData=[];
        // this.$refs.paged.$refs.cri.$refs.exports.footerData=[];
        this.other = [];
        this.footer = [];
        // let exportdata = this.getCondition;
        let otherInData = [];
        otherInData.push(`导出时间: ${this.$login.toStandardTimeString()}`);
        let footerData = [], exportfield = this.getfield;
        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);
      },
      search(){
        this.$refs.paged.$refs.cri.search()
      },
      selfSearch(args) {
        args.condition = `${args.condition} ` + this.orgCondtionStr
        this.model.search(args.condition, args.model)
        this.sumsmodel = this.$refs.paged.$refs.grid.model.sums
      },
      clear() {
        //清空部门和人员
        this.$refs.paged.$refs.cri.$refs.sel.$children[1].selectres = []
        //部门和人员变为全选
        this.$refs.paged.$refs.cri.$refs.sel.$children[1].$children[0].isSelectAll = false
        this.$refs.paged.$refs.cri.$refs.sel.$children[2].$children[0].isSelectAll = false
        Object.keys(this.$refs.paged.$refs.cri.model).forEach((key) => {
          this.$refs.paged.$refs.cri.model[key] = []
        })
      },
      show() {
        this.criteriaShow = true
      },
      hidden() {
        this.criteriaShow = !this.criteriaShow
      },
      getRes(obj) {
        this.orgCondtionStr = obj
      },
      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
      },
      dealmsg(val) {
        console.log('---------------dealmsg')
        this.rowdata=val
        this.show=true
        val.model = this.model.model
        this.$dispatch('deal-msg', val)
      },
      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()
      },
      sumsmodel: {
        handler: function (val) {
          this.getotherfooter();
        },
        deep: true
      }
    },
    computed: {
      pricetypes() {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('气价类型')]
      },
      getPricenames() {
        let f_user_type = this.$refs.paged.$refs.cri.model.f_user_type;
        let f_gasproperties = this.$refs.paged.$refs.cri.model.f_gasproperties;
        let pricetype = this.$refs.paged.$refs.cri.model.pricetype;
        console.log("打印一下:",f_user_type,f_gasproperties,pricetype,this.$login.f.orgid,this.prices)
        if(this.$refs.paged.$refs.cri.model !==null) {
          let rs = []
          let priceArr = []
          if ( pricetype.length >0) {
            let params = {
              f_price_type: pricetype[0],
              filter: this.$login.f.orgid,
              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)
            })
            rs = [{label: '全部', value: ''}, ...priceArr]
          }
          if (rs.length === 0) {
            console.log('rs读出来是空')
            this.$refs.paged.$refs.cri.model.f_price_name = ''
          }
          return rs
        }
      },
      getCondition() {
        return {
          condition: `${this.$refs.paged.$refs.cri.condition}` + this.orgCondtionStr,
          startDate: this.$refs.paged.$refs.cri.model.startDate,
          endDate: this.$refs.paged.$refs.cri.model.endDate
        }
      },
      getfield() {
        return exportConfig.balanceConfig
      },
      usertypes() {
        return [{label: ' 全部 ', value: ''}, ...this.$appdata.getParam('用户类型')]
      },
      inputtor () {
        // 获取抄表员
        console.log('获取抄表员', this.$login.f)
        let rs = []
        if (this.$login.f.f_gasman.length > 0) {
          for (let i = 0; i < this.$login.f.f_gasman.length; i++) {
            let temp = {
              label: this.$login.f.f_gasman[i].name,
              value: this.$login.f.f_gasman[i].name
            }
            rs.push(temp)
          }
        }

        return [{label: '全部', value: ''}, ...rs]
      },
    }
  }
</script>
