<template>
  <view class="page-container">
    <!-- 加载页 -->
    <up-loading-page
        :loading="loading"
        loading-text="加载中..."
        color="#577ee3"
        zIndex="1000"
    ></up-loading-page>

    <!-- 蓝色装饰块 -->
    <view class="blue-decor-block" v-if="!loading">
      <text class="welcome-text u-line-1">你好{{ userInfo?.user?.nickname || '' }}</text>
      <text class="platform-name">蓟城山水全域智能运营管理平台</text>
    </view>

    <!-- 内容容器 -->
    <view class="content-wrap">
      <!-- 空状态 -->
      <u-empty
          v-if="!filteredModuleList.length && !loading"
          mode="permission"
      ></u-empty>

      <view class="" v-if="!userInfo?.user?.nickname">
        <text class="welcome-text u-line-1 " style="padding: 20px 0;text-align: center;">本小程序仅限特定服务人群使用，需验证账号后方可登录</text>
        <up-button
            class="login-btn"
            type="primary"
            size="large"
            @click="ToLoginPage"
            shape="circle"
        >
          前往登录
        </up-button>
      </view>

      <!-- 菜单卡片列表 -->
      <view class="menu-card-wrap">
        <up-card
            :title-size="14"
            :titleColor="'#000'"
            :border="false"
            :shadow="true"
            :head-style="{ fontWeight:'500' }"
            :foot-border-top="false"
            v-for="(parentModule, index) in filteredModuleList"
            :key="`$parentModule.id_${index}`"
            :title="parentModule.name"
            class="card-container"
        >
          <template #body>
            <view class="card-content">
              <view
                  v-for="(listItem, listIndex) in parentModule.children"
                  :key="listItem.id"
                  class="content-block"
                  @click="handleMenuClick(listItem)"
              >
                <u-image
                    :src="listItem.icon"
                    mode="aspectFit"
                    width="48px"
                    height="48px"
                    lazy-load
                    radius="8px"
                    class="block-icon"
                ></u-image>
                <text class="grid-text">{{ listItem.name }}</text>
              </view>
            </view>
          </template>
        </up-card>
      </view>

      <!-- 工单统计模块 -->
      <view v-if="isInspectorGlobal" class="work-order-container">
        <view class="header-row">
          <view class="stat-title-main">工单统计</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>

        <up-tabs :list="tabList" @click="handleTabChange" lineWidth="50"></up-tabs>

        <!-- 空数据提示 -->
        <view class="empty-tip" v-if="isEmptyData">
          暂无统计数据
        </view>

        <!-- 图表+图例 左右布局区域 -->
        <view class="chart-wrap" v-else>
          <!-- 左侧图表 -->
          <view class="charts-box">
            <qiun-data-charts
              v-if="!isDatePickerOpen"
              type="ring"
              :opts="chartOpts"
              :chartData="chartData"
            />
          </view>
          <!-- 右侧图例：垂直排列、均分高度 + 点击事件 -->
          <view class="legend-wrap">
            <view
              class="legend-item"
              v-for="(item, idx) in tableData"
              :key="idx"
              @click="handleLegendClick(item)"
            >
              <view class="legend-color" :style="{backgroundColor: COLOR_POOL[idx % COLOR_POOL.length]}"></view>
              <text class="legend-text">{{ item.companyName }}</text>
            </view>
          </view>
        </view>

        <!-- 统计表格 -->
        <view class="stat-table" v-if="!isEmptyData">
          <view class="table-header">
            <text class="table-col">公司名称</text>
            <text class="table-col">工单量</text>
            <text class="table-col">已完成</text>
            <text class="table-col">进行中</text>
          </view>
          <view
            class="table-row"
            v-for="(row, idx) in tableData"
            :key="idx"
          >
            <view class="table-col">
              <view class="dot" :style="{backgroundColor: COLOR_POOL[idx % COLOR_POOL.length]}"></view>
              {{ row.companyName }}
            </view>
            <text class="table-col">{{ row.total }}</text>
            <text class="table-col">{{ row.finish }}</text>
            <text class="table-col"> {{ row.ongoing }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import {ref, computed, reactive, watch} from 'vue';
import {onShow} from '@dcloudio/uni-app';
import {useUserStore} from '@/pinia/user';
import globalConfig from '@/common/config/global';
import cache from '@/common/utils/cache';
import {timeFormat} from '@/uni_modules/uview-plus';
import {iWorkOrderSummary} from "@/api/index/index";

interface MenuItem {
  id: number;
  name: string;
  subtitle?: string;
  type: number;
  sort: number;
  parentId: number;
  icon: string;
  jumpUrl: string;
  miniAppId?: string;
  badgeText?: string;
  badgeColor?: string;
  statisticCount: number | null;
  hasStatistic: boolean;
  extra: any;
  children: MenuItem[];
}

// 接口返回结构定义
interface IOrderSummaryItem {
  companyName: string;
  companyId?: string | number;
  total: number;
  finish: number;
  ongoing: number;
  percent: number;
}
interface IOrderSummaryRes {
  totalNum: string | number;
  legend: string[];
  percents: number[];
  table: IOrderSummaryItem[];
}

// ========== 基础变量 ==========
const loading = ref(true);
const userStore = useUserStore();
const moduleList = ref<MenuItem[]>([]);
const userInfo = ref<any>(cache.get(globalConfig.cache.userInfoKey) || userStore.userInfo || {});
const isInspectorGlobal = ref(false);

const dateRange = ref<string[]>([]);
const maxDate = ref('');
const isDatePickerOpen = ref(false);

const activeTab = ref(0);
const tabList = ref([
  { name: '部派工单' },
  { name: '子公司全量工单' }
]);

// 颜色池，可随意增加颜色，自动循环复用
const COLOR_POOL = ['#e80a0e', '#00f', '#0ff', '#EFD234', '#9c27b0'];

// 接口返回业务数据
const summaryData = reactive<IOrderSummaryRes>({
  totalNum: 0,
  legend: [],
  percents: [],
  table: []
});

// 计算属性：判断是否为空数据
const isEmptyData = computed(() => {
  const num = Number(summaryData.totalNum);
  return num <= 0 || summaryData.table.length === 0;
});
const tableData = computed(() => summaryData.table);

const filteredModuleList = computed(() => {
  return moduleList.value.filter(item => {
    return Array.isArray(item.children) && item.children.length > 0;
  });
});

// ========== uCharts 图表配置 ==========
const showDataLabel = ref(true);
const chartOpts = ref({
  rotate: false,
  rotateLock: false,
  color: COLOR_POOL,
  dataLabel: showDataLabel.value,
  enableScroll: false,
  legend: {
    show: false,
    position: "right",
    lineHeight: 25
  },
  title: {
    name: "工单总量",
    fontSize: 12,
    color: "#666666"
  },
  subtitle: {
    name: "0",
    fontSize: 16,
    color: "#7cb5ec"
  },
  extra: {
    ring: {
      ringWidth: 15,
      activeOpacity: 0.5,
      activeRadius: 20,
      offsetAngle: 0,
      labelWidth: 5,
      border: true,
      borderWidth: 1,
      borderColor: "#FFFFFF",
      linearType: ""
    }
  }
});

const chartData = ref<any>({});

// 组装图表数据
const setChartData = () => {
  const seriesData = summaryData.table.map((item, idx) => {
    const percent = summaryData.percents[idx] ?? 0
    return {
      name: item.companyName || '未知',
      value: percent
    };
  });
  chartData.value = { series: [{ data: seriesData }] };
  chartOpts.value.subtitle.name = String(Number(summaryData.totalNum));
  chartOpts.value.dataLabel = showDataLabel.value;
};

// ========== 请求工单统计接口 ==========
const getWorkOrderSummary = async () => {
  if (!dateRange.value.length) return;
  const [beginTime, endTime] = dateRange.value;
  const queryType = activeTab.value === 0 ? '1' : '0';

  try {
    const res = await iWorkOrderSummary({
      queryType,
      beginTime,
      endTime
    });

    summaryData.totalNum = res.totalNum;
    summaryData.legend = res.legend || [];
    summaryData.percents = res.percents || [];
    summaryData.table = res.table || [];

    setChartData();
  } catch (err) {
    console.error('获取工单统计失败：', err);
    uni.showToast({ title: '数据加载失败', icon: 'none' });
    summaryData.totalNum = 0;
    summaryData.legend = [];
    summaryData.percents = [];
    summaryData.table = [];
    setChartData();
  }
};

// ========== 事件方法 ==========
const handlePopupShow = () => {
  isDatePickerOpen.value = true;
};
const handlePopupHide = () => {
  isDatePickerOpen.value = false;
};
const handleDateConfirm = (val: string[]) => {
  dateRange.value = val;
  getWorkOrderSummary();
};

// Tab 切换
const handleTabChange = (item: any) => {
  activeTab.value = item.index;
  console.log(activeTab.value);
  
  getWorkOrderSummary();
};

// 初始化默认日期
const initDefaultDate = () => {
  const today = new Date();
  maxDate.value = timeFormat(today, 'yyyy-mm-dd');

  const thirtyDaysAgo = new Date(today);
  thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
  dateRange.value = [
    timeFormat(thirtyDaysAgo, 'yyyy-mm-dd'),
    timeFormat(today, 'yyyy-mm-dd')
  ];
};

// 图例点击跳转工单页面
const handleLegendClick = (item: IOrderSummaryItem) => {
  const [beginTime, endTime] = dateRange.value;
  const targetUrl = `/pages-sub/problem/regional-order-manage/list?companyId=${item.companyId}&companyName=${item.companyName}&beginTime=${beginTime}&endTime=${endTime}&queryType=${activeTab.value}`;

  uni.navigateTo({
    url: targetUrl,
    fail: () => {
      uni.showToast({ title: '跳转失败', icon: 'none' });
    }
  });
};

onShow(async () => {
  try {
    loading.value = true;
    userInfo.value = cache.get(globalConfig.cache.userInfoKey) || userStore.userInfo || {};

    const isLogin = () => {
      const token = cache.get(globalConfig.cache.tokenKey) || userStore.token;
      const userInfoVal = userInfo.value;
      return !!token && !!userInfoVal;
    };

    if (!isLogin()) {
      loading.value = false;
      return;
    }

    const rawMenuData = userStore.moduleListInfo || cache.get(globalConfig.cache.moduleListKey);
    moduleList.value = rawMenuData || [];

    // 支持两个角色查看工单统计
    const USER_ROLES = userStore.userInfo?.roles || [];
    isInspectorGlobal.value = USER_ROLES.includes('Inspector_global') || USER_ROLES.includes('Inspector_global_leader');
//  isInspectorGlobal.value
    if(isInspectorGlobal.value){
      initDefaultDate();
      await getWorkOrderSummary();
    }
   

    loading.value = false;
  } catch (error) {
    console.error('获取菜单数据失败：', error);
    moduleList.value = [];
    loading.value = false;
  }
});

const ToLoginPage = () => {
  uni.reLaunch({
    url: '/pages/login/index',
    fail: (err) => {
      console.error('跳转登录页失败：', err);
      uni.showToast({ title: '跳转登录页异常', icon: 'none' });
    }
  });
};

const handleMenuClick = (item: MenuItem) => {
  if (!item.jumpUrl) {
    uni.showToast({ title: '暂无跳转链接', icon: 'none', duration: 2000 });
    return;
  }
  uni.navigateTo({
    url: item.jumpUrl,
    fail: (err) => {
      console.error('页面跳转失败：', err);
      uni.showToast({ title: '页面路径错误', icon: 'none', duration: 2000 });
    }
  });
};

const goToQuickWorkOrder = () => { };
const showDatePicker = () => { };

watch(showDataLabel, () => {
  chartOpts.value.dataLabel = showDataLabel.value;
});
</script>

<style scoped lang="scss">
.page-container {
  position: relative;
  min-height: 100vh;
}

.blue-decor-block {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  padding: 80px 15px 115px;
  background: url("https://img.jichengshanshui.com.cn:28207/appimg/bg.jpg") no-repeat;
  background-size: 100% 100%;
  z-index: 1;
  color: #fff;
  text-align: left;

  .welcome-text {
    font-size: 16px;
    display: block;
    margin-bottom: 4px;
  }

  .platform-name {
    margin-bottom: 10px;
    font-size: 16px;
    display: block;
  }
}

.content-wrap {
  position: relative;
  z-index: 2;
  padding: 125px 0 0;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.menu-card-wrap {
  width: 100%;
}

.card-container {
  --u-card-content-padding: 0;
  border-radius: 4px;
  overflow: hidden;
}

.card-content {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.content-block {
  width: calc((100% - 3 * 10px) / 4);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 7px 0;
  border-radius: 4px;
  touch-action: manipulation;
  transition: background-color 0.2s;
}

.content-block:active {
  background-color: #e9ecef;
}

.block-icon {
  display: block;
  margin: 0 auto;
}

.grid-text {
  font-size: 13px;
  color: #1C1C1C;
  text-align: center;
  margin-top: 5px;
  display: block;
}

/* 工单模块 */
.work-order-container {
  margin: 0 15px;
  background: #ffff;
  padding: 13px 15px;
}

.header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.stat-title-main {
  font-size: 16px;
  font-weight: 600;
  color: #000;
}

.date-picker-wrap {
  padding: 2px 4px;
  border-radius: 3px;
  transition: background-color 0.2s;
  position: relative;
  z-index: 9999 !important;
  &:active {
    background-color: #f5f5f7;
  }
}

/* 空数据提示样式 */
.empty-tip {
  text-align: center;
  padding: 60px 0;
  font-size: 14px;
  color: #999;
}

/* 图表+图例 左右布局核心样式 */
.chart-wrap {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

/* 左侧图表容器 */
.charts-box {
  width: 70%;
  height: 220px;
}

/* 右侧图例容器 */
.legend-wrap {
  width: 30%;
  height: 220px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}


/* 单个图例项 */
.legend-item {
  display: flex;
  align-items: center;
  padding: 4px 6px;
  border-radius: 4px;
  transition: background-color 0.2s;
  &:active {
    background-color: #f0f0f0;
  }
}

.legend-color {
  /* 固定尺寸，禁止压缩 */
  flex: 0 0 12px;
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 5px;
}

.legend-text {
  font-size: 13px;
  color: #333;
  /* 单行 + 溢出省略 */
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 表格样式 */
.stat-table {
  margin-top: 20px;
  border: 1px solid #eee;
  border-radius: 4px;
  overflow: hidden;
}

.table-header, .table-row {
  display: flex;
  align-items: center;
  padding: 10px 5px;
  border-bottom: 1px solid #eee;
  &:last-child {
    border-bottom: none;
  }
}

.table-header {
  background-color: #fafafa;
  font-weight: bold;
}

.table-col {
  flex: 1;
  text-align: center;
  font-size: 13px;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 表格圆点 */
.dot {
  flex: 0 0 10px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 5px;
}
</style>