<template>
	<view class="main">
		<uni-forms class="form" ref="form" :rules="rules" :modelValue="form" label-position="top" label-width='100'>
			<uni-forms-item label="退款理由(必填)" required name="content">
				<uni-easyinput type="textarea" v-model="form.content" placeholder="请输入退款理由" />
			</uni-forms-item>
			<uni-forms-item label="上传图片0/3(选填)" name="file">
				<upload class='upload' :list="form.file" name="file" :count="3" @uplSuc="uplSuc" @uplDel="uplDel">
				</upload>
			</uni-forms-item>
			<uni-forms-item label="联系方式(选填)" name="phone">
				<uni-easyinput v-model="form.phone" placeholder="请输入您的手机号" />
			</uni-forms-item>
		</uni-forms>
		<button class="button" type="primary" @click="submit('form')">提交</button>
	</view>
</template>

<script>
	import upload from '../../components/upload/index.vue';
	export default {
		components: {
			upload
		},
		data() {
			return {
				user: {},
				form: {
					file: []
				},
				// 校验规则
				rules: {
					content: {
						rules: [{
							required: true,
							errorMessage: '请输入建议描述'
						}]
					},
				},
			}
		},
		onLoad: function(e) {
			const that = this;
			that.searchToken();
		},
		methods: {
			searchToken() {
				const that = this;
				try {
					const res = uni.getStorageSync('token');
					if (res) {
						that.$set(that, `user`, res);
					}
				} catch (e) {
					uni.showToast({
						title: err.errmsg,
						icon: 'error',
						duration: 2000
					});
				}
			},
			// 图片上传
			uplSuc(e) {
				const that = this;
				that.$set(that.form, `${e.name}`, [...that.form[e.name], e.data]);
			},
			// 图片删除
			uplDel(e) {
				const that = this;
				let data = that.form[e.name];
				let arr = data.filter((i, index) => index != e.data.index);
				that.$set(that.form, `${e.name}`, arr)
			},
			submit(ref) {
				const that = this;
				that.$refs[ref].validate().then(async data => {
					data.user = that.user._id
					const res = await that.$api(`/opinion`, 'POST', data);
					if (res.errcode == '0') {
						uni.showToast({
							title: '意见反馈成功',
							icon: 'none'
						})
						uni.navigateBack({
							delta: 1
						})
					} else {
						uni.showToast({
							title: res.errmsg,
							icon: 'none'
						})
					}
				}).catch(err => {
					console.log('err', err);
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.main {
		padding: 4vw;

		.form-item {
			display: flex;
			align-items: center;
		}

		.button {
			background-color: var(--f3CColor);
		}
	}
</style>