<template>
  <div id="unit" class="flex-row">
    <div class="basic-main">
      <div class="flex">

        <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">
                <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="form-group col-sm-2">
                  <label class="font_normal_body">选择小区</label>
                  <v-select :value.sync="model.f_residential_area" :value-single="true"
                            class="select_list select"
                            style="width: 60%"
                            v-model="model.f_residential_area"
                            :options='$parent.$parent.residentialArea' placeholder='选择小区'
                            condition="ud.f_residential_area = '{}'"
                            close-on-select search="true">
                  </v-select>
                </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"
                                :field="$parent.$parent.getfield"
                                :footer="$parent.$parent.footer"
                                :header="$parent.$parent.other"
                                sqlurl="api/af-revenue/logic/openapi/exportfile"
                                sql-name="residentialquery"
                                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"
                              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 :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" >抄&nbsp;&nbsp;表&nbsp;员</label>
                  <v-select :value.sync="model.f_inputtor"
                            v-model="model.f_inputtor"
                            :options='$parent.$parent.inputtores' placeholder='请选择'
                            condition="f_inputtor = '{}'"
                            close-on-select :search="false">
                  </v-select>
                </div>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">抄&ensp;表&ensp;册</label>
                  <v-select :value.sync="model.f_meter_book" v-model="model.f_meter_book"
                            :options='$parent.$parent.meterbooks' placeholder='抄表册'
                            style="width:60%"
                            close-on-select
                            condition="f_meter_book_num = '{}'"></v-select>
                </div>
              </div>

            </div>
          </criteria>

          <data-grid :model="model" partial='list' class="list_area table_sy" 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>
              </tr>
            </template>
            <template partial='body'>
              <td style="text-align:center">
                <nobr>{{$index+1}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_residential_area}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.hushu}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.xinhushu}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_oughtfee}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_oughtamount}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_debt_money}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_charge_money}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_qianfei}}</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.hushu}}
            </td>
            <td style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px;font-weight: bold">
              新建户数合计:&emsp;{{sumsmodel.xinhushu}}
            </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_oughtamount}}
            </td>
            <td style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px;font-weight: bold">
              相抵合计:&emsp;{{sumsmodel.f_debt_money}}
            </td>
            <td style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px;font-weight: bold">
              实收合计:&emsp;{{sumsmodel.f_charge_money}}
            </td>
            <td style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px;font-weight: bold">
              欠费合计:&emsp;{{sumsmodel.f_qianfei}}
            </td>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>

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

  let readySomething = async function (self) {
    self.defaultfield = [...self.defaultfield, ...self.config.defaultPrint]
    //加载抄表册
    self.$MagGetSaleParam.initinputtor();
    self.getinputtores();
    self.initmeterbook();


    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.$MagLoadParams.loadParam()
    self.initParams()

    self.sumsmodel = self.$refs.paged.$refs.grid.model.sums
  }

  export default {
    title: '小区欠费汇总',
    data() {
      let model = new PagedList('api/af-revenue/sql/residentialArrearsQuery', 20, {
        startdate: 'this.model.startDate',
        enddate: 'this.model.endDate'
      },{
        hushu:0,
        xinhushu:0,
        f_oughtfee:0,
        f_oughtamount:0,
        f_debt_money:0,
        f_charge_money:0,
        f_qianfei:0
      })
      model.f_filialeid = this.$login.f.orgid
      return {
        //默认打印列
        defaultfield: [],
        config: {
          defaultPrint: ['xinhushu', 'f_oughtfee', 'f_charge_money']
        },
        data: {},
        other: [],
        footer: [],
        initres: {
          org:[this.$login.f.orgid],
          dep:[],
          user:[]
        },
        model: model,
        criteriaShow: false,
        f_filialeid: this.$login.f.orgid,
        orgid: [this.$login.f.orgid],
        //小区
        residentialArea: [],
        orgCondtionStr: '',
        //合计数据
        sumsmodel:{},
        meterbooks:[{label: '全部',value: ''}],  //抄表册
        inputtores:[{label: '全部',value: ''}],
        allorgid:[],
        tempfalg :false,
        lastorgstr:'',
      }
    },
    ready() {
      this.getaddress()
      readySomething(this).then(() => {
        this.$emit('ready')
      }).catch((error) => {
        this.$emit('error', error)
      })
    },
    methods: {
      async initmeterbook(orgstr){
        if(orgstr == null ){
          orgstr = this.f_filialeid;
        }
        //获取新的抄表册,先去清理所有的抄表册
        this.$GetSaleParam.meterbooks = [];
        //开始加载新的抄表册
        await this.$LoadParams.loadMeterBook(orgstr)
        this.meterbooks = [{label: '全部', value: ''}, ...this.$GetSaleParam.getMeterBooks()]
      },
      async updateParams() {
        await this.$MagLoadParams.loadParam(this.f_filialeid)
        this.inputtores = [];
        this.inputtores.push({label: "全部", value: ""})
        if(this.allorgid!=null){
          this.allorgid.forEach((res)=>{
            this.inputtores = this.inputtores.concat(this.$MagGetSaleParam.getresinputtor(res));
          })
        }
      },
      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)
          }
        }

        return [{label: '全部', value: ''}, ...rs]
      },
      //加载抄表册
      loadMeterBooks(){
        this.meterbooks = [{label: '全部', value: ''}, ...this.$GetSaleParam.getMeterBooks()]
      },
      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);
      },
      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 = [{label: '全部', value: ''}]
        for (let row of data.data) {
          console.log('开始保存小区')
          house.push({label: row.f_residential_area, value: row.f_residential_area})
        }
        this.residentialArea = house
      },
      selfSearch(args) {
        // if (this.orgCondtionStr)
        //   args.condition = `${args.condition}` + 'and f_filialeid in ' + this.orgCondtionStr
        // else
        //   args.condition = `${args.condition}` + 'and f_filialeid in ' + '(' + this.$login.f.orgid + ')'

        args.condition = `${args.condition}` + this.orgCondtionStr
        this.model.search(args.condition, args.model)
        this.sumsmodel = this.$refs.paged.$refs.grid.model.sums
      },
      async getRes(condition,obj) {
        console.log(condition,"========")
        this.orgCondtionStr = condition

      },
      clear() {
        Object.keys(this.$refs.paged.$refs.cri.model).forEach((key) => {
          this.$refs.paged.$refs.cri.model[key] = []
        })
      },
      hidden() {
        this.criteriaShow = !this.criteriaShow
      }
    },
    watch: {
      sumsmodel: {
        handler: function (val) {
          this.getotherfooter();
        },
        deep: true
      },
      async 'orgCondtionStr'(val) {
        this.$refs.paged.$refs.cri.model.f_inputtor = []
        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(/'(.*?)'/)
        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: {

      getCondition() {
        var con = ""
        if (this.orgCondtionStr) {
          con = `${this.$refs.paged.$refs.cri.condition} ` + this.orgCondtionStr
        } else {
          con = `${this.$refs.paged.$refs.cri.condition}`
        }
        return {
          startdate: this.$refs.paged.$refs.cri.model.startDate,
          enddate: this.$refs.paged.$refs.cri.model.endDate,
          condition: con
        }
      },
      getfield() {
        return exportConfig.ResidentialQuery
      }
    }

  }
</script>
