<template>
	<view class="content">
		<view class="top">
			<img src="../../static/首页海报图.jpg" class="topImg"/>
			<br />
			<h2 style="color: white; margin-top: 2%;">膳食管理科意见征集</h2>
			<text style="color: white">{{title}}</text>
		</view>
		<br />
		<view style="padding-left: 1rem;">
			<text style="color: white;">所属园区：</text>
			<a-dropdown-button @click="handleButtonClick">
			  总公司园区
			  <template #overlay>
				<a-menu @click="handleMenuClick">
				  <a-menu-item key="1">
					<UserOutlined />
					总公司园区
				  </a-menu-item>
				</a-menu>
			  </template>
			  <template #icon><down-outlined /></template>
			</a-dropdown-button>
		</view>
		<view class="formStyle">
			<a-form
				:model="formState"
				name="basic"
				:label-col="{ span: 8 }"
				:wrapper-col="{ span: 16 }"
				autocomplete="off"
				width="95%"
			  >
				<a-form-item
				  label="问题描述(必填)"
				  name="advice"
				  :rules="[{ required: true, message: '意见不能为空' }]">
				  <a-textarea
					  placeholder="请写下您的建议或意见, 我们会努力改进"
				      v-model:value="formState.advice" 
					  :rows="4" 
					  class="textAreaStyle"
					  @input="onAdviceChange"/>
				</a-form-item>
			
				<a-form-item
				  label="上传图片(最多三张)"
				  name="password"
				>
				  <div class="clearfix">
				    <a-upload
						multiple=true
						maxCount="3"
				        v-model:file-list="myfileList"
						@change="handleChange"
				        list-type="picture-card"
						@preview="handlePreview"
						@remove="handleRemove">
				          <div v-if="myfileList.length < 3">
				            <plus-outlined />
				          </div>
				    </a-upload>
				    <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
				        <img alt="example" style="width: 100%" :src="previewImage" />
				    </a-modal>
				  </div>
				</a-form-item>
			</a-form>				
			<div class=test>
				<a-button
					shape="round"
					type="primary" 
					@click="formSubmit" 
					style="font-size: 40rpx;" 
					class="subButton"
					:disabled="canSubmit" >提 交</a-button>
			</div>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref, reactive} from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import type { UploadProps, MenuProps} from 'ant-design-vue';
import {message, reject} from 'ant-design-vue'
import axios from 'axios';
import { DownOutlined } from '@ant-design/icons-vue';
import {baseUrl} from '@/config.js'

interface FormState {
  advice: string;
}

const formState = reactive<FormState>({
  advice: ''
});

const title = '为了完善餐厅管理，持续提高服务质量，尽心竭力让员工更加精神饱满的投入生产工作，值此，我们诚恳向广大员工征集意见及建议，敬请员工们给予热心指导批评。';
let filelist = []; // 图片链接集合（提交后台的）

// 图片预览相关的
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');

let myfileList = ref<UploadProps['fileList']>([]);  // 页面显示的图片集合
const canSubmit = ref(true) // 提交按钮可点击状态

// 图片移除
const handleRemove = (file: UploadProps['fileList'][number]) => {
  // 删除图片信息，防止提交冗余信息
  filelist = filelist.filter(item => item.uid !== file.uid);
  myfileList.value = myfileList.value.filter(f => f.uid !== file.uid);
  previewVisible.value = false;
  previewTitle.value = '';
};

function handleChange(info:any) {
	const file = info.file
	const isJPGorPNG = file.type === 'image/jpeg' || info.file.type === 'image/png' || file.type === 'image/jpg';
	const maxSize = 10 * 1024 * 1024;
	if(file.size>maxSize){
		message.error('单张图片需小于10MB');
		filelist = filelist.filter(item => item.uid !== file.uid);
		myfileList.value = myfileList.value.filter((file) => file.uid !== info.file.uid);
	}
	if (!isJPGorPNG) {
	  message.error('只能上传 JPG 或 PNG 格式的图片!');
	  filelist = filelist.filter(item => item.uid !== file.uid);
	  myfileList.value = myfileList.value.filter((file) => file.uid !== info.file.uid);
	}else{
		filelist = info.fileList;
	}
}

// 监听意见框输入
function onAdviceChange(event:any) {
    formState.advice = event.target.value;	
	canSubmit.value = !(formState.advice.trim().length > 0);
}

// 点击提交
function formSubmit(){
	console.log("点击提交")
	const formData = new FormData();
	filelist.forEach((file) => {
	    formData.append('images', file.originFileObj);
	});
	formData.append('advice', formState.advice);
	// uni.request({
	// 	url:'/api'+'/review',
	// 	data:formData,
	// 	method:'POST'
	// })
	axios.post(baseUrl+'/review', formData).then(response => {
		formState.advice = ''
		filelist = []
		uni.reLaunch({
		  url: './success'
		});
	  })
	  .catch(error => {
	    console.error('提交失败:', error);
	  });
}


function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

 const handlePreview = async (file: UploadProps['fileList'][number]) => {
      if (!file.url && !file.preview) {
        file.preview = (await getBase64(file.originFileObj)) as string;
      }
      previewImage.value = file.url || file.preview;
      previewVisible.value = true;
      previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
    };

const handleCancel = () => {
      previewVisible.value = false;
      previewTitle.value = '';
};

const handleButtonClick = (e: Event) => {
  console.log('click left button', e);
};
const handleMenuClick: MenuProps['onClick'] = e => {
  console.log('click', e);
};

</script>

<style scope>
	.content {
		display: flex;
		flex-direction: column;
		gap: 2%;
		background-color: rgb(85, 135, 158);
		height: 95vh;
	}
	
	.top{
		font-size: 25rpx;
		width: 94%;
		height: 35vh;
		margin-top: 5%;
		margin-left: 3%;
		padding: 2%;
		text-align: center;
	}
	
	.formStyle{
		display: flex;
		flex-direction: column;
		height: 80vh;
		background-color: white;
	}
	
	.textAreaStyle {
	  border-bottom: none !important;
	  border-radius: 0%;
	  width: 95%;
	  height: 30vh;
	  margin-left: 2.5%;
	  background-color: #F8F8F8;
	}
	.subButton{
		width: 80%;
		border-radius: 0%;
		height: auto;
		margin-left: 10%;
	}
	.ant-upload-select-picture-card i {
	  width: 50rpx !important;
	  color: yellow;
	}
	
	.ant-upload-select-picture-card{
	  width: 100rpx !important;
	  height: 100rpx !important;
	  margin-left: 2%;
	}
	
	.topImg{
		width: 50%;
		height: 70%;
	}
</style>
