<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-inline auto" partial>
              <div class="row">
                <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="span" style="float:right;">
                  <button class="button_search button_spacing" @click="search()">查询</button>
                  <button class="button_clear button_spacing" @click="$parent.$parent.clear()">清空</button>
                  <button :class="!$parent.$parent.isCurrentMonth ? 'button_new' : 'button_search button_spacing'"
                          @click="$parent.$parent.currentMonth()">
                    查询当月
                  </button>
                  <button :class="$parent.$parent.isCurrentMonth ? 'button_new' : 'button_search button_spacing'"
                          @click="$parent.$parent.historyMonth()">
                    历史查询
                  </button>
                  <export-excel :data="$parent.$parent.getCondition"
                                :field="$parent.$parent.getfield"
                                sqlurl="api/af-revenue/logic/openapi/exportfile"
                                :sql-name="$parent.$parent.sqlName"
                                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 class="row" v-show="$parent.$parent.criteriaShow">
                <res-select-group :show-component="$parent.$parent.resshow"
                                  :selectin="true"
                                  :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">客户地址</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 :options='$parent.$parent.gasproperties'
                            :value.sync="model.f_gasproperties"
                            close-on-select
                            condition="f_gasproperties = '{}'"
                            placeholder='用气性质'
                            style="width:60%"
                            v-model="model.f_gasproperties"
                            value-single="true">
                  </v-select>
                </div>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">气表品牌</label>
                  <v-select :value.sync="model.f_meter_brand"
                            v-model="model.f_meter_brand"
                            :options='$parent.$parent.meterbrands'
                            placeholder='请选择'
                            condition="f_meter_brand = '{}'"
                            close-on-select></v-select>
                </div>
                <div class="col-sm-2 form-group  flex-row" style="white-space: nowrap">
                  <label class="font_normal_body">累计用气量</label>
                  <div class="row">
                    <input type="text" style="width:27%" class="input_search" v-model="model.f_total_gas1"
                           condition="f_total_gas >= {} " placeholder="">
                    <label class="font_normal_body"> ≤ x ≤ </label>
                    <input type="text" style="width:27%" class="input_search" v-model="model.f_total_gas2"
                           condition="f_total_gas <= {} " placeholder="">
                  </div>
                </div>
                <div class="col-sm-2 form-group  flex-row" style="white-space: nowrap">
                  <label class="font_normal_body">日均用气量</label>
                  <div class="row">
                    <input type="text" style="width:27%" class="input_search" v-model="model.f_day_gas1"
                           condition="f_day_gas >= {} " placeholder="">
                    <label class="font_normal_body"> ≤ x ≤ </label>
                    <input type="text" style="width:27%" class="input_search" v-model="model.f_day_gas2"
                           condition="f_day_gas <= {} " placeholder="">
                  </div>
                </div>
                <div class="col-sm-2 form-group" v-show="!$parent.$parent.isCurrentMonth">
                  <label for="startDate" class="font_normal_body">开始月份</label>
                  <datepicker id="startDate"
                              placeholder="开始月份"
                              style="width:60%"
                              v-model="model.startMonth"
                              :value.sync="model.startMonth"
                              :format="'yyyy-MM'"
                              :show-reset-button="true"
                  >
                  </datepicker>
                </div>
                <div class="col-sm-2 form-group" v-show="!$parent.$parent.isCurrentMonth">
                  <label for="endDate" class="font_normal_body">结束月份</label>
                  <datepicker id="endDate"
                              placeholder="结束月份"
                              style="width:60%"
                              v-model="model.endMonth"
                              :value.sync="model.endMonth"
                              :format="'yyyy-MM'"
                              :show-reset-button="true"
                  >
                  </datepicker>
                </div>
                <div class="col-sm-2 form-group" v-show="$parent.$parent.isCurrentMonth">
                  <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'"
                              :disabled="true"
                              :show-reset-button="true"
                  >
                  </datepicker>
                </div>
                <div class="col-sm-2 form-group" v-show="$parent.$parent.isCurrentMonth">
                  <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'"
                              :disabled="true"
                              :show-reset-button="true"
                  >
                  </datepicker>
                </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>
                <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_month }}</nobr>
              </td>
              <td style="text-align: center;">
                <span @click="$parent.$parent.$parent.showmsg(row)"><a>{{row.f_userinfo_code}}</a></span>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_user_name }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_user_phone }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_address }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_gasproperties }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_calculation }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_meter_brand }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_total_gas }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_month_gas }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_day_gas }}</nobr>
              </td>
            </template>
            <template partial='foot'></template>
          </data-grid>
        </criteria-paged>
      </div>
      <div 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>
  </div>
</template>
<script>
import {PagedList} from 'vue-client'
import exportConfig from '../../../components/sale/config/exportConfig'
import plugins from "../../../plugins/GetLoginInfoService";


let readySomething = async function (self) {
  self.initDate()
  await self.$MagLoadParams.loadParam()
  self.initParams()
}
export default {
  title: '物联网表月用气查询',
  name: 'WebMeterMonthUserGasQuery',
  data() {
    return {
      model: new PagedList('api/af-revenue/sql/manage_webMeterUserGasQueryCurrMonth', 20),
      initres: {
        org: [this.$login.f.orgid]
      },
      sqlName: 'manage_webMeterUserGasQueryCurrMonth',
      resshow: ['company'],
      isCurrentMonth: true,
      other: [],
      footer: [],
      rowdata: {},
      gasproperties: [],
      show: false,
      criteriaShow: false,
      orgCondtionStr: '',
      modelval: [],
      condition: '',
      printshow: false,
      all: false,
      fields: {},
      thead: '',
      tfoot: '',
      defaultfield: [],
      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,
    }
  },
  ready() {
    readySomething(this)
  },
  methods: {
    initDate () {
      this.$refs.paged.$refs.cri.model.startDate = this.$login.toStartAndEndDateString()[0]
      this.$refs.paged.$refs.cri.model.endDate = this.$login.toStandardDateString()
    },
    initParams() {
      // 初始化气表品牌
      let brandArr = []
      this.$MagGetSaleParam.getGasbrand().forEach((item) => {
        if (item.value.f_meter_type === '物联网表') {
          let temp = {}
          temp.label = item.label
          temp.value = item.value.f_meter_brand
          brandArr.push(temp)
        }
      })
      this.meterbrands = [{label: '全部', value: ''}, ...brandArr]
    },
    currentMonth() {
      this.isCurrentMonth = true
    },
    historyMonth() {
      this.isCurrentMonth = false
    },
    // 加载抄表册
    loadMeterBooks() {
      this.meterbooks = [{label: '全部', value: ''}, ...this.$GetSaleParam.getMeterBooks()]
    },
    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);
    },
    search() {
      this.$refs.paged.$refs.cri.search()
    },
    cancel() {
      this.show = false
    },
    areBothMonthsBeforeCurrent(dateStr1, dateStr2) {
      let now = new Date();
      let currentMonthStart = new Date(now.getFullYear(), now.getMonth(), 1)
      // 将字符串转换为标准日期对象，这里采用'yyyy-MM'格式避免潜在的解析问题
      let date1 = new Date(dateStr1.replace(/-/g, '/'))
      let date2 = new Date(dateStr2.replace(/-/g, '/'))
      // 比较两个日期是否都在当前月份之前
      return date1 < currentMonthStart && date2 < currentMonthStart
    },
    getLastDayOfMonth(dateString) {
      // 分割字符串获取年和月
      let [year, month] = dateString.split('-')
      // 创建一个新日期对象，注意月份需要减1
      let date = new Date(parseInt(year), parseInt(month) - 1, 1)
      // 获取下一个月的第一天，然后回退一天得到本月最后一天
      date.setMonth(date.getMonth() + 1)
      date.setDate(date.getDate() - 1)
      // 格式化为 "yyyy-mm-dd"
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
    },
    selfSearch(args) {
      if (!this.orgCondtionStr) {
        args.condition = `${args.condition} and f_orgid = '${this.$login.f.orgid}'`
      } else {
        args.condition = args.condition + this.orgCondtionStr
      }
      if (this.isCurrentMonth ) {
        this.model.params.startDate = this.$refs.paged.$refs.cri.model.startDate
        this.model.params.endDate = this.$refs.paged.$refs.cri.model.endDate
      } else {
        if (this.$refs.paged.$refs.cri.model.startMonth && this.$refs.paged.$refs.cri.model.endMonth) {
          // 需要判断是选择月份
          if (this.areBothMonthsBeforeCurrent(this.$refs.paged.$refs.cri.model.startMonth,this.$refs.paged.$refs.cri.model.endMonth)) {
            this.model.params.startDate = this.$refs.paged.$refs.cri.model.startMonth + '-01'
            this.model.params.endDate = this.getLastDayOfMonth(this.$refs.paged.$refs.cri.model.endMonth)
          }else {
            this.$showMessage('请选择小于当前月份的开始月份和结束月份来查询历史数据！')
            return
          }
        } else {
          this.$showMessage('请选择开始月份和结束月份后再进行查询')
          return
        }
      }
      this.condition = args.condition
      this.model.search(args.condition, args.model)
    },
    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
    },
    showmsg(obj) {
      this.rowdata = obj
      this.show = true
    },
    getRes(condition, obj) {
      this.orgCondtionStr = condition
    },
    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
      console.log('选择的打印的字段', this.modelval)
    }
  },
  computed: {
    metertype() {
      return [{label: ' 全部 ', value: ''}, ...this.$appdata.getParam('气表类型')]
    },
    gasproperties() {
      return [{label: '全部', value: ''}, ...this.$appdata.getParam('用气性质')]
    },
    getCondition() {
      return {
        condition: this.condition,
        startDate: this.$refs.paged.$refs.cri.model.startDate,
        endDate: this.$refs.paged.$refs.cri.model.endDate
      }
    },
    getfield() {
      return exportConfig.webMeterMonthUserGasConfig
    },
    usertypes() {
      return [{label: ' 全部  ', value: ''}, ...this.$appdata.getParam('用户类型')]
    },
  },
  events: {},
  watch: {
    'isCurrentMonth' () {
      if (this.isCurrentMonth) {
        this.model.url = this.url =  'api/af-revenue/sql/manage_webMeterUserGasQueryCurrMonth'
        this.sqlName = 'manage_webMeterUserGasQueryCurrMonth'
      } else {
        this.model.url = this.url =  'api/af-revenue/sql/manage_webMeterUserGasQueryHisMonth'
        this.sqlName = 'manage_webMeterUserGasQueryHisMonth'
      }
    }
  }
}
</script>
<style>
.datapanel {
  color: #333;
  background-color: white;
  padding: 10px 20px;
  border-radius: 15px;
}
</style>
