<script>
import excel from '@/utils/excel';

export default {
	data(){
		return {
			insert_page: 1
		}
	},
    methods:{
		beforeUpload(file){
			const fileExt = file.name.split('.').pop().toLocaleLowerCase()
			if (fileExt === 'xlsx' || fileExt === 'xls') {
				this.readFile(file)
				this.file = file
			} else {
				this.$message.warning('文件：' + file.name + '不是EXCEL文件，请选择后缀为.xlsx或者.xls的EXCEL文件。')
			}
			return false;
		},
		// 读取文件
		readFile(file){
			const reader = new FileReader()
			reader.readAsArrayBuffer(file)
			reader.onloadstart = () => {
				this.uploadLoading = true
				this.tableLoading = true
				this.showProgress = true
			}
			reader.onprogress = e => {
				this.progressPercent = Math.round(e.loaded / e.total * 100)
			}
			reader.onerror = () => {
				this.$message.error('文件读取出错')
			}
			reader.onload = e => {
				this.$message.success('文件读取成功')
				const data = e.target.result
				const { header, results } = excel.read(data, 'array')
				console.log(header);
				this.insertData(results)
			}
		},
		insertData(data){console.log(data)
			let list = [];
			let pagesize = 100;
			var length = data.length;
			if (this.insert_page > Math.ceil(length / pagesize)) {
				this.$message.success('全部导入完成')
				// this.action.show = false;
				// this.loading = true;
				// this.search.page = 1;
				this.$refs.table.reload(this.search);
				return false;
			}else{
				for (var i = (pagesize * (this.insert_page - 1)); i < (pagesize * this.insert_page); i++) {
					list.push(data[i]);
				}
				let current = pagesize * (this.insert_page - 1) + 1;
				let lastNum = (pagesize * this.insert_page < length) ? (pagesize * this.insert_page) : length;
				this.$message.success('正在导入第' + current + '至' + lastNum + '条，请耐心等待导入，当出现“全部导入完成”后关闭窗口！');
				this.$API.customer.company.insert.post({data:list})
					.then(res => {
						if(res.code == 1){
							this.insert_page = this.insert_page + 1;
							this.$message.success('导入完成当前页！')
							this.insertData(data);
						}else{
							this.$message.success('导入失败，请重新导入!')
						}
					})
			}    
        }
    }
}
</script>