<template>
	<view class="scoped-box">
		<wm-watermark :text="userInfo2.phone" :num="50"></wm-watermark>
		<u-navbar
			:customBack="customBack"
			back-icon-color="#fff"
			:title="`案场确客(${curTotal})`"
			:background="{ backgroundColor: '#2080f0' }"
			title-color="#fff"
			:border-bottom="false"
		></u-navbar>

		<!-- 顶部筛选栏 -->
		<HM-filterDropdown :menuTop="menuTop" :filterData="filterData" :defaultSelected="filterDropdownValue" @confirm="confirmFilter"></HM-filterDropdown>

		<view class="customer-list-wrap">
			<view v-if="customerList.length == 0" class="empty-wrap"><u-empty mode="list" text="请选择顶部的管理楼盘进行筛选"></u-empty></view>
			<view v-for="(item, index) in customerList" class="customer-item" :key="index">
				<view class="info" @click="listItemHandle(item)">
					<view class="customer">
						<view class="relname">
							{{ item.name }}
							<u-icon
								class="u-m-l-5"
								:name="item.sex == 'male' ? 'man' : 'woman'"
								size="28"
								:color="item.sex == 'male' ? '#2080f0' : '#f85f69'"
							></u-icon>
						</view>

						<view class="item">
							<u-icon class="u-m-r-5" name="phone" size="28"></u-icon>
							{{ item.phone }}
						</view>
						<view class="item">
							<u-icon class="u-m-r-5" name="home" size="28"></u-icon>
							{{ item.estate_name }}
						</view>
						<!-- <view class="item">
							<u-icon class="u-m-r-5" name="rmb" size="22"></u-icon>
							预期最高收益{{ item.commission }}元
						</view> -->
					</view>
					<view class="data-wrap">
						<view class="date u-m-t-5">报备时间：{{item.create_at}}</view>
						<view class="date" v-if="item.lock_at">保护期截止：{{item.lock_at}}</view>
					</view>
				</view>
				<view class="tool-wrap">
					<view class="tag">
						<u-tag
							:text="item.report_state == 3 ? '无效客户' : item.report_state == 2 ? '审核中' : '有效客户'"
							:type="item.report_state == 3 ? 'error' : item.report_state == 2 ? 'warning' : 'success'"
							size="mini"
							class="u-m-r-10"
						></u-tag>
						<u-tag
							v-if="item.report_state == 1"
							:text="stepList[item.report_step]"
							:type="Number(item.report_step) > 1 ? 'success' : 'warning'"
							size="mini"
						></u-tag>
					</view>
					 <!-- v-if="curRoles == 1 || curRoles == 3 || curRoles == 5 || curRoles == 6" -->
					<view class="scoped-list-more-info">
						<text @click="dial(item.create_user.phone)">报备人:{{item.create_user.nickname}}</text>
						<u-tag
							@click="copyTextHandle(item)"
							style="margin-left: 10px;"
							text="复制"
							type="primary"
							size="mini"
						></u-tag>
					</view>
					<view class="tool">
						<u-icon
							v-if="item.report_step <= 1 && item.expire_time == 0"
							name="reload"
							size="32"
							label="重新报备"
							label-size="24"
							@click="pageTo('/pages/agent/recommend/create', { info: item })"
						></u-icon>
					</view>
				</view>
			</view>
		</view>

		<view class="float-search" @click="searchPopupShow = true"><u-icon name="search" size="42" color="#fff"></u-icon></view>

		<!-- 平台佣金政策弹窗 -->
		<u-popup v-model="searchPopupShow" mode="center" width="80%" height="440rpx" border-radius="20">
			<view class="bwin-popup">
				<view class="popup-header">客户搜索</view>
				<view class="popup-body">
					<u-input v-model="searchFormData.name" border placeholder="请输入客户姓名(支持模糊搜索)"></u-input>
					<u-divider marginTop="10" marginBottom="10">或</u-divider>
					<u-input v-model="searchFormData.phone" border placeholder="请输入客户手机号(可仅输入一部分)"></u-input>
				</view>
				<view class="popup-footer" style="position: absolute;">
					<u-button size="medium" @click="searchPopupShow = false">取消</u-button>
					<u-button size="medium" type="primary" @click="searchHandle()">搜索</u-button>
				</view>
			</view>
		</u-popup>

		<u-loadmore
			v-if="customerList.length > 0"
			marginTop="32"
			:line="true"
			:status="loadmore.status"
			:loading-text="loadmore.loadingText"
			:loadmore-text="loadmore.defaultText"
			:nomore-text="loadmore.nomoreText"
		/>
	</view>
</template>
<script>
import wmWatermark from '@/components/wm-watermark/wm-watermark.vue'
import uniCopy from '@/js_sdk/xb-copy/uni-copy.js'
var that;
export default {
	components: {
		wmWatermark
	},
	data() {
		return {
			searchKeyword: null,
			searchPopupShow: false,
			searchFormData: {
				name: '',
				phone: ''
			}, // 搜索栏数据
			menuTop: 110, // 筛选栏距顶部距离
			filterData: [
				{
					name: '日期范围',
					type: 'hierarchy',
					submenu: [
						{
							name: '全部',
							value: 0
						},
						{
							name: '24小时内',
							value: 24
						},
						{
							name: '7天内',
							value: 168
						},
						{
							name: '30天内',
							value: 720
						}
					]
				},
				{
					name: '管理楼盘',
					type: 'hierarchy',
					submenu: [
						{
							name: '全部',
							value: 999
						}
					]
				},
				{
					name: '客户状态',
					type: 'hierarchy',
					submenu: [
						{
							name: '全部状态',
							value: 999
						},
						{
							name: '有效',
							value: 1
						},
						{
							name: '审核中',
							value: 2
						},
						{
							name: '无效',
							value: 3
						}
					]
				},
				{
					name: '客户进度',
					type: 'hierarchy',
					submenu: [
						{
							name: '全部进度',
							value: 999
						},
						{
							name: '未到访',
							value: 1
						},
						{
							name: '已到访',
							value: 2
						},
						{
							name: '已认购',
							value: 3
						},
						{
							name: '已签约',
							value: 4
						},
						{
							name: '已结佣',
							value: 5
						}
					]
				},
				{
					name: '排序',
					type: 'hierarchy',
					submenu: [
						{
							name: '时间近到远',
							value: 1
						},
						{
							name: '时间远到近',
							value: 2
						},
						// {
						// 	name: '预期佣金高到底',
						// 	value: 2
						// },
						// {
						// 	name: '预期佣金低到高',
						// 	value: 3
						// }
					]
				}
			],
			filterHours: 0,
			filterPropertyId: 999,
			filterVerifyStatus: 999,
			filterStepStatus: 999,
			orderMethod: 0,
			filterDropdownValue: {}, // 默认筛选
			customerList: [], // 客户列表
			stepList: ['审核中', '未到访', '已到访', '已认购', '已签约', '已结佣'],
			loadmore: {
				status: 'loadmore',
				loadingText: '努力加载中',
				defaultText: '轻轻上拉 查看更多',
				nomoreText: '实在没有了',
				currnetPage: 1
			},
			curRoles: '',
			userInfo2: {},
			curTotal: 0,
		};
	},
	onLoad(params) {
		that = this;
		// #ifdef H5
		that.menuTop = 88;
		// #endif
		// #ifdef MP
		let systemInfo = wx.getSystemInfoSync();
		//状态栏高度
		let statusBarHeight = Number(systemInfo.statusBarHeight);
		let menu = wx.getMenuButtonBoundingClientRect();
		//导航栏高度
		let navBarHeight = menu.height + (menu.top - statusBarHeight) * 2;
		//状态栏加导航栏高度
		let navStatusBarHeight = statusBarHeight + menu.height + (menu.top - statusBarHeight) * 2; // 现在是px

		let rpxHeight = parseInt((navStatusBarHeight * 750) / systemInfo.windowWidth);
		rpxHeight = Math.ceil(rpxHeight / 10) * 10;
		that.menuTop = rpxHeight;
		// console.log(that.menuTop);
		// #endif

		// 默认筛选项
		if (params.filterStepStatus !== undefined) {
			that.filterStepStatus = parseInt(params.filterStepStatus);
			this.filterDropdownValue = [[],[],[],[that.filterStepStatus],[]]
		}

		// 项目筛选
		
		// uni.api.estate.apiestatelist({page_size: 100}).then(res => {
		// 	let propertyList = res.list || []
		// 	if (propertyList.length > 0) {
		// 		that.filterData[1]['submenu'] = propertyList.map(function(val, index) {
		// 			return { name: val.estate_name, value: val.estate_id };
		// 		});
		// 		that.filterData[1]['submenu'].unshift({ value: 999, name: '全部' });
		// 	}
		// })
		
		this.getDataList()
		
		this.userInfo2 = uni.getStorageSync('MD_userInfo2')
		this.curRoles = uni.getStorageSync('MD_userInfo2') ? uni.getStorageSync('MD_userInfo2').roles : ''
		let propertyList = this.userInfo2.estate_govern || []
		if (propertyList.length > 0) {
			that.filterData[1]['submenu'] = propertyList.map(function(val, index) {
				return { name: val.estate_name, value: val.estate_id };
			});
			// that.filterData[1]['submenu'].unshift({ value: 999, name: '全部' });
		}
	},
	onReachBottom() {
		if (that.loadmore.status == 'nomore') return;
		that.loadmore.currnetPage++
		this.getDataList()
	},
	onPullDownRefresh() {
		// 防止频繁刷新
	},
	methods: {
		dial(tel) {
			uni.makePhoneCall({
				phoneNumber: tel
			});
		},
		listItemHandle (item) {
			if (item.report_state == 2) {
				// if (this.curRoles == 1 || this.curRoles == 5 || this.curRoles == 7) {
				// 	uni.$msgConfirm('当前客户报备审核中,是否前往审核？', () => {
				// 		uni.navigateTo({
				// 			url: `/pages/agent/recommend/check?id=${item.id}&name=${item.name}-${item.phone}`
				// 		})
				// 	})
				// } else {
				// 	uni.$msgConfirm('当前客户报备审核中~')
				// }
				uni.$msgConfirm('当前客户报备审核中,是否前往审核？', () => {
					uni.navigateTo({
						url: `/pages/agent/recommend/check?id=${item.id}&name=${item.name}&phone=${item.phone}&eid=${item.estate_id}`
					})
				})
			} else {
				uni.navigateTo({
					url: '/pages/agent/recommend/detailGovern?id=' + item.id
				})
			}
		},
		copyTextHandle (item) {
			// return
			uniCopy({
				content: `项目：${item.estate_name}
客户姓名：${item.name}${item.sex == 'male'?'先生':'女士'}
客户电话：${item.phone}
经纪人姓名：${item.create_user.nickname}
经纪人电话：${item.create_user.phone}
预计到访时间：尽快`,
				success:(res)=>{
					uni.showToast({
						title: res,
						icon: 'none'
					})
				},
				error:(e)=>{
					uni.showToast({
						title: e,
						icon: 'none',
						duration:3000,
					})
				}
			})
		},
		getDataList (bc) {
			const that = this
			let params = {
				...this.searchFormData
			}
			if (that.filterHours > 0) {
				let d = +new Date()
				params.start_at = parseInt((d - 1000 * 60 * 60 * that.filterHours) / 1000)
				params.end_at = parseInt(d / 1000)
			}
			if (that.filterVerifyStatus < 999) {
				params.report_state = that.filterVerifyStatus
			}
			if (that.filterStepStatus < 999) {
				params.report_step = that.filterStepStatus
			}
			if (that.filterPropertyId < 999) {
				params.estate_id = that.filterPropertyId
			}
			
			if (that.orderMethod > 0) {
				if (that.orderMethod === 1) {
					params.order_by = JSON.stringify([{
						field: 'create_at',
						sort: 'desc',
					}])
				}
				if (that.orderMethod === 2) {
					params.order_by = JSON.stringify([{
						field: 'create_at',
						sort: 'asc',
					}])
				}
			}
			uni.api.estate.apigovernlist({
				page: that.loadmore.currnetPage,
				...params,
			}).then(res => {
				this.curTotal = res.total || 0
				const list = res.list || []
				if (list.length < 10) {
					that.loadmore.status = 'nomore';
				}
				if (res.current_page === 1) {
					if (list.length === 0) {
						uni.$msg('无搜索结果', 'none');
					}
					that.customerList = [...list]
				} else {
					that.customerList = that.customerList.concat(list)
				}
				if (bc) bc()
			})
		},
		customBack() {
			// uni.navigateBack();
			uni.reLaunch({
				url: '/pages/index/index'
			})
		},
		// 带监听器跳转
		pageTo(url, data) {
			/// xxxxx
			uni.navigateTo({
				url: url,
				events: {
					// 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
					update: function(data) {
						// 当B页面运行 eventChannel.emit('update', { a:1 }); 时，会运行这里的代码逻辑。
					}
				},
				success: function(res) {
					// 通过eventChannel向被打开页面传送数据
					res.eventChannel.emit('data', data);
				}
			});
		},
		searchHandle() {
			this.loadmore.currnetPage = 1
			this.getDataList(() => {
				this.searchPopupShow = false
			})
		},
		// 筛选
		confirmFilter(e) {
			if (e['value'][0][0] !== null) that.filterHours = e['value'][0][0];
			if (e['value'][1][0] !== null) that.filterPropertyId = e['value'][1][0];
			if (e['value'][2][0] !== null) that.filterVerifyStatus = e['value'][2][0];
			if (e['value'][3][0] !== null) that.filterStepStatus = e['value'][3][0];
			if (e['value'][4][0] !== null) that.orderMethod = e['value'][4][0];

			that.loadmore.currnetPage = 1;
			this.getDataList()
		},
		getTime(n) {
			let date = n ? new Date(n) : new Date()
			let year = date.getFullYear()
			let month = date.getMonth() + 1
			month = month > 9 ? month : '0' + month
			let day = date.getDate()
			day = day > 9 ? day : '0' + day
			let hour = date.getHours()
			hour = hour > 9 ? hour : '0' + hour
			let minute = date.getMinutes()
			minute = minute > 9 ? minute : '0' + minute
			let second = date.getSeconds()
			second = second > 9 ? second : '0' + second
			return `${year}-${month}-${day} ${hour}:${minute}:${second}`
		},
	}
};
</script>
<style lang="scss">
.scoped-box {
	font-size: 30rpx;
}
.search-wrap {
	padding: 20rpx;
}

.filter-wrap {
	position: relative;
}

// 列表
.customer-list-wrap {
	margin-top: 80rpx;
	width: 100%;

	.customer-item {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		font-size: $u-p;
		color: $u-content-color;
		border-bottom: 1rpx solid $u-border-color;
		padding: 24rpx 32rpx;

		.info {
			display: flex;
			align-items: flex-start;
			justify-content: space-between;
			width: 100%;
			margin-bottom: 10rpx;

			.customer {
				display: flex;
				flex-direction: column;
				align-items: flex-start;

				.relname {
					color: $u-main-color;
					font-size: 34rpx;
					font-weight: bold;
					margin-bottom: 10rpx;
				}

				.item {
					margin-bottom: 10rpx;
				}
			}

			.data-wrap {
				text-align: right;
				.date {
					font-size: $u-sub;
				}
			}
		}

		.tool-wrap {
			display: flex;
			align-items: center;
			justify-content: space-between;
			width: 100%;
		}
	}
}

.float-search {
	opacity: 0.9;
	position: fixed;
	right: 20rpx;
	bottom: 40rpx;
	padding: 20rpx;
	border-radius: 50%;
	background-color: $u-theme-color;
}

.scoped-list-more-info {
	position: absolute;
	right: 20rpx;
	font-size: 24rpx;
}
</style>
