<template>
  <view>
    <template>
      <view class="Wrapper-grid">
        <view class="serve-title client-title" v-if="userType == 2"></view>
        <up-grid :border="false" col="3">
          <up-grid-item v-for="(item, index) in serveiceList" :key="index" @click="handleGridClick(item)">
            <view class="grid-box">
              <view class="grid-image">
                <image :src="item.businessIcon" class="service-img" mode="aspectFit" />
              </view>
              <view class="grid-content">
                <text class="grid-text">{{ item.businessName }}</text>
                <text class="grid-text-bone">{{ item.businessDescribe }}</text>
              </view>
            </view>
          </up-grid-item>
        </up-grid>
        <up-toast ref="uToastRef" />

        <view class="paiBanSty" v-if="userType == 2">
          <!-- <image src="/static/serverImg/home/icon/icon8.png" class="service-img" mode="aspectFit" /> -->
          <image src="/static/img/14147@2x.png" class="images" mode="aspectFit" />
          <view class="paiBanTitle">我的排班</view>
          <view class="paiBanDesc">管理排班时间，合理分配服务订单</view>
          <button class="paiBanBtn" @click="DataInit">去管理排版</button>
          <swiper class="zhiYuanZheSwiper" vertical circular autoplay :interval="4000" :duration="800"
            :previous-margin="'20rpx'" :next-margin="'20rpx'" @change="onSwiperChange">
            <swiper-item v-for="(imgUrl, index) in volunteerImages" :key="index">
              <view class="swiper-item-container" :class="{ 'active-swiper': currentSwiperIndex === index }">
                <image :src="imgUrl" class="zhiYuanZhe" mode="aspectFill" />
              </view>
            </swiper-item>
          </swiper>
        </view>
      </view>
    </template>

    <Calendar ref="calendar" class="uni-calendar--hook" :clear-date="false" :date="info.date" :insert="info.insert"
      :lunar="info.lunar" :range="info.range" @change="change" :clearDate="true" @confirm="confirm" :selected="selected"
      @delete="onDelete" />
  </view>

</template>

<script setup>
import {
  ref,
  onMounted,
  watch,
  computed,
  provide
} from 'vue';
import {
  workDate,
  getDataTime,
  getVolunteerInfo
} from '@/api/volunteer.js'
import {
  volunteerSeachgetTreeList,
  volunteerVolunteerPicture
} from "@/api/volunteerDetailsApi/details.js"
import { getTreeList } from '@/api/volunteer'
import Calendar from '../../components/uni-calendar/components/uni-calendar/uni-calendar.vue'

const swiperList = ['integral', 'kefu-ermai', 'coupon', 'gift', 'scan', 'pause-circle', 'wifi', 'email', 'list'];

// Toast 控制宫格
const uToastRef = ref(null);
const userType = uni.getStorageSync('userType') //读取本地存储
// 用户/志愿者 识别标识
const userOrWorker = uni.getStorageSync('storage_data').vuex_userOrWorker //读取本地存储

const calendar = ref(null)
const info = ref({
  lunar: true,
  range: true,
  insert: false,
})
const selected = ref([])

const serveiceList = ref([]);

// 志愿者图片
const volunteerImages = ref([]);

const getVolunteerImages = () => {
  volunteerVolunteerPicture({}).then(res => {
    console.log('res', res);
    if (Array.isArray(res)) {
      volunteerImages.value = res;
    } else if (res.code === 200 && res.data) {
      volunteerImages.value = res.data;
    }
  })
}
// 当前显示的轮播图索引
const currentSwiperIndex = ref(0);

// 轮播图切换事件
const onSwiperChange = (e) => {
  currentSwiperIndex.value = e.detail.current;
};

// 宫格点击事件
const handleGridClick = async (service) => {
  // 用户
  if (userType == 1) {

    // 动态获取 parentId
    const params = {
      parentId: service.id,
    }
    const res = await volunteerSeachgetTreeList(params)
    uni.navigateTo({
      url: `/pages_home/pages/client/details?dataList=${encodeURIComponent(JSON.stringify(res.data))}&serviceCategory=${service.id}`
    });
  }
  // 志愿者
  if (userType == 2) {
    const res = await getVolunteerInfo({
      serviceCategory: service.id
    });
    if (res.code === 200 && res.data) {
      //已有注册，跳转详情页面
      uni.navigateTo({
        url: `/pages_home/pages/details/index?data=${encodeURIComponent(JSON.stringify({ ...service, key: service.id }))}`
      })
      return
    }

    uni.navigateTo({
      url: `/pages_home/pages/register/index?data=${encodeURIComponent(JSON.stringify({ ...service, key: service.id }))}`
    })

  }
};

const change = (e) => {
  console.log('change', e);
  let dates = [{
    date: e.fulldate,
    info: `${e.time.startTime}~${e.time.endTime}`,
    time: e.time
  }]
  if (e.range.before && e.range.after) {
    dates = e.range.data.map(item => {
      return {
        date: item,
        info: `${e.time.startTime}~${e.time.endTime}`,
        time: e.time
      }
    })
  }
  selected.value = [...selected.value, ...dates]
}

const onDelete = (e) => {
  selected.value = selected.value.filter(item => {
    console.log('item.fulldate !== e.date', item.date, e.fulldate);

    return item.date !== e.fulldate
  })
  console.log(e, selected.value);
}


//排班时间去重处理
const handleDates = computed(() => {
  const parmas = selected.value.map(item => {
    return {
      workDate: item.date,
      workStartTime: item.time.startTime,
      workEndTime: item.time.endTime
    }
  })
  return parmas.reduce((acc, current) => {
    const existing = acc.find(item => item.workDate === current.workDate);
    if (existing) {
      Object.assign(existing, current);
    } else {
      acc.push(current);
    }
    return acc;
  }, []);
});
const confirm = (e) => {
  const parmas = handleDates.value;
  console.log('确定', parmas);
  workDate(parmas).then(res => {
    if (res.code == 200) {
      uni.showToast({
        title: '修改成功',
        icon: 'success',
        success: () => {
          setTimeout(() => {
            close();
          }, 1000)
        }
      })

      return;
    }
    uni.showToast({
      title: res.msg,
      icon: 'none'
    })
  })
};
const close = () => {
  calendar.value.close();
}

const init = () => {
  getTreeList({ parentId: '0' }).then(res => {
    console.log("TCL: init -> res", res)
    serveiceList.value = res.data;
  })
}

const DataInit = () => {
  getDataTime().then(res => {
    console.log('res', res);
    if (res.code === 200) {
      selected.value = res.data.map(item => {
        return {
          date: item.workDate,
          info: `${item.workStartTime}~${item.workEndTime}`,
          time: {
            startTime: item.workStartTime,
            endTime: item.workEndTime
          }
        }
      })
      calendar.value.open();
    }


  })
}



onMounted(() => {
  init();
  getVolunteerImages();
});
</script>

<style scoped lang="scss">
.grid-box {
  width: 226rpx;
  height: 116rpx;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  margin-right: 5rpx;
  margin-left: 5rpx;
  background: #fff;
  border-radius: 14rpx;
  // background: red;
  background: linear-gradient(180deg, #FFF9F3 0%, #FFFFFF 100%);
  box-shadow: 0rpx 4rpx 10rpx 0rpx rgba(0, 0, 0, 0.04);
  margin-top: 10rpx;

  .grid-image {
    width: 64rpx;
    height: 68rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.grid-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;

  .grid-text {
    width: 112rpx;
    height: 36rpx;
    font-family: PingFang SC;
    font-size: 28rpx;
    font-weight: 500;
    line-height: 36rpx;
    letter-spacing: normal;
    color: #313131;
  }

  .grid-text-bone {
    width: 130rpx;
    height: 28rpx;
    font-family: PingFang SC;
    font-size: 22rpx;
    font-weight: normal;
    line-height: 28rpx;
    letter-spacing: -0.02em;
    color: #818181;
    margin-left: 6rpx;
    margin-top: 10rpx;
  }
}

.paiBanSty {
  .paiBanTitle {
    width: 136rpx;
    height: 40rpx;
    font-family: PingFang SC;
    font-size: 34rpx;
    font-weight: 600;
    line-height: 40rpx;
    letter-spacing: normal;
    color: rgba(0, 0, 0, 0.8);
    position: absolute;
    top: 1072rpx;
    left: 278rpx;
  }

  .paiBanDesc {
    width: 390rpx;
    height: 40rpx;
    font-family: PingFang SC;
    font-size: 26rpx;
    font-weight: normal;
    line-height: 40rpx;
    letter-spacing: normal;
    color: rgba(0, 0, 0, 0.5);
    position: absolute;
    top: 1136rpx;
    left: 278rpx;
  }

  .paiBanBtn {
    width: 200rpx;
    height: 60rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 36rpx;
    background: #D94342;
    font-family: PingFang SC;
    font-size: 28rpx;
    font-weight: 600;
    line-height: 30rpx;
    letter-spacing: normal;
    color: #FFF9F3;
    position: absolute;
    top: 1035rpx;
    left: 472rpx;
  }

  .images {
    width: 750rpx;
  }

  .zhiYuanZheSwiper {
    width: 205rpx;
    height: 298rpx;
    position: absolute;
    top: 876rpx;
    left: 43rpx;
    border-radius: 38rpx;
    overflow: hidden;
  }

  .swiper-item-container {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.5s ease;
    opacity: 0.8;
    transform: scale(0.95);
    
    &.active-swiper {
      opacity: 1;
      transform: scale(1);
      animation: fadeIn 0.8s ease forwards;
    }
  }

  .zhiYuanZhe {
    width: 100%;
    height: 100%;
    border-radius: 38rpx;
    transition: all 0.5s ease;
    box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.1);
    display: block; /* 确保没有额外的空间 */
  }
}
.home-ranking{
  
}
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: scale(0.9) translateY(10rpx);
  }

  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

@keyframes fadeOut {
  from {
    opacity: 1;
    transform: scale(1) translateY(0);
  }

  to {
    opacity: 0.8;
    transform: scale(0.95) translateY(-10rpx);
  }
}
</style>