<template>
	<view class="personal-pet-cat container">
		<view class="personal-pet-img">
			<view class="personal-pet-info-title">
				宠物头像
			</view>
			<view style="display: flex;justify-content: center;">
				<u-upload
					accept="image"
					:capture="['album','camera']"
					:fileList="fileList"
					@afterRead="afterRead"
					@delete="deletePic"
					:max-count="1"
					name="pet"
					width="60"
					height="60"
					:custom-style="{flex:0}"
				>
					
					<image src="https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/personal/index/cat_new.png" style="width: 60px;height: 60px;"></image>
				</u-upload>
			</view>
		</view>
		<PetBaseInfo :petType="petType" :petBaseInfo.sync="petBaseInfo" />
		<PetHealthInfo :petType="petType" :petHealthInfo.sync="petHealthInfo"/>
		<view class="personal-pet-info-btns">
			<view class="personal-pet-btns">
				<view class="personal-pet-btn">
					<u-button :disabled="optionType !='edit'" color="#FFF4E4" @click="deletePet">
						<view style="color: #FFAA48;">
							删除
						</view>
					</u-button>
				</view>
				<view class="personal-pet-btn" @click="save">
					<u-button color="#FFBF60" :loading="loading">
						<view style="color: #fff;">
							保存
						</view>
					</u-button>
				</view>
			</view>
		</view>
		<u-modal :show="showDel" 
			@confirm="confirmDel" 
			@cancel="showDel = false;" 
			ref="uModal" 
			showCancelButton 
			:asyncClose="true" 
			:content='delContent'>
		</u-modal>
	</view>
</template>

<script>
	import {addPet,getPetDetails,updatePet,delPet} from '@/api/system/pet'
	import PetBaseInfo from './components/petBaseInfo.vue'
	import PetHealthInfo from './components/petHealthInfo.vue'
	export default{
		data(){
			return {
				loading:false,
				fileList:[],
				petId:'',
				petType:'dog',
				optionType:'add',
				isNewOrder:false,
				delContent:'',
				photo:'',
				petBaseInfo:{
					name: '',
					gender: '',
					breed: '',
					bodyType: '',
					birthDate: '',
					personality: ''
				},
				petHealthInfo: {
					vaccineStatus: '',
					dewormingStatus: '',
					sterilization: '',
					doglicenseStatus:'',
					healthStatus: [],
					remark:''
				},
				showDel:false,
			}
				
		},
		components:{
			PetBaseInfo,
			PetHealthInfo
		},
		onLoad: function(option) {
			console.log(option.petType); //打印出上个页面传递的参数。
			this.petType = option.petType;
			this.optionType=option.optionType;
			if(this.optionType=='edit'){
				this.petId=option.petId;
				this.getPetDetails(option.petId); 
			}
			if(option.isNewOrder){
				this.isNewOrder=true;
			}
		},
		
		methods:{
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
			},
			
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.fileList[fileListLen]
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'https://store-test.catmdogd.com/test-api/h5/oss/upload',
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: (res) => {
							setTimeout(() => {
								if(res&&res.data){
									let resData = JSON.parse(res.data);
									resolve(resData.url);
								}
								reject("上传失败");
							}, 1000)
						}
					});
				})
			},
			getPetDetails(petId){
				getPetDetails(petId).then(res=>{
					if(res&& res.id){
						const { photo, name, gender,breed, bodyType, birthDate, personality, vaccineStatus, dewormingStatus, sterilization, doglicenseStatus, healthStatus,remark } = res;
						this.petBaseInfo = {
								name,
								gender,
								breed,
								bodyType,
								birthDate,
								personality
							};
						this.petHealthInfo = {
							vaccineStatus,
							dewormingStatus,
							sterilization,
							doglicenseStatus,
							healthStatus,
							remark
						}
						this.fileList=[{url:photo}]
					}else{
						this.$modal.showToast('获取pet失败')
					}
				})
			},
			save(){
				
				console.log(this.petBaseInfo)
				console.log(this.petHealthInfo)
				if(!(this.fileList.length>0&&this.fileList[0].url)){
					this.$modal.showToast('请上传宠物照片!')
					return;
				}
				this.photo = this.fileList[0].url;
				let params = { ...{petType:this.petType,photo:this.photo}, ...this.petBaseInfo,...this.petHealthInfo}
				
				if(!params.name){
					this.$modal.showToast('请填写宠物昵称!')
					return;
				}
				if(!params.breed){s
					this.$modal.showToast('请选择宠物品种!')
					return;
				}
				if(!params.bodyType){
					this.$modal.showToast('请选择宠物体重!')
					return;
				}
				if(!params.personality){
					this.$modal.showToast('请选择宠物性格，可多选!')
					return;
				}
				if(!params.vaccineStatus){
					this.$modal.showToast('请选择宠物疫苗情况!')
					return;
				}
				if(!params.dewormingStatus){
					this.$modal.showToast('请选择宠物驱虫情况!')
					return;
				}
				if(params.healthStatus==null || !params.healthStatus.length){
					this.$modal.showToast('请选择宠物健康情况，可多选!')
					return;
				}
				this.loading=true
				if(this.optionType=='edit'){
					params.id = this.petId;
					updatePet(params).then(res=>{
						if(res&&res.code==200){
							uni.showToast({
								title: '保存成功',
								duration: 3000,
								icon:"none"
								})
							setTimeout(() => {
								this.loading = false;
								if(this.isNewOrder){
									uni.redirectTo({url:'/pages/newOrder/petList'});
								}else{
									let len = getCurrentPages().length;
									if(len >= 2) {
										uni.navigateBack();
									}else{
										uni.redirectTo({url:'/pages/personalCenter/pet'});
									}
								}
							}, 1000);
						}else {
							this.loading=false
							uni.showToast({
								title: '更新pet失败',
								duration: 3000,
								icon:"none"
								})
						}
					})
				} else if(this.optionType=='add'){
					addPet(params).then(res=>{
						if(res&&res==1){
							uni.showToast({
								title: '保存成功',
								duration: 3000,
								icon:"none"
								})
							setTimeout(() => {
								this.loading = false;
								if(this.isNewOrder){
									uni.redirectTo({url:'/pages/newOrder/petList'});
								}else{
									let len = getCurrentPages().length;
									if(len >= 2) {  
										uni.navigateBack();  
									}else {  
										uni.redirectTo({url:'/pages/personalCenter/pet'});  
									}
								}
							}, 1000);
						}else {
							this.loading=false
							uni.showToast({
								title: '新增pet失败',
								duration: 3000,
								icon:"none"
								})
						}
					})
				}
			},
			deletePet(){
				this.delContent = `确定要删除${this.petBaseInfo.name}?`;
				this.showDel = true;
			},
			confirmDel(){
				delPet(this.petId).then(res=>{
					console.log(res);
					uni.showToast({
						title: '删除成功',
						duration: 3000,
						icon:"none"
						})
					this.showDel=false;
					setTimeout(() => {
						let len = getCurrentPages().length;  
						this.loading=false
						if(len >= 2) {  
						    uni.navigateBack();  
						}else {  
						    uni.redirectTo({url:'/pages/personalCenter/pet'});  
						}
					}, 2000);
				})
			},
			
		}
	}
</script>

<style lang="scss">
	.personal-pet-cat{
		
		.breed-select{
			background-color: #fff;
			width: 100%;
			padding: 20px;
			border-radius: 8px 8px 0 0;
			position: absolute;
			bottom: 0;
			.breed-select-btn{
				display: flex;
				justify-content: space-around;
				align-items: center;
			}
		}
		.personal-pet-info-title{
			font-size: 14px; 
			color: #333;
			font-weight: bold;
			padding-bottom: 10px;
			
		}
		.border-bottom{
			border-bottom: 1px solid #efefef;
		}
		.personal-pet-img{
			width: 100%;
			height: 118px;
			background-color: #fff;
			padding: 10px 20px;
		}
		.personal-pet-basic-info{
			background-color: #fff;
			margin-top: 10px;
			padding: 10px 20px;
			
		}
	}

	.container {
		position: relative;
		height: 100%;
		padding-bottom: 90px;
		.personal-pet-info-btns {
			background-color: #FFFFFF;
			padding: 10px 20px 40px;
			width: 100%;
			height: 90px;
			position: fixed;
			bottom: 0;
			z-index: 100;
			text-align: center;
			.personal-pet-btns{
				display: flex;
				justify-content: space-around;
				align-items: center;
				flex-wrap: nowrap;
				flex-direction: row;
				.personal-pet-btn{
					width: 40%;
				}
			}
		}
	}
	
</style>