<template>
	<div class="psychologicalScale-list"
  :style="`padding-top: ${showLeftArrow ? '10vw' : '0'};`">
		<van-nav-bar
			title="测评记录"
			:border="true"
			:left-arrow="true"
			@click-left="onNavBack"
			v-if="showLeftArrow"
      style="position: fixed; left: 0; top: 0;width: 100vw;"
		>
			<template #left>
				<van-icon name="arrow-left" size="23" style="padding: 0" />返回
			</template>
		</van-nav-bar>
		<div class="content" v-if="result.length">
			<div
				class="item"
				v-for="(item, index) in result"
				:key="index"
				@click="toDetail(item)"
			>
				<div class="left">
					<div class="name">{{ item.ScaleName }}</div>
          <div class="result">
						<span>评测结果：</span>
						<span>{{ item.Summary }}</span>
					</div>
					<div class="time">
						{{ formateDate('yyyy年mm月dd日 HH:MM', item.Time) }}
					</div>
				</div>
				<div class="right">
					<div class="button">查看结果</div>
				</div>
			</div>
      <div class="over">-- 没有更多了 --</div>
		</div>
		<div class="blank" v-else>暂无测评记录</div>
	</div>
</template>

<script>
import axios from 'axios'
import APICore from '@/api/core'

export default {
	name: 'PsychologicalScaleList',
	data() {
		return {
			uid: '',
			isError: null, //是否是答题错误
			showLeftArrow: false,
			fromSsjl: this.$store.getters.fromSsjl,
			result: [],
		}
	},
	computed: {
	},
	watch: {},
	mounted() {
		//页面标题
		window.document.title = '测评记录'

		//页面传参
		let params = { ...this.$route.query }

		if (params.uid) {
			this.uid = params.uid

			// 缓存从随手精灵传过来的token
			this.$store.commit('ssjlToken', params.accessToken || '')
			if (params.appType) {
				this.$store.commit('appType', params.appType)
			}
			// 缓存从随手精灵传过来的标识
			this.$store.commit('fromSsjl', params.fromSsjl)
			// 是否显示 返回标签
			if (params.showLeftArrow) {
				this.showLeftArrow = true
			}
			this.fromUrl = params.fromUrl
			console.log('fromUrl', this.fromUrl)

			//初始化
			this.init()
		} else {
			this.$toast('参数错误')
		}
	},
	methods: {
		async init() {
			if (!this.$route.query.accessToken) {
				//  如果当前url没有 accessToken， 获取token,并且存储到本地缓存里面
				let authToken = await this.getAuth()
				this.$store.commit('ssjlToken', authToken)
			}

			this.$toast.loading({
				message: '',
				forbidClick: true,
				duration: 0,
			})

			let re = await this.api(
				'/api/Question/GetScaleFillingRecord',
				{
					method: 'GET',
					sslVerify: false,
					withCredentials: false,
					params: {
						uid: this.uid,
					},
				},
				this.$store.getters.ssjlToken
			)
			if (re.success) {
				if (re.response && re.response.length) {
					this.result = re.response
				} else {
					// this.$toast('暂无测评结果')
				}
			} else {
				this.$toast(re.msg)
			}
		},
		toDetail(item) {
			this.$router.push({
				name: 'PsychologicalScaleDetail',
				query: {
					id: item.Id,
					uid: this.uid,
					accessToken: this.$store.getters.ssjlToken,
					showLeftArrow: 1,
				},
			})
		},
		onNavBack() {
			let fromSsjl = this.$store.getters.fromSsjl === 'true'
			if (fromSsjl) {
				let baseUrl = this.fromUrl
				window.location.href = `${baseUrl}/#/${
					this.$route.query.fromMenu || 'device'
				}`
			} else {
				window.history.go(-1)
			}
		},
		// 获取b端token
		getAuth() {
			let manufactorId = '5bf13062-a41e-4d00-ba14-1101aad12650'
			let that = this
			return new Promise((resolve, reject) => {
				APICore.getAuth({ manufactorId: manufactorId }).then((res) => {
					let data = res.data
					if (data.code === 0) {
						resolve(res.data.data)
					} else {
						that.$toast.fail(`${data.message}`)
						reject('')
					}
				})
			})
		},
		api(url, config, token) {
			setTimeout(() => {
				this.$toast.loading({
					message: '',
					forbidClick: true,
					duration: 1500,
				})
			}, 100)
			let baseUrl =
				process.env.NODE_ENV === 'production'
					? 'https://dbmq.rzliot.com/auth_heart'
					: 'https://dbmq.rzliot.com/heart'
			return new Promise((res) => {
				axios({
					url: `${baseUrl}${url}`,
					...config,
					// 增加请求头部 token
					headers: {
						AccessToken: token,
					},
				})
					.then((re) => {
						if (re) {
							if (re.data) {
								console.log(re.data)
								res(re.data)
								this.$toast.clear()
								return
							}
							this.$toast(`信息获取失败-${re.status}`)
							res(true)
							this.$toast.clear()
							return
						}
						this.$toast(`信息获取失败-${url}`)
						res(true)
						this.$toast.clear()
					})
					.catch((e) => {
						this.$toast(`信息获取失败-${url}`)
						res(true)
						this.$toast.clear()
						console.log(e)
					})
			})
		},
		formateDate(fmt = 'yyyy-mm-dd', date = '') {
			if (!date) {
				date = new Date()
			}

			try {
				if (typeof date == 'string') {
					date = date.replace(/-/g, '/').replace(/T/g, ' ')
					if (date.indexOf('/') == -1) {
						date = new Date(parseFloat(date))
					}
					date = new Date(date)
				} else if (typeof date == 'number') {
					date = new Date(date)
				}
			} catch (error) {
				console.log('时间格式化出错', error)
				date = new Date()
			}

			let ret
			let weak = (function (date) {
				let days = date.getDay()
				let weekArrTxt = [
					'星期天',
					'星期一',
					'星期二',
					'星期三',
					'星期四',
					'星期五',
					'星期六',
				]
				let weekArrTxt2 = [
					'周日',
					'周一',
					'周二',
					'周三',
					'周四',
					'周五',
					'周六',
				]
				return [weekArrTxt[days], weekArrTxt2[days]]
			})(date)
			const opt = {
				'y+': date.getFullYear().toString(), // 年
				'm+': (date.getMonth() + 1).toString(), // 月
				'd+': date.getDate().toString(), // 日
				'H+': date.getHours().toString(), // 时
				'M+': date.getMinutes().toString(), // 分
				'S+': date.getSeconds().toString(), // 秒
				// 有其他格式化字符需求可以继续添加，必须转化成字符串
				'W+': weak[0],
				'w+': weak[1],
			}
			for (let k in opt) {
				ret = new RegExp('(' + k + ')').exec(fmt)
				if (ret) {
					fmt = fmt.replace(
						ret[1],
						ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
					)
				}
			}
			return fmt
		},
	},
}
</script>

<style lang="scss">
.psychologicalScale-list {
	width: 100vw;
	min-height: 100vh;
	box-sizing: border-box;
	font-size: 3.6vw;
	text-align: left;
	background: #f4f4f4;
	padding-bottom: 8vw;

  .van-nav-bar__content {
		height: 10vw !important;

		.van-nav-bar__left,
		.van-nav-bar__title {
			font-size: 4vw !important;
			line-height: initial !important;

			.van-icon-arrow-left {
				font-size: 4vw !important;
			}
		}
	}

	.content {
		padding: 2vw;

		.item {
			display: flex;
			align-items: flex-end;
			justify-content: space-between;
      padding: 4vw;
			margin-top: 2vw;
			border-radius: 1vw;
			background: white;

      .left{

        .name{
          font-size: 4vw;
          font-weight: bold;
        }
        .time{
          color: gray;
          margin-top: 4vw;
        }
        .result{
          font-size: 3.8vw;
          margin-top: 4vw;
        }
      }
      .right{

        .button{
          color: #15C6BE;
          padding: 2vw 3vw;
          border-radius: 8vw;
          border: 1px solid #15C6BE;

          &:active{
            background-color: rgba($color: #15C6BE, $alpha: 0.1);
          }
        }
      }
		}
    .over{
      margin-top: 3vw;
      width: 100%;
      color: gray;
      text-align: center;
    }
	}

	.blank {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 80vh;
		color: gray;
		font-size: 5vw;
		font-weight: bold;
		letter-spacing: 5px;
	}
}
</style>
