<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 title="该区域包含权限：读卡限定、读卡2、综合收费导出权限">
          <card-info-modal :show.sync="$parent.$parent.cardModal_show" :cardinfo="$parent.$parent.cardInfo"
                           v-ref:cardinfo></card-info-modal>
          <div class="auto" v-if="$parent.$parent.$parent.sustainMoney != null">
            <h3 style="margin-top: 10px;margin-bottom: 0px">当前连续收款金额: <label class="b" style="color: #a94442">{{$parent.$parent.$parent.sustainMoney}}</label></h3>
          </div>
          <div  v-show="!$parent.$parent.authArr.includes('读卡限定')">
            <div class="form-group col-sm-3" >
              <label class="font_normal_body">客户编号</label>
              <input type="text" class="input_search" style="width:60%" v-model="model.f_userinfo_code" placeholder='客户编号'
                     condition="f_userinfo_code = '{}'" @keyup.enter="$parent.$parent.clean()">
            </div>
            <div class="form-group col-sm-3">
              <label class="font_normal_body">客户名称</label>
              <input type="text" class="input_search" style="width:60%"  v-model="model.f_user_name" placeholder='客户名称'
                     @keyup.enter="$parent.$parent.clean()" condition="f_user_name like '%{}%'">
            </div>
            <!--<div class="row" >-->
            <div  v-show="$parent.$parent.criteriaShow">
              <!--<div class="form-group col-sm-4"  v-if="$parent.$parent.clientWidth<1600">-->
              <!--<label class="font_normal_body">客户名称</label>-->
              <!--<input type="text" class="input_search" style="width:60%"  v-model="model.f_user_name" placeholder='客户名称'-->
              <!--@keyup.enter="search(), $parent.$parent.clean()" condition="f_user_name = '{}'">-->
              <!--</div>-->
              <div class="form-group col-sm-3">
                <label class="font_normal_body">合同编号</label>
                <input type="text" class="input_search" style="width:60%" v-model="model.f_contract_id" placeholder='合同编号'
                       condition="f_contract_id = '{}'">
              </div>

              <div class="form-group col-sm-3">
                <label class="font_normal_body">电&emsp;&emsp;话</label>
                <input type="text" class="input_search" style="width:60%"  v-model="model.f_user_phone" placeholder='电话'
                       condition="f_user_phone like '%{}%'">
              </div>
              <div class="form-group col-sm-3">
                <label class="font_normal_body">客户地址</label>
                <input type="text" class="input_search" style="width:60%" style="width:60%" v-model="model.f_address" placeholder='客户地址'
                       condition="address.f_address like '%{}%'">
              </div>
              <div class="form-group col-sm-3">
                <label class="font_normal_body">表&emsp;&emsp;号</label>
                <input type="text" class="input_search" style="width:60%" style="width:60%" v-model="model.f_meternumber" placeholder='表号'
                       condition="u.f_meternumber like '%{}%'">
              </div>

              <!--<div class="form-group col-sm-4">-->
              <!--<label class="font_normal_body">档案状态</label>-->
              <!--<v-select v-model="model.f_file_state"-->
              <!--placeholder='档案状态'-->
              <!--:value.sync="model.f_file_state"-->
              <!--:options='$parent.$parent.fileStates'-->
              <!--condition="u.f_table_state = '{}'"-->
              <!--style="width: 60%"-->
              <!--close-on-select></v-select>-->
              <!--</div>-->

              <div class="form-group col-sm-3">
                <label class="font_normal_body">气表状态</label>
                <v-select id="f_paytype"
                          v-model="model.f_table_state"
                          placeholder='气表状态'
                          :value.sync="model.f_table_state"
                          :options='$parent.$parent.tableStates'
                          condition="f_table_state = '{}'"
                          style="width: 60%"
                          close-on-select></v-select>
              </div>
              <div class="form-group col-sm-3">
                <label class="font_normal_body">气表品牌</label>
                <v-select id="f_meter_brand"
                          v-model="model.f_meter_brand"
                          placeholder='气表品牌'
                          :value.sync="model.f_meter_brand"
                          :options='$parent.$parent.meterbrand'
                          condition="f_meter_brand = '{}'"
                          close-on-select style="width: 60%"></v-select>
              </div>
              <div class="form-group col-sm-3">
                <label class="font_normal_body">用气性质</label>
                <v-select v-model="model.f_gasproperties"
                          placeholder='用气性质'
                          :value.sync="model.f_gasproperties"
                          :options='$parent.$parent.gasproperties'
                          condition="u.f_gasproperties = '{}'"
                          close-on-select style="width: 60%"></v-select>
              </div>
              <div class="form-group col-sm-3">
                <label class="font_normal_body">客户等级</label>
                <v-select v-model="model.f_user_level"
                          placeholder='客户等级'
                          :value.sync="model.f_user_level"
                          :options='$parent.$parent.userlevel'
                          condition="i.f_user_level = '{}'"
                          close-on-select style="width: 60%"></v-select>
              </div>
              <div class="form-group col-sm-3" >
                <label class="font_normal_body">组织机构</label>
                <res-select :initresid='$parent.$parent.curorgid'
                            @res-select="$parent.$parent.getorg"
                            class="select select_list"
                            restype='organization'
                            style="width: 60%">
                </res-select>
              </div>
              <div class="form-group col-sm-3">
                <label class="font_normal_body">卡&emsp;&emsp;号</label>
                <input type="text" class="input_search" style="width:60%" v-model="model.f_card_id" placeholder='卡号'
                       condition="f_card_id like '%{}%'">
              </div>
              <div class="form-group col-sm-3">
                <label class="font_normal_body">使用类型</label>
                <v-select v-model="model.f_usetype"
                          placeholder='使用类型'
                          :value.sync="model.f_usetype"
                          :options='$parent.$parent.usetype'
                          condition="u.f_usetype = '{}'"
                          close-on-select style="width: 60%"></v-select>
              </div>
              <div class="form-group col-sm-3">
                <label class="font_normal_body">旧客户号</label>
                <input type="text" class="input_search" style="width:60%" v-model="model.f_olduserinfo_code" placeholder='客户编号'
                       condition="f_olduserinfo_code = '{}'">
              </div>
            </div>
          </div>
          <div class="form-group col-sm-6" style="float:right;white-space: nowrap;width: auto" >
            <button class="button_clear" v-if="$parent.$parent.authArr.includes('连续收费') && $parent.$parent.$parent.sustainMoney == null" @click="$parent.$parent.startContinuousCharg()">启动连续收费</button>
            <button class="button_clear" v-if="$parent.$parent.authArr.includes('连续收费') && $parent.$parent.$parent.sustainMoney" @click="$parent.$parent.closeContinuousCharg()">关闭连续收费</button>
            <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" @click="$parent.$parent.testCard()" v-el:cx>测卡</button>
            <button class="button_search" v-show="!$parent.$parent.authArr.includes('读卡限定')" @click="search(), $parent.$parent.clean()" v-el:cx>查询</button>
            <button class="button_clear" v-show="!$parent.$parent.authArr.includes('读卡限定')" @click="$parent.$parent.clear()">清空</button>
            <button class="button_clear" v-if="$parent.$parent.authArr.includes('读卡2')" @click="$parent.$parent.readCardByFactory()">读卡2</button>
            <button class="button_clear" v-if="$parent.$parent.authArr.includes('磁条卡')" @click="$parent.$parent.readCiTiaoCard()">读磁条卡</button>
            <export-excel v-if="$parent.$parent.authArr.includes('收费综合导出权限')"
                          :data="{condition: $parent.$parent.excelCondition}"
                          :field="$parent.$parent.fields"
                          sqlurl="rs/logic/saleExport" sql-name="sale_getUser"
                          template-name='收费信息导出'
                          :choose-col="true">
            </export-excel>
          </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>
            {{row.f_userinfo_code}}
          </nobr> </td>
          <td style="white-space: nowrap;" :class="{'bg-danger' : row.f_table_state === '停用' }">
            <span @click="$parent.$parent.$parent.dealmsg(row)"><a>{{row.f_user_name}}&nbsp;&nbsp;{{row.f_user_phone}}&nbsp;&nbsp;{{row.f_address}}</a></span>
          </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}}&nbsp;&nbsp;{{row.f_table_state}}
          </td>
          <td style="white-space: nowrap;text-align: center;" :class="{'bg-danger' : row.f_table_state === '停用' }">{{row.f_meter_type}}&nbsp;&nbsp;({{ 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" v-if="this.model.rows.length==1">
          <label class="col-sm-2 control-label">客户名称</label>
          <div class="col-sm-4">
            <p class="form-control-static">{{this.model.rows[0].f_user_name}}</p>
          </div>

          <label class="col-sm-2 control-label">客户地址</label>
          <div class="col-sm-4">
            <p class="form-control-static">{{this.model.rows[0].f_address}}</p>
          </div>
        </div>
        <div class="form-group" v-if="this.model.rows.length>1">
          <label class="col-sm-2 control-label">信&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;息: </label>
          <div class="col-sm-8">
            <p class="form-control-static">该卡号出现重复，点击继续后,请确认该客户信息之后双击进入！！</p>
          </div>
        </div>
        <div class="form-group" v-if="this.model.rows.length<1">
          <label class="col-sm-2 control-label">信&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;息: </label>
          <div class="col-sm-8">
            <p class="form-control-static">此时的卡片信息和用户信息不匹配，请核实后在进行读卡 !!</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="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'
  import DetailManage from '../../../../components/charge/DetailManage'
  import Vue from 'vue'

let cardBtnGen = async function (self, val) {
    self.cardInfo = val.data
    let getUser = null
    // 判断读卡是否需要卡密码
    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 {
            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 == 1 && getUser.data[0].f_alias === self.cardInfo.Factory) {
              self.readCardParam = getUser.data[0].f_card_password
              self.cardInfo = await self.$refs.paged.$refs.cri.$refs.readcard.readCard2(getUser.data[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
      // 获取当前卡信息
      getMeterInfoGen3(self)
    } else {
      getMeterInfoGen(self)
    }

    self.$refs.paged.$refs.grid.$el.scrollTop = 0
  }
  let getMeterInfoGen2 = async function (self) {
    self.model.rows = []
    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 getMeterInfoGen3 = 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: '读卡失败'})
      }
      self.model.rows = getUser.data
    }
  }

  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()
    if (!self.authArr.includes('读卡限定')) {
      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: '',
        excelCondition: '',
        cardModal_show: false,
        bulkType: null, // 批量操作标识
        contract: [{label: '全部', value: ''},
          {label: '有', value: 'not null'},
          {label: '无', value: 'null'}],
        orderFields: {
          f_userinfo_id: 'no'
        },
        filiale: '',
        outlet: '',
        fields: {
          'f_userinfo_code': '用户编号',
          'f_user_name': '用户姓名',
          'f_user_phone': '用户电话',
          'f_address': '用户地址',
          'f_credentials': '证件类型',
          'f_idnumber': '证件号码',
          'f_user_id': '表编号',
          'f_gasproperties': '用气性质',
          'f_meter_brand': '气表品牌',
          'f_meter_style': '气表型号',
          'f_price_type': '气价类型',
          'f_price_name': '气价名称',
          'fenleixinxi': '分类信息'
        },
        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('用户等级')] : [],
        usetype: 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
      }
    },
    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: {
      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] = []
        })
      },
      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 () {
        if (!this.authArr.includes('读卡限定')) {
          this.$refs.paged.$refs.cri.search()
        } else {
          this.model.rows = []
        }
      },
      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.$dispatch('clean')
      },

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

      async selfSearch (args) {
        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.excelCondition = args.condition
        args.condition = `${args.condition}`
        if (this.defbtn === '发卡售气') {
          args.condition = `${args.condition} and f_whether_hairpin = '未发' and f_meter_classify like '%卡表%'`
        }
        this.isPager = true
        this.criteriaShow = true
        this.$parent.warningInfo = null
        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)
  },
  refreshRow (row) {
    this.isPager = false
    // 滚动条置顶
    // this.$refs.paged.$refs.grid.$el.scrollTop = 0
    this.model.rows = [row]
  },
  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 readCiTiaoCard () {
    console.log('读磁条卡，开始')
    let data = {}
    let getUser = {data: []}
    try {
      // let res = {data:{Factory : 'CiTiao',CardID : '5'}}
      this.$showAlert('请刷卡', 'warning', 50000)
      let res = await this.$resetpost('http://127.0.0.1:8003/ReadCard_HEC', data, {resolveMsg: null, rejectMsg: null})
      res.data.Err ? this.$showAlert(res.data.Err, 'danger', 2000) : ''
      this.$closeAlert()
      if (res.data.Err === null && res.data.Exception) {
        this.$showAlert(res.data.Exception, 'danger', 2000)
      } else {
        if (res.data.Factory === 'CiTiao') {
          // 获取用户信息
          getUser = await this.$resetpost('rs/sql/sale_getUser', {
            data: {
              condition: `gb.f_meter_type in ('机表','物联网表') and i.f_userinfo_code='${res.data.CardID}'`,
              orderitem: `${this.orderitem}`
            }
          }, {resolveMsg: '读卡成功', rejectMsg: '读卡失败'})
          this.model.rows = getUser.data
        }
      }
    } catch (error) {
      console.log('捕获到异常', error)
      this.$showAlert(error.data, 'danger', 2000)
    }
  },
  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)
    }
  },
  startContinuousCharg () {
    console.log('启动连续收费')
    window.localStorage.setItem('sustainMoney', 0)
    this.$parent.sustainMoney = 0
  },
  async closeContinuousCharg () {
    console.log('关闭连续收费')
    let res = await this.$showMessage('确定关闭连续收款吗, 数据将被清空?', ['confirm', 'cancel'])
    if (res != 'confirm') return
    window.localStorage.removeItem('sustainMoney')
    this.$parent.sustainMoney = null
  }
  },
  watch: {
    'model.rows.length' () {
      this.isSingleUser = this.model.rows
    }
  },
  computed: {
    authArr () {
      console.log('this.$login.r:', this.$login.r)
      console.log('this.$login.r.includes:', this.$login.r.includes('收费综合导出权限'))
      return this.$login.r ? this.$login.r : []
    }
  }
  }
</script>
<style>

</style>
