<template xmlns:v-el="">

  <div class="binary">
    <div class="basic-main" >
      <div class="flex">
        <criteria-paged :model="model" v-ref:paged @sort="sort">
          <criteria partial='criteria' v-ref:criteria @condition-changed="$parent.selfSearch">
            <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
              <div class="row">
                <div class="col-sm-2">
                  <label class="font_normal_body">用户编号</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.f_userinfo_code"
                         condition="f_userinfo_code='{}'" placeholder='用户编号'>
                </div>
                <div class="col-sm-2">
                  <label class="font_normal_body">用户姓名&nbsp;</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.f_user_name"
                         condition="f_user_name = '{}'" placeholder='用户姓名'>
                </div>
                <div class="col-sm-2">
                  <label class="font_normal_body">用户状态</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.f_user_state"
                         condition="f_user_state='{}'" placeholder='用户状态'>
                </div>

                <div class="span" style="float:right;">
                  <button class="btn btn-success" @click="$parent.$parent.writeCard()">批量发卡</button>
                  <button class="button_search button_spacing" @click="$parent.$parent.search()">查询</button>
                  <button class="button_clear button_spacing" @click="$parent.$parent.clear()">清空</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 class="row" v-show="$parent.$parent.criteriaShow">


                <div class="col-sm-2">
                  <label class="font_normal_body">用气性质</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.f_gasproperties"
                         condition="f_gasproperties='{}'" placeholder='用气性质'>
                </div>

                <div class="col-sm-2">
                  <label class="font_normal_body">电话</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.f_user_phone"
                         condition="f_user_phone='{}'" placeholder='电话'>
                </div>
                <div class="col-sm-2">
                  <label class="font_normal_body">证件类型</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.f_credentials"
                         condition="f_credentials='{}'" placeholder='证件类型'>
                </div>
                <div class="col-sm-2">
                  <label class="font_normal_body">证件号码</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.f_idnumber"
                         condition="f_idnumber='{}'" placeholder='证件号码'>
                </div>
                <div class="col-sm-2">
                  <label class="font_normal_body" title="起始用户编号">起始编号</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.f_start_userinfo_code"
                         condition="f_userinfo_code >= '{}'" placeholder='起始用户编号'>
                </div>
                <div class="col-sm-2">
                  <label class="font_normal_body" title="终止用户编号">终止编号</label>
                  <input type="text" style="width:60%" class="input_search" v-model="model.f_end_userinfo_code"
                         condition="f_userinfo_code <= '{}'" placeholder='终止用户编号'>
                </div>
              </div>
            </div>
          </criteria>
          <data-grid :model="model" partial='list' v-ref:grid class="list_area table_sy">
            <template partial='head'>
              <tr>
                <th style="text-align:center">
                  <nobr>全选</nobr>
                  <input @keyup.enter="search" style="width:60%" :checked="$parent.$parent.$parent.isallchecked" type="checkbox" v-model='$parent.$parent.$parent.checked1'
                         @click="$parent.$parent.$parent.checkedALL()">
                </th>
                <th>序号</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>用户状态</th>
                <th>证件类型</th>
                <th>证件号码</th>
                <th>电话</th>
                <th>开户银行及账号</th>
                <th>用户类型</th>
                <th>用气性质</th>
                <th>使用类型</th>
                <th>使用状态</th>
              </tr>
            </template>
            <template partial='body'>
              <td style="text-align:center"><input type="checkbox" name="opertioninput"
                                                   @click="$parent.$parent.$parent.checked(row)"></td>
              <td style="text-align: center;"> {{$index + 1}}</td>
              <td>{{row.f_userinfo_code}}</td>
              <td>{{row.f_whether_hairpin}}</td>
              <td>{{row.f_user_name}}</td>
              <td>{{row.f_user_state}}</td>
              <td>{{row.f_credentials}}</td>
              <td>{{row.f_idnumber}}</td>
              <td>{{row.f_user_phone}}</td>
              <td>{{row.f_paper_account}}</td>
              <td>{{row.f_user_type}}</td>
              <td>{{row.f_gasproperties}}</td>
              <td>{{row.f_usetype}}</td>
              <td>{{row.f_usestate}}</td>
            </template>
          </data-grid>
        </criteria-paged>
        <split-price :showdata="splitdata" :pricesplit="priceSplit" v-if="priceSplit"></split-price>
      </div>
    </div>
  </div>
</template>
<script>
  import {PagedList, HttpResetClass} from 'vue-client'

  export default {
    title: '批量发卡',
    data() {
      return {
        batchMeterShow: false,
        priceSplit: false,
        criteriaShow: false,
        model: new PagedList('rs/sql/sale_getUser', 30),
        rows: [],
        checked1: false,
        plans: [],//记录当前行是否被勾选
        all: false,//是否全选
        condition: '',
        orderDefault: 'id',
        map: new Map(),
        flg: false,
        checkFlg: false,
        isallchecked:false,
        f_userinfocode_end:'',
        writeCardindex:0,
        mapofarr:[]
      }
    },

    ready(){
        this.search();
    },
    methods: {
      selfSearch(args) {
        console.log("x")
        args.condition+= ` and f_whether_hairpin in ('无卡','未发') and  f_meter_type='机表' `
        this.model.search(args.condition, this.model)
      },
      // 全选
      checkedALL() {
        this.isallchecked = true;
        this.checked1 = !this.checked1
        let box = document.getElementsByName("opertioninput")
        for (var i = 0; i < box.length; i++) {
          box[i].checked = this.checked1;
        }
        if (this.checked1 === true) {
          for (let i = 0; i < this.model.rows.length; i++) {
             this.map.set(this.model.rows[i].f_userinfo_code,this.model.rows[i] )
          }
        }
        if (this.checked1 === false) {
          //  全不选
          this.map.clear()
        }
        this.mapofarr = Array.from(this.map);
      },

      // 单勾选框
      checked(val) {
        if(val == null){
          return;
        }
        // 选中行的数据
        let userinfoCode = val.f_userinfo_code;

        if (this.map.has(userinfoCode)) {
          this.map.delete(userinfoCode)
          //只要去掉一个肯定不是全选
          this.isallchecked = false;
        } else {
          this.map.set(userinfoCode, val)


        }
        this.mapofarr = Array.from(this.map);
      },
      //  批量发卡
      writeCard(){
        if (this.map.size === 0 || this.map === null) {
          this.$showMessage("请至少选择一条数据！！")
          return;
        }
        if(this.map.size >200){
          this.$showAlert("限制发卡数量200!",'warning',1000)
          return;
        }
        if(this.writeCardindex  == this.mapofarr.length){
          this.$showMessage(`批量发卡完成,共发卡${this.map.size}张，最后发卡用户编号为：${this.f_userinfocode_end}`);
          this.$refs.paged.$refs.criteria.search();
          this.writeCardindex = 0;
          this.mapofarr = [];
          this.checked1 = false
          let box = document.getElementsByName("opertioninput")
          for (var i = 0; i < box.length; i++) {
            box[i].checked = false
          }
          this.map.clear()
          return;
        }

        this.initCardGen(this.mapofarr[this.writeCardindex][1],this.writeCardindex).then((res)=>{
          this.writeCardindex +=1;
          this.writeCard();
        })


      },

      //  开户发卡
      async initCardGen(row,index) {
         row.f_card_id = row.f_userinfo_code
        if(row.f_userfiles_id == null || row.f_userfiles_id == '' ){
          return 500;
        }
        try{
          try{
            let sqldata = `update t_userfiles set f_card_id='${row.f_card_id}',f_whether_hairpin = '已发' where f_userfiles_id = '${row.f_userfiles_id}'`
            await this.$resetpost('rs/logic/runSQL', {data: {sql: sqldata}}, {resolveMsg: null, rejectMsg: '保存失败'})
          }catch(error){
            return;
          }
          try{
            let params = {
              factory: row.f_alias,
              kh: row.f_card_id == null? '': row.f_card_id,                                   // 卡号
              kmm: row.f_card_password==null?'':row.f_card_password,                              // 卡密码，写卡后返回新密码, 不论补卡还是先开户都没有密码
              bjql: 0,                              // 报警气量,t_gasbrand表中
              czsx:'',                             // 充值上线，t_gasbrand表中
              tzed: row.f_topup_ceil==null?'':row.f_topup_ceil,                          // 透支额度，t_gasbrand表中
              kzt: '1',                                            // 卡状态，0开户卡，1用户卡（0新开户，1补卡）
              bkcs: 0,                       // 补卡次数，从补卡表里通过表编号获得
              cs: row.f_times == null? '':row.f_times,                                      // 求购气次数，先开户为1
              yhh: '',                 // 用户号
              meterid: row.f_meternumber == null?'':row.f_meternumber,             // 表号
              meternumber: row.f_meternumber==null? '':row.f_meternumber,
              dqdm: '',                                          // 精益工业地区代码
              money: 0,                           // 购气金额
              klx: ''
            }
            let res = await this.$resetpost('http://127.0.0.1:8003/WriteNewCard', params, {
              resolveMsg: null,
              rejectMsg: '写卡服务错误'
            })
            index +=1;
            this.f_userinfocode_end = row.f_userinfo_code
            this.$showAlert(`第${index}个,用户:${row.f_userinfo_code}发卡完成!`, 'success', 1000);
            if (res.data.Err || res.data.Exception) {
              let sqldata = `update t_userfiles set f_whether_hairpin = '未发' where f_userfiles_id = '${row.f_userfiles_id}'`
              await this.$resetpost('rs/logic/runSQL', {data: {sql: sqldata}}, {resolveMsg: null, rejectMsg: '保存失败'})
            }else{
              return 200;
            }
          }catch(error){
            let sqldata = `update t_userfiles set f_whether_hairpin = '未发' where f_userfiles_id = '${row.f_userfiles_id}'`
            await this.$resetpost('rs/logic/runSQL', {data: {sql: sqldata}}, {resolveMsg: null, rejectMsg: '保存失败'})
          }

        }catch(error){
          return 500;
        }
      },

      // 隐藏折叠条件
      hidden() {
        this.criteriaShow = !this.criteriaShow
      },
      // 清空
      clear() {
        Object.keys(this.$refs.paged.$refs.criteria.model).forEach((key) => {
          this.$refs.paged.$refs.criteria.model[key] = []
        })
      },

      search() {
        //查询前清空选择项
        this.plans = []
        this.$refs.paged.$refs.criteria.search()
      },
    },

  }

</script>
<style lang="less" scoped>
  #handManager {
    display: flex;
    justify-content: space-around;
    align-items: center;

    .btn {
      margin: 0px;
    }
  }

  .hand-loading {
    border: 3px solid #ccc;
    border-right-color: #337ab7;
    border-radius: 50%;
    animation: spin 0.6s linear;
    position: absolute;
    animation-iteration-count: infinite;
    top: 0;
    right: 50%;
    z-index: 2;
    display: block;
    width: 28px;
    height: 28px;
    line-height: 28px;
    text-align: center;
    pointer-events: none;
  }

  @keyframes spin {
    100% {
      transform: rotate(360deg);
    }
  }
</style>
