<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-horizontal select-overspread container-fluid auto" partial>
              <div class="row">
                <div :class="$parent.$parent.style">
                  <label for="startDate" class="font_normal_body">开始日期</label>
                  <datepicker id="startDate" placeholder="开始日期" style="width:60%"
                              v-model="$parent.$parent.startDate"
                              :value.sync="$parent.$parent.startDate"
                              :format="'yyyy-MM-dd'"
                              :show-reset-button="true">
                  </datepicker>
                </div>
                <div :class="$parent.$parent.style">
                  <label for="endDate" class="font_normal_body">结束日期</label>
                  <datepicker id="endDate" placeholder="结束日期" style="width:60%"
                              v-model="$parent.$parent.endDate"
                              :value.sync="$parent.$parent.endDate"
                              :format="'yyyy-MM-dd'"
                              :show-reset-button="true">
                  </datepicker>
                </div>
                <div :class="$parent.$parent.style" v-if="!$parent.$parent.$parent.showDetail">
                  <label class="font_normal_body">单位编号</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.id"
                         condition="id = '{}' " placeholder="单位编号">
                </div>
                <div :class="$parent.$parent.style" v-if="!$parent.$parent.$parent.showDetail">
                  <label for="endDate" class="font_normal_body">单位名称</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.f_company_name"
                         condition="f_company_name like '%{}%' " placeholder="单位名称">
<!--                  <v-select :value.sync="model.f_company_id"-->
<!--                            class="select_list select"-->
<!--                            enter-push :disabled="$parent.$parent.isCompanyShow"-->
<!--                            v-model="model.f_company_id" multiple="true"-->
<!--                            :options='$parent.$parent.corporatename' placeholder='单位名称'-->
<!--                            condition="f_company_id in {}">-->
<!--                  </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"
                                :header="$parent.$parent.other"
                                :footer="$parent.$parent.footer"
                                sqlurl="api/af-revenue/logic/openapi/exportfile"
                                sql-name="manage_companyGasSummary"
                                template-name='单位用气售气汇总'
                                :choose-col="true"></export-excel>
                  <print-data :sum-field="$parent.$parent.getfield" :model="$parent.model"
                              :field="$parent.$parent.getfield"
                              titletable="单位用气售气汇总" :starthead="$parent.$parent.startDate"
                              :defaultfield="$parent.$parent.defaultfield"
                              :sumsmodel="$parent.$parent.sumsmodel"></print-data>
                  <div
                    :class="{'button_shrink_top':$parent.$parent.criteriaShow,'button_shrink_bottom':!$parent.$parent.criteriaShow}"
                    @click="$parent.$parent.hidden()"
                    class="button_spacing"
                    style="float: right"></div>
                </div>
              </div>
              <div class="row" v-if="$parent.$parent.criteriaShow">
                <res-select-group
                  :style="$parent.$parent.style"
                  :show-component="['company','slicearea']"
                  :initres="$parent.$parent.initres"
                  @re-res="$parent.$parent.getRes"
                  v-ref:sel
                ></res-select-group>
                <div :class="$parent.$parent.style" v-if="$parent.$parent.$parent.showDetail">
                  <label class="font_normal_body">单位编号</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.id"
                         condition="id = '{}' " placeholder="单位编号">
                </div>
                <div :class="$parent.$parent.style" v-if="$parent.$parent.$parent.showDetail">
                  <label for="endDate" class="font_normal_body">单位名称</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.f_company_name"
                         condition="f_company_name like '%{}%' " placeholder="单位名称">
                  <!--                  <v-select :value.sync="model.f_company_id"-->
                  <!--                            class="select_list select"-->
                  <!--                            enter-push :disabled="$parent.$parent.isCompanyShow"-->
                  <!--                            v-model="model.f_company_id" multiple="true"-->
                  <!--                            :options='$parent.$parent.corporatename' placeholder='单位名称'-->
                  <!--                            condition="f_company_id in {}">-->
                  <!--                  </v-select>-->
                </div>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">用户类型</label>
                  <v-select :value.sync="model.f_user_type"
                            :options='$parent.$parent.usertypes'
                            :value-single="true"
                            placeholder='请选择' v-model="model.f_user_type"
                            ></v-select>
                </div>
                <div class="col-sm-2 form-group">
                  <label for="f_user_usetype" class="font_normal_body ">用气类型</label>
                  <v-select :value.sync="model.f_userusetype" :search="false"
                            @change="$parent.$parent.userUseTypeChange()"
                            v-model="model.f_userusetype"
                            :multiple="true"
                            :options='$parent.$parent.userusetypes'
                            placeholder='用气类型'>
                  </v-select>
                </div>
                <div class="col-sm-2 form-group">
                  <label for="f_use_institution" class="font_normal_body">用气机构</label>
                  <v-select :value.sync="model.f_use_institution" :search="false"
                            @change="$parent.$parent.userUseInstitutionChange()"
                            v-model="model.f_use_institution"
                            :value-single="true"
                            :options='$parent.$parent.useinstitutions'
                            placeholder='用气机构'
                            close-on-select>
                  </v-select>
                </div>
                <div class="col-sm-2 form-group">
                  <label for="f_user_usenature" class="font_normal_body ">使用性质</label>
                  <v-select :value.sync="model.f_user_usenature" :search="false"
                            v-model="model.f_user_usenature"
                            :value-single="true"
                            :options='$parent.$parent.userusenatures'
                            placeholder='使用性质'
                            close-on-select>
                  </v-select>
                </div>
<!--                <div class="col-sm-2 form-group">-->
<!--                  <label for="endDate" class="font_normal_body">小区名称</label>-->
<!--                  <v-select :value.sync="model.f_residential_area_id"-->
<!--                            class="select_list select"-->
<!--                            enter-push :disabled="$parent.$parent.isAreaShow"-->
<!--                            v-model="model.f_residential_area_id" multiple="true"-->
<!--                            @select-search="$parent.$parent.getAreaList"-->
<!--                            :options='$parent.$parent.areaList' placeholder='小区名称'-->
<!--                            condition="f_residential_area_id in {}">-->
<!--                  </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>
                </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.id }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_company_name }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_oughtamount }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_oughtfee }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_pregas }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_collection }}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{ row.f_table_num }}</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_oughtamount.toFixed(2) }}m³
            </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.toFixed(2) }}元
            </td>
            <td style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px;font-weight: bold">
              售气量:&emsp;{{ sumsmodel.f_pregas.toFixed(2) }}m³
            </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.toFixed(2) }}元
            </td>
            <td style="display: inline-block;width: auto;border-right: 1px solid #F2F6FA;padding: 0px 10px 0px 10px;font-weight: bold">
              表具数量:&emsp;{{ sumsmodel.f_table_num }}
            </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 PrintDataSelf from '../../components/sale/common/PrintDataSelf'

let readySomething = async function (self) {
  self.startDate = self.getCurrentMonthFirst()
  self.endDate = self.getCurrentMonthLast()
  // self.getCompanyList()
}
export default {
  title: '单位用气售气',
  data () {
    return {
      depresid: [],
      userresid: [],
      f_orgid: this.$login.f.orgid,
      f_depid: this.$login.f.depids,
      f_operatorid: this.$login.f.id,
      operatorid: [],
      depid: [],
      orgname: '',
      depname: [],
      operatorname: '',
      condition: '',
      orgConditionStr: '',
      data: {},
      other: [],
      footer: [],
      model: new PagedList('api/af-revenue/sql/manage_companyGasSummary', 20, {
        startDate: 'this.model.startDate',
        endDate: 'this.model.endDate',
        f_user_type : 'this.model.f_user_type',
        f_user_usetype : 'this.model.f_user_usetype',
        f_user_usenature : 'this.model.f_user_usenature',
        f_use_institution : 'this.model.f_use_institution'
      }, {
        f_oughtamount: 0,
        f_oughtfee: 0,
        f_pregas: 0,
        f_collection: 0,
        f_table_num: 0
      }),
      gasproperties: [],
      show: false,
      rowdata: {},
      areaList: [],
      modelval: [],
      startDate: '',
      endDate: '',
      inputtouPerson: [],
      printshow: false,
      all: false,
      fields: {},
      thead: '',
      tfoot: '',
      defaultfield: [],
      sumsmodel: {},
      sumExport: { 'f_oughtamount': '期间用气量', 'f_pregas': '期间售气量'},
      initres: {
        org: [this.$login.f.orgid],
        slice_area: [],
      },
      criteriaShow: true,
      useinstitutions: [],
      userusenatures: [],
      corporatename: []
    }
  },
  props: {
    style: {
      type: String,
      default: 'col-sm-2 form-group'
    }
  },
  ready () {
    readySomething(this).then(() => {
      this.$emit('ready')
    }).catch((error) => {
      this.$emit('error', error)
    })
  },
  methods: {
    getCurrentMonthFirst() {
      let date = new Date()
      date.setDate(1)
      let month = parseInt(date.getMonth() + 1)
      let day = date.getDate()
      if (month < 10) month = '0' + month
      if (day < 10) day = '0' + day
      return  date.getFullYear() + '-' + month + '-' + day
    },
    getCurrentMonthLast() {
      let date = new Date()
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      month = month < 10 ? '0' + month : month
      let day = new Date(year, month, 0)
      return year + '-' + month + '-' + day.getDate()
    },
    // async getCompanyList(searchText){
    //   let condition = ' 1 = 1 '
    //   if (searchText) {
    //     condition = ` f_company_name like '%${searchText}%' `
    //   }
    //   let HttpReset = new HttpResetClass()
    //   HttpReset.load('POST', 'api/af-revenue/sql/manageSingleTable?pageNo=1&pageSize=100', {
    //     data: {
    //       items: 'f_company_name, id',
    //       tablename: 't_company',
    //       orderitem: 'id desc',
    //       condition: condition
    //     }
    //   }, {resolveMsg: null, rejectMsg: '获取单位信息失败!'}).then((req) => {
    //     let redata = []
    //     req.data.forEach((row, n) => {
    //       redata[n] = {
    //         label: row.f_company_name,
    //         value: row.id
    //       }
    //     })
    //     this.corporatename = [{label: '全部', value: ''}, ...redata]
    //   })
    // },
    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] = []
      })
    },
    userTypeChange () {
      console.log("======"+this.$refs.paged.$refs.cri.model.f_user_type)
      this.userusetypes = []
      this.userusenatures = []
      this.useinstitutions = []
      this.$refs.paged.$refs.cri.model.f_userusetype = []
      this.$refs.paged.$refs.cri.model.f_use_institution = ''
      this.$refs.paged.$refs.cri.model.f_user_usenature = ''
      if (this.$refs.paged.$refs.cri.model.f_user_type) {
        let str = this.$refs.paged.$refs.cri.model.f_user_type + '用气类型'
        this.userusetypes = this.$appdata.getParam(str)
      }
    },
    userUseTypeChange () {
      this.useinstitutions = []
      this.userusenatures = []
      this.$refs.paged.$refs.cri.model.f_use_institution = ''
      this.$refs.paged.$refs.cri.model.f_user_usenature = ''
      if (this.$refs.paged.$refs.cri.model.f_userusetype.length > 0) {
        for (var i = 0; i < this.$refs.paged.$refs.cri.model.f_userusetype.length; i++) {
          let str = this.$refs.paged.$refs.cri.model.f_userusetype[i] + '机构'
          let getParam = this.$appdata.getParam(str)
          Array.prototype.push.apply(this.useinstitutions, getParam);
        }
      }
      let temp = {}
      this.useinstitutions = this.useinstitutions.filter(function(item) {
        var key = JSON.stringify(item);
        return temp.hasOwnProperty(key) ? false : (temp[key] = true);
      });
    },
    userUseInstitutionChange () {
      this.userusenatures = []
      this.$refs.paged.$refs.cri.model.f_user_usenature = ''
      if (this.$refs.paged.$refs.cri.model.f_use_institution) {
        let str = this.$refs.paged.$refs.cri.model.f_use_institution + '使用性质'
        this.userusenatures = this.$appdata.getParam(str)
      }
    },
    hidden () {
      this.criteriaShow = !this.criteriaShow
    },
    getotherfooter () {
      this.other = []
      this.footer = []
      let exportdata = this.getCondition
      let otherInData = []
      otherInData.push(`导出时间: ${this.$login.toStandardTimeString()}`)
      let footerData = [], exportfield = this.sumExport
      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()
    },
    appendCondition (data) {
      console.log('data=====>',data)
      let stringValue = ''
      for (var i = 0; i < data.length; i++) {
        if (data[i]) {
          if (i === data.length - 1) {
            stringValue = stringValue + "'" + data[i] + "'"
          } else {
            stringValue = stringValue + "'" + data[i] + "',"
          }
        }
      }
      return stringValue
    },
    async selfSearch (args) {
      let companyCondition2 = '1=1'
      if (this.$refs.paged.$refs.cri.model.f_userusetype.length > 0) {
        this.$refs.paged.$refs.cri.model.f_user_usetype = this.appendCondition(this.$refs.paged.$refs.cri.model.f_userusetype)
      } else {
        this.$refs.paged.$refs.cri.model.f_user_usetype = ''
      }
      if (!this.orgConditionStr) {
        args.condition = `${args.condition}` + ' and f_orgid = ' + this.$login.f.orgid
      } else {
        args.condition = `${args.condition}` + this.orgConditionStr
      }
      this.$refs.paged.$refs.cri.model.startDate = this.startDate
      this.$refs.paged.$refs.cri.model.endDate = this.endDate
      this.condition = args.condition
      console.log("查看条件",this.condition)
      await this.model.search(args.condition, args.model)
      this.sumsmodel = this.$refs.paged.$refs.grid.model.sums
      this.card = ''
      this.IdCardInfo = ''
      console.log('合计字段', this.sumsmodel)
      this.$dispatch('cancel')
    },
    getRes (obj) {
      this.orgConditionStr = 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
    },
    dealmsg (val) {
      console.log('---------------dealmsg')
      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)
    }
  },
  watch: {
    'all' (val) {
      if (val) {
        this.modelval = this.bodyData
      } else {
        this.modelval = defaultPrint.config
        this.put()
      }
    },
    sumsmodel: {
      handler: function (val) {
        this.getotherfooter()
      },
      deep: true
    },
    'modelval.length' () {
      this.put()
    }
  },
  computed: {
    getCondition () {
      return {
        condition: this.condition,
        startDate: this.startDate,
        endDate: this.endDate,
        f_user_usetype : this.$refs.paged.$refs.cri.model.f_user_usetype,
        f_user_type : this.$refs.paged.$refs.cri.model.f_user_type,
        f_user_usenature : this.$refs.paged.$refs.cri.model.f_user_usenature,
        f_use_institution : this.$refs.paged.$refs.cri.model.f_use_institution
      }
    },
    getfield () {
      return exportConfig.manageCompanyGasSummary
    },
    userusetypes() {
      return [{label: '全部', value: ''}, ...this.$appdata.getParam('用气类型')]
    },
    useTypes () {
      return [{label: '全部', value: ''}, ...this.$appdata.getParam('使用类型')]
    },
    usertypes () {
      return [{label: ' 全部 ', value: ''}, ...this.$appdata.getParam('用户类型')]
    }
  }
}
</script>

