<template>
  <div id="unit" class="flex-row">
    <div :class="{'basic-main':((!isdetail) && (!usershow)),'binary-left':isdetail||usershow}" @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">
                <div
                  :class="{'col-sm-2 form-group':!$parent.$parent.usershow,'col-sm-3 form-group':$parent.$parent.usershow}">
                  <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':!$parent.$parent.usershow,'col-sm-3 form-group':$parent.$parent.usershow}">
                  <label for="endDate" class="font_normal_body">&nbsp;&nbsp;&nbsp;&nbsp;至&nbsp;&nbsp;&nbsp;&nbsp;&ensp;</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':!$parent.$parent.usershow,'col-sm-3 form-group':$parent.$parent.usershow}">
                  <label class="font_normal_body">小区名称</label>
                  <v-select :value.sync="model.f_residential_area"
                            class="select_list select"
                            enter-push
                            multiple="true"
                            v-model="model.f_residential_area"
                            style="width: 60%"
                            :options='$parent.$parent.residentialArea' placeholder='选择小区'
                            close-on-select>
                  </v-select>
                </div>
                <div
                  :class="{'col-sm-2 form-group':!$parent.$parent.usershow,'col-sm-3 form-group':$parent.$parent.usershow}">
                  <label class="font_normal_body">抄&ensp;表&ensp;员</label>
                  <v-select :value.sync="model.f_inputtor"
                            v-model="model.f_inputtor"
                            :options='$parent.$parent.inputtores' placeholder='请选择'
                            multiple="true"
                            close-on-select></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="handPeopleQuery1"
                                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">
                <res-select-group :show-component="['company']" :initres="$parent.$parent.initres"  @re-res="$parent.$parent.getRes" v-ref:sel></res-select-group>
              </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>
              </tr>
            </template>
            <template partial='body'>
              <td style="text-align: center;">
                <nobr>{{ row.f_residential_area }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_inputtor }}</nobr>
              </td>
              <td style="text-align: center">
                <nobr>{{ row.f_user_number }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_oughtamount }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_oughtfee }}</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_user_number }}
            </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_oughtfee }}
            </td>
          </tr>
        </table>
      </div>
    </div>
    <div class="binary-right" v-if="usershow">
      <handplan-user :start-date.sync="startd"
                     :end-date.sync="endd"
                     :inputtor.sync="selectinputtor" :f_filialeid="f_filialeid"></handplan-user>
    </div>
  </div>
</template>

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

let readySomething = async function (self) {
  self.defaultfield = [...self.defaultfield, ...self.config.defaultPrint]
  self.$MagGetSaleParam.initinputtor();
  self.getinputtores();
  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'
  self.startd = self.$login.toStandardDateString() + ' 00:00:00'
  self.endd = self.$login.toStandardDateString() + ' 23:59:59'
  await self.$MagLoadParams.loadParam()
  self.initParams()
  self.sumsmodel = self.$refs.paged.$refs.grid.model.sums
}
export default {
  title: '抄表员统计',
  data() {
    return {
      defaultfield: [],
      config: {
        defaultPrint: ['f_residential_area', 'f_inputtor', 'f_user_number', 'f_oughtamount', 'f_oughtfee']
      },
      other: [],
      footer: [],
      showinfo: false,
      data: {},
      show: false,
      rowdata: {},
      initres: {
        org: [this.$login.f.orgid],
        dep: [],
        user: []
      },
      model: new PagedList('api/af-revenue/sql/handPeopleQuery1', 20, {
        startDate: 'this.model.startDate',
        endDate: 'this.model.endDate'
      }, {
        f_user_number: 0,
        f_oughtamount: 0,
        f_oughtfee: 0
      }),
      criteriaShow: false,
      orgCondtionStr: '',
      // 下拉框
      meterbrands: [],
      meterbooks: [{label: '全部', value: ''}],
      pricenames: [],
      prices: [],
      area: [],
      //小区
      residentialArea: [],
      sumsmodel: {},
      inputtouPerson: [],
      inputtores2: [], // 下发时使用自定义抄表员,
      f_filialeid: this.$login.f.f_orgid,
      f_orgid: this.$login.f.orgid,
      f_depid: this.$login.f.depids,
      f_operatorid: this.$login.f.id,
      inputtores: [{label: '全部', value: ''}],  //抄表员
      bookSlice: [{label: '全部', value: ''}],   //表册片区
      allorgid: [],
      isdetail: false,
      usershow: false,
      selectinputtor: '',
      startd: '',
      endd: ''
    }
  },
  ready() {
    this.getaddress()
    readySomething(this).then(() => {
      this.$emit('ready')
    }).catch((error) => {
      this.$emit('error', error)
    })
  },
  methods: {
    //显示抄表户数
    operate(inputtor) {
      if (inputtor != null) {
        this.selectinputtor = inputtor;
      } else {
        this.$showAlert('当前抄表员有误', 'warning', 2000)
        return;
      }
      this.isdetail = true;
      this.usershow = true;
    },
    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 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 = []
        arr.forEach((res) => {
          this.bookSlice.push({label: res.name, value: res.name})
        })
      }
    },
    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: ""})
      this.initSlice(this.f_filialeid)
      if (this.allorgid != null) {
        this.allorgid.forEach((res) => {
          this.inputtores = this.inputtores.concat(this.$MagGetSaleParam.getresinputtor(res));
        })
      }
      this.initParams()
    },
    getotherfooter() {
      this.other = [];
      this.footer = [];
      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);
      let date = []
      date.push(`起始时间:${this.$refs.paged.$refs.cri.model.startDate}`)
      date.push(`终止时间:${this.$refs.paged.$refs.cri.model.endDate}`)
      this.other.push(date)
    },
    async getaddress() {
      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: '获取小区失败!'})
      let house = [{label: '全部', value: ''}]
      for (let row of data.data) {
        house.push({label: row.f_residential_area, value: row.f_residential_area})
      }
      this.residentialArea = house
    },
    //把数据库查询数据转换为下拉数据
    calculate(rows) {
      let data = []
      rows.forEach((row, n) => {
        data[n] = {label: row.f_residential_area, value: row.id}
      })
      return data
    },

    search() {
      this.$refs.paged.$refs.cri.search()
    },
    cancel() {
      this.show = false
    },
    showmsg(obj) {
      this.rowdata = obj
      this.show = true
    },
    initParams() {
      // 初始化气表品牌
      let brandArr = []
      this.$MagGetSaleParam.getGasbrand().forEach((item) => {
        let temp = {}
        temp.label = item.label
        temp.value = item.value.f_meter_brand
        brandArr.push(temp)
      })
      this.meterbrands = [{label: '全部', value: ''}, ...brandArr]
      //初始化气表价格
      this.prices = this.$MagGetSaleParam.getPrices();
    },
    selfSearch(args) {
      if (this.$refs.paged.$refs.cri.model.startDate == '' || this.$refs.paged.$refs.cri.model.endDate == '') {
        this.$showAlert('请先选择开始时间、结束时间，再进行查询操作！', 'warning', 3000)
        return
      }
      //抄表员查询条件
      this.inputtouPerson = this.$refs.paged.$refs.cri.model.f_inputtor
      if (this.inputtouPerson.length !== 0) {
        let str = JSON.stringify(this.inputtouPerson)
        str = str.replace(/"/g, `'`)
        str = str.replace(/\[/g, ``)
        str = str.replace(/\]/g, ``)
        if(str !== `''`){
          args.condition += ` and f_inputtor in  ( ${str} )`
        }
        //查询多个抄表员时条件
      }
      //小区查询条件
      this.area = this.$refs.paged.$refs.cri.model.f_residential_area
      if (this.area.length !== 0) {
        let str = JSON.stringify(this.area)
        str = str.replace(/"/g, `'`)
        str = str.replace(/\[/g, ``)
        str = str.replace(/\]/g, ``)
        //查询多个小区时条件
        if(str !== `''`){
          args.condition += ` and ua.f_residential_area in  ( ${str} )`
        }
      }
      let f_orgstr = this.orgCondtionStr
      args.condition = `${args.condition} ` + f_orgstr
      self.startd = args.model.startDate;
      self.endd = args.model.endDate;
      this.model.search(args.condition, args.model)
      this.sumsmodel = this.$refs.paged.$refs.grid.model.sums;
      this.isdetail = false;
      this.usershow = false;
    },
    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] = []
      })

    },
    dealmsg(val) {
      val.model = this.model.model
      this.$dispatch('deal-msg', val)
    },
    show() {
      this.criteriaShow = true
    },
    hidden() {
      this.criteriaShow = !this.criteriaShow
    },
    getRes(obj) {
      this.orgCondtionStr = obj
    },
  },
  events: {
    'getidcard'(IdCard) {
      this.$refs.paged.$refs.cri.model.f_info_idnumber = IdCard.strID
    }
  },
  watch: {
    'model'(val) {
    },
    'orgCondtionStr'(val) {
      this.$refs.paged.$refs.cri.model.f_inputtor = []
      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.replace(/'/g, "");
            this.allorgid = resorgid.split(",")
          }
        }
        this.updateParams()
      }
    },
    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,
        condition: `${this.$refs.paged.$refs.cri.condition}` + this.orgCondtionStr
      }
    },
    inputtor() {
      return [{label: '全部', value: ''}, ...this.$appdata.getParam('抄表员')]
    },
    getfield() {
      return exportConfig.handPeopleConfig1
    }
  }
}
</script>
