<!--
* @Description 我的计划列表
 -->
<template>
  <view class="con-body">
    <view class="con-bg">
      <!-- 头部 -->
      <customHeader ref="customHeaderRef" :title="'周计划列表'" :leftFlag="true" :rightFlag="true">
        <template #right>
          <view class="head-right" @click="handleCreate">
            <uni-icons type="plus" size="24" color="#B7D2FF"></uni-icons>
            新增
          </view>
        </template>
      </customHeader>
      <!-- 高度来避免头部遮挡 -->
      <view class="top-height"></view>

      <view class="week-plan-title">
        <!--        <view v-if="userInfo.nickName">姓名：<strong>{{ userInfo.nickName || userInfo.userName }}</strong></view>-->
        <view v-if="weekNum">
          {{ yearMonth }}
          <view v-if="isThisWeek" style=" display: inline-block;">
            <strong>本周</strong>
          </view>
          <view v-else style="display: inline-block"> 第 <strong>{{ weekNum }}</strong> 周</view>
        </view>
      </view>

      <view class="nav-list">
        <view class="nav-item" :class="{'active': index == activeTab}"
              v-for="(item,index) in allPlans" :key="index"
              @click="handleNav(index)"
        >{{ getTapLabel(item) }}
        </view>
      </view>
      <uni-transition :duration="300"
                      :mode-class="['fade','slide-bottom']"
                      :styles="{'width':'100%', 'background-color':'#f0f0f0','border-top-left-radius': '8px', 'border-top-right-radius': '8px'}"
                      :show="showTrans">
        <view v-if="onShowPlan" v-for="(item, index) in OrdinalDate" :key="index">
          <!-- 计划详情 -->
          <view class="white-bg white-bg-2" :class="{'white-bg-r':index === 0}">
            <view class="report-list">
              <view class="w-b-title">
                <view class="r-left">{{ getWorkDate(index) }} {{ WeekCN[index] }}</view>
                <view class="r-right btn-edit" @click="handleEdit(index)">编辑</view>
              </view>
              <view class="r-list">
                <view class="r-left">工作类型</view>
                <view class="r-right">{{ getWorkType(index) || '' }}</view>
              </view>
              <view class="border-bottom b-width"></view>
              <view class="r-list">
                <view class="r-left">内容</view>
                <view class="r-right">{{ getWorkEvent(index) || '' }}</view>
              </view>
            </view>
          </view>
          <view class='bottom-spliter'></view>
        </view>

        <view v-else style="text-align: center; margin-top: 50%; color: white">
          暂无数据
        </view>
      </uni-transition>
      <!-- 底部加高度来避免tabbar遮挡 -->
      <!-- <view class="bottom-height bg-gray"></view> -->
    </view>


  </view>
</template>

<script setup>

import {onMounted, ref, computed, watch} from "vue";
import {useRoute} from "vue-router"
import customHeader from '@/components/customHeader.vue'
import {WeekCN, WorkType, WorkEvent, OrdinalDate} from "./dataMap";
import {getCurrentWeekNum} from "./dateTimeUtils";
import {getWeeklyPlanList} from "@/api/crm/plan/getPlan";
import {judgeThisWeek} from "@/api/crm/plan/updatePlan";

const userInfo = ref(null)
const route = useRoute();
userInfo.value = {
  nickName: '',
  userName: ''
}
const queryParams = ref({
  pageNum: 1,
  pageSize: 10
});
const date = new Date(); // 当前日期
const activeTab = ref(0);
const yearMonth = ref(null);
const weekNum = ref(0);
const allPlans = ref([]);
const onShowPlan = ref(null);
let getWorkDate = (index) => {
  return onShowPlan.value ? onShowPlan.value[OrdinalDate[index]] : '';
};
let getWorkType = (index) => {
  return onShowPlan.value ? onShowPlan.value[WorkType[index]] : '';
};
let getWorkEvent = (index) => {
  return onShowPlan.value ? onShowPlan.value[WorkEvent[index]] : '';
};
// 刷新计划列表
const refreshPlanList = () => {
  showTrans.value = false;
  uni.showLoading();
  // 获取用户信息
  // getUserInfo().then(res => {
  //   userInfo.value = res.user;
  //   console.log(route.path, "：用户信息获取成功");
  // }).catch(err => {
  //   console.warn(err, "用户信息获取失败")
  // });
  // 获取周计划列表
  getWeeklyPlanList(queryParams.value).then(res => {
    const {rows} = res;
    if (rows.length > 0) {
      allPlans.value = rows;
      onShowPlan.value = rows[0];
      weekNum.value = rows[0].date;
      yearMonth.value = rows[0].firstDayOfTheWeek.substring(0, 7);
    }
    console.log(route.path, "用户周计划列表获取成功");
  }).catch(err => {
    console.log(err, "周计划列表获取失败")
  }).finally(() => {
    uni.hideLoading();
    setTimeout(() => showTrans.value = true, 20);
  })
}

onMounted(() => {
  refreshPlanList();
})

// 判断计划是否为本周
let isThisWeek = computed(() => {
  let theYear = onShowPlan.value.firstDayOfTheWeek.substring(0, 4); // 获取年份
  weekNum.value = onShowPlan.value.date; // 当目前展示的计划列表变化时，更新weekNum.value
  yearMonth.value = onShowPlan.value.firstDayOfTheWeek.substring(0, 7); // 获取年月
  return date.getFullYear() === parseInt(theYear) &&
      date.getMonth() + 1 === onShowPlan.value.month &&
      getCurrentWeekNum() === onShowPlan.value.date;
})

// 跳转到计划编辑页
function handlePlanEdit(param, isAdd) {
  // 在起始页面跳转到planEdit.vue页面，并监听planEdit.vue发送过来的事件数据
  uni.navigateTo({
    url: '/pages/business/CRM/plan/planEdit',
    events: {
      // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
      // 监听页面返回事件，用于刷新数据
      refreshData: function () {
        refreshPlanList(); // 页面返回时调用刷新函数
      }
    },
    success: function (res) {
      // 通过eventChannel向被打开页面传送数据
      res.eventChannel.emit('editPlanData', {param, isAdd})
    }
  })
}

// 创建计划
function handleCreate() {
  console.log("handleCreate", "前往增加计划");
  const itemList = ["本周", "下周"];
  uni.showActionSheet({
    itemList,
    success(result) {
      // console.log("选择"+itemList[res.tapIndex])
      // if(res.tapIndex == 0){ // 创建本周计划
      judgeThisWeek({
        month: new Date().getMonth() + 1,
        date: getCurrentWeekNum()
      }).then((res) => {
        console.log(res, "可以创建周计划")
        handlePlanEdit({itemList, selectIndex: result.tapIndex}, true);
      }).catch((err) => {
        console.warn(err, "已存在周计划")
        // uni.showToast({
        //   icon: 'error',
        //   title: '已有本周或下周计划',
        //   duration: 2000
        // })
      })
      // }else{ // 创建下周计划
      // }
    },
    fail(err) {

    }
  })

}

// 获取计划时间段
function getTapLabel(row) {
  return row.firstDayOfTheWeek.substring(0, 4) + '年' + row.month + '月 第' + row.date + '周';
}

// 展示动画
const showTrans = ref(false);
// 监听 activeTab 变化，触发动画
watch(activeTab, (newVal, oldVal) => {
  if (oldVal !== newVal) { // 确保不是初始化时的触发
    showTrans.value = false; // 先隐藏
    setTimeout(() => {
      onShowPlan.value = allPlans.value[newVal]; // 更新计划列表视图
      showTrans.value = true; // 再显示，触发动画
    }, 20);
  }
});

// 选中计划时间段
function handleNav(index) {
  console.log(index, "tab更换时间段");
  activeTab.value = index;
  onShowPlan.value = allPlans.value[index]; // 更新计划列表视图
}

// 修改计划
function handleEdit(index) {
  const {
    planId, // 主键ID
    year, // 年
    month, // 月
    date, // 周
    planDateId, // 周计划ID
  } = onShowPlan.value;

  let formData = {
    planId, year, month, date, planDateId
  };

  for (let i = 0; i < OrdinalDate.length; i++) {
    // 周一到周日的日期
    formData[OrdinalDate[i]] = getWorkDate(i);
    // 周一到周日的工作类型
    formData[WorkType[i]] = getWorkType(i);
    // 周一到周日的工作内容
    formData[WorkEvent[i]] = getWorkEvent(i);
  }

  // console.log(JSON.stringify(formData))
  console.log(route.path, formData, "前往修改页面");
  const editFields = [OrdinalDate[index], WorkType[index], WorkEvent[index]];
  let userName = null; // userInfo.value.userName || userInfo.value.nickName;
  handlePlanEdit({userName, formData, editFields}, false);
}


</script>

<style scoped>
.week-plan-title {
  color: #fff;
  padding: 0 30rpx;
  display: flex;
  justify-content: space-between;
}

.white-bg {
  width: 690rpx;
  margin: 0;
  border-radius: 0;
}

.white-bg-r {
  width: 690rpx;
  margin: 0;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.white-bg .w-b-title {
  color: #3384DF;
  font-size: 38rpx;
}

.white-bg.white-bg-2 {
  /*  margin-bottom: 20rpx; */
}

.bottom-spliter {
  height: 20rpx;
}

.bg-gray {
  background-color: #f0f0f0;
}

.report-list .w-b-title .btn-edit {
  background-color: #5C96F7;
}

.con-bg {
  /*height: 100%;*/
  /*  overflow-y: auto;*/
}

.nav-list {
  /*  display: flex;*/
  /*  width: 690rpx;*/
  overflow-x: auto; /* 允许横向滚动 */
  /*overflow-y: hidden;  隐藏垂直滚动 */
  /*-ms-overflow-style: none;   IE 隐藏滚动条 */
  /* scrollbar-width: none; */ /*Firefox 隐藏滚动条 */
  /* 添加高度以确保有足够的空间 */
  /*  height: 80rpx;*/
  white-space: nowrap; /* 保持子元素在同一行显示 */
  /* 添加这些属性确保滚动正常工作 */
  scroll-behavior: smooth;
  /* #ifdef APP-PLUS */
  padding: 80rpx 30rpx 0;
  /* #endif */
  /* #ifndef APP-PLUS */
  padding: 20rpx 30rpx 0;
  /* #endif */
}

/* 为 Webkit 浏览器隐藏滚动条 */
.nav-list::-webkit-scrollbar {
  background-color: transparent;
}

.nav-list .nav-item {
  /*  flex: 0 0 auto; 关键：不放大、不缩小、自动宽度 */
  /*  width: 200rpx;*/
  display: inline-block;
  background-color: #05A3F4;
  border-radius: 10rpx;
  color: #FFFFFF;
  font-size: 28rpx;
  text-align: center;
  padding: 10rpx 25rpx;
  margin-right: 15rpx;
  margin-bottom: 20rpx;
  white-space: nowrap;
}

/*.nav-list .nav-item:nth-child(3n){
  margin-right:0;
}*/

.nav-list .nav-item.active {
  background-color: #fff;
  color: #3384DF;
  font-weight: bold;
}
</style>