<template>
  <view class="page-container">
    <!-- 用户信息栏 -->
    <view class="user-info-bar">
      <view class="user-info">
        <view class="user-text">
          <view class="username">你好{{ userName }}</view>
          <view class="login-desc">蓟城山水全域智能运营管理平台</view>
        </view>
      </view>
      <view class="msg-icon" @click="handleMsgClick" hover-class="msg-icon--hover">
        <up-icon name="chat" color="#fff" size="24" />
        <view class="msg-badge">
          <up-badge type="error" showZero="true" max="999" :value="msgCount"></up-badge>
        </view>
      </view>
    </view>

    <view class="content-wrap">
      <!-- 图表区域 增加平滑动画容器 -->
      <view class="chart-wrap" v-show="showChartArea">
        <!-- 任务完成情况标题 -->
        <view class="module-title">任务完成情况</view>

        <!-- 任务完成情况卡片 -->
        <view class="task-chart-card">
          <view class="card-header">
            <view class="unit-tip">单位: 个</view>
            <view class="date-picker-wrap">
              <neo-datetime-pro v-model="dateRange" type="daterange" :clearable="false" placeholder="请选择日期范围"
                @confirm="handleDateConfirm" :max-date="maxDate" @popup-show="handlePopupShow"
                @popup-hide="handlePopupHide" />
            </view>
          </view>

          <!-- 双折线K线图 -->
          <view class="chart-container">
            <uni-charts v-if="!isDatePickerOpen" type="line" :data="klineChartData" :categories="klineCategories"
              :option="klineOption" :width="chartWidth" :height="chartHeight" />
          </view>
        </view>
      </view>

      <view class="con-wrap">
        <view class="con-title">养护任务 </view>

        <!-- 手写Tab切换：胶囊分段样式 -->
        <view class="custom-tab-wrap">
          <view class="tab-capsule" :class="{ active: currentTabValue === 0 }" @click="handleTabClick(0)">
            待办事项({{ todoTotal }})
          </view>
          <view class="tab-capsule" :class="{ active: currentTabValue === 1 }" @click="handleTabClick(1)">
            已办事项({{ doneTotal }})
          </view>
        </view>


        <!-- 动态组信息文案 -->
        <!-- <view class="tip-top" style="padding: 8px 0  0 70px;">
          <text>{{ tipText }}</text>
        </view> -->

        <!-- 顶部进度提示栏 -->
        <view v-if="showTipHeader" class="tip-header">
          <up-icon name="checkmark-circle" color="#00b42a" size="20"></up-icon>
          <text style="color: #1677ff;">今日组内：您已经完成{{ finishNum }}项，小组均值{{ avgNum }}项</text>
        </view>


        <scroll-view 
          class="task-list-container" 
          scroll-y 
          @scroll="onListScroll" 
          @scrolltoupper="handleTouchTop"
          enhanced
        >
          <view v-if="taskList.length === 0" class="empty-box">
            <up-empty />
          </view>
          <view class="task-item" v-for="(item, index) in taskList" :key="`${item.taskName}_${index}`"
            hover-class="task-item--hover" @click="handleTaskClick(item)">
            <view class="task-item__content">
              <view class="name-fixed-wrap">
                <view class="task-item__name ">
                  事项{{ index + 1 }} 
                </view>
                <view class="task-name-text">
                  {{ item.taskName || '无' }}
                </view>
              </view>

              <view v-if="currentTabValue === 0" class="task-item__footer" style="padding-left:  60px;">
                <image class="loc-icon" src="https://img.jichengshanshui.com.cn:28207/appimg/定位icon@3x.png" mode="aspectFit"></image>
                <template v-if="isWalkTextMode">
                  <text>距离当前{{ item.distance }}m ·约{{ item.estimatedWalkingMinutes }}分钟步行</text>
                </template>
                <template v-else>
                  <text>{{ item.distance }}m ·</text>
                  <up-icon name="star-fill" color="#ffd21d" size="20"></up-icon>
                  <text>历史完成率{{ item.historyCompletionRate }}%</text>
                </template>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, nextTick } from 'vue';
import { onShow,onUnload } from '@dcloudio/uni-app'
import { useUserStore } from '@/pinia/user';
import { timeFormat } from '@/uni_modules/uview-plus';
import uniCharts from '@/components/uni-charts/uni-charts.vue';
import { getUnreadCount } from "@/api/user";
import {
  getTaskCompletionSummary,
  taskDetailsWithDistance,
  taskDetailsWithSmartSort
} from "@/api/index/index";

const userStore = useUserStore();
const deptId = computed(() => String(userStore.userInfo?.user?.deptId ?? ''));

// ====================== 分组配置（多部门归属同一组） ======================
type GroupItem = {
  deptIds: string[]; // 多个部门ID数组
  label: string;
  showTipHeader: boolean; // 是否展示顶部进度条
  useWalkText: boolean;   // 是否展示步行距离文案
};
const groupConfig: GroupItem[] = [
  // 组2 A1B2 纯效率·有提醒
  {
    deptIds: ['361', '363', '279', '277', '270'],
    label: '[组2  A1B2 纯效率·有提醒]',
    showTipHeader: true,
    useWalkText: true
  },
  // 组3 A2B1 个性化·无提醒
  {
    deptIds: ['252', '273', '274', '337', '359', '360'],
    label: '[组3  A2B1 个性化·无提醒]',
    showTipHeader: false,
    useWalkText: false
  },
  // 组4 A2B2 个性化·有提醒
  {
    deptIds: ['281', '272', '271', '338', '280'],
    label: '[组4  A2B2 个性化·有提醒]',
    showTipHeader: true,
    useWalkText: false
  },
];
// 默认组1：未匹配到的所有部门
const defaultGroup: GroupItem = {
  deptIds: [],
  label: '[组1  A1B1 纯效率·无提醒]',
  showTipHeader: false,
  useWalkText: true
};

// 获取当前部门所属分组
const currentGroup = computed(() => {
  const targetDept = deptId.value;
  // 遍历匹配部门ID
  for (const group of groupConfig) {
    if (group.deptIds.includes(targetDept)) {
      return group;
    }
  }
  // 无匹配返回默认组1
  return defaultGroup;
});

// 自动读取分组配置，无需修改其他业务代码
const tipText = computed(() => currentGroup.value.label);
const showTipHeader = computed(() => currentGroup.value.showTipHeader);
const isWalkTextMode = computed(() => currentGroup.value.useWalkText);
const useDistanceApi = computed(() => currentGroup.value.useWalkText);
// =========================================================================

const finishNum = ref(0);
const avgNum = ref(0);
const msgCount = ref(0);
const currentTabValue = ref(0);

const dateRange = ref<string[]>([]);
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const maxDate = ref(timeFormat(yesterday, 'yyyy-mm-dd'));
const minDate = '2026-01-06';

const isDatePickerOpen = ref(false);
const handlePopupShow = () => {
  isDatePickerOpen.value = true;
};
const handlePopupHide = () => {
  isDatePickerOpen.value = false;
};

const todoTotal = ref(0);
const doneTotal = ref(0);
const todoFullList = ref<any[]>([]);
const doneFullList = ref<any[]>([]);
const taskList = computed(() => {
  return currentTabValue.value === 0 ? todoFullList.value : doneFullList.value;
});

const chooseOptions = computed(() => [
  { title: `待办事项(${todoTotal.value})`, id: 'todo' },
  { title: `已办事项(${doneTotal.value})`, id: 'done' }
]);

const currentLon = ref<string>('');
const currentLat = ref<string>('');
const chartWidth = ref(0);
const chartHeight = ref(300);

const klineCategories = ref<string[]>([]);
const klineChartData = ref([
  {
    name: '已完成任务数',
    data: [] as number[],
    color: '#25AF69'
  },
  {
    name: '总任务数',
    data: [] as number[],
    color: '#B34C17'
  }
]);

const klineOption = ref({
  grid: {
    top: '25%',
    left: '12%',
    right: '8%',
    bottom: '16%'
  },
  xAxis: {
    axisLabel: { fontSize: 12, color: '#666' }
  },
  yAxis: {
    min: 0,
    splitLine: { lineStyle: { color: '#f5f5f7' } },
    axisLabel: { fontSize: 12, color: '#666' }
  },
  tooltip: {
    trigger: 'axis',
    formatter: (params: any[]) => {
      return `${params[0].name}<br/>
      ${params[0].seriesName}: ${params[0].data}<br/>
      ${params[1].seriesName}: ${params[1].data}`;
    }
  },
  legend: {
    show: true,
    top: '5%',
    textStyle: { fontSize: 12 }
  }
});

const userName = computed(() => userStore.userInfo?.user?.nickname || '用户');

const rpx2px = (rpx: number) => {
  const systemInfo = uni.getSystemInfoSync();
  return Math.floor(systemInfo.screenWidth / 750 * rpx);
};

// ========== 滚动逻辑 终极优化 ==========
const showChartArea = ref(true);
// 隐藏阈值：超过80rpx收起
const scrollHideThreshold = rpx2px(80);
// 安全显示区间：≤80rpx一律显示，覆盖所有回弹残留(70/80/90)
const safeShowThreshold = rpx2px(130);
let scrollTimer: number | null = null;

// 下拉触顶强制展示
const handleTouchTop = () => {
  showChartArea.value = true;
};

const onListScroll = (e: any) => {
  const scrollTop = e.detail.scrollTop;
  console.log('scrollTop', scrollTop)
  if (scrollTimer) clearTimeout(scrollTimer);

  // 实时：只要在安全区间立刻显示
  if (scrollTop <= safeShowThreshold) {
    showChartArea.value = true;
  } else if (scrollTop > scrollHideThreshold) {
    showChartArea.value = false;
  }

  // 滚动停止兜底二次校验
  scrollTimer = setTimeout(() => {
    if (scrollTop <= safeShowThreshold) {
      showChartArea.value = true;
    }
  }, 100);
};

// 切换tab重置图表显示
const handleTabClick = (tabIndex: number) => {
  if (currentTabValue.value === tabIndex) return;
  currentTabValue.value = tabIndex;
  // 切换tab强制显示图表
  showChartArea.value = true;
};

// 页面每次显示强制重置图表为显示状态
onShow(async () => {
  showChartArea.value = true;
  chartWidth.value = rpx2px(750 - 60);
  chartHeight.value = rpx2px(300);
  initRecent7Days();
  getUnread();
  await loadAllTaskByDept();
});

// 页面销毁清除定时器
onUnload(() => {
  if (scrollTimer) clearTimeout(scrollTimer);
});
// ======================================

const getCurrentLocation = (): Promise<{ lon: string; lat: string }> => {
  return new Promise((resolve, reject) => {
    uni.getSetting({
      success: (settingRes) => {
        if (!settingRes.authSetting['scope.userLocation']) {
          uni.authorize({
            scope: 'scope.userLocation',
            success: () => {
              uni.getLocation({
                type: 'gcj02',
                success: (loc) => {
                  console.log(loc.longitude)
                   console.log(loc.latitude)
                  resolve({
                    lon: loc.longitude.toFixed(6),
                    lat: loc.latitude.toFixed(6)
                  })
                },
                fail: (err) => {
                  uni.showToast({ title: '获取位置失败，请打开手机定位', icon: 'none' })
                  reject(err)
                }
              })
            },
            fail: () => {
              uni.showModal({
                title: '需要定位权限',
                content: '请允许获取位置才能正常使用',
                confirmText: '去设置',
                success: (modal) => {
                  if (modal.confirm) {
                    uni.openSetting()
                  }
                }
              })
              reject('用户拒绝定位权限')
            }
          })
        } else {
          uni.getLocation({
            type: 'gcj02',
            success: (loc) => {
               console.log(loc.longitude)
                   console.log(loc.latitude)
              resolve({
                lon: loc.longitude.toFixed(6),
                lat: loc.latitude.toFixed(6)
              })
            },
            fail: (err) => {
              uni.showToast({ title: '获取位置失败，请打开手机定位', icon: 'none' })
              reject(err)
            }
          })
        }
      },
      fail: (err) => {
        reject('获取权限失败：' + err.errMsg)
      }
    })
  })
}

const initRecent7Days = async () => {
  const yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  const sevenDaysAgo = new Date(yesterday);
  sevenDaysAgo.setDate(yesterday.getDate() - 6);

  dateRange.value = [
    timeFormat(sevenDaysAgo, 'yyyy-mm-dd'),
    timeFormat(yesterday, 'yyyy-mm-dd')
  ];
  initChartData(dateRange.value[0], dateRange.value[1]);
};

const getUnread = async () => {
  try {
    const res = await getUnreadCount();
    msgCount.value = res || 0;
  } catch (error) {
    console.error('获取未读消息数失败:', error);
    msgCount.value = 0;
  }
};

const initChartData = async (beginTime: string, endTime: string) => {
  try {
    const postData = { beginTime, endTime };
    const res = await getTaskCompletionSummary(postData);
    klineCategories.value = res.map((item: any) => item.currentDate);
    klineChartData.value[0].data = res.map((item: any) => item.completedNum);
    klineChartData.value[1].data = res.map((item: any) => item.countpendingNum);
  } catch (error) {
    console.error('获取图表数据失败:', error);
  }
};

const loadDistanceApiTask = async (lon: string, lat: string) => {
  try {
    const paramsTodo = { queryType: 1, currentLon: lon, currentLat: lat };
    const paramsDone = { queryType: 2, currentLon: lon, currentLat: lat };
    const [todoRes, doneRes] = await Promise.all([
      taskDetailsWithDistance(paramsTodo),
      taskDetailsWithDistance(paramsDone)
    ]);
    todoFullList.value = todoRes?.sortedTasks || [];
    doneFullList.value = doneRes?.sortedTasks || [];
    todoTotal.value = Number(todoRes?.totalPendingTasks) || 0;
    doneTotal.value = Number(doneRes?.totalPendingTasks) || 0;
    finishNum.value = todoRes?.teamProgress?.userCompletedCount ?? 0;
    avgNum.value = doneRes?.teamProgress?.teamAverage ?? 0;
    await nextTick();
  } catch (err) {
    uni.showToast({ title: '加载任务失败', icon: 'none' });
    console.error('加载distance接口任务报错', err);
    todoFullList.value = [];
    doneFullList.value = [];
    todoTotal.value = 0;
    doneTotal.value = 0;
  }
};

const loadSmartSortTask = async (lon: string, lat: string) => {
  try {
    const [todoRes, doneRes] = await Promise.all([
      taskDetailsWithSmartSort({
        queryType: 1,
        currentLon: lon,
        currentLat: lat
      }),
      taskDetailsWithSmartSort({
        queryType: 2,
        currentLon: lon,
        currentLat: lat
      })
    ]);
    todoFullList.value = todoRes?.sortedTasks || [];
    doneFullList.value = doneRes?.sortedTasks || [];
    todoTotal.value = Number(todoRes?.totalPendingTasks) || 0;
    doneTotal.value = Number(doneRes?.totalPendingTasks) || 0;
    finishNum.value = todoRes?.teamProgress?.userCompletedCount ?? 0;
    avgNum.value = doneRes?.teamProgress?.teamAverage ?? 0;
    await nextTick();
  } catch (err) {
    uni.showToast({ title: '加载任务失败', icon: 'none' });
    console.error('加载smartSort接口任务报错', err);
    todoFullList.value = [];
    doneFullList.value = [];
    todoTotal.value = 0;
    doneTotal.value = 0;
  }
};

const loadAllTaskByDept = async () => {
  const loc = await getCurrentLocation();
  currentLon.value = loc.lon;
  currentLat.value = loc.lat;
  if (useDistanceApi.value) {
    await loadDistanceApiTask(loc.lon, loc.lat);
  } else {
    await loadSmartSortTask(loc.lon, loc.lat);
  }
};

const handleDateConfirm = (e: string[]) => {
  dateRange.value = e;
  initChartData(e[0], e[1]);
};

const handleMsgClick = () => {
  uni.navigateTo({ url: '/pages-sub/msg/index' });
};

const handleTaskClick = (item: any) => {
  if (item.taskType == "maintain") {
    if (currentTabValue.value === 0) {
      uni.navigateTo({ url: `/pages-sub/daily/maintain-manage/add-record?planNo=${item.planNo || ''}` });
    }
    if (currentTabValue.value === 1) {
      uni.navigateTo({ url: `/pages-sub/daily/maintain-manage/finish-plan-detail?planNo=${item.planNo || ''}` });
    }
  }
  if (item.taskType == "inspection") {
    if (currentTabValue.value === 0) {
      uni.navigateTo({ url: `/pages-sub/daily/patrol-manage/add-patrol-record?planNo=${item.planNo}&batchNo=${item.batchNo}` });
    }
    if (currentTabValue.value === 1) {
      uni.navigateTo({ url: `/pages-sub/daily/patrol-manage/finish-plan-detail?planNo=${item.planNo || ''}` });
    }
  }
};
</script>

<style scoped lang="scss">
$primary-color: #1677ff;
$danger-color: #E53935;
$text-color: #333;
$text-color-light: #666;
$text-color-placeholder: #999;
$bg-color: #f5f5f7;
$card-bg: #fff;
$border-radius: 16px;
$card-radius: 5px;
$spacing-sm: 5px;
$spacing-md: 10px;
$spacing-lg: 15px;
$border-color: #e5e5e5;

.page-container {
  height: 100vh;
  background-color: $bg-color;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.user-info-bar {
  flex-shrink: 0;
  background: url("https://img.jichengshanshui.com.cn:28207/appimg/bg.jpg") no-repeat;
  background-size: 100% 100%;
  padding: 80px $spacing-lg 135px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #fff;

  .username {
    font-size: 16px;
    margin-bottom: 4px;
  }
  .login-desc {
    font-size: 16px;
  }
  .msg-icon {
    position: relative;
    padding: 5px;
    top: 10px;
    border-radius: 50%;
    &--hover {
      background-color: rgba(255, 255, 255, 0.2);
    }
    .msg-badge {
      position: absolute;
      top: -2px;
      right: -3px;
    }
  }
}

.content-wrap {
  flex: 1;
  margin-top: -122px;
  border-radius: $border-radius $border-radius 0 0;
  background-color: $bg-color;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.chart-wrap {
  flex-shrink: 0;
  transition: all 0.35s ease-out;
  opacity: 1;
  overflow: hidden;
}
.chart-wrap[hidden] {
  opacity: 0;
  height: 0;
  margin: 0;
}

.module-title {
  padding: $spacing-lg;
  font-size: 14px;
  font-weight: 600;
  color: $text-color-light;
  flex-shrink: 0;
}

.task-chart-card {
  background-color: $card-bg;
  border-radius: $card-radius;
  margin: 0 $spacing-lg $spacing-md;
  padding: $spacing-md;
  flex-shrink: 0;
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    color: $text-color-placeholder;
    margin-bottom: $spacing-md;
    .date-picker-wrap {
      padding: 2px 4px;
      border-radius: 3px;
      transition: background-color 0.2s;
      position: relative;
      z-index: 999;
      &:active {
        background-color: $bg-color;
      }
    }
  }
  .chart-container {
    width: 100%;
    height: 150px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.con-wrap {
  border-radius: 8px;
  background-color: #fff;
  margin: 0 15px;
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.con-title {
  padding: 10px 15px;
  border-bottom: 1px solid #f0e9e9;
  flex-shrink: 0;
}

.custom-tab-wrap {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 20rpx 0 20rpx 20rpx;
  background: #fff;
  flex-shrink: 0;
}

.tab-capsule {
  padding: 10rpx 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #999;
  background: #f5f5f5;
  border-radius: 0;
  transition: all 0.2s ease;
  font-weight: 500;
}
.tab-capsule.active {
  color: #d4af37;
  background: #fff8dc;
}

.tip-header {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 15rpx;
  background: #e6f7ff;
  font-size: 14px;
  color: #000;
  flex-shrink: 0;
}

.tip-top {
  padding: 8px 0  0 70px;
  flex-shrink: 0;
}

.task-list-container {
  width: 100%;
  height: 100%;
  padding-bottom: 300rpx;
  box-sizing: border-box;
}

.empty-box {
  padding: 60rpx 0;
}

.task-item {
  padding: $spacing-md;
  transition: background-color 0.2s;
  border-bottom: 1px solid $border-color;
  &:last-child {
    border-bottom: none;
  }
  &--hover {
    background-color: $bg-color;
  }
  &__content {
    width: 100%;
  }
  .name-fixed-wrap {
    display: flex;
  }
  .task-item__name {
    width: 60px;
  }
 .task-name-text {
  flex: 1;
  font-size: 14px;
  color: $text-color;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
  &__name {
    font-size: 15px;
    color: $text-color;
    display: inline-block;
  }
  &__footer {
    display: flex;
    align-items: flex-start;
    gap: 6rpx;
    font-size: 13px;
    color: $text-color-light;
    margin-top: $spacing-sm;
    align-items: center;
  }
}
.loc-icon {
  width: 20px;
  height: 20px;
}

.urgency-tag {
  color: #7D7D7D;
}
</style>