<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/img/14147@2x.png" class="background-image" mode="aspectFill" />

          <!-- 左侧轮播图 -->
          <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 class="content-wrapper">
            <view class="title-button-row">
              <view class="paiBanTitle">我的排班</view>
              <button class="paiBanBtn" @click="DataInit">去管理排班</button>
            </view>
            <view class="paiBanDesc">管理排班时间，合理分配服务订单</view>
          </view>
        </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'
import { getToken } from '@/utils/auth'
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 => {
    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) => {
  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 => {

    return item.date !== e.fulldate
  })
}


//排班时间去重处理
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;
  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 => {
    serveiceList.value = res.data;
  })
}

const DataInit = () => {
  getDataTime().then(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();
  const token = getToken();
  token && 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 {
  position: relative;
  margin-top: 30rpx;
  display: flex;
  flex-direction: row;
  background: #FFFFFF;
  border-radius: 20rpx;
  box-shadow: 0rpx 4rpx 10rpx 0rpx rgba(0, 0, 0, 0.04);
  overflow: hidden;
  height: 300rpx;

  .background-image {
    position: absolute;
    width: 100%;
    height: 100%;
    object-fit: cover;
    z-index: 0;
  }

  .zhiYuanZheSwiper {
    width: 196rpx;
    height: 240rpx;
    border-radius: 38rpx;
    overflow: hidden;
    margin: 30rpx;
    z-index: 1;
    position: relative;
  }

  .swiper-item-container {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;

    &.active-swiper {
      transform: scale(1);
    }
  }

  .zhiYuanZhe {
    width: 100%;
    height: 100%;
    border-radius: 38rpx;
    box-shadow: 0 8rpx 20rpx rgba(0, 0, 0, 0.1);
  }

  .content-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    padding: 30rpx;
    z-index: 1;
    position: relative;
  }

  .title-button-row {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12rpx;
    width: 100%;
    margin-top: 129rpx;
    margin-left: 0rpx;
  }

  .paiBanTitle {
    font-family: PingFang SC;
    font-size: 34rpx;
    font-weight: 600;
    line-height: 40rpx;
    letter-spacing: normal;
    color: rgba(0, 0, 0, 0.8);
    width: 136rpx;
    height: 40rpx;


    position: relative;
    left: -2rpx;
    top: 17rpx;
  }

  .paiBanDesc {
    font-family: PingFang SC;
    font-size: 26rpx;
    font-weight: normal;
    line-height: 40rpx;
    color: rgba(0, 0, 0, 0.5);
    margin-top: 8rpx;
    left: -2rpx;
    position: relative;
  }

  .paiBanBtn {
    width: 200rpx;
    height: 70rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 36rpx;
    background: #D94342;
    font-family: PingFang SC;
    font-size: 28rpx;
    font-weight: 500;
    line-height: 30rpx;
    color: #FFFFFF;
    border: none;
    padding: 0;
    position: relative;
    top: -20rpx;
    left: 4rpx;
  }
}

.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>