<template>
  <div id="unit" class="flex-row">
    <div class="basic-main" @keyup.enter="search">
      <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 class="font_normal_body" >气价名称</label>
                  <v-select :value.sync="model.f_price_name" v-model='model.f_price_name'
                            :options='$parent.$parent.priceNames'
                            condition="f_price_name = '{}'"  @change="$parent.$parent.selectPrice()"
                            close-on-select style="width:60%"
                            v-el:cc></v-select>
                </div>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body" >单&emsp;&emsp;价</label>
                  <v-select :value.sync="model.f_price" v-model='model.f_price'
                            :options='$parent.$parent.pricesAll'
                            condition="detailvalue like '%{}%'"
                            close-on-select style="width:60%"
                            v-el:cc></v-select>
                </div>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">气价类型</label>
                  <v-select :value.sync="model.pricetype" v-model="model.pricetype"
                            @change="$parent.$parent.pricetypechanged"
                            placeholder='气价类型' :options="$parent.$parent.pricetypes"
                            close-on-select v-ref:type>
                  </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"
                                sqlurl="api/af-revenue/logic/openapi/exportfile" sql-name="gasPriceQuery" 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.criteriaShow=!$parent.$parent.criteriaShow"></div>
                </div>
              </div>
              <div class="row" v-show="$parent.$parent.criteriaShow">
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">客户类型</label>
                  <v-select :value.sync="model.f_user_type"
                            @change="$parent.$parent.userTypeChange1()"
                            :options='$parent.$parent.usertypes' placeholder='请选择' v-model="model.f_user_type"
                            condition="f_user_type = '{}'"
                            close-on-select></v-select>
                </div>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">用气性质</label>
                  <v-select :value.sync="model.f_gasproperties" v-model="model.f_gasproperties"
                            :options='$parent.$parent.gasproperties1' placeholder='请选择'
                            condition="f_gasproperties = '{}'"
                            close-on-select></v-select>
                </div>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body">是否启用</label>
                  <v-select :value.sync="model.price_state" v-model='model.price_state'
                            :options='$parent.$parent.pricestate'
                            condition="price_state = '{}'"
                            close-on-select style="width:60%" :value-single="true"
                            v-el:cc></v-select>
                </div>
                <div class="col-sm-2 form-group">
                  <label class="font_normal_body" :title="'参数名为：气价状态'">气价状态</label>
                  <v-select :value.sync="model.f_state" v-model='model.f_state'
                            :options='$parent.$parent.stateprice' placeholder='气价状态'
                            condition="f_state = '{}'"
                            close-on-select style="width:60%" :value-single="true"
                            v-el:cc></v-select>
                </div>
                <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>
            </div>
          </criteria>
          <data-grid :model="model" class="table_sy"  partial='list' v-ref:grid>
            <template partial='head'>
              <th>
                <!--<nobr>气价编号</nobr>-->
                <data-order field="f_price_id" name="气价编号" :order.sync="$parent.$parent.$parent.orderFields.f_price_id"></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>-->
                <data-order field="f_perform_date" name="执行日期" :order.sync="$parent.$parent.$parent.orderFields.f_perform_date"></data-order>
              </th>
              <th>
                <!--<nobr>截止日期</nobr>-->
                <data-order field="f_end_date" name="截止日期" :order.sync="$parent.$parent.$parent.orderFields.f_end_date"></data-order>
              </th>
              <th><nobr>版本号</nobr></th>
              <th><nobr>状态</nobr></th>
              <th><nobr>气价信息</nobr></th>
            </template>
            <template partial='body'>
              <td style="text-align:center">{{row.f_price_id}}</td>
              <td style="text-align:center">{{row.f_price_type  }}</td>
              <td style="text-align:center">{{row.f_price_name}}</td>
              <td style="text-align:center">{{row.f_user_type}}</td>
              <td style="text-align:center">{{row.f_gasproperties}}</td>
              <td style="text-align:center">{{row.f_stairmonths}}</td>
              <td style="text-align:center">{{row.f_perform_date}}</td>
              <td style="text-align:center;white-space: nowrap;">{{row.f_end_date}}</td>
              <td style="text-align:center">{{row.f_version}}</td>
              <td style="text-align:center">{{row.f_state}}</td>
              <td style="text-align:center;white-space: nowrap;">{{row.detailvalue}}</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>
          </tr>
        </table>
      </div>
    </div>
  </div>
</template>

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

  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'
    self.defaultfield = [...self.defaultfield, ...self.config.defaultPrint]
    await self.$MagLoadParams.loadParam()
    self.getPricenames()
    self.sumsmodel = self.$refs.paged.$refs.grid.model.sums
  }
  export default {
    props:['data'],
    title: '业务查询',
    data() {
      return {
        data: {},
        other: [],
        footer: [],
        model: new PagedList('api/af-revenue/sql/gasPriceQuery', 20, {orderitem: this.orderitem?'"' + this.orderitem + ' "':`'f_price_id desc'`} ),
        criteriaShow: false,
        bodyData: ["f_userinfo_code", "f_user_name", "f_orgname", "f_depname", "f_operator"],
        orgCondtionStr: '',
        show:false,
        rowdata:{},
        modelval: [],
        printshow: false,
        all: false,
        fields: {},
        //排序
        orderitem:'f_price_id desc',
        orderFields: {
          f_price_id: 'no'
        },
        thead: '',
        tfoot: '',
        defaultfield: [],
        resshow:['company'],
        initres: {
          org:[this.$login.f.orgid],
          dep:[],
          user:[]
        },
        gasproperties1:[],
        f_filialeid: this.$login.f.orgid,
        priceNames: [],
        config: {
          defaultPrint: ['f_userinfo_code', 'f_user_name', 'f_meternumber']
        },
        pricestate:[{label:'未启用',value:'未启用'},{label:'已启用',value:'已启用'}],
        pricesSum:[],
        pricesAll:[{label: '全部', value: ''}],
        //合计数据
        sumsmodel: {},
        stateprice: this.$appdata.getParam('气价状态') ? [{label: '全部',value: ''}, ...this.$appdata.getParam('气价状态')] : [],
      }
    },
    ready() {
      readySomething(this).then(() => {
        this.$emit('ready')
      }).catch((error) => {
        this.$emit('error', error)
      })
    },
    methods: {
      getPricenames() {
        this.priceNames = []
        let priceArr = []
        debugger
        this.$MagGetSaleParam.prices.forEach((item) => {
          console.log('111111111',item);
          this.pricesSum.push(item)
          let temp = {}
          temp.label = item.f_price_name
          temp.value = item.f_price_name
          priceArr.push(temp)
        })
        this.priceNames  = [{label: '全部', value: ''}, ...priceArr]
      },
      selectPrice(){
        this.pricesAll=[{label: '全部', value: ''}]
        this.$refs.paged.$refs.cri.model.f_price=''
        this.pricesSum.forEach((item)=>{
          if(this.$refs.paged.$refs.cri.model.f_price_name==item.f_price_name){
              item.detailprice.forEach((item)=>{
                let temp={}
                temp.label=item.f_price
                temp.value=item.f_price
                this.pricesAll.push(temp)
              })
          }
        })
      },
      pricetypechanged(){
        this.$refs.paged.$refs.cri.model.f_price_name = []
      },
      userTypeChange1 () {
        this.gasproperties1 = []
        if (this.$refs.paged.$refs.cri.model !== null) {
          this.$refs.paged.$refs.cri.model.f_gasproperties1 = ''
          this.gasproperties1 = this.$appdata.getParam(this.$refs.paged.$refs.cri.model.f_user_type[0])
        } else {
          this.gasproperties1 = [{label: '全部', value: ''}]
        }
      },
      getotherfooter() {
        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);
      },
      search(){
        this.$refs.paged.$refs.cri.search()
      },
      selfSearch(args) {
        console.log(this.$refs.paged.$refs.cri.model.price_state)
        if(this.$refs.paged.$refs.cri.model.price_state){
          args.condition = `${args.condition} ` + this.orgCondtionStr
        }
        args.condition = `${args.condition}` + this.orgCondtionStr
        this.model.search(args.condition, args.model)
        this.sumsmodel = this.$refs.paged.$refs.grid.model.sums
      },
      clear() {
        Object.keys(this.$refs.paged.$refs.cri.model).forEach((key) => {
          this.$refs.paged.$refs.cri.model[key] = []
        })
      },
      getRes(condition,obj) {
        this.orgCondtionStr = condition
        this.orgname = obj.orgnames[0]
        this.depname = obj.depnames[0]

      },
      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>'
      },
      cancel() {
        this.show = false
      },
      dealmsg(val) {
        console.log('---------------dealmsg')
        this.rowdata=val
        this.show=true
        val.model = this.model.model
        this.$dispatch('deal-msg', val)
      },
      print() {
        this.$refs.print.PrintAsFile()
        this.printshow = false
      },
      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)
      },
      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: {
      '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.$refs.paged.$refs.cri.condition}` + this.orgCondtionStr,orderitem:this.orderitem}
      },
      getfield() {
        console.log('export',exportConfig.gasPriceConfig)
        return exportConfig.gasPriceConfig
      },
      pricetypes() {
        return [{label: '全部', value: ''}, ...this.$appdata.getParam('气价类型')]
      },
      usertypes() {
        return [{label: ' 全部 ', value: ''}, ...this.$appdata.getParam('用户类型')]
      },
    }
  }
</script>
