You need to sign in or sign up before continuing.
VisitAnalysis.vue 13.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
<template>
  <span style="margin-left: 50px; font-size: 18px">选择年份:</span>
  <a-select
    v-model:value="yearValue"
    show-search
    placeholder="请选择"
    style="width: 200px"
    :options="yearOptions"
    :filter-option="filterOption"
    @change="handleChangeYear"
  />
  <span style="margin-left: 50px; font-size: 18px">对比年份:</span>
  <a-select
    v-model:value="value1"
    show-search
    placeholder="请选择"
    style="width: 200px"
    :options="yearOptions"
    :filter-option="filterOption"
    mode="multiple"
  />
  <span style="right: 10px"
    ><a-button
      type="default"
      @click="clearData"
      :style="{ marginLeft: '100px', borderRadius: '5px 5px 5px 5px' }"
    >
      重置
    </a-button>
    <a-button
      :style="{ marginLeft: '20px', borderRadius: '5px 5px 5px 5px' }"
      shape="default"
      type="primary"
      @click="updateData"
      >查询</a-button
    ></span
  >
  <div style="position: fixed; top: 80px; right: 70px">
    <a-radio-group
      v-model:value="periodCopy"
      class="custom-radio-group"
      :style="{ marginLeft: '100px' }"
    >
      <a-radio-button value="月" @click="handlePeriodChange('月')">月</a-radio-button>
      <a-radio-button value="年" @click="handlePeriodChange('年')">年</a-radio-button>
    </a-radio-group>
  </div>
  <div ref="chartRef" :style="{ height: '500px', width }"></div>
</template>

<script lang="ts" setup>
  import { ref, Ref, watchEffect } from 'vue';
  import { useECharts } from '/@/hooks/web/useECharts';
  import { basicProps } from './props';
  import { max } from 'lodash-es';
  import { useDataStoreWithOut } from '/@/store/modules/data';
  import { getChartData } from '/@/api/project/global';
  import { dateTime, period } from '/@/store/modules/user';
  import { useMessage } from '/@/hooks/web/useMessage';

  defineProps({
    ...basicProps,
  });
  const yearValue = ref('2025');
  const dateTimes = ref();
  const value1 = ref();
  const yearOptions = [
    {
      label: '2025',
      value: 2025,
    },
    {
      label: '2024',
      value: 2024,
    },
    {
      label: '2023',
      value: 2023,
    },
  ];
  const periodCopy = ref('月');
  const monthOrYear = ref('月');
  const { createMessage } = useMessage(); //错误提示组件
  const { error } = createMessage;
  const chartRef = ref<HTMLDivElement | null>(null);
  const { setOptions } = useECharts(chartRef as Ref<HTMLDivElement>);
  const filterOption = (input: string, option: any) => {
    return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0;
  };
  function updateData() {
    if (period.value == null) {
      period.value = '月';
      periodCopy.value = '月';
    } else {
      period.value = monthOrYear.value;
    }
    dateTime.value = yearValue.value;
    dateTimes.value = value1.value;
  }
  function clearData() {
    yearValue.value = null;
    period.value = null;
    dateTime.value = null;
    value1.value = [];
    dateTimes.value = [];
  }
  function handlePeriodChange(value) {
    //没选年份报错
    if (value == '月') {
      if (dateTime.value == undefined) {
        error('请选择年份');
        return;
      }
    } else if (value == '年') {
      yearValue.value = null;
      dateTime.value = null;
    }
    monthOrYear.value = value;
    period.value = value;
  }
  function handleChangeYear(value) {
    yearValue.value = value;

    if (period.value == '年') {
      dateTime.value = value;
    }
  }
  const dataStore = useDataStoreWithOut();
  //监控选择器变化
  watchEffect(async () => {
    const periodValue = period.value;
    const dateTimeValue = dateTime.value;
    const customerCodeParams = dateTimes.value
      ? dateTimes.value.map((code) => `dateTimes=${encodeURIComponent(code)}`).join('&')
      : '';
    const dateTimeCode = ref();
    const periodParam = ref();
    if (dateTime.value && period.value) {
      dateTimeCode.value = `dateTime=${encodeURIComponent(dateTimeValue)}`;
      periodParam.value = `period=${encodeURIComponent(periodValue)}`;
    } else if (period.value) {
      periodParam.value = `period=${encodeURIComponent(periodValue)}`;
    }

    // 构造完整请求 URL
    const baseURL = '/basic-api/order/erp/index/chartData';
    const fullURL = `${baseURL}?${customerCodeParams}&${periodParam.value}&${dateTimeCode.value}`;
    // 使用 fetch 或其他请求库发送请求
    const response = await fetch(fullURL);
    const chartData = await response.json();
    // const data = dataStore?.getChartData || {};
    // const res = await getChartData({
    //   dateTime: dateTime.value,
    //   period: period.value,
    //   dateTimes: dateTimes.value,
    // });

    // const res = [
    //   { date: '2024-01', totalPrice: 499586, yearType: '2024' },
    //   { date: '2024-01', totalPrice: 234586, yearType: '2025' },
    //   { date: '2024-02', totalPrice: 442786, yearType: '2024' },
    //   { date: '2024-02', totalPrice: 642786, yearType: '2025' },
    //   { date: '2024-03', totalPrice: 520464, yearType: '2024' },
    //   { date: '2024-03', totalPrice: 520464, yearType: '2023' },
    //   { date: '2024-04', totalPrice: 311304, yearType: '2024' },
    //   { date: '2024-04', totalPrice: 311304, yearType: '2023' },
    //   { date: '2024-05', totalPrice: 181457, yearType: '2024' },
    //   { date: '2024-06', totalPrice: 257328, yearType: '2024' },
    //   { date: '2024-07', totalPrice: 316477, yearType: '2024' },
    //   { date: '2024-08', totalPrice: 318257, yearType: '2024' },
    //   { date: '2024-09', totalPrice: 822149, yearType: '2024' },
    //   { date: '2024-10', totalPrice: 553308, yearType: '2024' },
    //   { date: '2024-11', totalPrice: 654249, yearType: '2024' },
    //   { date: '2024-12', totalPrice: 2884033, yearType: '2024' },
    // ];
    // const res = [
    //   { date: '2025', totalPrice: 499586, yearType: '' },
    //   { date: '2023', totalPrice: 234586, yearType: '' },
    //   { date: '2024', totalPrice: 442786, yearType: '' },
    // ];
    // const res = chartData.data;
    // // console.log(res, '5656res1', dateTimes.value);
    // console.log('5656res1', dateTimes.value);
    // // 获取去重的所有类型
    // const types = [...new Set(res.map((item) => item.yearType))];

    // // 初始化 x 轴和 y 轴数据
    // const x: string[] = [];
    // const yData: Record<string, number[]> = {};

    // // 初始化 y 轴数据容器
    // types.forEach((yearType) => {
    //   yData[yearType] = [];
    // });
    // // 遍历数据,填充 x 轴和各类型的 y 轴数据
    // for (const item of res) {
    //   if (!x.includes(item.date)) {
    //     x.push(item.date); // 避免重复日期
    //   }
    //   yData[item.yearType].push(item.totalPrice);
    // }
    const res = chartData.data;
    const isYearMonth = res.every((item) => /^\d{4}-\d{2}$/.test(item.date));
    if (isYearMonth) {
      // 提取所有的年份和月份,并按顺序生成 x 轴数据
      const x = [...new Set(res.map((item) => item.date))].sort((a, b) => {
        const [yearA, monthA] = a.split('-').map(Number);
        const [yearB, monthB] = b.split('-').map(Number);
        return yearA !== yearB ? yearA - yearB : monthA - monthB;
      });
      // 获取所有的 yearType 类型
      const types = [...new Set(res.map((item) => item.yearType))];

      // 初始化 x 轴的月份(按照 1-12 月顺序)
      const months = Array.from({ length: 12 }, (_, i) => `${i + 1}`.padStart(2, '0'));

      // 初始化 x 轴的日期(完整的年份和月份,如 2025-01 到 2025-12)

      // 初始化 yData,确保每种类型都有 12 个数据点(初始值为 0)
      const yData: Record<string, number[]> = {};
      types.forEach((yearType) => {
        yData[yearType] = Array(12).fill(0);
      });

      // 遍历数据,将 totalPrice 填充到对应的 yearType 和月份中
      res.forEach(({ date, totalPrice, yearType }) => {
        const monthIndex = months.indexOf(date.split('-')[1]); // 获取月份的索引
        if (monthIndex !== -1) {
          yData[yearType][monthIndex] = totalPrice;
        }
      });
      const maxY =
        Math.ceil(
          (Math.max(
            ...(Object.values(yData)
              .flat()
              .filter((v) => v !== null) as number[]),
          ) +
            300000) /
            100000,
        ) * 100000;

      // 设置不同类型的颜色
      const colors = ['#5ab1ef', '#019680', '#f36c6c', '#d48265', '#91c7ae'];

      // 构造 series 数据
      const series = types.map((yearType, index) => ({
        name: yearType, // 用 type 作为图例名称
        smooth: true,
        data: yData[yearType],
        type: 'line',
        areaStyle: {
          // color: 'transparent', // 设置折线下方区域为透明
        },
        itemStyle: {
          color: colors[index % colors.length], // 分配颜色
        },
      }));

      // 配置图表
      setOptions({
        legend: {
          data: types, // 动态设置图例,显示所有类型
          top: 10, // 图例距离顶部 10px
        },
        grid: {
          left: '1%',
          right: '1%',
          top: 40, // 图表距离顶部 40px(legend + 30px)
          bottom: 0,
          containLabel: true,
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              width: 1,
              color: '#019680',
            },
          },
        },
        xAxis: {
          type: 'category',
          data: x,
          splitLine: {
            show: true,
            lineStyle: {
              width: 1,
              type: 'solid',
              color: 'rgba(226,226,226,0.5)',
            },
          },
          axisTick: {
            show: false,
          },
        },
        yAxis: [
          {
            type: 'value',
            max: maxY + 20,
            splitNumber: 20,
            axisTick: {
              show: false,
            },
            splitArea: {
              show: true,
              areaStyle: {
                color: ['rgba(255,255,255,0.2)', 'rgba(226,226,226,0.2)'],
              },
            },
            axisLabel: {
              formatter: function (value) {
                return '$' + value; // Add "$" symbol to the y-axis label
              },
            },
          },
        ],
        grid: {
          left: '1%',
          right: '1%',
          top: '2%',
          bottom: 0,
          containLabel: true,
        },
        series,
      });
    } else {
      const x = [];
      const y = [];

      // 遍历 res,提取 date 和 totalPrice
      for (const item of res) {
        console.log(item, 'Processing item');
        x.push(item.date); // 提取日期
        y.push(item.totalPrice); // 提取总价
      }

      const data = { x, y };

      const maxY = data?.y ? Math.max(...data.y) : 0;
      setOptions({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            lineStyle: {
              width: 1,
              color: '#019680',
            },
          },
        },
        xAxis: {
          type: 'category',
          data: data?.x,
          splitLine: {
            show: true,
            lineStyle: {
              width: 1,
              type: 'solid',
              color: 'rgba(226,226,226,0.5)',
            },
          },
          axisTick: {
            show: false,
          },
        },
        yAxis: [
          {
            type: 'value',
            max: maxY + 20,
            splitNumber: 20,
            axisTick: {
              show: false,
            },
            splitArea: {
              show: true,
              areaStyle: {
                color: ['rgba(255,255,255,0.2)', 'rgba(226,226,226,0.2)'],
              },
            },
          },
        ],
        grid: { left: '1%', right: '1%', top: '2  %', bottom: 0, containLabel: true },
        series: [
          {
            smooth: true,
            data: data?.y,
            type: 'line',
            areaStyle: {},
            itemStyle: {
              color: '#5ab1ef',
            },
          },
          // {
          //   smooth: true,
          //   data: [
          //     33, 66, 88, 333, 3333, 5000, 18000, 3000, 1200, 13000, 22000, 11000, 2221, 1201, 390,
          //     198, 60, 30, 22, 11,
          //   ],
          //   type: 'line',
          //   areaStyle: {},
          //   itemStyle: {
          //     color: '#019680',
          //   },
          // },
        ],
      });
    }
  });
</script>
<style scoped>
  .custom-radio-group .ant-radio-button-wrapper {
    border-color: #1684fc; /* 未选中按钮的边框颜色 */
    background-color: white; /* 未选中按钮的背景颜色为白色 */
    color: #1684fc; /* 未选中按钮的文字颜色为 #1684fc */
  }

  .custom-radio-group .ant-radio-button-wrapper-checked {
    border-color: #1684fc; /* 选中按钮的边框颜色 */
    background-color: #1684fc; /* 选中按钮的背景颜色为 #1684fc */
    color: white; /* 选中按钮的文字颜色为白色 */
  }

  .custom-radio-group .ant-radio-button-wrapper-checked:hover {
    background-color: #1684fc; /* 悬停在选中按钮时保持相同的背景颜色 */
    color: white; /* 悬停在选中按钮时保持文字为白色 */
  }

  .custom-radio-group .ant-radio-button-wrapper:hover {
    border-color: #1684fc; /* 悬停在未选中按钮时的边框颜色 */
  }

  .custom-radio-group .ant-radio-button-wrapper:not(.ant-radio-button-wrapper-checked):hover {
    color: #1684fc; /* 悬停在未选中按钮时文字颜色为 #1684fc */
  }
</style>