<template>
	<view class="personal-pet">
		<view v-if="petList.length>0" class="personal-pet-list">			
			<view v-for="(item,index) in petList" :key="index">
				<view :class="['personal-pet-list-item',item.gender=='男生'?'.personal-pet-list-item_backgroud_m':'.personal-pet-list-item_backgroud_f' ]">
					<view class="personal-pet-info">
						<view>
							<u-avatar :src="item.photo?item.photo:defaultPhoto" size="60" shape="circle"></u-avatar>
						</view>
						<view class="personal-pet-info-1" style="width: calc(100% - 120px);">
							<view class="personal-pet-info-2">
								<view class="personal-pet-name ellipsis">
									{{item.name}}
								</view>
								<view class="personal-pet-sex">
									<img :src="item.gender=='男生'?'../../static/images/details/boy.svg':'../../static/images/details/girl.svg'" alt="sex" 		
												style="width: 16px;height: 16px;"/>
								</view>
							</view>
							<view class="personal-pet-info-3" style="width: 100%;">
								<view class="ellipsis" style="max-width: 25%;" >
									{{item.breed || '未知'}}
								</view>
								<view class="personal-pet-info-age" style="max-width: 90px;">
									{{item.birthDate || '未知'}}
								</view>
								<view class="ellipsis" style="max-width: 25%;">
									{{item.bodyType || '未知'}}
								</view>
							</view>	
						</view>
						<view style="margin-left: auto; width: 20px;">
							<u-checkbox-group v-model="item.checked">
								<u-checkbox shape="circle" activeColor="#ffbf60"></u-checkbox>
							</u-checkbox-group>
						</view>
					</view>
					<view class="personal-pet-info-disposition ellipsis">
						性格： {{item.personality}}
					</view>
					<view class="personal-pet-info-btns">
						<view style="display: flex; align-items: center;">
							<u-button v-if="item.selectedDate.length==0" color="#FFBF60" size="mini" iconPlacement="right" shape="circle" plain @click="selectDate(item)">
                <view style="font-size: 14px;">请选择服务日期</view> 
                <u-icon name="arrow-right" color="#FFBF60" size="14" style="margin-right: 5px;"></u-icon>
							</u-button>
							<u-button v-else  color="#FFBF60" type="primary" size="mini" iconPlacement="right" shape="circle" @click="selectDate(item)">
                <view style="font-size: 14px;">{{ showSelectedDate(item.selectedDate) }}</view>	
                <u-icon name="arrow-right" color="#ffffff" size="14" style="margin-right: 5px;"></u-icon>
							</u-button>
						</view>
            <view style="display: flex; align-items: center; justify-content: flex-end;">
              <view class="personal-pet-info-btn" @click="editPet(item)">
                <u-icon name="edit-pen" color="#7d8196" size="16" style="margin-right: 5px;"></u-icon>
                <view style="margin-left: 5px;">
                  编辑
                </view>
              </view>
              <view class="personal-pet-info-btn" @click="deletePet(item)">
                <u-icon name="trash" color="#7d8196" size="16"></u-icon>
                <view style="margin-left: 5px;">
                  删除
                </view>
              </view>
            </view>

						
					</view>
				</view>
			</view>
		</view>
		<view v-else class="personal-pet-none">
			<img src="https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/personal/pet/catdog.png" alt="pet"  
			style="width: 149px;height: 124px;" mode="widthFix"/>
			<view class="personal-pet-none-text">这里还没有您的宠物,请点击添加吧~</view>
		</view>
		
		<view class="personal-pet-add">
			<view style="width: 45%;">
				<u-button class="personal-pet-add-btn" color="#FFF4E4" @click="addPet">
          <view style="font-size: 32rpx;font-weight: 500;color: #FFAA48;">
            新增宠物
          </view>
        </u-button>
			</view>
      <view style="width: 45%;">
        <u-button class="personal-pet-add-btn" color="#FFBF60" @click="confirm">
          <view style="font-size: 32rpx;font-weight: 500;color: #fff;">
            确定
          </view>
        </u-button>
      </view>
		</view>
		
		<view class="">
			<u-picker
				:showToolbar='false'
				:show="show"
				:columns="petTypes"
				@change="petTypeChange"
				@cancel="cancel"
				@confirm="confirmPetType"
			></u-picker>
		</view>
		<u-modal :show="showDel" 
			@confirm="confirmDel" 
			@cancel="cancelDel" 
			ref="uModal" 
			showCancelButton 
			:asyncClose="true" 
			:content='delContent'>
    </u-modal>
    <view v-if="showCalendar" class="calendar-popup">
      <view class="calendar-mask" ></view>
      <view class="calendar-content">
        <uni-calendar class="uni-calendar--hook" :selected="selectedDate" :startDate="startDate" :endDate="endDate"
          @change="change" :showMonth="false" />
        <u-button color="#FFBF60" type="primary" @click="confirmCanlendar">确定</u-button>
      </view>
      
    </view>
    
	</view>
</template>

<script>
	import { getDictList } from "@/api/system/user.js"
	import { getPetList,delPet } from "@/api/system/pet"
	export default{
		data(){
			return{
				defaultPhoto:'https://catmdogf.oss-cn-shanghai.aliyuncs.com/CMDF/front/personal/pet/catdog.png',
				petList:[],
				show:false,
				showDel:false,
				petTypes:[],
				delContent:'',
				deleteId:'',
				petType:'',
        startDate: '',
				endDate: '',
        showCalendar: false,
        selectedDate:[],
        currentPets:[]
			}
		},
		onShow() {
			this.getPetList();
		},
		onPullDownRefresh() {
			this.getPetList();
		},
		mounted() {
			this.getPetTypeList();
			this.getPetList();
      this.getCalendarDate();
		},
		methods:{
			getPetList(){
				this.petList=[]
				getPetList().then(res=>{
          let currentPets = this.$globalData.newOrderData.currentPets
					if(res&&res.content){
						this.petList=res.content.map(e=>{
              const currentPet = currentPets.find(item => item.id === e.id)
              if(currentPet) {
                e.selectedDate = currentPet.selectedDate
                e.checked = currentPet.checked
              } else {
                e.selectedDate = []
                e.checked = false
              }
							return e
						})
						this.showDel = false;
					} 
				})
				
			},
			getPetTypeList(){
				getDictList('pet_type').then(res=>{
					if (res.code == 200) {
						let petType = res.data.map(e=>e.dictLabel)
						this.petTypes=[petType]
						console.log(this.petTypes)
					} else {
						this.$modal.showToast('获取pet type失败')
					}
				})
			},
			addPet(){
				this.show = true;
			},
			cancel() {
				this.show = false
			},
			petTypeChange(e){
				console.log(e)
				this.petType=e.value[0]
			},
			confirmPetType(e) {
				console.log(e)
				this.show = false
				// 获取宠物类型,优先使用已选择的petType,否则使用e.value[0]
				const type = this.petType || e.value[0]
				
				// 根据宠物类型映射到英文类型
				const petTypeMap = {
					'猫猫': 'cat',
					'狗狗': 'dog'
				}
				
				const petType = petTypeMap[type]
				if(petType) {
					uni.navigateTo({
						url: `/pages/personalCenter/petInfo?petType=${petType}&optionType=add&isNewOrder=true`
					});
				}
			},
			editPet(item){
				const petTypeMap = {
					'猫猫': 'cat',
					'cat': 'cat', 
					'狗狗': 'dog',
					'dog': 'dog'
				}
				const petType = petTypeMap[item.petType]
				if(petType) {
					uni.navigateTo({
						url: `/pages/personalCenter/petInfo?petType=${petType}&optionType=edit&petId=${item.id}&isNewOrder=true`
					});
				}
			},
			deletePet(item){
				this.delContent = "确定要删除"+item.name+'?';
				this.showDel = true;
				this.deleteId=item.id;
			},
			confirmDel(){
				delPet(this.deleteId).then(res=>{
					console.log(res);
					this.$modal.showToast('删除成功');
					this.getPetList()
				})
				
				
			},
			cancelDel(){
				this.showDel = false;
				this.deleteId='';
			},
      getCalendarDate() {
				let tomorrow = new Date()
				tomorrow.setDate(tomorrow.getDate());
				this.startDate = this.formatDate(tomorrow);

				// 获取三个月后的日期
				let threeMonthsLater = new Date();
				threeMonthsLater.setMonth(threeMonthsLater.getMonth() + 3);
				this.endDate = this.formatDate(threeMonthsLater);
			},
			formatDate(date) {
				let year = date.getFullYear();
				let month = (date.getMonth() + 1).toString().padStart(2, '0');
				let day = date.getDate().toString().padStart(2, '0');
				return year + '-' + month + '-' + day;
			},
      selectDate(item){
        this.currentId= item.id
        this.selectedDate = item.selectedDate
        this.showCalendar = true;
      },
      confirmCanlendar(){
        this.petList.find(e=>e.id==this.currentId).selectedDate = this.selectedDate.sort((a,b) => new Date(a.date) - new Date(b.date))
        this.selectedDate = []
        this.showCalendar = false;
      },
      change(e){
        const selectedValue = this.selectedDate.find(item => item.date === e.fulldate)
				if (selectedValue) {
					// 存在则移除
					this.selectedDate = this.selectedDate.filter(item => item.date !== e.fulldate);
				} else {
					this.selectedDate.push({
						date: e.fulldate,
						info: '预定'
					})
				}
      },
      confirm(){
        const selectedPets = this.petList.filter(e=>e.checked)
        const unselectedDatePets = selectedPets.filter(pet => !pet.selectedDate || pet.selectedDate.length === 0)
        
        if(unselectedDatePets.length > 0) {
          const petNames = unselectedDatePets.map(pet => pet.name).join('、')
          this.$modal.showToast(`请为${petNames}选择服务时间`)
          return
        }
        
        this.$globalData.newOrderData.currentPets = selectedPets
        uni.redirectTo({
          url: '/pages/newOrder/serviceNew'
        })
      },
			showSelectedDate(selectedDate){
				// 显示格式：首日...最后一日 共几天 
				// 日期格式只需要月份和日期 例如：01/01...01/07
				const firstDate = selectedDate[0].date.substring(5).replace('-', '/')
				const lastDate = selectedDate[selectedDate.length - 1].date.substring(5).replace('-', '/')
				const days = selectedDate.length
				return `${firstDate}${days>2?'...':''}${days==2?',':''}${days>1?lastDate:''} 共${days}天`
			}
		}
	}
</script>

<style lang="scss">
	.personal-pet{
		position: relative;
		height: 100%;
		padding-bottom: 90px;
		.personal-pet-add{
			background-color: #FFFFFF;
			padding:10px 20px 40px;
			width: 100%;
			height: 90px;
			position: fixed;
			bottom: 0;
			z-index: 100;
			display: flex;
      justify-content: space-between;
			.personal-pet-add-btn{
				width: 100%;
				border-radius: 6px;
				font-size: 16px;
			}
		}

		.personal-pet-list{
			.personal-pet-list-add{
				width: 100%;
				height: 44px;
				background-color: #FFFFFF;
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 0 15px;
				.personal-pet-list-add-btn{
					font-size: 14px;
					color:#AAA;
					display: flex;
					align-items: center;
				}
				
			}
			.personal-pet-list-item_backgroud_m{
				background: linear-gradient(179deg, #EDF5FE 0.75%, #FFF 34.11%);
			}
			.personal-pet-list-item_backgroud_f{
				background: linear-gradient(179deg, #FFF4F6 0.75%, #FFF 34.11%);
			}
			.personal-pet-list-item{
				margin: 10px 10px 0 10px;
				border-radius: 5px;
				padding: 20px 10px 10px;
				.personal-pet-info{
					display: flex;
					align-items: center;
					justify-content: flex-start;
					.personal-pet-info-1{
						margin-left: 10px;
						.personal-pet-info-2{
							display: flex;
							flex-wrap: wrap;
							.personal-pet-name{
								color: #333;
								font-size: 16px;
								margin-right: 10px;
							}
						}
						.personal-pet-info-3 {
							display: flex;
							align-items: baseline;
							font-size: 14px;
							margin-top: 5px;
							color: #7D8196;
							.personal-pet-info-age{
								padding: 0 10px; 
								margin: 0 10px;
								border-left: solid 2px #7D8196;
								border-right: solid 2px #7D8196;
							}
							
						}
						
					}
					
				}
				.personal-pet-info-disposition{
					padding: 10px; 
					color: #7D8196;
					font-size: 14px;
					background: #f9f9f9;
					border-radius: 5px;
					margin-top: 10px;
				}
				.personal-pet-info-btns{
					display: flex;
					justify-content: space-between;
					margin-top: 10px;
					.personal-pet-info-btn{
						display: flex;
						font-size: 14px;
						color: #7D8196;
						margin-left: 20px;
					}
				}
			}
			
		}
		.personal-pet-none{
			display:flex;
			justify-content: center;
			align-items: center;
			flex-wrap: wrap;
			margin-top: 40%;
			.personal-pet-none-text{
				color: #666;
				text-align: center;
				font-size: 14px;
				width: 100%;
				margin-top: 10px;
			}
		}
    .calendar-popup{
      position: fixed; 
      bottom: 0; 
      left: 0; 
      right: 0; 
      z-index: 999;
      .calendar-content{
        background: #fff; 
        border-radius: 16px 16px 0 0; 
        padding: 0 20px 20px;
      }
    }
    .calendar-mask {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.5); /* 半透明黑色 */
      z-index: 998; /* 确保在内容下方 */
      pointer-events: none; /* 使遮罩层不阻止点击事件 */
    }
    .calendar-content {
      position: relative; /* 确保内容在遮罩层之上 */
      z-index: 999; /* 确保内容在遮罩层之上 */
    }
		
	}
	
</style>