import { defineComponent, reactive, ref, onMounted, computed } from "vue";
import styles from "./index.module.less";
import { Button, Cell, Field, Tab, Tabs, showToast, DropdownMenu, DropdownItem, Uploader } from "vant";
import { sysSuggestionAdd, getSuggestionList } from "/src/page-instrument/api";
import { storeData } from "/src/store";
import state, { IPlatform } from "/src/state";
import { headImg } from "/src/page-instrument/header-top/image";
import { fileUpload } from "/src/helpers/oss-file-upload"

export default defineComponent({
	name: "recommendation",
	emits: ["close"],
	setup(props, { emit }) {
		const suggestionTypeList = ref<any[]>([]);
		const recommenData = reactive({
			message: "",
			suggestId: "",
		});
		const fileList = ref<any[]>([])  // 上传列表
		// 获取建议类别
		const getTypeList = async () => {
			try {
				const res = await getSuggestionList({ rows: 9999, page: 1, useClient: "SMART_PRACTICE" });
				const data = res.data.rows || [];
				suggestionTypeList.value = data.map((item:any) => {
					return {
						text: item.name,
						value: item.id
					}
				})
			} catch (e) {
				//
			}
		};

		/** 提交意见反馈 */
		const handleSubmit = async () => {
			if (!recommenData.message || !recommenData.suggestId) {
				const desc = !recommenData.suggestId ? '请先选择反馈类型' : '请先填写意见反馈'
				showToast({
					message: desc,
					position: "top",
				});
				return;
			}
			try {
				const attachmentUrlsArr = fileList.value.reduce((arr,item)=>{
					item.url && arr.push(item.url)
					return arr
				},[])
				await sysSuggestionAdd({
					content: recommenData.message,
					type: "SMART_PRACTICE",
					suggestionTypeId: recommenData.suggestId,
					mobileNo: storeData.user?.phone,
					attachmentUrls: attachmentUrlsArr.join(",")
				});
				showToast({
					message: "意见反馈已提交",
					position: "top",
				});
				emit("close");
				recommenData.suggestId = ""
				recommenData.message = ''
				fileList.value = []
			} catch (error) {}
		};
		const currItem = computed(()=>{
			const currItem = suggestionTypeList.value.find((item:any)=>{
				return item.value === recommenData.suggestId
			})
			return currItem
		})
		/* 文件上传 */
		const afterRead = (file:any[]|Record<string,any>) => {
			let files:any[] = []
			if(Array.isArray(file)){
				files = file.map(item =>{
							item.status = 'uploading';
							item.message = '上传中...';
							item.key = new Date().getTime() + item.file.name
							return item
						})
			} else {
				file.status = 'uploading';
				file.message = '上传中...';
				file.key = new Date().getTime() + file.file.name
				files.push(file)
			}
			files.map(async item=>{
				try {
					const url = await fileUpload(item.key,item.file)
					item.status = ""
					item.url = url
				}catch{
					item.status = "failed"
					item.message = "上传失败"
				}
			})
		};
		const maxSize = 5
		const onOversize = () => {
			showToast(`文件大小不能超过 ${maxSize}M`);
		};
		onMounted(() => {
			getTypeList();
		});
		function beforeRead(file:any[]){
			if(file.length + fileList.value.length > 5){
				showToast(`最多只能选择5张图片`);
			}
			return true
		}
		return () => (
			<div class={[styles.recommendation,styles[state.modeType]]}>
				<div class={[styles.head, "top_draging"]}>
					<img class={styles.headTit} src={headImg("recommendationName.png")} />
					<img class={styles.closeImg} src={headImg("closeImg.png")} onClick={()=>{ emit("close") }} />
				</div>
				<div class={styles.content}>
                    <div class={styles.conBox}>
						<div class={styles.rowCon}>
							<DropdownMenu class={[styles.dropdownMenu, currItem.value && styles.currItem]} overlay={false}>
								<DropdownItem class={['recommendationDropdownItem']} title={ currItem.value?currItem.value.name:"请选择反馈类型"} v-model={recommenData.suggestId} options={suggestionTypeList.value}/>
							</DropdownMenu>
							<div class={styles.tit}>{`${recommenData.message.length >= 200 ? 200 : recommenData.message.length }/200`}</div>
						</div>
						<Field
							class={styles.field}
							v-model={recommenData.message}
							border={false}
							type="textarea"
							maxlength={200}
							placeholder="请详细描述您遇到的问题，以便我们尽快为您解决"
						/>
						<Uploader accept=".jpg,jpeg,.png" class={styles.uploader} max-size={maxSize * 1024 * 1024} onOversize={onOversize} v-model={fileList.value} beforeRead={beforeRead} after-read={afterRead} multiple max-count={5}>
							<div class={styles.uploaderbox}>
								<img class={styles.img} src={headImg("photo.png")}></img>
								<div>上传图片</div>
							</div>
						</Uploader>
						<div class={styles.btnCon}>
							<img class={styles.img} src={headImg("qx.png")} onClick={()=>{ emit("close") }}></img>
							<img class={styles.img} src={headImg("tj.png")} onClick={handleSubmit}></img>
						</div>
                    </div>  
                </div>
			</div>
		);
	},
});
