<template>
	<view>
		<banklist :options="bankData" :hot="false" @change="change" @filter-method="search"></banklist>
	</view>
</template>

<script>
	import {
		getList
	} from '@/api/bank.js'
	import banklist from '@/components/nyn-city-list/nyn-city-list.vue';
	const hot = [{
		id: 'h1',
		name: '建设银行'
	}, {
		id: 'h2',
		name: '河北省农村信用社联合社'
	}, {
		id: 'h3',
		name: '农业银行'
	}, {
		id: 'h4',
		name: '工商银行'
	}, {
		id: 'h5',
		name: '中国邮政储蓄银行'
	}, {
		id: 'h6',
		name: '中国银行'
	}, {
		id: 'h8',
		name: '交通银行'
	}, {
		id: 'h7',
		name: '河北银行'
	}, {
		id: 'h9',
		name: '招商银行'
	}, {
		id: 'h10',
		name: '光大银行'
	}, {
		id: 'h11',
		name: '浦发银行'
	}, {
		id: 'h12',
		name: '民生银行'
	}]

	function getFirstLetter(str) {
		return str[0];
	}

	function fortmat(data) {
		const dic = {}
		const banks = []

		const constKey = (key) => {
			return dic.hasOwnProperty(key)
		}

		for (let i = 0; i < data.length; i++) {
			let item = data[i]
			let key = getFirstLetter(item.quickQuery)
			if (!constKey(key)) {
				dic[key] = {
					banks: []
				}
				banks.push({
					key,
					value: dic[key].banks
				})
			}
			dic[key].banks.push(item)
		}
		return banks
	}

	export default {
		components: {
			banklist
		},
		data() {
			return {
				searchKey: '',
				banks: []
			}
		},
		onShow() {
			getList().then(resp => {
				this.banks = resp.data.data
			})
		},
		methods: {
			change: function(e) {
				uni.navigateBack({
					delta: 1
				})
				uni.$emit('icCardSetBank', e)
			},
			search(value) {
				this.searchKey = value
			}
		},
		computed: {
			bankData() {
				if (this.searchKey) {
					let searchKey = this.searchKey.toUpperCase()

					let data = this.banks.filter(item => {
						return item.name.indexOf(searchKey) > -1 || item.quickQuery.toUpperCase().startsWith(searchKey) || item.simpleSpelling
							.toUpperCase()
							.startsWith(searchKey)
					})
					return fortmat(data)
				} else {
					const data = fortmat(this.banks)
					data.unshift({
						key: '热',
						value: hot
					})
					
					return data
				}
			}
		}
	}
</script>

<style>

</style>
