<template>
	<view>
		<!-- 新增客户跟进 -->
		<view class="follow_up">
			<view class="follow_content_title tixingBox"
				v-if="orderRemindDate1=='' || orderRemindDate1 == null || overdue == true">
				<image src="https://qufang.oss-cn-beijing.aliyuncs.com/upload/icon/xcx/jjycrm/ld.png" class="tixing1">
				</image>
				跟进提醒
				<view class="tixing" @tap="onClose">
					<text>设置</text>
				</view>
			</view>
			<view class="follow_content_title tixingBox" v-else>
				<image src="https://qufang.oss-cn-beijing.aliyuncs.com/upload/icon/xcx/jjycrm/ld.png" class="tixing1">
				</image>
				跟进提醒
				<view class="tixing active1" @tap="onClose1">
					<text>已设置</text>
				</view>
			</view>
			
			
			<!-- 最新状态 -->
			<view class="follow_up_list">
				<view class="follow_up_list_title">
					<image src="https://qufang.oss-cn-beijing.aliyuncs.com/upload/icon/xcx/jjycrm/index/xh.png"></image>
					<label>最新状态</label>
				</view>
				<view class="follow_up_list_label">
					<view v-for="(item, i) in sortList" :key="i" :class="'taga-item ' + (state===i?'active':'')"
						:data-state="i" @tap="tagChoose">
						{{item.stageName}}
					</view>
				</view>
			</view>
			
			<!-- 意向级别 -->
			<view class="follow_up_list" style="padding-bottom: 10rpx;">
				<view class="follow_up_list_title">
					<image src="https://qufang.oss-cn-beijing.aliyuncs.com/upload/icon/xcx/jjycrm/index/xh.png"></image>
					<label>意向级别</label>
				</view>
				<view class="follow_level_selection">
					<view class="assess-star">
						<view class="star-wrap">
							<view v-for="(item, index) in stars" :key="index" class="star-item" :data-index="index"
								@tap="starClick">
								<image v-if="item.flag==1"
									src="https://qufang.oss-cn-beijing.aliyuncs.com/upload/icon/xcx/jjycrm/index/index12.png">
								</image>
								<image v-else
									src="https://qufang.oss-cn-beijing.aliyuncs.com/upload/icon/xcx/jjycrm/index/index13.png">
								</image>
							</view>
						</view>
						<view class="star-desc" v-if="level==1">A级</view>
						<view class="star-desc" v-if="level==2">B级</view>
						<view class="star-desc" v-if="level==3">C级</view>
						<view class="star-desc" v-if="level==4">D级</view>
					</view>
				</view>
			</view>
			
			
			
			<!-- 客户类型 -->
			<view class="follow_up_list">
				<view class="follow_up_list_title">
					<image src="https://qufang.oss-cn-beijing.aliyuncs.com/upload/icon/xcx/jjycrm/index/xh.png"></image>
					<label>客户类型</label>
				</view>
				<view class="total" style="font-size: 22rpx;">
					<u-icon style="margin-right:14rpx" name="checkmark-circle-fill" color="#FD6B18"></u-icon>
					已选择<text style="color: #FD6B18;">{{chosedCustomer.length}}</text>个
				</view>
				<view class="list" @click="showList" :class="{chosed:chosedCustomer.length>0}">
					<view v-for="(item, i) in chosedCustomerType" :key="i" class="taga-item"
						:class="{active:chosedCustomer.includes(item.keywords)}">
						{{item.keywords}}
					</view>
				</view>
				<view class="more" @click="showList">
					选择更多
				</view>
			</view>
			
			
			
			
			<!-- 跟进内容 -->
			<view class="follow_content">
				<view class="follow_content_title">
					跟进内容
					<em>（{{feedbackContent.length}}/50）</em>
				</view>
				<textarea v-show="!customerTypeShow" class="follow_content_textarea" v-if="show==false"
					:value="feedbackContent" maxlength="50" @input="note" placeholder="请输入跟进内容,按话筒按钮可以语音识别"
					placeholder-class="place"></textarea>
				<!-- <image class="voice" @click="changeVoiceShow" src="/static/images/yuyin.png" mode="widthFix"></image> -->
			</view>

			<view :class="'follow_btn ' + (value!=='' && state!== '' && level !==''  ?'follow_btn_active':'')"
				@tap="ok">
				保存
			</view>
			
			
		</view>
		<!-- 提醒 -->
		<view class="mask" v-if="show==true" @tap="timeClose"></view>
		<view class="time-box" v-if="show==true">
			<view class="time-text">
				{{year}}-{{month}}-{{day}} {{hour}}:{{minute}}
				<view class="time-sure" @tap="timeSure">确定</view>
				<view class="time-sure" style="float:left" @tap="timeClose">取消</view>
			</view>
			<view class="time-title-box">
				<view class="time-title">年</view>
				<view class="time-title">月</view>
				<view class="time-title">日</view>
				<view class="time-title">时</view>
				<view class="time-title">分</view>
			</view>
			<picker-view indicator-style="height: 50px;"
				style="width: 100%; height: 300px;display: flex;background:#fff;" :value="value" @change="bindChange">
				<picker-view-column class="picker-text">
					<view v-for="(item, index) in years" :key="index" style="line-height: 50px">{{item}}</view>
				</picker-view-column>
				<picker-view-column class="picker-text">
					<view v-for="(item, index) in months" :key="index" style="line-height: 50px">{{item}}</view>
				</picker-view-column>
				<picker-view-column class="picker-text">
					<view v-for="(item, index) in days" :key="index" style="line-height: 50px">{{item}}</view>
				</picker-view-column>
				<picker-view-column class="picker-text">
					<view v-for="(item, index) in hours" :key="index" style="line-height: 50px">{{item}}</view>
				</picker-view-column>
				<picker-view-column class="picker-text">
					<view v-for="(item, index) in minutes" :key="index" style="line-height: 50px">{{item}}</view>
				</picker-view-column>
			</picker-view>
		</view>
		<cover-view class="voiceContent" v-if="voiceShow" @click="changeVoiceShow">
			<cover-view class="box" @click.stop="" @touchstart="voiceStart" @touchend="voiceEnd">
				<cover-view class="center">
					<cover-image class="voice" src="/static/images/voice.png" mode="widthFix"></cover-image>
					<cover-view class="text">
						{{isRecording?'正在输入':'长按语音输入'}}
					</cover-view>
				</cover-view>
			</cover-view>
		</cover-view>
		<u-popup v-model="customerTypeShow" mode="center" border-radius="22" width="690" height="785">
			<view class="customerTypePopup">
				<view class="search">
					<input class="input" type="text" v-model="customerTypeSearch" />
				</view>
				<scroll-view class="list" :scroll-y="true">
					<view v-for="(item,index) in filterCustomerList" :key="index"
						@click="choseCustomerName(item.keywords)" class="item"
						:class="{active:chosedCustomerTmp.includes(item.keywords)}">
						{{item.keywords}}
					</view>
				</scroll-view>
				<view class="save" @click="saveCustomerType">
					保存
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	var util = require("../../../../utils/util.js");
	var config = require("../../../../config");
	var plugin = requirePlugin("WechatSI")
	let manager = plugin.getRecordRecognitionManager();
	var WXB_SESSION_LOGIN_DATA = 'weapp_session_login_data';
	var app = getApp(); // 定义年、月、日、时、分的数组都为空
	// 定义年、月、日、时、分的数组都为空
	const date = new Date();
	const years = [];
	const months = [];
	const days = [];
	const hours = [];
	const minutes = [];
	var thisMon = date.getMonth();
	var thisDay = date.getDate(); // 获取年
	// 获取日期
	var totalDay = mGetDate(date.getFullYear(), thisMon);
	// 获取年
	for (let i = 0; i <= date.getFullYear() + 1; i++) {
		years.push(i)
	}
	// 获取月份
	for (let i = 0; i <= 11; i++) {
		var k = i;
		if (0 <= i && i < 9) {
			k = "0" + (i + 1);
		} else {
			k = (i + 1);
		}
		months.push(k)
	}
	if (0 <= thisMon && thisMon < 9) {
		thisMon = "0" + (thisMon + 1);
	} else {
		thisMon = (thisMon + 1);
	}
	if (0 <= thisDay && thisDay < 10) {
		thisDay = "0" + thisDay;
	}
	// 获取日期
	var totalDay = mGetDate(date.getFullYear(), thisMon);
	for (let i = 1; i <= 31; i++) {
		var k = i;
		if (0 <= i && i < 10) {
			k = "0" + i
		}
		days.push(k)
	}
	// 获取小时
	for (let i = 0; i <= 23; i++) {
		var k = i;
		if (0 <= i && i < 10) {
			k = "0" + i
		}
		hours.push(k)
	}
	// 获取分钟
	for (let i = 0; i <= 59; i++) {
		var k = i;
		if (0 <= i && i < 10) {
			k = "0" + i
		}
		minutes.push(k)
	}
	// 给新的日期赋值
	function mGetDate(year, month) {
		var d = new Date(year, month, 0);
		return d.getDate();
	}

	export default {
		data() {
			return {
				isokColor: false,
				sortList: [],
				starDesc: '',
				stars: [{
					lightImg: 'https://qufang.oss-cn-beijing.aliyuncs.com/upload/icon/xcx/jjycrm/index/index12.png',
					blackImg: 'https://qufang.oss-cn-beijing.aliyuncs.com/upload/icon/xcx/jjycrm/index/index13.png',
					flag: 1,
					message: 'A',
					level: 1
				}, {
					lightImg: 'https://qufang.oss-cn-beijing.aliyuncs.com/upload/icon/xcx/jjycrm/index/index12.png',
					blackImg: 'https://qufang.oss-cn-beijing.aliyuncs.com/upload/icon/xcx/jjycrm/index/index13.png',
					flag: 1,
					message: 'B',
					level: 2
				}, {
					lightImg: 'https://qufang.oss-cn-beijing.aliyuncs.com/upload/icon/xcx/jjycrm/index/index12.png',
					blackImg: 'https://qufang.oss-cn-beijing.aliyuncs.com/upload/icon/xcx/jjycrm/index/index13.png',
					flag: 1,
					message: 'C',
					level: 3
				}, {
					lightImg: 'https://qufang.oss-cn-beijing.aliyuncs.com/upload/icon/xcx/jjycrm/index/index12.png',
					blackImg: 'https://qufang.oss-cn-beijing.aliyuncs.com/upload/icon/xcx/jjycrm/index/index13.png',
					flag: 1,
					message: 'D',
					level: 4
				}],
				state: null,
				feedbackContent: "",
				level: "",
				customerId: "",
				// 提醒
				years: years,
				year: date.getFullYear(),
				months: months,
				month: thisMon,
				days: days,
				day: thisDay,
				value: [date.getFullYear(), date.getMonth(), Number(date.getDate() - 1), Number(date.getHours()), Number(
					date.getMinutes())],
				hours: hours,
				hour: date.getHours(),
				minutes: minutes,
				minute: date.getMinutes(),
				show: false,
				overdue: false,
				code: "",
				orderRemindDate: "",
				orderRemindDate1: "",
				allItem: 0,
				item: 0,
				voiceShow: false,
				isRecording: false,
				customerType: [],
				customerTypeShow: false,
				customerTypeSearch: "",
				chosedCustomer: [],
				chosedCustomerTmp: [],
			};
		},
		onLoad(e) {
			// console.log(e,'123')
			const that = this;
			uni.login({
				success(res) {
					if (res.code) {
						// that.setData({
						// 	code: res.code
						// });
					} else {
						console.log('登录失败！' + res.errMsg);
					}
				}
			});
			var customerId = e.id;
			var day = Number(date.getDate()) < 10 ? '0' + date.getDate() : date.getDate();
			var moth = Number(date.getMonth() + 1) < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
			var hour = Number(date.getHours()) < 10 ? '0' + date.getHours() : date.getHours();
			var min = Number(date.getMinutes()) < 10 ? '0' + date.getMinutes() : date.getMinutes();
			this.setData({
				customerId: customerId,
				orderRemindDate: date.getFullYear() + '-' + moth + '-' + day + ' ' + hour + ':' + min,
				orderRemindDate1: e.followRemindDate,
				hour: hour,
				minute: min
			});

			if (e.followRemindDate) {
				var setData = new Date(e.followRemindDate).getTime();
				var newData = new Date().getTime();

				if (setData < newData) {
					this.setData({
						overdue: true
					});
				} else {
					this.setData({
						overdue: false
					});
				}
			}
			this.getNewStatus();
			this.getCustomerType();
		},
		onShow() {
			this.initRecord();
		},

		methods: {
			setData: function(obj) {
			      let that = this;
			      let keys = [];
			      let val, data;
			      Object.keys(obj).forEach(function(key) {
			        keys = key.split(".");
			        val = obj[key];
			        data = that.$data;
			        keys.forEach(function(key2, index) {
			          if (index + 1 == keys.length) {
			            that.$set(data, key2, val);
			          } else {
			            if (!data[key2]) {
			              that.$set(data, key2, {});
			            }
			          }
			          data = data[key2];
			        });
			      });
			    },
			getCustomerType() {
				this.$u.get("/customer/queryKeyWords").then(res => {
					this.customerType = res;
				})
			},
			showList() {
				this.chosedCustomerTmp = this.chosedCustomer;
				this.customerTypeShow = true;
			},
			choseCustomerName(name) {
				const tmp = new Set(this.chosedCustomerTmp);
				if (tmp.has(name)) {
					tmp.delete(name)
				} else {
					tmp.add(name)
				}
				this.chosedCustomerTmp = Array.from(tmp);
			},
			saveCustomerType() {
				this.chosedCustomer = this.chosedCustomerTmp;
				this.customerTypeShow = false;
			},
			changeVoiceShow() {
				this.voiceShow = !this.voiceShow;
			},
			voiceStart: function() {
				manager.start({
					lang: "zh_CN"
				});
			},
			voiceEnd: function() {
				if (this.isRecording) {
					uni.showLoading({
						title: "识别中"
					})
				}

				this.voiceShow = false;
				this.isRecording = false;
				manager.stop();
			},
			initRecord() {
				const that = this;
				manager.onStart = function(res) {
					console.log(res.msg);
					that.isRecording = true;
					// this.voiceState = "onStart:" + res.msg + "正在录音"
				};
				//有新的识别内容返回，则会调用此事件  
				manager.onRecognize = (res) => {
					console.log('ing' + res.result);
				}

				// 识别结束事件  
				manager.onStop = (res) => {
					uni.hideLoading();
					let newText = that.feedbackContent + res.result;
					if (newText.length > 50) {
						newText = newText.substring(0, 50)
					}
					that.feedbackContent = newText;
				}

				// 识别错误事件  
				manager.onError = (res) => {
					uni.hideLoading();
					console.error(res.msg)
					// this.voiceState = "onError" + res.msg;

				}
			},
			// 关闭提醒
			timeClose() {
				this.setData({
					show: false,
					years: years,
					year: date.getFullYear(),
					months: months,
					month: thisMon,
					days: days,
					day: thisDay,
					value: [date.getFullYear(), date.getMonth(), date.getDate() - 1, date.getHours(), date
						.getMinutes()
					],
					hours: hours,
					hour: date.getHours(),
					minutes: minutes,
					minute: date.getMinutes()
				});
			},

			// 打开提醒
			onClose() {
				const that = this; // 检测是否已经授权，有授权直接弹窗，没授权弹出授权

				uni.getSetting({
					withSubscriptions: true,

					success(res) {
						console.log(res);

						if (res && res.subscriptionsSetting && res.subscriptionsSetting.itemSettings && res
							.subscriptionsSetting
							.itemSettings['cBnJvhkMPHp0ReUiSdpM_Pd2usGeEEW6wx-5s6X4hEI'] == 'accept') {
							that.setData({
								show: true
							});
						} else {
							uni.requestSubscribeMessage({
								tmplIds: ['cBnJvhkMPHp0ReUiSdpM_Pd2usGeEEW6wx-5s6X4hEI'],

								success(res) {
									that.setData({
										show: true
									});
								},

								fail(res) {
									console.log(res);
									util.showNone("请授权");
								}

							});
						}
					},

					fail(res) {
						console.log(res);
					}

				});
			},

			onClose1() {
				util.showNone(this.orderRemindDate1);
			},

			timeSure() {
				var that = this;
				var params = {
					customerId: that.customerId,
					followRemindTime: that.orderRemindDate + ':00',
					code: that.code
				};
				util.getRequestPromise(config.service.updateByPrimaryKey, params).then(data => {
					uni.showToast({
						title: '操作成功'
					});
					var data = that.orderRemindDate + ':00';
					var setData = new Date(data).getTime();
					var newData = new Date().getTime();
					console.log(setData, newData);

					if (setData < newData) {
						this.setData({
							overdue: true
						});
					} else {
						this.setData({
							overdue: false
						});
					}

					this.setData({
						show: false,
						value: [this.year, Number(this.month) - 1, Number(this.day) - 1, this.hour, this
							.minute
						],
						orderRemindDate1: that.orderRemindDate + ':00'
					});
				});
			},

			// 获取新的日期和时间
			bindChange: function(e) {
				const val = e.detail.value;
				this.setData({
					year: this.years[val[0]],
					month: this.months[val[1]],
					day: this.days[val[2]],
					hour: this.hours[val[3]],
					minute: this.minutes[val[4]],
					orderRemindDate: this.years[val[0]] + '-' + this.months[val[1]] + '-' + this.days[val[2]] +
						' ' + this.hours[
							val[3]] + ':' + this.minutes[val[4]]
				});
			},
			// 最新状态
			tagChoose: function(options) {
				var that = this;
				var state = options.currentTarget.dataset.state;
				that.setData({
					'state': state
				});
			},
			// 意向级别
			starClick: function(e) {
				var that = this;

				for (var i = 0; i < that.stars.length; i++) {
					var allItem = 'stars[' + i + '].flag';
					that.setData({
						[allItem]: 1
					});
				}

				var index = e.currentTarget.dataset.index;

				for (var i = 0; i <= index; i++) {
					var item = 'stars[' + i + '].flag';
					that.setData({
						[item]: 2
					});
				}

				this.setData({
					starDesc: this.stars[index].message,
					level: this.stars[3 - index].level
				});
			},
			// textarea
			note: function(e) {
				this.feedbackContent = e.detail.value
			},
			getNewStatus: function() {
				var that = this;
				let premo={
					houseId:uni.getStorageSync('buildingID').id
				}
				util.getRequestPromise(config.service.getStage, premo).then(data => {
					this.sortList = data;
				});
			},
			//提交
			ok(){
				var that = this;
				var state = that.state;
				var feedbackContent = that.feedbackContent;
				var level = that.level;
				var customerId = that.customerId;
				if (state === null || this.chosedCustomer.length == 0 || level === "") {
					uni.showModal({
						title: '提示',
						content: '请选择状态、级别、类型',
						showCancel: false
					});
					return;
				}
				uni.showLoading({
					title: "保存中~",
					mask: true
				})
				const chosedState = this.sortList[state];
				var param = {
					"stageCode": chosedState.stageCode,
					"stageName": chosedState.stageName,
					"remarks": feedbackContent,
					words: this.chosedCustomer,
					// "settingTime":"",
					"agentRelationPo": {
						"customerId": customerId,
						"level": level,
						"state": chosedState.id
					}
				}

				util.getRequestPromise(config.service.followRecord, param, true).then(data => {
					util.showSuccess("提交成功");
					uni.hideLoading();
					uni.navigateBack();
				});
			}
		},
		
		
		computed: {
			filterCustomerList() {
				return this.customerType.filter(item => {
					return item.keywords.includes(this.customerTypeSearch)
				});
			},
			chosedCustomerType() {
				if (this.chosedCustomer.length > 0) {
					return this.customerType.filter(item => {
						return this.chosedCustomer.includes(item.keywords)
					})
				} else {
					return this.customerType
				}
			}
		},
	};
</script>
<style lang="scss" scoped>
	@import "./newFollowup.css";

	.voiceContent {
		position: fixed;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		width: 100vw;
		height: 100vh;
		display: flex;
		justify-content: center;
		align-items: center;
		background: rgba(30, 30, 30, 0.4592);
		z-index: 10001;
	}

	.box {
		background: rgba(21, 144, 233, 0.299);
		width: 524upx;
		height: 524upx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;

		.center {
			width: 412upx;
			height: 412upx;
			background: #1590E9;
			border-radius: 50%;
			display: flex;
			align-items: center;
			justify-content: center;
			flex-direction: column;

			.voice {
				width: 110upx;
				height: 133upx;
			}

			.text {
				color: #FFFFFF;
				font-size: 36upx;
				margin-top: 24upx;
			}
		}
	}

	.follow_up_list {
		.total {
			font-size: 22rpx;
			margin-top: 20rpx;
			line-height: 1;
		}

		.list {
			display: flex;
			font-size: 22rpx;
			flex-wrap: wrap;
			margin: 0 -30rpx;
			padding: 0 15rpx;
			max-height: calc(3em + 90rpx + 66rpx);
			overflow: hidden;

			&.chosed {
				max-height: unset;
			}

			.taga-item {
				line-height: 1;
				padding: 11rpx 33rpx;
				color: #333333;
				background: rgba(136, 136, 136, 0.1);
				border: 1rpx solid rgba(232, 103, 17, 0);
				border-radius: 6rpx;
				margin: 15rpx;

				&.active {
					background: rgba(253, 84, 43, 0.1);
					border: 1rpx solid rgba(232, 103, 17, 0.5) !important;
					color: #FD6D2B !important;
				}
			}
		}

		.more {
			text-align: center;
			color: #999999;
			font-size: 22rpx;
			position: relative;
			top: 4rpx;
		}
	}

	.customerTypePopup {
		width: 100%;
		height: 100%;

		.search {
			padding: 25rpx;

			.input {
				box-sizing: border-box;
			}
		}

		.list {
			height: calc(100% - 200rpx);
			display: flex;
			flex-wrap: wrap;
			padding: 0 15rpx;
			overflow: hidden;

			.item {
				line-height: 1;
				padding: 11rpx 33rpx;
				color: #333333;
				background: rgba(136, 136, 136, 0.1);
				border: 1rpx solid rgba(232, 103, 17, 0) !important;
				border-radius: 6rpx;
				margin: 15rpx;
				display: inline-flex;

				&.active {
					background: rgba(253, 84, 43, 0.1) !important;
					border: 1rpx solid rgba(232, 103, 17, 0.5) !important;
					color: #FD6D2B !important;
				}
			}
		}

		.save {
			background: #2B6EFD;
			width: 600rpx;
			height: 78rpx;
			line-height: 78rpx;
			text-align: center;
			margin: 0 auto;
			border-radius: 17rpx;
			font-size: 36rpx;
			color: #FFFFFF;
		}
	}
</style>
