<template style="position: absolute">
  <div style="flex:1.2;" class="flex">
    <criteria-paged :model="model" v-ref:paged :pager="componentName === '' || bulkType !== null"  @sort="sort">
      <criteria partial='criteria' @condition-changed='$parent.selfSearch' v-ref:cri>
        <div novalidate class="form-inline" partial>
          <card-info-modal :show.sync="$parent.$parent.cardModal_show" :cardinfo="$parent.$parent.cardInfo" v-ref:cardinfo></card-info-modal>
          <div class="form-group">
            <read-card @read-info="$parent.$parent.cardBtn" v-if="!$parent.$parent.noRead"></read-card>
          </div>
          <div class="form-group">
            <input  type="text" class="input_search" style="width:60%" v-model="model.f_userinfo_code" placeholder='客户编号'
            condition="u.f_userinfo_code = '{}'"
            :size="model.f_userinfo_code ? model.f_userinfo_code.length : 4">
          </div>
          <!-- <div class="form-group">
            <input  type="text" class="input_search" style="width:60%" v-model="model.f_contract_id" placeholder='合同编号'
            condition="u.f_contract_id = '{}'"
            :size="model.f_contract_id ? model.f_contract_id.length : 4">
          </div> -->
          <div class="form-group">
            <input  type="text" class="input_search" style="width:60%" v-model="model.f_user_name" placeholder='客户姓名'
            condition="u.f_user_name like '%{}%'"
            :size="model.f_user_name ? model.f_user_name.length * 2 : 4">
          </div>
          <div class="form-group">
            <input  type="text" class="input_search" style="width:60%" v-model="model.f_user_phone" placeholder='电话'
            condition="u.f_user_phone = '{}'"
            :size="model.f_user_phone ? model.f_user_phone.length : 2">
          </div>
          <div class="form-group">
            <input  type="text" class="input_search" style="width:60%" v-model="model.f_address" placeholder='用户地址'
            condition="u.f_address like '%{}%'"
            :size="model.f_address ? model.f_address.length * 2 : 4">
          </div>
          <!--<div class="form-group">-->
            <!--<input  type="text" class="input_search" style="width:60%" v-model="model.f_user_id" placeholder='表编号'-->
            <!--condition="u.f_user_id = '{}'"-->
            <!--:size="model.f_user_id ? model.f_user_id.length : 3">-->
          <!--</div>-->
          <div class="form-group">
              <input  type="text" class="input_search" style="width:60%" v-model="model.f_meternumber" placeholder='表号'
              condition="f_meternumber = '{}'"
              :size="model.f_meternumber ? model.f_meternumber.length : 2">
          </div>
          <div class="form-group">
            <v-select id="f_paytype"
            v-model="model.f_table_state"
            placeholder='气表状态'
            :value.sync="model.f_table_state"
            :options='$parent.$parent.tableStates'
            condition="u.f_table_state = '{}'"
            close-on-select ></v-select>
          </div>
          <div class="form-group">
            <v-select id="f_meter_brand"
            v-model="model.f_meter_brand"
            placeholder='气表品牌'
            :value.sync="model.f_meter_brand"
            :options='$parent.$parent.meterbrand'
            condition="u.f_meter_brand = '{}'"
            close-on-select ></v-select>
          </div>
          <div class="form-group">
            <button class="button_search" @click="search(), $parent.$parent.clean()" v-el:cx>查询</button>
          </div>
          <div class="form-group" v-if="!$parent.$parent.noBatch">
            <dropdown>
             <button type="button" data-toggle="dropdown" class="btn btn-default dropdown-toggle width-100">
               批量操作
             </button>
             <ul slot="dropdown-menu" class="dropdown-menu">
               <li>
                 <a href="#" @click="$parent.$parent.bulkOperations('抄表员变更', 'change-meter-reader')">抄表员变更</a>
                 <a href="#" @click="$parent.$parent.bulkOperations('气价变更', 'change-price')">气价变更</a>
               </li>
             </ul>
           </dropdown>
          </div>
        </div>
      </criteria>
      <data-grid :model="model" partial='list' v-ref:grid>
        <template partial='head'>
          <tr>
             <th>序号</th>
             <th v-if="$parent.$parent.$parent.bulkType === '抄表员变更'">抄表员</th>
             <th>
                 <data-order field="f_userinfo_code" name="客户编号" :order.sync="$parent.$parent.$parent.orderFields.f_userinfo_code"></data-order>
             </th>
			       <th>客户基本信息</th>
             <th>表具信息</th>
             <th style="white-space: nowrap;">分类信息</th>
              <th>操作</th>
          </tr>
        </template>
        <template partial='body'>
          <td :class = "{'bg-danger' : row.f_states === '停用' }"  style="text-align: center;">{{$index+1}}</td>
          <td :class = "{'bg-danger' : row.f_states === '停用' }"  v-if="$parent.$parent.$parent.bulkType === '抄表员变更'">{{row.f_inputtor}}</td>
          <td :class = "{'bg-danger' : row.f_states === '停用' }" > {{row.f_userinfo_code}}</td>
          <td :class = "{'bg-danger' : row.f_states === '停用' }" >{{row.f_user_name}}&nbsp;&nbsp;{{row.f_user_phone}}&nbsp;&nbsp;{{row.f_address}}</td>
          <td :class = "{'bg-danger' : row.f_states === '停用' }" >{{row.f_user_id}}&nbsp;&nbsp;{{row.f_gasproperties}}&nbsp;&nbsp;{{row.f_meter_brand}}
            &nbsp;&nbsp;{{row.f_meter_style}}&nbsp;&nbsp;{{row.f_price_type}}</td>
          <td  :class = "{'bg-danger' : row.f_states === '停用' }"  style="text-align: center;">{{row.f_meter_type}}&nbsp;&nbsp;({{row.f_states}})

          </td>
            <td :class = "{'bg-danger' : row.f_states === '停用' }"  style="text-align: center;">
               <dropdown>
                <!-- <button type="button" data-toggle="dropdown" class="btn btn-default dropdown-toggle">
                  选择操作
                </button> -->
                <button type="button" data-toggle="dropdown" style="border: 0px;background: none;">
                  <span class="glyphicon glyphicon-th-list" style="position: inherit;"></span>
                </button>
                <ul slot="dropdown-menu" class="dropdown-menu dropdown-menu-right">
                  <li v-if="row.f_states === '未发' && $parent.$parent.$parent.jurisdiction.includes('发卡售气') " >
                    <a href="#" @click.stop="$parent.$parent.$parent.operate('发卡售气', 'show-card-sell-gas', row)">发卡售气</a>
                  </li>
                  <li v-if="row.f_states === '停用' && $parent.$parent.$parent.jurisdiction.includes('启用') ">
                    <a href="#" @click.stop="$parent.$parent.$parent.operate('表具启用', 'enable-manage', row)">表具启用</a>
                  </li>
                  <li v-if="(row.f_states === '正常' || row.f_states === '补卡' || row.f_states === '换表') && row.f_meter_type === '物联网表' && $parent.$parent.$parent.jurisdiction.includes('物联网表收费') ">
                    <a href="#" @click.stop="$parent.$parent.$parent.IOTCenter(row)">物联网表收费</a>
                  </li>
                  <li v-if="(row.f_states === '正常' || row.f_states === '换表') && row.f_meter_type === '机表' && $parent.$parent.$parent.jurisdiction.includes('机表收费') ">
                    <a href="#" @click.stop="$parent.$parent.$parent.operate('机表收费', 'machine-charge', row)">机表收费</a>
                  </li>
                  <li v-if="(row.f_states === '正常' || row.f_states === '补卡') && (row.unWriteSell ? row.unWriteSell.length === 0 : true) && $parent.$parent.$parent.isCard(row.f_meter_type) && $parent.$parent.$parent.cardInfo.Gas === 0  && $parent.$parent.$parent.jurisdiction.includes('卡表收费') ">
                    <a href="#" @click.stop="$parent.$parent.$parent.operate('卡表收费', 'card-meter-center', row)">卡表收费</a>
                  </li>
                  <li v-if="$parent.$parent.$parent.jurisdiction.includes('其他收费') ">
                    <a href="#" @click.stop="$parent.$parent.$parent.operate('其他收费', 'other-charge', row)">其他收费</a>
                  </li>
                  <li v-if="((row.f_states === '正常' || row.f_states === '补卡'))&& $parent.$parent.$parent.isCard(row.f_meter_type) && $parent.$parent.$parent.jurisdiction.includes('补卡')">
                    <a href="#" @click.stop="$parent.$parent.$parent.operate('补卡管理', 'replace-card-manage', row)">补卡管理</a>
                  </li>
                  <li v-if="(row.f_states === '正常' || row.f_states === '补卡' || row.f_states === '换表')  && $parent.$parent.$parent.jurisdiction.includes('换表')">
                    <a href="#" @click.stop="$parent.$parent.$parent.operate('换表管理', 'change-meter', row)">换表管理</a>
                  </li>
                  <li v-if="(row.f_states === '正常' || row.f_states === '换表' || row.f_states === '补卡')  && $parent.$parent.$parent.jurisdiction.includes('过户')">
                    <a href="#" @click.stop="$parent.$parent.$parent.operate('过户管理', 'transfer-manage', row)">过户管理</a>
                  </li>
                  <li v-if="row.f_states !== '停用' && $parent.$parent.$parent.jurisdiction.includes('停用') ">
                    <a href="#" @click.stop="$parent.$parent.$parent.operate('表具停用', 'disable-manage', row)">表具停用</a>
                  </li>
                  <li v-if="row.f_states === '超用' && $parent.$parent.$parent.jurisdiction.includes('超用收费')">
                    <a href="#" @click.stop="$parent.$parent.$parent.operate('超用收费', 'over-use-charge', row)">超用收费</a>
                  </li>
                  <li v-if="row.f_states === '补卡' && $parent.$parent.$parent.cardInfo.Gas === 0 && $parent.$parent.$parent.cardInfo.Money === 0 && $parent.$parent.$parent.jurisdiction.includes('掉气补气')">
                    <a href="#" @click.stop="$parent.$parent.$parent.operate('掉气补气', 'off-gas-add-gas', row)">掉气补气</a>
                  </li>
                  <li v-if="row.f_remanent_gas > 0 && $parent.$parent.$parent.isCard(row.f_meter_type) && $parent.$parent.$parent.jurisdiction.includes('换表补气')">
                    <a href="#" @click.stop="$parent.$parent.$parent.operate('换表补气', 'change-meter-add-gas', row)">换表补气</a>
                  </li>
                  <li v-if="row.f_meter_type === '物联网表' || ($parent.$parent.$parent.isCard(row.f_meter_type) && $parent.$parent.$parent.cardInfo.Gas === 0 && $parent.$parent.$parent.cardInfo.Money === 0) && $parent.$parent.$parent.jurisdiction.includes('其他补气')">
                    <a href="#" @click.stop="$parent.$parent.$parent.operate('其他补气', 'other-gas', row)">其他补气</a>
                  </li>
                  <li v-if="row.f_states === '正常' && $parent.$parent.$parent.operCard.cardState === 1 && $parent.$parent.$parent.isCard(row.f_meter_type) && ($parent.$parent.$parent.cardInfo.Gas > 0 ||  $parent.$parent.$parent.cardInfo.Money > 0)">
                    <a href="#" @click.stop="$parent.$parent.$parent.operate('购气撤销', 'card-meter-charge-cancel', row)">购气撤销</a>
                  </li>
                  <li v-if="(row.f_states === '正常' || row.f_states === '换表' || row.f_states === '补卡') && $parent.$parent.$parent.isCard(row.f_meter_type) && $parent.$parent.$parent.jurisdiction.includes('无卡收费')">
                    <a href="#" @click.stop="$parent.$parent.$parent.operate('无卡收费', 'no-card-meter-center', row)">无卡收费</a>
                  </li>
                  <li  v-if= "row.f_states !== '超用' && $parent.$parent.$parent.jurisdiction.includes('退费') ">
                    <a href="#" @click.stop="$parent.$parent.$parent.operate('余额退款', 'refund-manage', row)">余额退款</a>
                  </li>
                  <li v-if="row.f_meter_type === '物联网表' && $parent.$parent.$parent.jurisdiction.includes('补费扣费')">
                    <a href="#" @click.stop="$parent.$parent.$parent.operate('补费扣费', 'deduction-manage', row)">补费扣费</a>
                  </li>
                </ul>
              </dropdown>
            </td>
        </template>
      </data-grid>
  </criteria-paged>
  </div>
</template>

<script>
/**
*用户档案查询列表以及添加操作组件
*/
import { PagedList } from 'vue-client'

import cardlisten from '../../../plugins/CardListen'

let cardBtnGen = async function (self, val) {
  self.cardInfo = val.data
  if (val.data.CardID && val.data.Factory) {
    // 获取未写卡或者写卡失败记录
    let getUnWriteSell = await self.$SqlService.singleTable('t_sellinggas', `f_state = '有效' and f_write_card != '已写卡' and f_card_id = '${val.data.CardID}' and f_filialeids = '${self.$login.f.f_orgids}'`)
    console.log('获取未写卡记录', getUnWriteSell)
    if (getUnWriteSell.data.length > 1) {
      self.$showAlert('此卡已缴费多次未写卡。请核实后处理！！', 'warning', 5000)
    }
    // 获取用户信息
    let getUser = await self.$resetpost('rs/sql/singleTable_User', {data: {condition: `u.f_meter_type in ('气量卡表', '金额卡表') and u.f_card_id='${val.data.CardID}' and u.f_filialeids = '${self.$login.f.f_orgids}' and u.f_alias='${val.data.Factory}'`, orderitem: `${self.orderitem} Desc`}}, {resolveMsg: '读卡成功', rejectMsg: '读卡失败'})
    if (getUser.data.length === 0) {
      self.model.state = '错误'
      self.model.rows = null
      self.model.error = '没有符合条件的记录'
      self.cardModal_show = true
    } else if (getUser.data.length === 1) {
      getUser.data[0].unWriteSell = getUnWriteSell.data
      self.model.rows = getUser.data
      self.model.pageIndex = 1
      self.model.state = '正确'
      self.$refs.paged.$refs.grid.select(self.model.rows[0])
    } else if (getUser.data.length > 1) {
      self.model.rows = getUser.data
      self.model.pageIndex = 1
      self.model.state = '正确'
      self.$showAlert('该卡号出现重复，请确认该用户信息之后执行清零换表功能！！', 'warning', 5000)
    }
  }
}

let asyncReadyGen = async function (self) {
  // 获取营收参数
  await self.search()
  await self.$LoadParams.loadParam()
  self.initQueryParam()
}

export default {
  data () {
  //   Vue.filter('currencyDisplay', {
  //     // model -> view
  //     // 在更新 `<input>` 元素之前格式化值
  //     read: function(val) {
  //       return '￥'+(val-0).toFixed(2)
  //     },
  //     // view -> model
  //     // 在写回数据之前格式化值
  //     write: function(val, oldVal) {
  //       var number = +val.replace(/[^\d.]/g, '')
  //       return isNaN(number) ? 0 : parseFloat(number.toFixed(2))
  //     }
  // })
    return {
      model: new PagedList('rs/sql/singleTable_User', 30,
        {orderitem: '"' + this.orderitem + ' DESC"'}),
      asideTitle: '用户操作',
      rows: null,
      cardInfo: '',
      cardModal_show: false,
      bulkType: null, // 批量操作标识
      operCard: cardlisten,
      contract: [{label: '全部', value: ''},
      {label: '有', value: 'not null'},
      {label: '无', value: 'null'}],
      orderFields: {
        f_userinfo_id: 'no'
      },
      filiale: '',
      outlet: '',
      filialeName: [],
      outletsname: [],
      filialetype: '',
      jurisdiction: this.$login.r,
      tableStates: this.$appdata.getParam('表状态') ? [{label: '全部', value: ''}, ...this.$appdata.getParam('表状态')] : [],
      meterbrand: []
    }
  },
  props: {
    btns: {
      type: Array,
      default: function () {
        return []
      }
    },
    orderitem: {
      type: String,
      default: 'f_userinfo_id'
    },
    excelurl: {
      type: String
    },
    queryGroup: {
      type: Array,
      default: function () {
        return []
      }
    },
    defbtn: {
      type: String
    },
    opeHeight: {
      default: 400
    },
    componentName: {
      type: String
    },
    noRead: {
      type: Boolean,
      default: false
    },
    noBatch: {
      type: Boolean,
      default: false
    },
    row: {}
  },
  ready () {
    console.log('获取权限', this.jurisdiction)
    asyncReadyGen(this)
  },
  methods: {
    search () {
      this.$refs.paged.$refs.cri.search()
    },
    reset () {
      this.$refs.paged.$refs.cri.model = {}
      this.model.rows = ''
    },
    operate (title, name, row) {
      this.asideTitle = this.componentName = title
      // 单条业务逻辑操作不管批量操作是否为true统一都修改为false
      this.bulkType = null
      this.$dispatch('select-oper', title, name, row)
    },
    IOTCenter (row) {
      row.f_calculation !== '预付费' ? this.operate('物联网表收费', 'machine-charge', row) : this.operate('物联网表收费', 'iot-meter-center', row)
    },
    clean () {
      this.cardInfo = {}
      this.componentName = ''
      // 清除批量操作
      this.bulkType = null
      this.$refs.paged.$refs.grid.select(null)
      this.$dispatch('clean')
    },
    cardBtn (val) {
      cardBtnGen(this, val)
    },
    // 针对发卡售气移动选择后面第一条未发卡的数据
    // toNext () {
    //   let index = this.model.rows.indexOf(this.$refs.paged.$refs.grid.selected)
    //   if (this.model.rows.length > 1) {
    //     do{
    //       index++
    //       // 档index大于本页页码，提示用户本页发完，提醒翻页
    //       if (index > this.model.pageSize) {
    //         this.$showMessage('本页已经发完，请翻页')
    //         return
    //       }
    //     }while(this.model.rows[index].f_whether_hairpin !== '未发')
    //
    //     this.$refs.paged.$refs.grid.select(this.model.rows[index])
    //   }
    // },
    bulkOperations (type, name) {
      this.$refs.paged.$refs.grid.select(null)
      // this.search()
      // 标记批量操作为true
      this.bulkType = type
      this.$dispatch('bulk-oper', type, name, {condition: this.model.condition, count: this.model.count})
    },
    // 判断是不是卡表
    isCard (str) {
      return (str.includes('卡表'))
    },
    refreshRow (row) {
      this.model.rows = [row]
    },
    selfSearch (args) {
      if (!this.$login.f.parent.parent.name.includes('统一资源管理')) {
        args.condition = `${args.condition} and u.f_filialeids = '${this.$login.f.f_orgids}'`
      }
      if (this.defbtn === '发卡售气') {
        args.condition = `${args.condition} and f_whether_hairpin = '未发' and f_meter_classify like '%卡表%'`
      }
      this.model.search(args.condition, args.model).then(() => {
        this.$emit('ready')
      })
    },
    // 判断当前登陆人是不是子公司的人员
    isHead () {
      return this.$login.f.parent.parent.name.includes('统一资源管理')
    },
    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()
    },
    initQueryParam () {
      let arr = []
      this.$GetSaleParam.getGasbrand().forEach((item) => {
        let temp = {}
        temp.label = item.label
        temp.value = item.value.f_meter_brand
        arr.push(temp)
      })
      this.meterbrand = [{label: '全部', value: ''}, ...arr]
    }
    // 单条更新,业务逻辑成功后，单条刷新
    // singleRefresh (data) {
    //   let index = this.model.rows.findIndex((row, index, arr) => {
    //     return  row.f_user_id === data.f_user_id
    //   })
    //   this.$resetpost('rs/sql/singleTable_User', {data: {orderitem: this.orderitem, condition: `n.f_userinfo_id=${data.f_user_id}`}}).then((res) => {
    //     this.model.rows[index] = res.data[0]
    //   })
    // }
  },
  watch: {
    // 观察是否有业务组件
    'componentName' (val) {
      // 判断是不是批量操作,并且是否是单选的操作过程中
      if (this.bulkType) {
        if (this.rows && this.rows.length > 0) {
          this.model.rows = this.rows
          this.rows = null
        }
      } else {
        // this.componentName为空，表示业务界面消失，否则业务界面存在或打开
        if (this.componentName !== '') {
          // 若果业务界面存在且this.rows不为null说明是在有业务界面的情况下切换业务界面，数据保持不动
          if (!this.rows) {
            this.rows = this.model.rows
            this.model.rows = [this.row]
          }
        } else {
          this.model.rows = this.rows
          this.rows = null
        }
      }
    },
    'model.state' (val) {
      console.log(val)
      if (val === '正确') {
        if (this.model.rows.length === 1 && !this.$parent.comps) {
          this.$refs.paged.$refs.grid.select(this.model.rows[0])
        } else {
          this.$parent.comps = null
        }
      }
    }
  }
}
</script>
<style media="screen">
  .divtext {
    min-width: 50px;
    max-width: 200px;
    border: 1px solid green;
    display: inline-block;
  }
</style>
