<template>
  <div id="unit" class="flex-row">
    <div class="basic-main" @keyup.enter="search" v-if="!show">
      <div class="flex">
        <div style="flex:1;" class="flex" >
          <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">
                  <res-select-group :show-component="['company']" :initres="$parent.$parent.initres"  @re-res="$parent.$parent.getRes" v-ref:sel></res-select-group>
                  <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"
                                condition="f_input_date >= '{}'">
                    </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"
                                condition="f_input_date <= '{}'">
                    </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.a_khbm"
                           condition="a_khbm = '{}' " placeholder="用户编号">
                  </div>

                  <div class="col-sm-2 form-group">
                    <label class="font_normal_body">用气性质</label>
                    <v-select :value.sync="model.l_yqxz"
                              :options='$parent.$parent.yqxzArray' placeholder='请选择' v-model="model.l_yqxz" multiple
                              condition="l_yqxz in {}"
                              ></v-select>
                  </div>

                  <div class="col-sm-2 form-group">
                    <label class="font_normal_body">气表类型</label>
                    <v-select :value.sync="model.o_blx"
                              :options='$parent.$parent.bjlxArray' placeholder='请选择' v-model="model.o_blx" multiple
                              condition="o_blx in {}"
                              ></v-select>
                  </div>

                  <div class="span" style="float:right;">
                    <button class="button_search button_spacing" @click="$parent.$parent.search()">查询</button>
                    <button class="button_clear button_spacing" @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"
                                  :footer="$parent.$parent.footer"
                                  :header="$parent.$parent.other"
                                  sqlurl="api/af-revenue/logic/openapi/exportfile" sql-name="qnJgqCbmxZD" template-name='物联网抄表明细导出'
                                  :choose-col="true"></export-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>


              </div>
            </criteria>

            <data-grid :model="model" partial='list' class="list_area table_sy" @dblclick="$parent.dblclick" 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>
                  <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'>
                <td style="text-align: center;">
                  <nobr>{{row.a_khbm}}</nobr>
                </td>
                <td style="text-align: center;">
                  <nobr>{{row.b_yhmc}}</nobr>
                </td>
                <td style="text-align: center;">
                  <nobr>{{row.c_dz}}</nobr>
                </td>
                <td style="text-align: center;">
                  <nobr>{{row.d_qf}}</nobr>
                </td>
                <td style="text-align: center;">
                  <nobr>{{row.e_zf}}</nobr>
                </td>
                <td style="text-align: center;">
                  <nobr>{{row.f_dj}}</nobr>
                </td>
                <td style="text-align: center;">
                  <nobr>{{row.g_ql}}</nobr>
                </td>
                <td style="text-align: center;">
                  <nobr>{{row.h_je}}</nobr>
                </td>
                <td style="text-align: center;">
                  <nobr>{{row.i_yd}}</nobr>
                </td>
                <td style="text-align: center;">
                  <nobr>{{row.cbrq}}</nobr>
                </td>
                <td style="text-align: center;">
                  <nobr>{{row.j_bh}}</nobr>
                </td>
                <td style="text-align: center;">
                  <nobr>{{row.k_yhlx}}</nobr>
                </td>
                <td style="text-align: center;">
                  <nobr>{{row.l_yqxz}}</nobr>
                </td>
                <td style="text-align: center;">
                  <nobr>{{row.m_jgmc}}</nobr>
                </td>
                <td style="text-align: center;">
                  <nobr>{{row.n_cby}}</nobr>
                </td>
                <td style="text-align: center;">
                  <nobr>{{row.o_blx}}</nobr>
                </td>
                <td style="text-align: center;">
                  <nobr>{{row.p_jbcb}}</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.g_ql}}&emsp;&emsp;金额合计:&emsp;{{sumsmodel.h_je}}
              </td>
            </tr>
          </table>
        </div>

      </div>
    </div>
    <div class="basic-main" style="width:99%;height:98%;margin-bottom:0px" v-if="show">
      <user-info-detail-manage-new :f_userinfo_id="rowdata.f_userinfo_id" @cancel-main="cancel"></user-info-detail-manage-new>
    </div>
  </div>
</template>

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

  let readySomething = async function (self) {
    self.$MagGetSaleParam.initinputtor();
    self.getinputtores();
    // 获取区县
     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()
    self.sumsmodel = self.$refs.paged.$refs.grid.model.sums
    self.defaultfield = [...self.defaultfield, ...self.config.defaultPrint]
  }

  export default {
    title: '物联网抄表明细',
    data() {
      return {
        other:[],
        footer:[],
        model: new PagedList('api/af-revenue/sql/qnJgqCbmxZD', 20, {}, {g_ql: 0, h_je: 0}),
        criteriaShow: false,
        orgCondtionStr: '',
        modelval: [],
        printshow: false,
        all: false,
        fields: {},
        //排序
        orderitem:'',
        orderFields: {

        },
        gasproperties:[],
        //默认打印列
        defaultfield: [],
        config: {
          defaultPrint: []
        },
        balance2:'',
        thead: '',
        tfoot: '',
        area: [],
        //合计数据
        sumsmodel: {},
        initres: {
          org:[this.$login.f.orgid],
          dep:[],
          user:[],
        },
        userdetail: {
          show: false,
          f_userinfo_code: '',
          f_filialeids: ''
        },

        show:false,
        rowdata:{},
        meterInfo:{},
        deviceInfo:{},
        condition2:'',


        weixinSign:[{label:"全部",value:""},{label:"已绑定",value:"已绑定"},{label:"未绑定",value:"未绑定"}],
        //小区
        residentialArea: [],
        //缴费月份
        jfnfArray: [],
        yqxzArray: [],
        bjlxArray: [],
        //表册片区
        bookSlice:[{label: '全部',value: ''}],
        inputtores:[{label: '全部',value: ''}],  //抄表员
        allorgid:[],
        f_filialeid: this.$login.f.f_orgid,
        dypayment:[{label:"全部",value:""},{label:"银行代扣",value:"银行代扣",},{label:"现金缴费",value:"现金缴费",}],
      }
    },
    ready() {
       this.getaddress()
      // this.$refs.paged.$refs.cri.model.f_user_state=['正常']
      readySomething(this).then(() => {
        this.$emit('ready')
      }).catch((error) => {
        this.$emit('error', error)
      })
      this.initAreas(this.$login.f.orgid)
      //self.$refs.paged.$refs.cri.model.startDate = self.$login.toStandardDateString()
      //self.$refs.paged.$refs.cri.model.endDate = self.$login.toStandardDateString()
      this.getjfyf()
      this.getBjlx()
      this.getYqxz()
      this.userTypeChange ();
    },
    methods: {
      async getinputtores () {
        // 获取抄表员
        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)
          }
        }
        this.inputtores = [{label: '全部', value: ''}, ...rs]
      },
      async updateParams() {
        await this.$MagLoadParams.loadParam(this.f_filialeid)
        this.inputtores = [];
        this.inputtores.push({label: "全部", value: ""})
        this.initSlice(this.f_filialeid)
        if(this.allorgid!=null){
          this.allorgid.forEach((res)=>{
            this.inputtores = this.inputtores.concat(this.$MagGetSaleParam.getresinputtor(res));
          })
        }
      },
      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.getExportField;
        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);
      },
      async  getaddress(){
        console.log('开始获取小区')
        let HttpReset = new HttpResetClass()
        var data = await HttpReset.load('POST', 'api/af-revenue/sql/manage_getarealist', {
          data: {
            condition: `1=1 and s.f_filialeid = '${this.$login.f.orgid}'`
          }
        }, {resolveMsg: null, rejectMsg: '获取小区失败!'})
        console.log('小区',data)
        let house = []
        for (let row of data.data){
          console.log('开始保存小区')
          house.push({label: row.f_residential_area, value: row.f_residential_area})
        }
        this.residentialArea = house
      },
      async  getjfyf(){
        let HttpReset = new HttpResetClass()
        var data = await HttpReset.load('POST', 'api/af-revenue/sql/singleTable_Final', {
          data: {
            condition: '1=1',
            tablename: 'qn_jgq_cb_zd',
            groupitem: 'i_yd',
            orderitem: 'i_yd',
            items: 'i_yd'
          }
        }, {resolveMsg: null, rejectMsg: '获取失败!'})
        let nameArr = [{label: '全部', value: ''}]
        for (let row of data.data){
          nameArr.push({label: row.i_yd, value: row.i_yd})
        }
        this.jfnfArray = nameArr
      },
      async  getYqxz(){
        let HttpReset = new HttpResetClass()
        var data = await HttpReset.load('POST', 'api/af-revenue/sql/singleTable_Final', {
          data: {
            condition: '1=1',
            tablename: 'qn_jgq_cb_zd',
            groupitem: 'l_yqxz',
            orderitem: 'l_yqxz',
            items: 'l_yqxz'
          }
        }, {resolveMsg: null, rejectMsg: '获取失败!'})
        let nameArr = [{label: '全部', value: ''}]
        for (let row of data.data){
          nameArr.push({label: row.l_yqxz, value: row.l_yqxz})
        }
        this.yqxzArray = nameArr
      },
      async  getBjlx(){
        let HttpReset = new HttpResetClass()
        var data = await HttpReset.load('POST', 'api/af-revenue/sql/singleTable_Final', {
          data: {
            condition: '1=1',
            tablename: 'qn_jgq_cb_zd',
            groupitem: 'o_blx',
            orderitem: 'o_blx',
            items: 'o_blx'
          }
        }, {resolveMsg: null, rejectMsg: '获取失败!'})
        let nameArr = [{label: '全部', value: ''}]
        for (let row of data.data){
          nameArr.push({label: row.o_blx, value: row.o_blx})
        }
        this.bjlxArray = nameArr
      },
      //把数据库查询数据转换为下拉数据
      calculate(rows){
        let data = []
        rows.forEach((row, n) => {
          data[n] = {label: row.f_residential_area, value: row.id}
        })
        return data
      },
      search(){
        console.log("=====search====")
        //this.$refs.paged.$refs.cri.search()
        this.$refs.paged.$refs.cri.search()
      },
      cancel(obj) {
        console.log("=====cancel====" + obj)
        this.show = false
      },
      showmsg(obj){
        this.rowdata=obj
        this.show=true
        // let http = new HttpResetClass()
        // http.load('POST','api/af-revenue/sql/getUserMeter',{data: {condition: `f_userinfo_id ='${obj.f_userinfo_id}'`}},
        //   {resolveMsg: null, rejectMsg: null}).then((res) => {
        //   this.meterInfo = res.data})
        // let http2 = new HttpResetClass()
        // http2.load('POST','api/af-revenue/sql/deviceQuery',{data: {condition: `f_userinfo_id ='${obj.f_userinfo_id}'`}},
        //   {resolveMsg: null, rejectMsg: null}).then((res) => {
        //   this.deviceInfo = res.data})

        // this.f_userinfo_id=obj.f_userinfo_id
      },
      userTypeChange () {
        this.gasproperties=[]
        if(this.$refs.paged.$refs.cri.model !==null) {
          this.$refs.paged.$refs.cri.model.f_gasproperties=''
          this.gasproperties = this.$appdata.getParam('非民用')
        }
        else{
          this.gasproperties =[{label: '全部', value: ''}]
        }
      },
      //初始化片区
      async initSlice (val) {
        if (val) {
          let getAllArea = await this.$resetpost('/rs/search', {
            source: 'this.getParentByType($organization$).getAllChildrens().where(row.getType() == $zone$)',
            userid: this.$login.f.id
          }, {resolveMsg: null, rejectMsg: '获取片区出错！！！'})
          let arr = getAllArea.data.filter((res) => {
            return res.parentid == val
          })
          this.bookSlice = []
          console.log('过滤之后的片区-------------------', arr)
          arr.forEach((res) => {
            this.bookSlice.push({label: res.name, value: res.name})
          })
        }
      },
      async initAreas (val) {

        if (val) {
          let getAllArea = await this.$resetpost('/rs/search', {
            source: 'this.getParentByType($organization$).getAllChildrens().where(row.getType() == $zone$)',
            userid: this.$login.f.id
          }, {resolveMsg: null, rejectMsg: '获取片区出错！！！'})

          let arr = getAllArea.data.filter((res) => {
            return res.parentid == val
          })
          console.log('过滤之后的片区', arr)
          this.sliceArea = []
          arr.forEach((res) => {
            this.sliceArea.push({label: res.name, value: res.name})
          })
        }
      },
      selfSearch(args) {
        console.log('args', args)
        console.log('this.orgCondtionStr', this.orgCondtionStr)
        if (!this.orgCondtionStr) {
          args.condition = `${args.condition}` + " and tr.f_orgid = " + this.$login.f.orgid
        } else {
          args.condition = `${args.condition}` + this.orgCondtionStr
        }
        this.condition2 = args.condition
        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] = []
        })
      },
      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
      },
      close() {
        this.printshow = 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)
      },
      dblclick(row, index) {
        console.log('双击之后数据', row, index)
        this.userdetail.show = true
        this.userdetail.f_userinfo_code = row.f_userinfo_code
        this.userdetail.f_filialeids = row.f_filialeids
      },
      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()
      }
    },

    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
      },
      'orgCondtionStr'(val) {
        let res = val.match(/'(.*?)'/)
        console.log('正则提取:',res && res[1])
        if (res) {
          this.f_filialeid = res[1]
          if(res.input !=null){
            let resorgid = res.input.substring(res.input.indexOf("'"));
            if(resorgid!= null && resorgid!=''){
              resorgid = resorgid.substring(0,resorgid.lastIndexOf("'")+1);
              // resorgid = resorgid.replaceAll("'","");
              resorgid = resorgid.replace(/'/g,"");
              this.allorgid = resorgid.split(",")
            }
          }
          this.updateParams()
        }
      },
    },
    computed: {
      // defaultexport() {
      //   return exportConfig.chargeexportConfig
      // },
      authArr () {
        return this.$login.r ? this.$login.r : []
      },

      getCondition() {
        return {condition: this.condition2,orderitem:this.orderitem}
      },
      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.qnJgqCbmxZD
      },
      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]
      },
      userstates() {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('客户状态')]
      },
      userLevels () {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('用户等级')]
      },
      usertypes () {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('用户类型')]
      },
      hairpin() {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('发卡状态')]
      },
      addressstate() {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('地址状态')]
      },
      fcalculation() {
        return [{label: ' 全部 ', value: ''}, ...this.$appdata.getParam('结算方式')]
      },
      metertypes() {
        return [{label: ' 全部 ', value: ''}, ...this.$appdata.getParam('气表类型')]
      },
      accountsState() {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('下账状态')]
      }
    }
  }
</script>
<style>
  .back-red{		/* 红色背景 */
    background-color: #F6C6CE;
  }
  .back-blue{		/* 蓝色背景 */

  }
</style>
