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

                <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_charge_date >= '{}'">
                  </datepicker>
                </div>
                <div class="col-sm-2 form-group">
                  <label for="endDate" class="font_normal_body">&nbsp;&nbsp;&nbsp;&nbsp;至&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</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_charge_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.f_userinfo_code"
                         condition="f_userinfo_code = '{}' " placeholder="客户编号">
                </div>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">缴&nbsp;费&nbsp;人&nbsp;</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.f_charge_person"
                         condition="f_charge_person like '%{}%'" placeholder="缴费人">
                </div>
                <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" :footer="$parent.$parent.footer"
                                :field="$parent.$parent.getfield" :header="$parent.$parent.other"
                                sqlurl="api/af-revenue/logic/openapi/exportfile" sql-name="gaslossQuery" template-name='气损收费导出'
                                :choose-col="true"></export-excel>
                  <print-data :sum-field="$parent.$parent.getfield" :model="$parent.model" :field="$parent.$parent.getfield"
                              :defaultfield="$parent.$parent.defaultfield" print-name="气损收费打印"
                               titletable="气损收费打印"
                              :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">
                <res-select-group :show-component="['company','operator']" :initres="$parent.$parent.initres"  @re-res="$parent.$parent.getRes" v-ref:sel></res-select-group>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">地&emsp;&emsp;址</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.f_charge_address"
                         condition="f_charge_address like '%{}%'" placeholder="缴费人地址">
                </div>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body" title="参数:付款方式查询">付款方式</label>
                  <v-select :value.sync="model.f_payment" multiple
                            v-model="model.f_payment"
                            :options='$parent.$parent.payment' placeholder='请选择'
                            condition="f_payment in {}"
                            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>-->
                  <data-order field="f_userinfo_code" name="客户编号" :order.sync="$parent.$parent.$parent.orderFields.f_userinfo_code"></data-order>
                </th>
                <th>
                  <nobr>客户姓名</nobr>
                </th>
                <th>
                  <data-order field="f_address" name="客户地址" :order.sync="$parent.$parent.$parent.orderFields.f_address"></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>-->
                  <data-order field="f_charge_date" name="缴费日期" :order.sync="$parent.$parent.$parent.orderFields.f_charge_date"></data-order>
                </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_charge_person}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_charge_phone}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_charge_address}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_collection}}</nobr>
              </td>

              <td style="text-align: center;">
                <nobr>{{row.f_payment}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_bill_style}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_serial_id}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_pay_id}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.detail}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_charge_date}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_operator}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_depname}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_orgname}}</nobr>
              </td>
<!--              <td style="text-align: center;"><nobr>-->
<!--                <button class="button_search button_spacing width-60" @click.stop="$parent.$parent.$parent.view(row)">查看</button>-->
<!--              </nobr></td>-->
            </template>
            <template partial='foot'></template>
          </data-grid>
        </criteria-paged>

        <table class="table-hover">
          <tr style="position: relative;margin-top: -16px;" 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_collection}}
            </td>

          </tr>
        </table>
      </div>
    </div>
    <div class="flex" v-if="show">
      <user-info-detail-manage-new :f_userinfo_id="rowdata.f_userinfo_id" @cancel-main="cancel"></user-info-detail-manage-new>
    </div>
    <modal :show.sync="showupload" v-if="showupload" width="80%" style="width:auto;"  v-ref:modal middle backdrop="false">
      <article slot="modal-body">
        <upload :blodid="selected.f_userinfo_id" :businessid="selected.id" v-ref:upload isupload="false" takeimg="false"  fusetype="气损收费" :isremark="false" style="width:auto" ></upload>
      </article>
      <footer slot="modal-footer" class="modal-footer">
      </footer>
    </modal>


    <modal :show.sync="progressShow" v-ref:modal backdrop="true"  width="50%" style="width:auto;" >
      <header slot="modal-header" class="modal-header">
        反盘导入
      </header>
      <article slot="modal-body" class="modal-body">
        <div class="progress" style="margin: 20px" >
          <div class="progress-bar progress-bar-success progress-bar-striped active" :style="{width: percent+'%'}">
            {{percent}}%
          </div>
        </div>
      </article>
      <footer slot="modal-footer" class="modal-footer">
        <button type="button" class="btn btn-default" @click='progressclose'>关闭</button>
      </footer>
    </modal>
    <work-busy :is-busy="iswork" v-show="iswork"></work-busy>
  </div>
</template>

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

  let readySomething = async function (self) {

    self.$refs.paged.$refs.cri.model.startDate = self.data ? self.data.startDate : self.$login.toStandardDateString() + ' 00:00:00'
    self.$refs.paged.$refs.cri.model.endDate = self.data ? self.data.endDate : self.$login.toStandardDateString() + ' 23:59:59'
    await self.$getConfig(self, 'GasLossQuery')
    self.defaultfield = [...self.defaultfield, ...self.config.defaultPrint]
    console.log('开始查询')
    self.sumsmodel = self.$refs.paged.$refs.grid.model.sums
  }
  export default {
    props:['data'],
    title: '气损收费查询',
    data() {
      return {
        iswork:false,
        other:[],
        footer:[],
        data: {},
        model: new PagedList('api/af-revenue/sql/gaslossQuery', 20, {orderitem: this.orderitem?'"' + this.orderitem + ' "':`'f_userinfo_code desc'`}, {
          f_collection: 0
        }),
        initres: {
          org:[this.$login.f.orgid],
          dep:[],
          user:[],
        },
        show:false,
        rowdata:{},
        criteriaShow: false,

        orgCondtionStr: '',
        modelval: [],

        inputtouPerson: [],
        meterbrands: [],
        printshow: false,
        f_filialeid: this.$login.f.f_orgid,
        all: false,
        fields: {},
        //排序
        orderitem:'f_userinfo_code desc',
        orderFields: {
          f_userinfo_code: 'no'
        },
        thead: '',
        tfoot: '',
        showupload:false,
        selected:{},

        // 下拉框

        //合计数据
        sumsmodel: {},
        defaultfield: [],
        config: {
          defaultPrint: ['f_userinfo_code', 'f_charge_person', 'f_charge_phone', 'f_charge_address', 'f_collection']
        },
        prices: [],
        meterbooks:[{label: '全部',value: ''}],  //抄表册
        tempfalg :false,
        lastorgstr:'',
        allorgid:[],
        inputtores:[{label: '全部',value: ''}],  //抄表员
        //表册片区
        bookSlice:[{label: '全部',value: ''}],
        imgshow:false,
        imgfilename:'',
        percent:0,
        progressShow:false,
        uuida:'',
        timer:'',
      }
    },
    ready() {
      readySomething(this).then(() => {
        this.$emit('ready')
      }).catch((error) => {
        this.$emit('error', error)
      })
    },
    methods: {
      getuuid(){
        let uuidA = '';
        var s = [];
        var hexDigits = '0123456789abcdef';
        for (var i = 0; i < 36; i++) {
          s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = '4';
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
        s[8] = s[13] = s[18] = s[23] = '-';
        uuidA = s.join('');
        this.uuida = uuidA;
      },
      progressclose(){
        this.progressShow = false;
        if(this.timer != null){
          clearInterval(this.timer);
        }
      },

      view(row){
        this.showupload = true
        this.selected= row
      },
      imgclose(){
        this.imgshow = false
      },
      imgShow(val){
        this.imgfilename = `rs/image/file/`+val
        this.imgshow = true
      },
      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);
      },

      Fileinput(){
        this.batchmoneyShow=true;
      },
      search(){
        this.$refs.paged.$refs.cri.search()
      },
      cancel() {
        this.show = false
      },
      selfSearch(args) {
        if (this.data) {
          this.$parent.$parent.$parent.data.startDate=this.$refs.paged.$refs.cri.model.startDate
          this.$parent.$parent.$parent.data.endDate=this.$refs.paged.$refs.cri.model.endDate
        }
        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] = []
        })
        this.$refs.paged.$refs.cri.model.f_meter_classify = []
      },
      show() {
        this.criteriaShow = true
      },
      hidden() {
        this.criteriaShow = !this.criteriaShow
      },
      async getRes(condition,obj) {
        this.orgCondtionStr = condition

      },
      stamp() {
        this.all = false
        //默认选择要打印的列
        this.modelval = defaultPrint.config
        this.fields = this.getfield
        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) {
        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
      },
      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: {
      'model.rows'(val) {
        if(val.length === 0){
          this.sumsmodel = {}
        }
      },
      async 'orgCondtionStr'(val) {
        this.$refs.paged.$refs.cri.model.f_inputtor=[]
        this.$refs.paged.$refs.cri.model.f_book_slice_area=[]
        this.$refs.paged.$refs.cri.model.f_meter_book = []
        this.meterbooks = [{label: '全部',value: ''}];
        if(this.lastorgstr != val){
          this.tempfalg = true;
          this.lastorgstr = val;
        }
        if(this.tempfalg && val != null && val!=''  && val.indexOf("(")>-1){
          this.tempfalg = false;
          let a = val.substring(val.indexOf("(")+2)
          await this.initmeterbook(a.substring(0,a.indexOf(")")-1));
        }
        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()
        }
      },
      '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: {

      getCondition() {
        return {
          startDate: this.$refs.paged.$refs.cri.model.startDate,
          endDate: this.$refs.paged.$refs.cri.model.endDate,
          orderitem: this.orderitem,
          condition: `${this.$refs.paged.$refs.cri.condition}` + this.orgCondtionStr}
      },
      getfield() {
        return exportConfig.gaslossConfig
      },
      payment() {
        return [{label: '全部', value: ''},...this.$appdata.getParam('付款方式查询')]
      }

    },
    events:{
      'onFileUpload': async function (file, res) {
        if (this.batchmoneyShow) {
          this.percent = 0;
          this.getuuid();
          let param = {
            filepath: res.f_downloadpath,
            f_operator: this.$login.f.name,
            f_operatorid: this.$login.f.id,
            f_orgid: this.$login.f.orgid,
            f_orgname: this.$login.f.orgs,
            f_depid: this.$login.f.depids,
            f_depname: this.$login.f.deps,
            uuid: this.uuida
          }
          this.batchmoneyShow=false;
          try{
            await this.$resetpost('rs/logic/SumSettleFileImport',{data: param},{resolveMsg: null, rejectMsg: null},1000).then((res)=>{
              if(res.data){
              }
            })
          }catch(error){}
          let getparam = {
            uuid: this.uuida
          }
          let self = this;
          this.progressShow=true;
          this.timer = setInterval(function(){
            self.$resetpost('/rs/logic/getBatchOperaPro',{data:getparam},{resolveMsg: null, rejectMsg: null}, 0).then((res)=>{
              if(res.data ){
                if(res.data.speed){
                  if(res.data.speed>= 100){
                    clearInterval(self.timer);
                    if(res.data.speed){
                      self.percent = 99;
                    }
                    setTimeout(()=>{
                      self.percent = 100;
                      self.progressclose();
                      self.$showMessage(`导入成功! 累计导入:${res.data.totalsum}, 成功:${res.data.successsum},失败:${res.data.errorsum}(包含之前导入${res.data.aftersum}),失败数据请在稽查查询中错误查询进行查看!!`);
                    },600);
                  }else{
                    self.percent = res.data.speed
                  }
                }else{
                  self.percent=0;
                }
              }
            });
          },3000);
        }
      }
    }
  }
</script>
