<template>
	<view class="page-news">
		<uni-list ref="list" class="listview" :class="{ 'margin-bot': nid === '0' }" :enableBackToTop="true" :scroll-y="true" @scrolltolower="loadMore()">
			<uni-refresh class="refresh" @refresh="onrefresh" @pullingdown="onpullingdown" :display="refreshing ? 'show' : 'hide'">
				<div class="refresh-view">
					<image class="refresh-icon" :src="refreshIcon" :style="{ width: refreshing || pulling ? 0 : '32px' }" :class="{ 'refresh-icon-active': refreshFlag }"></image>
					<uni-load-more v-if="refreshing" class="loading-icon" status="loading" :contentText="loadingMoreText"></uni-load-more>
					<text class="loading-text">{{ refreshText }}</text>
				</div>
			</uni-refresh>
			<uni-cell v-for="(item, index) in dataList" :key="item.id">
				<order-item :newsItem="item" :isCheck="nid === '0'" :idx="index" @handleCheck="handleCheck"></order-item>
			</uni-cell>
			<uni-cell v-if="isLoading || dataList.length > 4">
				<view class="loading-more">
					<text class="loading-more-text">{{ loadingText }}</text>
				</view>
			</uni-cell>
		</uni-list>
		<no-data class="no-data" v-if="isNoData" @retry="loadMore"></no-data>
	</view>
</template>

<script>
import { mapState } from 'vuex';
import uniList from '@/components/uni-list.vue';
import uniCell from '@/components/uni-cell.vue';
import uniRefresh from '@/components/uni-refresh.vue';
import uniLoadMore from '@/components/uni-load-more.vue';
import noData from '@/components/nodata.nvue';
import { getDhk, getSubmitDhk } from '@/servers/loan.js';
import orderItem from './order-item.nvue';
export default {
	components: {
		uniList,
		uniCell,
		uniRefresh,
		uniLoadMore,
		noData,
		orderItem
	},
	props: {
		nid: {
			type: [Number, String],
			default: ''
		},
		tabIndex: {
			type: [Number, String],
			default: ''
		},
		conditions: {
			type: Object,
			default: () => {}
		}
	},
	data() {
		return {
			dataList: [],
			navigateFlag: false,
			pulling: false,
			refreshing: false,
			refreshFlag: false,
			refreshText: '',
			isLoading: false,
			loadingText: '加载中...',
			isNoData: false,
			pulling: false,
			angle: 0,
			loadingMoreText: {
				contentdown: '',
				contentrefresh: '',
				contentnomore: ''
			},
			refreshIcon:
				'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAMAAABg3Am1AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAB5QTFRFcHBw3Nzct7e39vb2ycnJioqK7e3tpqam29vb////D8oK7wAAAAp0Uk5T////////////ALLMLM8AAABxSURBVHja7JVBDoAgDASrjqj//7CJBi90iyYeOHTPMwmFZrHjYyyFYYUy1bwUZqtJIYVxhf1a6u0R7iUvWsCcrEtwJHp8MwMdvh2amHduiZD3rpWId9+BgPd7Cc2LIkPyqvlQvKxKBJ//Qwq/CacAAwDUv0a0YuKhzgAAAABJRU5ErkJggg==',
			page: {
				page: '1',
				PAGESIZE: '10'
			},
			loadParams: {
				total: 0,
				totalPage: 1,
				isDone: false,
				isRefresh: false
			},
			condition: {
				page: 1,
				pagesize: 20
			},
			allCheck: false,
			totalAmount: 0
		};
	},
	computed: {
		...mapState(['sysinfo', 'userInfo'])
	},
	created() {
		this.pullTimer = null;
		this.requestParams = {
			columnId: this.nid,
			minId: 0,
			pageSize: 10,
			column: 'id,post_id,title,author_name,cover,published_at,comments_count'
		};

		this._isWidescreen = false;
		// #ifdef H5
		var mediaQueryOb = uni.createMediaQueryObserver(this);
		mediaQueryOb.observe(
			{
				minWidth: 768
			},
			(matches) => {
				this._isWidescreen = matches;
			}
		);
		// #endif
	},
	methods: {
		showConfirmation(message, confirmCallback, cancelCallback) {
			uni.showModal({
				title: '提示',
				content: message,
				showCancel: true,
				cancelText: '取消',
				cancelColor: '#000000',
				confirmText: '确认',
				confirmColor: '#3963bc',
				success: function (res) {
					if (res.confirm) {
						// 用户点击确定
						confirmCallback && confirmCallback();
					} else if (res.cancel) {
						// 用户点击取消
						cancelCallback && cancelCallback();
					}
				}
			});
		},
		async changeStatus(mode) {
			const data = this.dataList.filter((v) => v.checked);
			const str = '终端：' + data[0].terminal_name +'\r\n' +'折扣金额为：' + data[0].total_amount+'元。';
			this.showConfirmation(
				str,
				() => {
					console.log('用户点击了确认');
					// 这里执行确认后的逻辑
					this.submitBtn(mode, data);
				},
				() => {
					console.log('用户点击了取消');
					// 这里执行取消后的逻辑
				}
			);
		},
		async submitBtn(mode, data) {
			const params = {
				mode,
				user_bp: this.userInfo.code,
				role: 'WLY001',
				data
			};
			const res = await getSubmitDhk(params);
			uni.showToast({
				title: res.message,
				duration: 2000,
				icon: 'none'
			});
			if (res.msgtype === 'E') {
				return;
			}
			this.conditions.state[0].low = this.nid;
			this.refreshData();
		},
		// checkAll(){
		// 	this.totalAmount = 0
		// 	this.allCheck = !this.allCheck
		// 	 this.dataList.forEach((ele,idx) => {
		// 	      this.totalAmount += this.allCheck?(ele.total_amount-0):0
		// 		  this.$set(this.dataList,idx,{...this.dataList[idx],checked: this.allCheck})
		// 	    });
		// },
		changeTab() {
			// this.totalAmount = 0
			// this.allCheck = false
			this.dataList.forEach((ele, idx) => {
				this.$set(this.dataList, idx, { ...this.dataList[idx], checked: false });
			});
		},
		handleCheck(idx) {
			this.dataList.forEach((ele, idx) => {
				ele.checked = false;
			});
			this.$set(this.dataList, idx, { ...this.dataList[idx], checked: !this.dataList[idx].checked });
		},
		async loadData(refresh) {
			if (this.isLoading) {
				return;
			}
			this.isLoading = true;
			this.isNoData = false;
			this.requestParams.time = new Date().getTime() + '';
			const obj = JSON.parse(JSON.stringify(this.conditions));
			console.log(obj);
			const params = {
				...this.condition,
				...obj,
				user_bp: this.userInfo.code,
				role: 'WLY001'
			};
			params.fee_code[0].low = params.fee_code[0].low ? '*' + params.fee_code[0].low + '*' : delete params.fee_code;
			params.terminal_code[0].low = params.terminal_code[0].low ? '*' + params.terminal_code[0].low + '*' : delete params.terminal_code;
			params.product_code[0].low = params.product_code[0].low ? '*' + params.product_code[0].low + '*' : delete params.product_code;
			params.terminal_name[0].low = params.terminal_name[0].low ? '*' + params.terminal_name[0].low + '*' : delete params.terminal_name;
			params.product_name[0].low = params.product_name[0].low ? '*' + params.product_name[0].low + '*' : delete params.product_name;
			if (params.state[0].low === '3') {
				params.state = [
					{ sign: 'I', option: 'EQ', low: '2', high: '' },
					{ sign: 'I', option: 'EQ', low: '3', high: '' }
				];
			}
			!params.state[0].low && delete params.state;
			let res = null;
			res = await getDhk(params);
			if (res.msgtype == 'S') {
				this.isLoading = false;
				if (refresh) {
					this.refreshing = false;
					this.refreshFlag = false;
					this.refreshText = '已刷新';
					if (this.pullTimer) {
						clearTimeout(this.pullTimer);
					}
					this.pullTimer = setTimeout(() => {
						this.pulling = false;
					}, 1000);
				}
			} else {
				this.isNoData = true;
				this.refreshing = false;
				this.refreshFlag = false;
				this.isLoading = false;
				this.refreshText = '已刷新';
				this.dataList = [];
				return;
			}
			this.isNoData = res.data.length <= 0;
			this.loadParams.totalPage = Math.ceil(((res.total * 1) / this.condition.pagesize) * 1);
			if (refresh) {
				this.dataList = res.data;
				this.requestParams.minId = 0;
			} else {
				this.dataList = this.dataList.concat(res.data);
			}

			// if (this.dataList.length > 0 && this._isWidescreen && this.dataList.length <= 10) {
			// 	this.goDetail(this.dataList[0]);
			// }
		},
		loadMore(e) {
			if (this.condition.page < this.loadParams.totalPage) {
				this.condition.page++;
				this.loadData(false);
			} else {
				this.loadingText = '--已到底--';
			}
		},
		clear() {
			this.dataList.length = 0;
			this.requestParams.minId = 0;
		},
		goDetail(detail, type = null) {
			if (type) {
				uni.navigateTo({
					url: `/pages/purchase/purchase-apply?id=${detail.id}&sourceType=myPurchase`
				});
			}
		},
		refreshData() {
			if (this.isLoading) {
				return;
			}
			this.condition.page = 1;
			this.pulling = true;
			this.refreshing = true;
			this.refreshText = '正在刷新...';
			this.loadData(true);
		},
		onrefresh(e) {
			this.conditions.state[0].low = this.nid;
			this.refreshData();
			// #ifdef APP-NVUE
			// this.$refs.list.resetLoadmore();
			// #endif
		},
		onpullingdown(e) {
			if (this.refreshing) {
				return;
			}

			// var angle = (e.pullingDistance) / e.viewHeight * 180;
			// if (angle > 180) {
			// 	angle = 180;
			// }
			// tab.angle = angle;

			this.pulling = false;
			if (Math.abs(e.pullingDistance) > Math.abs(e.viewHeight)) {
				this.refreshFlag = true;
				this.refreshText = '释放立即刷新';
			} else {
				this.refreshFlag = false;
				this.refreshText = '下拉可以刷新';
			}
		},
		newGuid() {
			let s4 = function () {
				return ((65536 * (1 + Math.random())) | 0).toString(16).substring(1);
			};
			return (s4() + s4() + '-' + s4() + '-4' + s4().substr(0, 3) + '-' + s4() + '-' + s4() + s4() + s4()).toUpperCase();
		}
	}
};
</script>

<style lang="scss" scoped>
.no-data {
	flex: 1;
	position: absolute;
	left: 0;
	top: 0;
	right: 0;
	bottom: 0;
	z-index: 10;
}

.page-news {
	flex: 1;
	flex-direction: column;
	position: absolute;
	left: 0;
	top: 0;
	right: 0;
	bottom: 0;
}

.listview {
	position: absolute;
	left: 0;
	top: 0;
	right: 0;
	bottom: 0;
	/* #ifndef APP-NVUE */
	display: flex;
	flex-direction: column;
	/* #endif */
	/* #ifndef MP-ALIPAY */
	flex-direction: column;
	/* #endif */
}

.refresh {
	justify-content: center;
}

.refresh-view {
	/* #ifndef APP-NVUE */
	display: flex;
	/* #endif */
	width: 750rpx;
	height: 64px;
	flex-direction: row;
	flex-wrap: nowrap;
	align-items: center;
	justify-content: center;
}

.refresh-icon {
	width: 32px;
	height: 32px;
	transition-duration: 0.5s;
	transition-property: transform;
	transform: rotate(0deg);
	transform-origin: 15px 15px;
}

.refresh-icon-active {
	transform: rotate(180deg);
}

.loading-icon {
	width: 28px;
	height: 28px;
	margin-right: 5px;
	color: gray;
}

.loading-text {
	margin-left: 2px;
	font-size: 16px;
	color: #999999;
}

.loading-more {
	align-items: center;
	justify-content: center;
	padding-top: 14px;
	padding-bottom: 14px;
	text-align: center;
}

.loading-more-text {
	font-size: 12px;
	color: #999;
}
.bottom-box {
	position: fixed;
	display: flex;
	bottom: 0;
	left: 0;
	z-index: 10;
	width: 750rpx;
	height: 100rpx;
	justify-content: space-around;
	align-items: center;
	background: #fff;
	padding: 0 20rpx;
}
.bottom-btn {
	width: 328rpx;
	height: 92rpx;
	border-radius: 50%;
	justify-content: space-between;
	align-items: center;
}

.subBtn {
	background: $wly-primary-color;
	border: none;
	width: 120rpx;
	height: 60rpx;
	line-height: 60rpx;
}

.btn-text {
	color: #fff;
	font-size: 28rpx;
}
.empty-block {
	width: 750rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
}
.margin-bot {
	margin-bottom: 120rpx;
}
.red {
	color: #f61d30;
	font-size: 24rpx;
}
.font-sc {
	color: #333;
	font-size: 24rpx;
}
.flex-column {
	display: flex;
	flex-direction: column;
}
.check-box {
	::v-deep  .uni-checkbox-wrapper {
		margin-top: 14rpx;
		margin-right: 10rpx;
	}
}
</style>