<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="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"
            />
          </view>
        </view>

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

      <!-- 使用up-tabs组件实现Tab切换 -->
      <up-tabs
          :list="tabList"
          lineWidth="60"
          @change="handleTabChange"
          class="task-tab-container"
          :scrollable="false"
          :activeStyle="{
            color: '#000000',
            fontSize: '14'
        }"
          :inactiveStyle="{
           color: '#787070',
            fontSize: '14'
        }"
      ></up-tabs>

      <!-- z-paging分页列表 -->
      <z-paging
          ref="paging"
          v-model="currentTaskList"
          @query="queryList"
          :auto-show-system-loading="true"
          :page-size="10"
          use-page-scroll
      >
        <template #empty>
          <up-empty/>
        </template>
        <view class="task-list-container">
          <view
              class="task-item"
              v-for="(item,index) in currentTaskList"
              :key="`${item.taskName}_${index}`"
              hover-class="task-item--hover"
              @click="handleTaskClick(item)"
          >
            <view class="task-item__content">
              <view class="task-item__name u-line-1">
                {{ item.taskName || '无' }}
              </view>
              <view class="task-item__footer u-flex common-item-center common-justify-between"
                    style="font-size: 13px; margin-top: 5px;">
                <view class="urgency-tag">
                  紧急程度： {{ uni.$dict.getDictLabel('workorder_pressing_type', item.pressingType) || '--' }}
                </view>
                <view style="font-size: 13px;color: #333">{{
                    timeFormat(item.busiDateTime, 'yyyy-mm-dd hh:MM:ss')
                  }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </z-paging>
    </view>
  </view>
</template>

<script setup lang="ts">
import {ref, watch, computed, reactive} from 'vue';
import {onShow} 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, getTaskDetails} from "@/api/index/index";


// ========== 2. 响应式数据 ==========
const msgCount = ref(0);
const currentTab = ref('todo'); // todo:待办 done:已办
const dateRange = ref([]);
const maxDate = ref(timeFormat(new Date(), 'yyyy-mm-dd'));

//  Tab列表配置
const tabList = ref([]);
const todoTotal = ref(0); // 待办事项总数
const doneTotal = ref(0); // 已办事项总数

// 分页相关
const paging = ref(null);
const currentTaskList = ref([]); // 当前显示的任务列表（分页数据）

// 折线图数据配置
const chartWidth = ref(0);
const chartHeight = ref(300);
const klineCategories = ref([]); // X轴日期
const klineChartData = ref([
  {
    name: '已完成任务数',
    data: [],
    color: '#25AF69'
  },
  {
    name: '待完成总任务数',
    data: [],
    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) => {
      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}
  }
});

// ========== 3. 计算属性 ==========
const userStore = useUserStore();
const userName = computed(() => userStore.userInfo?.user?.nickname || '用户');

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


const initRecent7Days = async () => {
  const now = new Date();
  const sevenDaysAgo = new Date();
  sevenDaysAgo.setDate(now.getDate() - 6);
  // 格式化日期为 YYYY-MM-DD 格式
  dateRange.value = [
    timeFormat(sevenDaysAgo, 'yyyy-mm-dd'),
    timeFormat(now, 'yyyy-mm-dd')
  ];

  initChartData(timeFormat(sevenDaysAgo, 'yyyy-mm-dd'), timeFormat(now, 'yyyy-mm-dd'));
};

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

/**
 * 初始化图表数据
 * @param {string} beginTime 开始时间
 * @param {string} endTime 结束时间
 */
const initChartData = async (beginTime, endTime) => {
  try {
    let postData = {
      beginTime: beginTime,
      endTime: endTime
    };
    const res = await getTaskCompletionSummary(postData);
    console.log('图表数据:', res);
    klineCategories.value = res.map(item => item.currentDate);
    klineChartData.value[0].data = res.map(item => item.completedNum);
    klineChartData.value[1].data = res.map(item => item.countpendingNum);
  } catch (error) {
    console.error('获取图表数据失败:', error);
  }
};

/**
 *  获取所有Tab的总数（初始化时调用）
 */
const getAllTabTotal = async () => {
  try {
    // 同时请求待办和已办的总数（只请求第1页，每页1条，仅获取total）
    const [todoRes, doneRes] = await Promise.all([
      getTaskDetails({queryType: 1, pageNo: 1, pageSize: 1}),
      getTaskDetails({queryType: 2, pageNo: 1, pageSize: 1})
    ]);

    // 更新总数
    todoTotal.value = todoRes?.total || 0;
    doneTotal.value = doneRes?.total || 0;
    console.log('已办:')
    console.log(doneRes)
    tabList.value = [
      {name: `待办事项(${todoTotal.value})`},
      {name: `已办事项(${doneTotal.value})`},
    ]
    console.log('初始化总数：', {todoTotal: todoTotal.value, doneTotal: doneTotal.value});
  } catch (error) {
    console.error('获取Tab总数失败:', error);
    // 保底：如果已办请求失败，至少保证待办数据正常
  }
};

// ========== 5. 业务逻辑 ==========
/**
 *  up-tabs切换事件处理
 * @param {object} item 选中的Tab项
 */
const handleTabChange = (item) => {
  // 解析Tab类型（todo/done）
  console.log(item)
  const newTab = item.name.includes('待办') ? 'todo' : 'done';
  if (currentTab.value === newTab) return;

  currentTab.value = newTab;
  // 切换标签后刷新分页数据
  paging.value?.reload();
};

/**
 * 分页查询列表数据
 * @param {number} pageNo 页码
 * @param {number} pageSize 每页条数
 */
const queryList = async (pageNo, pageSize) => {
  try {
    // 1:待完成 2:已完成
    const queryType = currentTab.value === 'todo' ? 1 : 2;
    const postData = {
      queryType,
      pageNo,
      pageSize,
    };

    const res = await getTaskDetails(postData);
    console.log(`${currentTab.value}列表数据:`, res);

    // 更新当前Tab的总数
    if (currentTab.value === 'todo') {
      todoTotal.value = res?.total || 0;
    } else {
      doneTotal.value = res?.total || 0;
    }

    // 适配z-paging分页（注意接口返回结构是res.data.list）
    paging.value.complete(res?.list || [], res?.total || 0);
  } catch (error) {
    console.error(`加载${currentTab.value}列表失败：`, error);
    paging.value?.complete(false);
    uni.showToast({title: '加载失败，请重试', icon: 'none'});
  }
};

// 日期选择确认事件
const handleDateConfirm = (e) => {
  console.log('日期选择确认:', e);

  // 更新选中的日期范围
  dateRange.value = e;

  // 加载选择日期后的图表数据
  initChartData(e[0], e[1]);
};

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

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

// ========== 6. 生命周期 ==========
onShow(async () => {
  // 初始化图表尺寸
  chartWidth.value = rpx2px(750 - 60);
  chartHeight.value = rpx2px(300);

  // 初始化默认日期范围（最近7天）
  initRecent7Days();

  // 获取未读消息数
  getUnread();
  await getAllTabTotal();

  // 初始化分页数据（待办列表）
  if (paging.value) {
    paging.value.reload();
  }
});
</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 {
  min-height: 100vh;
  background-color: $bg-color;
}

.user-info-bar {
  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;
  position: relative;
  z-index: 1;

  .username {
    font-size: 16px;
    font-weight: 500;
    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 {
  margin-top: -122px;
  border-radius: $border-radius $border-radius 0 0;
  background-color: $bg-color;
  position: relative;
  z-index: 999;
  overflow: hidden;
  padding-bottom: $spacing-lg;
}

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

.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: 12px;
    color: $text-color-placeholder;
    margin-bottom: $spacing-md;

    .date-picker-wrap {
      padding: 2px 4px;
      border-radius: 3px;
      transition: background-color 0.2s;

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

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

.task-tab-container {
  position: relative;
  z-index: 4;
  margin: 0 $spacing-lg $spacing-sm;
}

.task-list-container {
  margin: 0 $spacing-lg;
  background-color: $card-bg;
  border-radius: $card-radius;
  overflow: hidden; // 防止边框溢出圆角
}

.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 {
    font-size: 13px;
    color: $text-color;
    margin-bottom: $spacing-sm;
  }

  &__footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

// 紧急程度标签样式
.urgency-tag {
  color: #7D7D7D;

}
</style>