<template>
  <view class="home-page">
    <!-- 用户信息栏 -->
    <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" v-if="msgCount > 0">
          <up-badge type="error" max="999" :value="msgCount"></up-badge>
        </view>
      </view>
    </view>

    <view class="content-wrap">
      <!-- 任务完成情况标题 -->
      <view class="module-title">任务完成情况（K线图）</view>

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

        <!-- 双折线K线图（匹配示例图） -->
        <view class="chart-container">
          <uni-charts
              type="line"
              :data="klineChartData"
              :categories="klineCategories"
              :option="klineOption"
              :width="chartWidth"
              :height="chartHeight"
          />
        </view>
      </view>

      <!-- 待办/已办切换栏 -->
      <view class="tab-switch-bar">
        <view
            class="tab-item"
            :class="{ active: currentTab === 'todo' }"
            @click="switchTab('todo')"
            hover-class="tab-item--hover"
        >
          待办事项({{ todoList.length }})
          <view class="tab-active-line" v-if="currentTab === 'todo'"></view>
        </view>
        <view
            class="tab-item"
            :class="{ active: currentTab === 'done' }"
            @click="switchTab('done')"
            hover-class="tab-item--hover"
        >
          已办事项({{ doneList.length }})
          <view class="tab-active-line" v-if="currentTab === 'done'"></view>
        </view>
      </view>

      <!-- 事项列表 -->
      <view class="task-list-container">
        <up-empty v-if="!currentTaskList.length" text="暂无相关事项" />
        <view
            class="task-item"
            v-for="(item, index) in currentTaskList"
            :key="index"
            @click="handleTaskClick(item)"
            hover-class="task-item--hover"
        >
          <view class="task-name">
            {{ item.name }}
          </view>
          <view class="task-meta">
            <view class="urgency-tag" :class="`urgency-tag--${getUrgencyType(item.urgency)}`">
              {{ item.urgency || '普通' }}
            </view>
            <view class="task-time">{{ timeFormat(item.time) }}</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, watch, computed, onMounted } from 'vue';
import { useUserStore } from '@/pinia/user';
import { timeFormat } from '@/uni_modules/uview-plus';
import uniCharts from '@/components/uni-charts/uni-charts.vue';

// ========== 1. 常量抽离 ==========
const FORMAT_CONST = {
  DATE: 'MM.DD', // 匹配示例图的日期格式（12.28）
  DATETIME: 'YYYY-MM-DD HH:mm',
  TIME: 'HH:mm'
};

const URGENCY_MAP = {
  特急: 'urgent',
  紧急: 'high',
  一般: 'normal',
  普通: 'normal',
  '--': 'normal'
};

// ========== 2. 响应式数据 ==========
const msgCount = ref(9999);
const currentTab = ref('todo');
const dateRange = ref([]);

// 双折线K线图专用数据
const chartWidth = ref(0);
const chartHeight = ref(300);
const klineCategories = ref([]); // X轴日期（12.28/12.29...）
const klineChartData = ref([
  {
    name: '已完成任务数', // 匹配示例图的绿色折线
    data: [],
    color: '#25AF69'
  },
  {
    name: '待完成总任务数', // 匹配示例图的棕色折线
    data: [],
    color: '#B34C17'
  }
]);
// 图表配置（匹配示例图样式）
const klineOption = ref({
  grid: {
    top: '25%',
    left: '15%',
    right: '8%',
    bottom: '20%'
  },
  xAxis: {
    axisLabel: { fontSize: 12, color: '#666' }
  },
  yAxis: {
    min: 0,

    splitLine: { lineStyle: { color: '#f5f5f7' } },
    axisLabel: { fontSize: 12, color: '#666' }
  },
  tooltip: {
    trigger: 'axis',
    formatter: (params) => {
      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 todoList = ref([
  { name: '绿地卫生验收', urgency: '特急', time: '2025-12-31 15:45:23' },
  { name: '阜成门内大街年度计划巡检', urgency: '--', time: '2025-12-31 09:02:00' },
  { name: '金融街年度计划巡检', urgency: '--', time: '2025-12-31 09:02:00' },
  { name: '示例事项', urgency: '一般', time: '2026-01-04 10:00:00' }
]);
const doneList = ref([
  { name: '道路清洁验收', urgency: '普通', time: '2025-12-30 14:20:00' }
]);

// ========== 3. 计算属性 ==========
const userStore = useUserStore();
const userName = computed(() => userStore.userInfo?.user?.nickname || '用户');
const currentTaskList = computed(() => {
  return currentTab.value === 'todo' ? todoList.value : doneList.value;
});

// ========== 4. 工具函数 ==========
const rpx2px = (rpx) => {
  const systemInfo = wx.getSystemInfoSync();
  return Math.floor(rpx * (systemInfo.screenWidth / 750));
};

const getUrgencyType = (urgency) => {
  return URGENCY_MAP[urgency] || 'normal';
};

const initRecent7Days = () => {
  const now = new Date();
  const sevenDaysAgo = new Date();
  sevenDaysAgo.setDate(now.getDate() - 6);
  dateRange.value = [sevenDaysAgo, now];
};

/**
 * 初始化双折线K线数据（匹配示例图）
 */
const fetchKlineData = async () => {
  try {
    // 模拟示例图数据（日期+已完成+待完成）
    const rawData = [
      { date: '12.21', done: 10, total: 110 },
      { date: '12.22', done: 35, total: 70 },
      { date: '12.23', done: 55, total: 728 },
      { date: '12.24', done: 35, total: 65 },
      { date: '12.25', done: 65, total: 78 },
      { date: '12.26', done: 50, total: 272 },
      { date: '12.22', done: 35, total: 70 },
      { date: '12.23', done: 55, total: 78 },
      { date: '12.24', done: 35, total: 65 },
      { date: '12.25', done: 65, total: 78 },
      { date: '12.26', done: 50, total: 72 },
      { date: '12.27', done: 72, total: 92 }
    ];

    // 转换为uni-charts格式
    klineCategories.value = rawData.map(item => item.date);
    klineChartData.value[0].data = rawData.map(item => item.done);
    klineChartData.value[1].data = rawData.map(item => item.total);
  } catch (error) {
    wx.showToast({ title: '获取K线数据失败', icon: 'none' });
  }
};

// ========== 5. 业务逻辑 ==========
const switchTab = (tabType) => {
  if (currentTab.value === tabType) return;
  currentTab.value = tabType;
};

const openDatePicker = () => {};

const handleDateConfirm = (e) => {
  if (!e?.value?.length) return;
  fetchKlineData();
};

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

const handleTaskClick = (item) => {
  wx.navigateTo({ url: `/pages-sub/task/detail?id=${item.id || ''}` });
};

// ========== 6. 生命周期 ==========
onMounted(() => {
  chartWidth.value = rpx2px(750 - 60);
  chartHeight.value = rpx2px(300);
  initRecent7Days();
  fetchKlineData();
});
</script>

<style scoped lang="scss">
/* 样式保持不变，无需修改 */
$primary-color: #1677ff;
$danger-color: #E53935;
$success-color: #4CAF50;
$text-color: #333;
$text-color-light: #666;
$text-color-placeholder: #999;
$bg-color: #f5f5f7;
$card-bg: #fff;
$border-radius: 32rpx;
$card-radius: 10rpx;
$spacing-sm: 10rpx;
$spacing-md: 20rpx;
$spacing-lg: 30rpx;

.home-page {
  background-color: $bg-color;
  min-height: 100vh;
}

.user-info-bar {
  background: url("https://img.jichengshanshui.com.cn:28207/appimg/bg.jpg") no-repeat;
  background-size: 100% 100%;
  padding: 200rpx $spacing-lg 270rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #fff;
  position: relative;
  z-index: 1;

  .username {
    font-size: 32rpx;
    font-weight: 500;
    margin-bottom: 8rpx;
  }

  .login-desc {
    font-size: 24rpx;
    opacity: 0.8;
  }

  .msg-icon {
    position: relative;
    padding: 10rpx;
    border-radius: 50%;
    transition: background-color 0.2s;

    &--hover {
      background-color: rgba(255, 255, 255, 0.2);
    }

    .msg-badge {
      position: absolute;
      top: -10rpx;
      right: -10rpx;
    }
  }
}

.content-wrap {
  margin-top: -245rpx;
  border-radius: $border-radius $border-radius 0 0;
  background-color: $bg-color;
  position: relative;
  z-index: 2;
  overflow: hidden;
}

.module-title {
  padding: $spacing-lg $spacing-lg 0;
  font-size: 30rpx;
  font-weight: 600;
  color: $text-color-light;
  margin-bottom: $spacing-sm;
}

.task-chart-card {
  background-color: $card-bg;
  border-radius: $card-radius;
  margin: 0 $spacing-lg $spacing-md;
  padding: $spacing-md;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 24rpx;
    color: $text-color-placeholder;
    margin-bottom: $spacing-md;

    .date-picker-wrap {
      padding: 4rpx 8rpx;
      border-radius: 6rpx;
      transition: background-color 0.2s;

      &:active {
        background-color: $bg-color;
      }
    }
  }

  .chart-container {
    width: 100%;
    height: 300rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.tab-switch-bar {
  display: flex;
  margin: 0 $spacing-lg;
  background-color: $card-bg;
  border-radius: $card-radius $card-radius 0 0;

  .tab-item {
    flex: 1;
    text-align: center;
    padding: $spacing-md 0;
    font-size: 28rpx;
    color: $text-color-light;
    position: relative;
    transition: color 0.2s;

    &--hover {
      background-color: $bg-color;
    }

    &.active {
      color: $primary-color;
      font-weight: 500;
    }

    .tab-active-line {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 4rpx;
      background-color: $primary-color;
    }
  }
}

.task-list-container {
  background-color: $card-bg;
  margin: 0 $spacing-lg;
  padding: $spacing-md;
  border-radius: 0 0 $card-radius $card-radius;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

  .task-item {
    padding: $spacing-md;
    border-bottom: 1px solid $bg-color;
    transition: background-color 0.2s;

    &--hover {
      background-color: $bg-color;
    }

    &:last-child {
      border-bottom: none;
    }

    .task-name {
      font-size: 28rpx;
      color: $text-color;
      margin-bottom: $spacing-sm;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .task-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 24rpx;

      .urgency-tag {
        padding: 2rpx 8rpx;
        border-radius: 4rpx;
        color: #fff;

        &--urgent {
          background-color: $danger-color;
        }

        &--high {
          background-color: #fa8c16;
        }

        &--normal {
          background-color: $text-color-placeholder;
        }
      }

      .task-time {
        color: $text-color-placeholder;
      }
    }
  }
}
</style>