<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  @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 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"
                              condition="f_operate_date >= '{}'">
                  </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"
                              condition="f_operate_date <= '{}'">
                  </datepicker>
                </div>
                <div class="span" style="float:right;">
                  <!--<read-idcard></read-idcard>-->
                  <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" :footer="$parent.$parent.footer"
                                :field="$parent.$parent.getfield" :header="$parent.$parent.other"
                                :defaultselect="$parent.$parent.defaultexport"
                                sqlurl="api/af-revenue/logic/openapi/exportfile" sql-name="recordQuery" template-name='操作记录查询导出'
                                :choose-col="true">
                  </export-excel>

<!--                  <print-data :model="$parent.model" :field="$parent.$parent.getfield" -->
<!--                              :defaultfield="$parent.$parent.defaultfield" print-name="操作记录查询"-->
<!--                              :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 :show-component="$parent.resshow" :initres="$parent.initres"  @re-res="$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>
                <th>
                  <nobr>部门名称</nobr>
                </th>
                <th>
                  <nobr>操作人员</nobr>
                </th>
              </tr>
            </template>
            <template partial='body'>
              <td style="text-align: center;">
                <nobr>{{row.f_operat_type}}</nobr>
              </td>

              <td style="text-align: center;">
                <nobr>{{row.f_describe}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_state}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_operate_date}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_orgname}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_depname}}</nobr>
              </td>
              <td style="text-align: center;">
                <nobr>{{row.f_operator}}</nobr>
              </td>
            </template>
            <template partial='foot'></template>
          </data-grid>
        </criteria-paged>
        <table class="table-hover">
          <tr style="position: relative" class="table-bordered">

          </tr>
        </table>
      </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>
    <modal :show.sync="showupload" v-if="showupload" width="80%" style="width:auto;"  v-ref:modal middle backdrop="false">
      <article slot="modal-body">
        <upload :blodid="selected.f_userinfo_id" :businessid="selected.id" v-ref:upload isupload="false" takeimg="false"  fusetype="%收费" :isremark="false" style="width:auto" ></upload>
      </article>
      <footer slot="modal-footer" class="modal-footer">
      </footer>
    </modal>
  </div>
</template>

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

  let readySomething = async function (self) {
    self.$refs.paged.$refs.cri.model.startDate = self.data.startDate
    self.$refs.paged.$refs.cri.model.endDate = self.data.endDate
    // 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.$refs.paged.$refs.cri.search()
    self.defaultfield = [...self.defaultfield, ...self.config.defaultPrint]
    await self.$MagLoadParams.loadParam()
    self.initParams()
    self.sumsmodel = self.$refs.paged.$refs.grid.model.sums;
  }
  export default {
    props:['data'],
     data() {
      return {
        resshow:['company','department','operator','slicearea'],
        other:[],
        footer:[],
        config: {
          defaultPrint: ['f_userinfo_code', 'f_user_name', 'f_pregas', 'f_collection', 'f_stairamount1', 'f_stair2amount', 'f_stair3amount']
        },
        //排序
        orderitem:'f_userinfo_code',
        orderFields: {
          f_userinfo_id: 'no'
        },
        //f_price_name:[],
        gasproperties:[],
        showinfo: false,
        data: {},
        show:false,
        rowdata:{},
        initres: {
          org:[this.$login.f.orgid],
          dep:[],
          user:[]
        },
        model: new PagedList('api/af-revenue/sql/recordQuery', 20, {
          startDate: 'this.model.startDate',
          endDate: 'this.model.endDate'
        }),
        criteriaShow: false,
        orgCondtionStr: '',
        // 下拉框
        meterbrands: [],
        pricenames: [],
        prices: [],
        area: [],
        //合计数据
        defaultfield: [],
        //小区
        residentialArea: [],
        sumsmodel: {},
        f_filialeid: this.$login.f.f_orgid,
        wxstate:[
          {label: '全部', value: ''},
          {label: '已退款', value: `= '3'`},
          {label: '未退款', value: `!= '3'`}
        ],
        privilege_money:[
          {label: '全部', value: ''},
          {label: '已优惠', value: '> 0'},
          {label: '未优惠', value: '= 0'}
        ],
        showupload:false,
        selected:{}
      }
    },
    ready() {
      this.getaddress()
      this.initres.dep.push(this.$login.f.depids)
      readySomething(this).then(() => {
        this.$emit('ready')
      }).catch((error) => {
        this.$emit('error', error)
      })

    },
    methods: {
       //显示附件
      view(row){
        this.showupload = true
        this.selected= row
      },
      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(){
        let HttpReset = new HttpResetClass()
        var data = await HttpReset.load('POST', 'api/af-revenue/sql/manage_getarealist', {
          data: {
            condition: `1=1 and s.f_orgid = '${this.$login.f.orgid}'`
          }
        }, {resolveMsg: null, rejectMsg: '获取小区失败!'})
        console.log('小区',data)
        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(){
        console.log("bbb")
        this.$refs.paged.$refs.cri.search()
      },
      cancel() {
        this.show = false
      },
      showmsg(obj){
        this.rowdata=obj
        this.show=true
      },
      userTypeChange () {
        this.gasproperties=[]
        if(this.$refs.paged.$refs.cri.model !==null) {
          this.$refs.paged.$refs.cri.model.f_gasproperties=''
          this.gasproperties = this.$appdata.getParam(this.$refs.paged.$refs.cri.model.f_user_type[0])
        }
        else{
          this.gasproperties =[{label: '全部', value: ''}]
        }
      },
      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) {
        this.$parent.$parent.$parent.data.startDate=this.$refs.paged.$refs.cri.model.startDate
        this.$parent.$parent.$parent.data.endDate=this.$refs.paged.$refs.cri.model.endDate
        console.log("aaa")
        args.condition = `${args.condition} `
        console.log(`${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] = []
        })

      },
      dealmsg(val) {
        val.model = this.model.model
        this.$dispatch('deal-msg', val)
      },
      show() {
        this.criteriaShow = true
      },
      hidden() {
        this.criteriaShow = !this.criteriaShow
      },
      getRes(condition,obj) {
        this.orgCondtionStr = condition
        this.orgname = obj.orgnames[0]
        this.depname = obj.depnames[0]
      },
      async updateParams() {
        await this.$MagLoadParams.loadParam(this.f_filialeid)
        this.initParams()
      },
      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()
      }

    },
    events:{
      'getidcard'(IdCard){
        // console.log(param)
        this.$refs.paged.$refs.cri.model.f_info_idnumber=IdCard.strID
      }
    },
    watch: {
      'model.rows'(val) {
        if(val.length === 0){
          this.sumsmodel = {}
        }
      },
      'orgCondtionStr'(val) {
        let res = val.match(/'(.*?)'/)
        console.log('正则提取:',res && res[1])
        if (res) {
          this.f_filialeid = res[1]
          this.updateParams()
        }
      },
      sumsmodel:{
        handler: function(val) {
          this.getotherfooter();
        },
        deep: true
      }
    },
    computed: {
         chooserow(){
             let aaa= true
             if(this.$login.r && this.$login.r.includes('打印项选择')){
                 aaa =  false
             }
             return aaa
         },
      getPricenames() {
        let f_user_type = this.$refs.paged.$refs.cri.model.f_user_type;
        let f_gasproperties = this.$refs.paged.$refs.cri.model.f_gasproperties;
        let pricetype = this.$refs.paged.$refs.cri.model.pricetype;
        console.log("打印一下:",f_user_type,f_gasproperties,pricetype,this.f_filialeid,this.prices)
        if(this.$refs.paged.$refs.cri.model !==null) {
          let rs = []
          let priceArr = []
          if ( pricetype.length >0) {
            let params = {
              f_price_type: pricetype[0],
              filter: this.f_filialeid,
              prices: this.prices
            }
            this.$MagGetSaleParam.getPrice(params).forEach((item) => {
              let temp = {}
              temp.label = item.label
              temp.value = item.value.f_price_name
              priceArr.push(temp)
            })
            rs = [{label: '全部', value: ''}, ...priceArr]
          }
          if (rs.length === 0) {
            console.log('rs读出来是空')
            this.$refs.paged.$refs.cri.model.f_price_name = ''
          }
          return rs
        }
      },
      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,
          orderitem: this.orderitem?'"' + this.orderitem + ' "':`'f_userinfo_code'`
        }
      },
      getfield() {
        return exportConfig.recordConfig
      },
      defaultexport() {
          return exportConfig.recordConfig
      }
    }
  }
</script>
