<template >
  <div @keyup.enter="search">
    <criteria-paged :model="model"  v-ref:paged :pager="isPager">
      <criteria partial='criteria' @condition-changed='$parent.selfSearch' v-ref:cri>
        <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
          <card-info-modal :show.sync="$parent.$parent.cardModal_show" :cardinfo="$parent.$parent.cardInfo"
                           v-ref:cardinfo></card-info-modal>
          <div class="col-sm-7">
            <p style="font-weight: bold;margin: 0">档案信息</p>
            <div class="row" >
              <div class="col-sm-6">
                <label class="font_normal_body_new">用户姓名</label>
                <input type="text" class="input-underline"  style="width: 75%" v-model="model.f_user_name" placeholder='用户姓名'
                       condition="f_user_name like '%{}%'" @keyup.enter="search(), $parent.$parent.clean()" >
              </div>
              <div class="col-sm-3">
                <label class="font_normal_body_new">用户编号</label>
                <input type="text" class="input-underline text-primary" style="width: 50%" v-model="model.f_userinfo_code" placeholder='用户编号'
                       condition="f_userinfo_code = '{}'"  @click="$parent.$parent.dealmsg2(row)"
                       @keyup.enter="search(), $parent.$parent.clean()" >
              </div>
              <div class="col-sm-3">
                <label class="font_normal_body_new">用户电话</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="model.f_user_phone" placeholder='用户电话'
                       condition="f_user_phone = '{}'" @keyup.enter="search(), $parent.$parent.clean()">
              </div>
              <div class="col-sm-3">
                <label class="font_normal_body_new">协议号码</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="model.f_rent_phone" placeholder='协议号码'
                       condition="f_userinfo_code = '{}'" @keyup.enter="search(), $parent.$parent.clean()">
              </div>
              <div class="col-sm-3">
                <label class="font_normal_body_new">小&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;区</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="model.f_residential_area" placeholder='小区'
                       condition="address.f_residential_area like '%{}%'" @keyup.enter="search(), $parent.$parent.clean()" :disabled="row">
              </div>
              <div class="col-sm-3">
                <label class="font_normal_body_new">楼&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="model.f_building" placeholder='楼号'
                       condition="address.f_building = '{}'" @keyup.enter="search(), $parent.$parent.clean()" :disabled="row">
              </div>
              <div class="col-sm-3">
                <label class="font_normal_body_new">单&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;元</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="model.f_unit" placeholder='单元'
                       condition="address.f_unit = '{}'" @keyup.enter="search(), $parent.$parent.clean()" :disabled="row">
              </div>
              <div class="col-sm-6">
                <label class="font_normal_body_new">用户地址</label>
                <input type="text" class="input-underline"  style="width: 75%" v-model="model.f_address" placeholder='用户地址'
                       condition="address.f_address like '%{}%'" @keyup.enter="search(), $parent.$parent.clean()" :disabled="row">
              </div>
              <div class="col-sm-3">
                <label class="font_normal_body_new">楼&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;层</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="model.f_floor" placeholder='楼层'
                       condition="address.f_floor = '{}'" @keyup.enter="search(), $parent.$parent.clean()" :disabled="row">
              </div>
              <div class="col-sm-3">
                <label class="font_normal_body_new">门&nbsp;牌&nbsp;号&nbsp;</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="model.f_room" placeholder='门牌号'
                       condition="address.f_room = '{}'" @keyup.enter="search(), $parent.$parent.clean()" :disabled="row">
              </div>
              <div class="col-sm-6">
                <label class="font_normal_body_new">身份证号</label>
                <input type="text" class="input-underline"  style="width: 75%" v-model="model.f_idnumber" placeholder='身份证号'
                       condition="i.f_idnumber = '{}'" @keyup.enter="search(), $parent.$parent.clean()">
              </div>
              <div class="col-sm-3" >
                <label class="font_normal_body_new" >开户时间</label>
                <datepicker style="width:60% " placeholder="开户时间"
                            :value.sync="model.f_open_date"
                            v-model="model.f_open_date"
                            :format="'yyyy-MM-dd HH:mm:ss'"
                            condition="f_open_date = '{}'"
                ></datepicker>
              </div>
              <div class="col-sm-3">
                <label class="font_normal_body_new">发卡状态</label>
                <input type="text" class="input-underline"  style="width: 50%" v-model="model.f_whether_hairpin" placeholder='发卡状态'
                       condition="u.f_whether_hairpin = '{}'" @keyup.enter="search(), $parent.$parent.clean()">
              </div>
            </div>
          </div>
          <div class="col-sm-5">
            <p style="font-weight: bold;margin: 0">表具信息</p>
            <div class="row">
              <div class="col-sm-4">
                <label class="font_normal_body_new">气表编号</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="model.f_meternumber" placeholder='气表编号'
                       condition="u.f_meternumber = '{}'" @keyup.enter="search(), $parent.$parent.clean()" :disabled="row">
              </div>
              <div class="col-sm-4">
                <label class="font_normal_body_new">气表品牌</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="model.f_meter_brand" placeholder='气表品牌'
                       condition="gb.f_meter_brand = '{}'" @keyup.enter="search(), $parent.$parent.clean()" :disabled="row">
              </div>
              <div class="col-sm-4">
                <label class="font_normal_body_new">气表型号</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="model.f_meter_style" placeholder='气表型号'
                       condition="gm.f_meter_style = '{}'" @keyup.enter="search(), $parent.$parent.clean()" :disabled="row">
              </div>
              <div class="col-sm-4">
                <label class="font_normal_body_new">购气次数</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="model.f_times" placeholder='购气次数'
                       condition="f_times = '{}'" @keyup.enter="search(), $parent.$parent.clean()" :disabled="row">
              </div>
              <div class="col-sm-4">
                <label class="font_normal_body_new">用户类型</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="model.f_user_type" placeholder='用户类型'
                       condition="u.f_user_type = '{}'" @keyup.enter="search(), $parent.$parent.clean()" :disabled="row">
              </div>
              <div class="col-sm-4">
                <label class="font_normal_body_new">阶梯类型</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="model.f_price_name" placeholder='阶梯类型'
                       condition="sp.f_price_name = '{}'" @keyup.enter="search(), $parent.$parent.clean()" :disabled="row">
              </div>
              <div class="col-sm-4">
                <label class="font_normal_body_new">累计购气</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="model.f_total_gas" placeholder='累计购气'
                       condition="f_balance = '{}'" @keyup.enter="search(), $parent.$parent.clean()" :disabled="row">
              </div>
              <div class="col-sm-4">
                <label class="font_normal_body_new">卡内气量</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="$parent.$parent.cardInfo.Gas" placeholder='卡内气量'
                        @keyup.enter="search(), $parent.$parent.clean()" disabled>
              </div>
              <div class="col-sm-4">
                <label class="font_normal_body_new">卡内金额</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="$parent.$parent.cardInfo.Money" placeholder='卡内气量'
                        @keyup.enter="search(), $parent.$parent.clean()" disabled>
              </div>
              <div class="col-sm-12">
                <label class="font_normal_body_new">卡&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="model.f_card_id" placeholder='阶梯类型'
                       condition="u.f_card_id = '{}'" @keyup.enter="search(), $parent.$parent.clean()" :disabled="row">
              </div>
              <div class="col-sm-8">
                <label class="font_normal_body_new">表具备注</label>
                <input type="text" class="input-underline" style="width: 75%" v-model="model.f_comments" placeholder='表具备注'
                       condition="u.f_comments like '%{}%'" @keyup.enter="search(), $parent.$parent.clean()" >
              </div>
              <div class="col-sm-4"v-if="model.f_meter_brand =='莱德物联网表'||model.f_meter_brand =='天信NB物联网表'">
                <label class="font_normal_body_new" v-if="model.f_meter_brand =='莱德物联网表'">气表&nbsp;&nbsp;&nbsp;ID</label>
                <label class="font_normal_body_new" v-if="model.f_meter_brand =='天信NB物联网表'">模&nbsp;组&nbsp;&nbsp;码</label>
                <input type="text" class="input-underline" style="width: 50%" v-model="model.f_imei" placeholder=''
                       @keyup.enter="search(), $parent.$parent.clean()" disabled>
              </div>
              <div class="form-group col-sm-12" style="float:right;white-space: nowrap;width: auto">
                <read-card :is-single.sync="$parent.$parent.isSingleUser" @read-info="$parent.$parent.cardBtn" v-if="!$parent.$parent.noRead" v-ref:readcard></read-card>
                <button class="button_search button_spacing" @click="$parent.$parent.testCard()" v-el:cx>测卡</button>
                <button class="button_search button_spacing" @click="search(), $parent.$parent.clean()" v-el:cx>查询</button>
                <button class="button_clear button_spacing" @click="$parent.$parent.clear()">清空</button>
                <button class="button_clear button_spacing" @click="$parent.$parent.saveuser()">保存</button>
                <!--<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>
        </div>
      </criteria>
      <data-grid :model="model"   partial='list' class="list_area table_sy" v-ref:grid v-if="!$parent.row" >
        <template partial='head' >
          <tr>
            <th style="white-space: nowrap;" >序号</th>
            <!--<th>-->
            <!--<data-order field="f_userinfo_code" name="客户编号"-->
            <!--:order.sync="$parent.$parent.$parent.orderFields.f_userinfo_code"></data-order>-->
            <!--</th>-->
            <th style="white-space: nowrap;" >客户编号</th>
            <th style="white-space: nowrap;" >客户基本信息</th>
            <th style="white-space: nowrap;" >表具信息</th>
            <th style="white-space: nowrap;" >分类信息</th>

          </tr>
        </template>
        <template partial='body'>
          <td  :class="{'bg-danger' : row.f_table_state === '停用' }" style="text-align: center;">{{$index + 1}}</td>
          <td  :class="{'bg-danger' : row.f_table_state === '停用' }"><nobr>
            <span @click="$parent.$parent.$parent.dealmsg(row)"><a>{{row.f_userinfo_code}}</a></span>
          </nobr> </td>
          <td style="white-space: nowrap;" :class="{'bg-danger' : row.f_table_state === '停用' }">{{row.f_user_name}}&nbsp;&nbsp;{{row.f_user_phone}}&nbsp;&nbsp;{{row.f_address}}</td>
          <td style="white-space: nowrap;" :class="{'bg-danger' : row.f_table_state === '停用' }">{{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}}&nbsp;&nbsp;{{row.f_price_name}}
          </td>
          <td style="white-space: nowrap;" :class="{'bg-danger' : row.f_table_state === '停用' }" style="text-align: center;">{{row.f_meter_type}}&nbsp;&nbsp;({{row.f_meter_type.includes('物联网表') ? row.f_table_state : row.f_whether_hairpin }})
          </td>

        </template>
      </data-grid>
      <!--<meter-charge-record-query partial='list' v-if="$parent.row"  :searchdata="$parent.row"></meter-charge-record-query>-->
      <!--<data-grid :model="recordModel" class="list_area table_sy" partial='list' v-if="$parent.row"  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>-->
      <!--</tr>-->
      <!--</template>-->
      <!--<template partial='body' >-->
      <!--<tr >-->
      <!--<td style="text-align:center">{{row.fee}}</td>-->
      <!--<td style="text-align:center">{{row.gas}}</td>-->
      <!--<td style="text-align:center">{{row.type}}</td>-->
      <!--<td style="text-align:center">{{row.f_operator}}</td>-->
      <!--<td style="text-align:center">{{row.f_operate_date}}</td>-->
      <!--<td style="text-align:center">{{row.note}}</td>-->
      <!--</tr>-->
      <!--</template>-->
      <!--</data-grid>-->
    </criteria-paged>
  </div>
  <div class="basic-main flex" :model="model"  v-if="row"  style="height: 250px;background:#E6E6FA;">
    <meter-charge-record-query  :searchdata="row" @dblclick="recordClick()"></meter-charge-record-query>
  </div>

  <modal :show.sync="showCardInfo" v-ref:modal backdrop="false">
    <header slot="modal-header" class="modal-header">
      <h4 class="modal-title">卡上信息</h4>
    </header>
    <article slot="modal-body" class="modal-body">
      <form class="form-horizontal">
        <div class="form-group">
          <label class="col-sm-2 control-label">卡&emsp;&emsp;号</label>
          <div class="col-sm-4">
            <p class="form-control-static">{{cardInfo.CardID}}</p>
          </div>

          <label class="col-sm-2 control-label">卡上次数</label>
          <div class="col-sm-4">
            <p class="form-control-static">{{cardInfo.Times}}</p>
          </div>
        </div>
        <div class="form-group">
          <label class="col-sm-2 control-label">卡上气量</label>
          <div class="col-sm-4">
            <p class="form-control-static">{{cardInfo.Gas}}</p>
          </div>

          <label class="col-sm-2 control-label">卡上金额</label>
          <div class="col-sm-4">
            <p class="form-control-static">{{cardInfo.Money}}</p>
          </div>
        </div>
        <div class="form-group" v-if="cardInfo.NewParam.IsInsert == 0">

          <label class="col-sm-2 control-label">累购气量</label>
          <div class="col-sm-4">
            <p class="form-control-static">{{cardInfo.NewParam.ljgql}}</p>
          </div>

        </div>
        <!--<div class="form-group">-->
        <!--<strong>卡上有气，请告知客户接表后再来充值！如进行其他业务请点击“继续”</strong>-->
        <!--</div>-->
      </form>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <strong>卡上有气，请告知客户接表后再来充值！如进行其他业务请点击“继续”</strong>
      <button type="button" class="button_search" @click='hasGasContinue'>继续</button>
      <button type="button" class="button_search" @click='cxqcontrol'>擦虚气</button>
      <button type="button" class="btn btn-default" @click='hasGasClose'>取消</button>
    </footer>
  </modal>

  <modal :show.sync="showCardError" v-ref:modal backdrop="false">
    <header slot="modal-header" class="modal-header">
      <h4 class="modal-title">卡上信息</h4>
    </header>
    <article slot="modal-body" class="modal-body">
      <form class="form-horizontal">
        <div class="form-group">
          <label class="col-sm-2 control-label">卡&emsp;&emsp;号</label>
          <div class="col-sm-2">
            <p class="form-control-static">{{cardInfo.CardID}}</p>
          </div>

          <label class="col-sm-2 control-label">卡上次数</label>
          <div class="col-sm-2">
            <p class="form-control-static">{{cardInfo.Times}}</p>
          </div>
          <label class="col-sm-2 control-label">系统次数</label>
          <div class="col-sm-2">
            <p class="form-control-static">{{systemTimes}}</p>
          </div>
          <label class="col-sm-2 control-label">用户编号</label>
          <div class="col-sm-2">
            <p class="form-control-static">{{userCode}}</p>
          </div>
          <label class="col-sm-2 control-label">用户姓名</label>
          <div class="col-sm-2">
            <p class="form-control-static">{{userName}}</p>
          </div>
          <label class="col-sm-2 control-label">用户地址</label>
          <div class="col-sm-2">
            <p class="form-control-static">{{userAddress}}</p>
          </div>
        </div>
        <div class="form-group" style="margin-left:10%;">
          <p class="text-left" style="font-size:20px;line-height:60px;font-height:800;">当前卡充值次数与系统不符,请检查是否是正确的卡</p>
        </div>
      </form>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <button type="button" v-if="showCardError2" class="button_search" @click='hasGasContinue'>继续</button>
      <button type="button" class="btn btn-default" @click='hasGasClose'>取消</button>
    </footer>
  </modal>

</template>

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

  let cardBtnGen = async function (self, val) {
    self.cardInfo = val.data

    // 判断读卡是否需要卡密码
    console.log('读卡上的信息', self.cardInfo)

    if (self.cardInfo.NewParam) {
      if (self.cardInfo.NewParam.error) {
        if (self.cardInfo.NewParam.error === '0001') {
          // 需要重新读卡并传卡密码
          if (self.model.rows.length == 1 && self.model.rows[0].f_alias === self.cardInfo.Factory) {
            self.readCardParam = self.model.rows[0].f_card_password
            self.cardInfo = await self.$refs.paged.$refs.cri.$refs.readcard.readCard2(self.model.rows[0].f_card_password)
          } else {
            self.$showAlert('此卡需要先获取客户信息。请通过条件查询该客户信息之后进行读卡！！', 'warning', 2000)
            return
          }
        }
      }
    }

    // 验证卡上是否有气， 1）. 卡上的气量和金额大于0   2）. 只认累购的表会有一个新参数  NewParam.IsInsert (0: 未接表 1: 已接表)

    let cardHasGas = false

    if ((self.cardInfo.Gas - 0) > 0 || (self.cardInfo.Money - 0) > 0) {
      cardHasGas = true
    }

    if (self.cardInfo.NewParam) {
      if (self.cardInfo.NewParam.hasOwnProperty('IsInsert')) {
        cardHasGas = (self.cardInfo.NewParam.IsInsert == 0)
      }
    }

    if (cardHasGas) {
      // 卡上有气， 弹出框提示
      self.showCardInfo = true
    } else {
      getMeterInfoGen(self)
    }

    self.$refs.paged.$refs.grid.$el.scrollTop = 0
  }
  let getMeterInfoGen2 = async function (self) {
    if (self.cardInfo.CardID && self.cardInfo.Factory) {
      // 存在机表和物联网表读卡发卡的情况，这里对读卡返回的Factory进行判断区分， 物联网和机表直接返回 JiBiao。
      // 还有一种方式： 在建立气表品牌的时候机表和物联网表别名直接给成JiBiao
      let getUser = null
      if (self.cardInfo.Factory == 'JiBiao' || self.cardInfo.Factory == 'JiChengADSystem') {
        // 获取用户信息
        getUser = await self.$resetpost('rs/sql/sale_getUser', {
          data: {
            condition: `f_meter_type in ('机表','物联网表') and u.f_card_id='${self.cardInfo.CardID}'
          and u.f_filialeid = '${self.$login.f.orgid}' and f_whether_hairpin != '未发'`,
            orderitem: `${self.orderitem} Desc`
          }
        }, {resolveMsg: '读卡成功', rejectMsg: '读卡失败'})
      } else {
        // 获取用户信息
        getUser = await self.$resetpost('rs/sql/sale_getUser', {
          data: {
            condition: `gb.f_meter_type in ('气量卡表', '金额卡表','物联网表') and u.f_card_id='${self.cardInfo.CardID}'
          and u.f_filialeid = '${self.$login.f.orgid}' and f_alias='${self.cardInfo.Factory}' and f_whether_hairpin != '未发'`,
            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) {
        // 验证卡上信息和获取的用户信息
        if (self.cardInfo.CardID != getUser.data[0].f_card_id || self.cardInfo.Factory != getUser.data[0].f_alias) {
          self.$showAlert(`此时的卡片信息和用户信息不匹配，请核实后在进行读卡。卡上信息: 卡号-${self.cardInfo.CardID},厂家-${self.cardInfo.Factory}。
          用户信息: 卡号-${getUser.data[0].f_card_id},厂家-${getUser.data[0].f_alias}`, 'warning', 5000)
          return
        }
        self.model.state = '正确'
        self.model.rows = getUser.data
        self.$dispatch('dblclick', getUser.data[0], 0, self.cardInfo) // 这里的0是角标位置（暂无用）
      } else if (getUser.data.length > 1) {
        if (self.model.rows.length == 1) {
          // 处理读卡时需要卡密码的问题：此时已经查出一户数据来，验证此数据的卡号和读出的卡号是否一致，一致则不用去查询
          let hasMatchingData = false
          getUser.data.forEach((res, index) => {
            if (self.model.rows[0].f_userfiles_id == res.f_userfiles_id) {
              self.model.rows = [getUser.data[index]]
              self.model.state = '正确'
              hasMatchingData = true
              self.$dispatch('dblclick', getUser.data[index], 0, self.cardInfo)
            }
          })
          if (!hasMatchingData) {
            self.model.rows = getUser.data
            self.model.pageIndex = 1
            self.model.state = '正确'
            self.$dispatch('clean')
            self.$showAlert('该卡号出现重复，请确认该客户信息之后双击进入！！', 'warning', 5000)
          }
        } else {
          self.model.rows = getUser.data
          self.model.pageIndex = 1
          self.model.state = '正确'
          self.$dispatch('clean')
          self.$showAlert('该卡号出现重复，请确认该客户信息之后双击进入！！', 'warning', 5000)
        }
      }
    }
  }

  let getMeterInfoGen = async function (self) {
    if (self.cardInfo.CardID && self.cardInfo.Factory) {
      // 存在机表和物联网表读卡发卡的情况，这里对读卡返回的Factory进行判断区分， 物联网和机表直接返回 JiBiao。
      // 还有一种方式： 在建立气表品牌的时候机表和物联网表别名直接给成JiBiao
      let getUser = null
      if (self.cardInfo.Factory == 'JiBiao' || self.cardInfo.Factory == 'JiChengADSystem') {
        // 获取用户信息
        getUser = await self.$resetpost('rs/sql/sale_getUser', {
          data: {
            condition: `gb.f_meter_type in ('机表','物联网表') and u.f_card_id='${self.cardInfo.CardID}'
          and u.f_filialeid = '${self.$login.f.orgid}' and f_whether_hairpin != '未发'`,
            orderitem: `${self.orderitem} Desc`
          }
        }, {resolveMsg: '读卡成功', rejectMsg: '读卡失败'})
      } else {
        // 获取用户信息
        getUser = await self.$resetpost('rs/sql/sale_getUser', {
          data: {
            condition: `gb.f_meter_type in ('气量卡表', '金额卡表','物联网表') and u.f_card_id='${self.cardInfo.CardID}'
          and u.f_filialeid = '${self.$login.f.orgid}' and f_alias='${self.cardInfo.Factory}' and f_whether_hairpin != '未发'`,
            orderitem: `${self.orderitem} Desc`
          }
        }, {resolveMsg: '读卡成功', rejectMsg: '读卡失败'})
      }
      // 判断是否是旧卡
      if (getUser.data.length > 0) {
        if (self.cardInfo.Times < getUser.data[0].f_times) {
          self.systemTimes = getUser.data[0].f_times
          self.userCode = getUser.data[0].f_userinfo_code
          self.userName = getUser.data[0].f_user_name
          self.userAddress = getUser.data[0].f_address
          if (getUser.data[0].f_is_check != '否') {
            self.showCardError = true
            self.showCardError2 = true
            return
          }
          // self.$showMessage('当前卡充值次数与系统不符,请检查是否是正确的卡.')
        }
      }
      // 判断是否是旧卡
      if (getUser.data.length > 0) {
        if (self.cardInfo.Times > getUser.data[0].f_times) {
          self.systemTimes = getUser.data[0].f_times
          self.userCode = getUser.data[0].f_userinfo_code
          self.userName = getUser.data[0].f_user_name
          self.userAddress = getUser.data[0].f_address
          if (getUser.data[0].f_is_check != '否') {
            self.showCardError2 = false
            self.showCardError = true
            return
          }
        }
      }

      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) {
        // 验证卡上信息和获取的用户信息
        if (self.cardInfo.CardID != getUser.data[0].f_card_id || self.cardInfo.Factory != getUser.data[0].f_alias) {
          self.$showAlert(`此时的卡片信息和用户信息不匹配，请核实后在进行读卡。卡上信息: 卡号-${self.cardInfo.CardID},厂家-${self.cardInfo.Factory}。
          用户信息: 卡号-${getUser.data[0].f_card_id},厂家-${getUser.data[0].f_alias}`, 'warning', 5000)
          return
        }
        self.model.state = '正确'
        self.model.rows = getUser.data
        self.$dispatch('dblclick', getUser.data[0], 0, self.cardInfo) // 这里的0是角标位置（暂无用）
      } else if (getUser.data.length > 1) {
        if (self.model.rows.length == 1) {
          // 处理读卡时需要卡密码的问题：此时已经查出一户数据来，验证此数据的卡号和读出的卡号是否一致，一致则不用去查询
          let hasMatchingData = false
          getUser.data.forEach((res, index) => {
            if (self.model.rows[0].f_userfiles_id == res.f_userfiles_id) {
              self.model.rows = [getUser.data[index]]
              self.model.state = '正确'
              hasMatchingData = true
              self.$dispatch('dblclick', getUser.data[index], 0, self.cardInfo)
            }
          })
          if (!hasMatchingData) {
            self.model.rows = getUser.data
            self.model.pageIndex = 1
            self.model.state = '正确'
            self.$dispatch('clean')
            self.$showAlert('该卡号出现重复，请确认该客户信息之后双击进入！！', 'warning', 5000)
          }
        } else {
          self.model.rows = getUser.data
          self.model.pageIndex = 1
          self.model.state = '正确'
          self.$dispatch('clean')
          self.$showAlert('该卡号出现重复，请确认该客户信息之后双击进入！！', 'warning', 5000)
        }
      }
    }
  }

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

  export default {
    title: '收费',
    data () {
      return {
        // 公司下拉
        curorgid: [this.$login.f.orgid],
        f_orgid: '',
        showCardError2: false,
        model: new PagedList('rs/sql/sale_getUser', 30, {orderitem: '"' + this.orderitem + ' DESC"'}),
        isPager: true,
        rows: null,
        cardInfo: '',
        cardModal_show: false,
        bulkType: null, // 批量操作标识
        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('气表状态')] : [],

        fileStates: this.$appdata.getParam('档案状态') ? [{label: '全部', value: ''}, ...this.$appdata.getParam('档案状态')] : [],

        // userTypes: this.$appdata.getParam('用户类型') ? [{label: '全部', value: ''}, ...this.$appdata.getParam('用户类型')] : [],
        gasproperties: this.$appdata.getParam('用气性质') ? [{label: '全部', value: ''}, ...this.$appdata.getParam('用气性质')] : [],

        meterbrand: [],
        userlevel: this.$appdata.getParam('用户等级') ? [{label: '全部', value: ''}, ...this.$appdata.getParam('用户等级')] : [],

        criteriaShow: true,

        // 读卡是否需要额外参数
        readCardNeedParam: false,
        readCardParam: {},
        systemTimes: '',
        userCode: '',
        userName: '',
        userAddress: '',

        // 当列表是一户的时候直接读卡，跳过判卡
        isSingleUser: null,

        // 默认不查询
        specialCondition: false,

        // 卡信息弹出框
        showCardInfo: false,

        // 流水记录显示
        recordModel: {rows: []},
        clientWidth: document.body.clientWidth,
        showCardError: false,
        chooserow: null
      }
    },
    props: {
      orderitem: {
        type: String,
        default: 'f_userinfo_id desc'
      },
      defbtn: {
        type: String
      },
      noRead: {
        type: Boolean,
        default: false
      },
      row: {}
    },
    ready () {
      asyncReadyGen(this)
    },
    compiled () {
      window.onresize = () => {
        return (() => {
          this.clientWidth = document.body.clientWidth
        })()
      }
  },
    methods: {
      // 擦虚气
      async cxqcontrol () {
        try {
          let self = this
          let getUser = await self.$resetpost('rs/sql/sale_getUser', {
            data: {
              condition: `gb.f_meter_type in ('气量卡表', '金额卡表','物联网表') and u.f_card_id='${self.cardInfo.CardID}'
          and u.f_filialeid = '${self.$login.f.orgid}' and f_alias='${self.cardInfo.Factory}' and f_whether_hairpin != '未发'`,
              orderitem: `${self.orderitem} Desc`
            }
          }, {resolveMsg: null, rejectMsg: '获取用户信息失败'})
          if (getUser.data.length > 0) {
            this.$CardService.replacecXq(this.cardInfo, getUser.data[0]).then((res) => {
              console.log(res)
              if (res.status == 0) {
                this.$showAlert('擦虚气成功!!', 'success', 0)
                this.$refs.paged.$refs.cri.$refs.readcard.readCard()
              } else {
                this.$showAlert('擦虚气失败!!', 'danger', 0)
                this.search()
              }
              this.showCardInfo = !this.showCardInfo
            })
          }
        } catch (e) {
          this.$showAlert('擦虚气失败,请重启或联系管理员!!', 'warning', 3000)
        }
      },
      getorg (val) {
        this.f_orgid = this.$login.convertToIn(val)
        this.$parent.f_orgid = this.f_orgid
      },
      recordClick () {
        // DoNothing, 消除流水界面出发的双击事件
      },
      hidden () {
        this.criteriaShow = !this.criteriaShow
      },
      clear () {
        Object.keys(this.$refs.paged.$refs.cri.model).forEach((key) => {
          this.$refs.paged.$refs.cri.model[key] = []
        })
      },
      async saveuser () {
        if (!this.chooserow) {
          this.$showAlert('未选择用户，无法修改', 'warning', 2000)
          return
        }
        let param = []
        if (this.$refs.paged.$refs.cri.model.f_user_phone != this.chooserow.f_user_phone) {
          let object = {}
          object.f_field_name = '电话号码'
          object.f_field_ename = 'f_user_phone'
          object.f_new_content = this.$refs.paged.$refs.cri.model.f_user_phone
          object.f_used_content = this.chooserow.f_user_phone
          param.push(object)
        }
        if (this.$refs.paged.$refs.cri.model.f_rent_phone != this.chooserow.f_rent_phone) {
          let object = {}
          object.f_field_name = '协议号码'
          object.f_field_ename = 'f_rent_phone'
          object.f_new_content = this.$refs.paged.$refs.cri.model.f_rent_phone
          object.f_used_content = this.chooserow.f_rent_phone
          param.push(object)
        }
        if (this.$refs.paged.$refs.cri.model.f_idnumber != this.chooserow.f_idnumber) {
          let object = {}
          object.f_field_name = '身份证号'
          object.f_field_ename = 'f_idnumber'
          object.f_new_content = this.$refs.paged.$refs.cri.model.f_idnumber
          object.f_used_content = this.chooserow.f_idnumber
          param.push(object)
        }
        console.log('修改明细', param)
        let a = 0
        if (this.$refs.paged.$refs.cri.model.f_times != this.chooserow.f_times) {
          let sqldata = `update t_userfiles set f_times = '${this.$refs.paged.$refs.cri.model.f_times}' where f_userfiles_id = '${this.row.f_userfiles_id}'`
          await this.$resetpost('rs/logic/runSQL', {data: {sql: sqldata}}, {resolveMsg: '更新成功', rejectMsg: '更新失败'})
          a = a + 1
        }
        if (this.$refs.paged.$refs.cri.model.f_comments != this.chooserow.comments) {
          let sqldata = `update t_userfiles set f_comments = '${this.$refs.paged.$refs.cri.model.f_comments}' where f_userfiles_id = '${this.row.f_userfiles_id}'`
          await this.$resetpost('rs/logic/runSQL', {data: {sql: sqldata}}, {resolveMsg: '更新成功', rejectMsg: '更新失败'})
          a = a + 1
        }
        if (this.$refs.paged.$refs.cri.model.f_open_date != this.chooserow.f_open_date) {
          let sqldata = `update t_userfiles set f_open_date = '${this.$refs.paged.$refs.cri.model.f_open_date}' where f_userfiles_id = '${this.row.f_userfiles_id}'`
          await this.$resetpost('rs/logic/runSQL', {data: {sql: sqldata}}, {resolveMsg: '更新成功', rejectMsg: '更新失败'})
          a = a + 1
        }
        if (param.length > 0) {
          let data = {
            param: param,
            f_userinfo_id: this.chooserow.f_userinfo_id,
            f_userfiles_id: this.chooserow.f_userfiles_id,
            f_user_id: this.chooserow.f_user_id,
            f_user_name: this.chooserow.f_user_name,
            f_operator: this.$login.f.name,
            f_operatorid: this.$login.f.id,
            f_orgid: this.$login.f.orgid,
            f_orgname: this.$login.f.orgs,
            f_depid: this.$login.f.depids,
            f_depname: this.$login.f.deps,
            f_change_reason: ''
          }
          console.log('传参', data)
          await this.$resetpost('rs/logic/chargechange', {data: data}, {resolveMsg: '更新成功', rejectMsg: '更新失败'})
          this.search()
        } else if (a > 0) {
          this.search()
        } else {
          this.$showAlert('当前不能更改地址和表具信息，可更改项未变化', 'warning', 2000)
        }
      },
      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]
      },
      search () {
        this.$refs.paged.$refs.cri.search()
      },
      searchNoData () {
        this.specialCondition = true
        this.$refs.paged.$refs.cri.model.aa = '1!=1'
        this.$refs.paged.$refs.cri.conditions.aa = '1!=1'
        this.search()
      },
      clean () {
        this.cardInfo = ''
        // 清除批量操作
        // this.$refs.paged.$refs.grid.select(null)
        this.row = null
        this.chooserow = null
        this.$dispatch('clean')
      },

      // 判断是不是卡表
      isCard (str) {
        return (str.includes('卡表'))
      },

      async selfSearch (args) {
        args.condition = `${args.condition}`
        if (this.defbtn === '发卡售气') {
          args.condition = `${args.condition} and f_whether_hairpin = '未发' and f_meter_classify like '%卡表%'`
        }
        if (this.$refs.paged.$refs.cri.model.f_userinfo_code && this.$refs.paged.$refs.cri.model.f_userinfo_code != '') {
          args.condition = `f_userinfo_code ='${this.$refs.paged.$refs.cri.model.f_userinfo_code}'`
        }
        if (!this.f_orgid) {
          this.getorg([this.$login.f.orgid])
        }
        if (this.f_orgid) {
          args.condition = `u.f_filialeid in ${this.f_orgid} and ${args.condition}`
        }
        this.isPager = true
        this.criteriaShow = true
        this.cardInfo = ''
        if (!this.specialCondition) {
          if (args.condition.includes('1!=1')) {
            args.condition = args.condition.replace('1!=1', '1=1')
          }
        }
        this.specialCondition = false

        await this.model.search(args.condition, args.model)
        if (this.model.rows.length == 1) {
          this.$parent.toBusiness(this.model.rows[0])
        }
      },
      cardBtn (val) {
        this.clear()
        cardBtnGen(this, val)
      },
      dealmsg (val) {
        this.$dispatch('deal-msg', val)
      },
      dealmsg2 (val) {
        if (this.chooserow && this.$refs.paged.$refs.cri.model.f_userinfo_code && this.$refs.paged.$refs.cri.model.f_userinfo_code != '') {
          this.$dispatch('deal-msg', this.chooserow)
        } else {

        }
      },
      refreshRow (row) {
        this.isPager = false
        // 滚动条置顶
        // this.$refs.paged.$refs.grid.$el.scrollTop = 0
        this.model.rows = [row]
        console.log('当前这一行', row)
        this.chooserow = row
        console.log('当前model', this.$refs.paged.$refs.cri.model)
        this.$refs.paged.$refs.cri.model.f_open_date = row.f_open_date
        this.$refs.paged.$refs.cri.model.f_user_name = row.f_user_name
        this.$refs.paged.$refs.cri.model.f_user_phone = row.f_user_phone
        this.$refs.paged.$refs.cri.model.f_userinfo_code = row.f_userinfo_code
        this.$refs.paged.$refs.cri.model.f_street = row.f_street
        this.$refs.paged.$refs.cri.model.f_residential_area = row.f_residential_area
        this.$refs.paged.$refs.cri.model.f_building = row.f_building
        this.$refs.paged.$refs.cri.model.f_unit = row.f_unit
        this.$refs.paged.$refs.cri.model.f_address = row.f_address
        this.$refs.paged.$refs.cri.model.f_floor = row.f_floor
        this.$refs.paged.$refs.cri.model.f_room = row.f_room
        this.$refs.paged.$refs.cri.model.f_slice_area = row.f_slice_area
        this.$refs.paged.$refs.cri.model.f_idnumber = row.f_idnumber
        this.$refs.paged.$refs.cri.model.f_meternumber = row.f_meternumber
        this.$refs.paged.$refs.cri.model.f_meter_brand = row.f_meter_brand
        this.$refs.paged.$refs.cri.model.f_meter_style = row.f_meter_style
        this.$refs.paged.$refs.cri.model.f_user_type = row.f_user_type
        this.$refs.paged.$refs.cri.model.f_times = row.f_times
        this.$refs.paged.$refs.cri.model.f_total_gas = row.f_total_gas
        this.$refs.paged.$refs.cri.model.f_rent_phone = row.f_rent_phone
        this.$refs.paged.$refs.cri.model.f_price_name = row.f_price_name
        this.$refs.paged.$refs.cri.model.f_imei = row.f_imei
        this.$refs.paged.$refs.cri.model.f_card_id = row.f_card_id
        this.$refs.paged.$refs.cri.model.f_comments = row.comments
        this.$refs.paged.$refs.cri.model.f_whether_hairpin = row.f_meter_type.includes('物联网表') ? row.f_table_state : row.f_whether_hairpin
      },
      userTypeChange () {
        this.gasproperties = []
        if (this.$refs.paged.$refs.cri.model.f_user_type.length === 1) {
          if (this.$refs.paged.$refs.cri.model.f_user_type[0]) {
            this.gasproperties = this.$appdata.getParam(this.$refs.paged.$refs.cri.model.f_user_type[0])
          } else {
            this.$refs.paged.$refs.cri.model.f_gasproperties = ''
          }
        }
      },
      async hasGasContinue () {
        this.showCardError = false
        this.showCardInfo = false
        getMeterInfoGen2(this)
      },
      hasGasClose () {
        this.showCardInfo = false
        this.showCardError = false
        this.showCardError2 = false
      },
      async testCard () {
        try {
          let res = await this.$resetpost('http://127.0.0.1:8003/CardTest', {}, {resolveMsg: null, rejectMsg: null})
          let preMsg = res.data.code == 1 ? '成功：' : '错误：'
          this.$showMessage(preMsg + res.data.msg)
        } catch (e) {
          this.$showMessage('错误：连接卡服务失败')
        }
      },

      async readCardByFactory () {
        console.log('通过厂家读卡', this.model.rows.length)
        if (this.model.rows.length == 1) {
          let operConfirm = await this.$showMessage(`当前用户的表厂家为: ${this.model.rows[0].f_meter_brand}。请确认读卡器插入的卡为${this.model.rows[0].f_meter_brand}的卡。`, ['confirm', 'cancel'])
          if (operConfirm == 'confirm') {
            let data = {
              factory: this.model.rows[0].f_alias
            }
            try {
              let res = await this.$resetpost('http://127.0.0.1:8003/ReadCard', data, {resolveMsg: null, rejectMsg: null})
              res.data.Err ? this.$showAlert(res.data.Err, 'danger', 2000) : ''
              if (res.data.Err === null && res.data.Exception) {
                this.$showAlert(res.data.Exception, 'danger', 2000)
              } else if (!res.data.CardID) {
                this.$showAlert(`请确认当前读卡器插入的卡为: ${this.model.rows[0].f_meter_brand} 的卡`, 'danger', 5000)
              } else {
                this.cardBtn(res)
              }
            } catch (error) {
              console.log('捕获到异常', error)
              this.$showAlert(error.data, 'danger', 2000)
            }
          } else {

          }
        } else {
          this.$showAlert('请通过条件精确查询到此卡属于的用户信息，保证列表只有一条用户数据。再点击按钮“读卡2”', 'warning', 5000)
        }
      }
    },
    watch: {
      'model.rows.length' () {
        this.isSingleUser = this.model.rows
      }
    }
  }
</script>
<style>

  .input-underline {
    border-bottom: 1px solid #dbdbdb;
    border-top: 0px;
    border-left: 0px;
    border-right: 0px;
  }
  .font_normal_body_new {
    font-weight: 100;
    float: left;
    margin-top: 0px;
    font-size: 1.4rem !important;
    line-height: 30px;
  }
</style>
