<template>
    <div>
      <VanField
          :value="value"
          :label="label" :rules="requireRule(required, label)" readonly clickable
          :placeholder="placeholder || `请选择${label}`" :clearable="clearable" :disabled="disabled" :required="required"
          @click="showPicker"/>
      <VanPopup v-model="visible" round position="top">
          <VanPicker
            show-toolbar
            :columns="bankList.map(bank => bank.lName)"
            :loading="loading"
            @confirm="handleSelect"
            @cancel="hidePicker">
            <template #title>
              <VanField v-model="keyword" @blur="() => getBankList(1)" placeholder="请输入关键字" style="width: 50%"/>
            </template>
          </VanPicker>
      </VanPopup>
    </div>
</template>

<script>
import mixin from './mixin'
import {querybankaps} from '@/api/merchant/merchant'
import { Field as VanField, Picker as VanPicker, Popup as VanPopup, Toast  } from 'vant'
/**
 * 输入框组件
 */
export default {
  name: "BankPicker",
  components: {VanField, VanPicker, VanPopup},
  mixins: [mixin],
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    card: {
      type: String
    }
  },
  data(){
    return {
      visible: false,
      keyword: this.value,
      loading: false,
      bankList: []
    }
  },
   watch: {
      value(){
          this.keyword = this.value
      }
  },
  methods: {
      showPicker(){
        if(!this.card || this.card.trim() === ''){
          Toast('请先录入银行账号');
          return
        }
        this.getBankList(1)
        this.visible = true
      },
      hidePicker(){
        this.visible = false
      },
      handleSelect(value){
        this.$emit('change', value)
        this.$emit('codeChange', this.bankList.filter(bank => bank.lName === value)[0].bankCode)
        this.hidePicker()
      },
      async getBankList(page){
            if (page === 1) {
                this.bankList = []
                this.loading = true
            }

            const res = await querybankaps({card: this.card, key: this.keyword || '', page: page})
            if (res.data.resp.RespCode === '200') {
                this.bankList.push(...res.data.data.record)
            }
            this.loading = false

            // 该接口最多只能查5页
            if (page <= 4) {
               this.getBankList(page + 1)
            }

      }
  }
}
</script>
