<template>
  <div class="home-container">
    <!-- 头部 -->
    <s-header
      :name="sys ? sys.title : $t('public.sysName')"
      :noback="true"
      :isFixed="false"
      class="app-header"
    />
    <!-- 主体内容 -->
    <main class="main-content">
      <!-- 通知栏 -->
      <van-notice-bar
        v-if="noticeContent.title"
        class="smart-notice"
        left-icon="volume-o"
        :text="noticeContent.title"
        @click="noticeClk"
        :scrollable="true"
        color="#404B74"
        background="#ffffff"
      />

      <!-- 用户信息卡 -->
      <div class="user-card">
        <div class="user-info">
          <div class="avatar">
            <van-icon name="user-circle-o" size="48px" color="#2c87c8" />
          </div>
          <div class="user-meta">
            <h3 class="user-name">{{ userName }}</h3>
            <div class="device-status">
              <span class="status-item total">
                <van-icon name="desktop-o" size="14px" />
                {{ $t("home.totalEquipment") }}:
                {{ equipStatus.machineTotalNum }}
              </span>
              <span class="status-item running">
                <van-icon name="desktop-o" size="14px" />
                {{ $t("home.running") }}: {{ equipStatus.machineUseNum }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <dateSelectList
        v-if="showDataDiv"
        @update="update($event)"
      ></dateSelectList>
      <typeDownMenu
        v-if="showDataDiv"
        :isHome="true"
        @upselectdata="upselectdata($event)"
      ></typeDownMenu>
      <!-- 数据概览 -->
      <section v-if="showDataDiv" class="data-section">
        <div class="section-header">
          <div class="header-main">
            <h3 class="section-title">
              {{ $t("home.dataOverview") }}
            </h3>
            <div class="data-entry" @click="pushOrderCenter">
              <span>{{ $t("home.orderData") }}</span>
              <van-icon name="arrow" class="entry-arrow" />
            </div>
          </div>
        </div>

        <!-- 数据卡片 -->
        <div class="data-cards">
          <div class="data-card income">
            <div class="card-content">
              <div class="card-text">
                <div class="value">
                  {{ currencySymbol }}{{ salesVolume.toFixed(2) }}
                </div>
                <div class="label">{{ $t("home.totalIncome") }}</div>
              </div>
            </div>
          </div>

          <div class="data-card sales">
            <div class="card-content">
              <div class="card-text">
                <div class="value">{{ salesNumber }}</div>
                <div class="label">{{ $t("home.productNum") }}</div>
              </div>
            </div>
          </div>
        </div>

        <div
          v-if="showDataDiv"
          class="c-text-c"
          style="font-size: 18px; margin-top: 5px"
        >
          {{ Format_time(dateSelect.startDate, "YYYY/MM/DD") }}-{{
            Format_time(dateSelect.endDate, "YYYY/MM/DD")
          }}
        </div>

        <!-- 图表 -->
        <div class="chart-container">
          <div
            v-if="!noData(salesVolume, salesNumber)"
            ref="chartBox"
            class="sales-chart"
          ></div>
          <k-no-data v-else />
        </div>
      </section>

      <!-- 常用工具 -->
      <section class="tools-section">
        <h3 class="section-title">{{ $t("home.commonTools") }}</h3>
        <van-row :gutter="12">
          <van-col v-for="(item, index) in pushToolList" :key="index" span="8">
            <div class="tool-item" @click="pushToolPage(item)">
              <img class="tool-icon" :src="showLogo(item)" />
              <span class="tool-name">{{ $t("permission." + item) }}</span>
            </div>
          </van-col>
        </van-row>
      </section>
    </main>

    <!-- 通知弹窗 -->
    <kDialog
      :dialogTitle="$t('home.notificationPop.notification')"
      :cancelBtnTxt="$t('home.notificationPop.nextTime')"
      :confirmBtnTxt="$t('home.notificationPop.roger')"
      ref="kDialogRef"
      @confirmclk="confirmClk"
    >
      <template #content>
        <div
          class="o-w"
          style="max-height: 50vh; overflow-y: auto"
          v-html="noticeContent.note"
        ></div>
      </template>
    </kDialog>
    <van-dialog
      v-model:show="showAlarm"
      :title="$t('home.alarmTitle')"
      @confirm="confirmAlarm"
    >
      <div style="max-height: 30vh; overflow-y: auto">
        <div
          v-for="(item, index) in alarmList"
          :key="index"
          style="padding: 2px 5px"
        >
          <van-cell
            :title="
              $t('home.alarmDevice') +
              (item.name ? item.name : item.clientId.slice(-6)) +
              $t('home.alarmContent') +
              item.alarmContent
            "
          />
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
// 导入无数据组件
import kNoData from "../../components/commom/kNoData/index.vue";
import kDialog from "../../components/commom/kDialog/index.vue";
import { onMounted, ref, nextTick } from "vue";
import sHeader from "../../components/SimpleHeader";
import dateSelectList from "../../components/dateSelectList";
import typeDownMenu from "../../components/typeDownMenu";
import { getLoginUser, Format_time } from "../../common/js/utils";
import { useRouter } from "vue-router";
import {
  getStatistics,
  Api_getNotice,
  Api_postMachineNum,
  Api_getUpdateNotice,
  getIsAlarm,
} from "../../service/home";
import { getAdminRole } from "@/service/user";
import dateUtil from "../../utils/dateUtil";
import { useI18n } from "vue-i18n";
import { showToast } from "vant";
import { getLocal, setLocal, navigatorLanguage } from "@/common/js/utils";

export default {
  name: "home",
  components: {
    sHeader,
    dateSelectList,
    typeDownMenu,
    kDialog,
    kNoData,
  },
  setup() {
    // 设备状况
    const equipStatus = ref({});
    // 获取设备情况
    const getMachineNum = () => {
      Api_postMachineNum({ adminId: user.id }).then((res) => {
        equipStatus.value = res.data.data || {};
      });
    };
    const noticeContent = ref({});
    // 获取公告
    const getNotice = () => {
      Api_getNotice({ adminId: user.id }).then((res) => {
        noticeContent.value = res.data.data || {};
      });
    };
    const { t } = useI18n();
    // 通知弹窗
    const kDialogRef = ref(null);
    // 点击通知栏
    const noticeClk = () => {
      kDialogRef.value.openDialog();
    };
    // 点击右侧按钮
    const confirmClk = () => {
      Api_getUpdateNotice({
        adminId: user.id,
      }).then((res) => {
        showToast(res.data.message);
        setTimeout(() => {
          getNotice();
        }, 500);
      });
    };
    const firstLogin = ref(true);
    const user = getLoginUser();
    const router = useRouter();
    const userName = ref(user.name);
    const sys = ref(null);
    const sysTitle = ref("");
    // 自定义货币符号
    const currencySymbol = ref("￥");
    if (user.currencySymbol) {
      currencySymbol.value = user.currencySymbol;
    } else {
      currencySymbol.value = "￥";
    }

    // 图表对象
    const chartBox = ref();
    let chartObj = null;
    // 跳转订单中心
    const pushOrderCenter = () => {
      router.push({ path: "/orderCenter" });
    };
    const dateSelect = ref({});
    const update = (uDate) => {
      dateSelect.value = uDate;
      getStatisticsFun();
    };
    let typeSelectData = {};
    const upselectdata = (uSData) => {
      typeSelectData = uSData;
      getStatisticsFun();
    };
    const salesVolume = ref(0);
    const salesNumber = ref(0);
    const orderNumber = ref(0);
    // 查询图表
    const getStatisticsFun = async () => {
      const params = {
        ...dateSelect.value,
        adminId:
          typeSelectData.adminId === null ? user.id : typeSelectData.adminId,
        ifForeign:
          typeSelectData.ifForeign === ""
            ? user.ifForeign
            : typeSelectData.ifForeign,
        payType: typeSelectData.payType,
        clientId: typeSelectData.clientId,
        username: typeSelectData.userName, // 商家
        companyType: typeSelectData.companyType, // 公司平台
        machineType: typeSelectData.machineType, // 设备类型
        equipmentId:
          typeSelectData.equipmentId === "" ? null : typeSelectData.equipmentId,
      };
      const { data } = await getStatistics(params);
      if (data.code && data.data) {
        salesVolume.value = 0;
        salesNumber.value = 0;
        orderNumber.value = 0;
        data.data.series[0].data.forEach((item) => {
          salesNumber.value = parseInt(salesNumber.value + item);
        });
        data.data.series[1].data.forEach((item) => {
          salesVolume.value = parseFloat(salesVolume.value) + parseFloat(item);
        });
        data.data.series[2].data.forEach((item) => {
          orderNumber.value = parseInt(orderNumber.value + item);
        });
        data.data.categories.forEach((item, index) => {
          if (item == "周1") {
            data.data.categories[index] = t("home.week.mon");
          }
          if (item == "周2") {
            data.data.categories[index] = t("home.week.tue");
          }
          if (item == "周3") {
            data.data.categories[index] = t("home.week.wed");
          }
          if (item == "周4") {
            data.data.categories[index] = t("home.week.thu");
          }
          if (item == "周5") {
            data.data.categories[index] = t("home.week.fri");
          }
          if (item == "周6") {
            data.data.categories[index] = t("home.week.sat");
          }
          if (item == "周日") {
            data.data.categories[index] = t("home.week.sun");
          }
        });
        // 解决eacharts与v-if的渲染问题
        await nextTick();
        if (chartBox.value) {
          chartObj = window.echarts.init(chartBox.value, null, {
            renderer: "canvas",
            useDirtyRect: false,
          });
          const option = {
            tooltip: {
              trigger: "axis",
              axisPointer: {
                type: "shadow",
              },
            },
            grid: {
              top: "10%",
              left: "3%",
              right: "4%",
              bottom: "10%",
              containLabel: true,
              height: "auto",
            },
            legend: {
              bottom: 0,
              right: 10,
              itemWidth: 10,
              itemHeight: 10,
              icon: "rect",
            },
            // 固定屏幕显示多少个，其余的滑动
            dataZoom: [
              // {
              // 	type: 'slider',
              // 	xAxisIndex: 0,
              // 	filterMode: 'none',
              // 	// 开始的值
              // 	startValue: null,
              // 	// 结束的值
              // 	endValue: null,
              // 	// 锁定滑动的区域
              // 	// zoomLock:true,
              // },
              {
                type: "inside",
                xAxisIndex: 0,
                filterMode: "none",
                startValue: 0,
                endValue: 50,
                zoomLock: true,
              },
            ],
            xAxis: {
              type: "category",
              axisLabel: {
                rotate: 35,
              },
              data: data.data.categories,
            },
            yAxis: {
              type: "value",
            },
            series: [
              {
                ...data.data.series[0],
                type: "bar",
                itemStyle: { color: "#f6d258" },
                name: t("home.productNum"),
                label: {
                  show: true,
                  position: "top",
                },
              },
              {
                ...data.data.series[1],
                type: "bar",
                itemStyle: { color: "#2c87c8" },
                name: t("home.salesAmount"),
                label: {
                  show: true,
                  position: "top",
                },
              },
            ],
          };

          option.dataZoom[0]["startValue"] =
            data.data.categories[data.data.categories.length - 4];
          option.dataZoom[0]["endValue"] =
            data.data.categories[data.data.categories.length - 1];
          // option.dataZoom[0].start =
          //   (data.data.categories.length - 5) * 10;
          // option.dataZoom[0].end =
          //   (data.data.categories.length - 1) * 10;
          chartObj && chartObj.setOption(option);
          //图形宽度随屏幕宽度改变而改变
          window.onresize = chartObj.resize;
        }
      }
    };
    const pushToolList = ref([]);
    // 是否有报警
    const showAlarm = ref(false);
    const alarmList = ref([]);
    // 页面初始化
    onMounted(async () => {
      // 加载样式
      // 检测语言是否有缓存
      if (!getLocal("curLang")) {
        //  根据浏览器语言重新缓存到localstorage
        setLocal("curLang", navigatorLanguage());
      }
      if (localStorage.getItem("loginSys")) {
        const loginSysString = localStorage.getItem("loginSys");
        sys.value = JSON.parse(loginSysString);
      }
      firstLogin.value = localStorage.getItem("firstLogin");
      // 设置菜单权限
      // menuSet();
      // 设置菜单权限, 只执行一次
      // once(menuSet);
      dateSelect.value = {
        chartType: "day",
        startDate: dateUtil.formateDate(
          new Date(new Date(new Date().getTime()).setHours(0, 0, 0, 0)),
          "yyyy-MM-dd hh:mm:ss"
        ),
        endDate: dateUtil.formateDate(
          new Date(new Date(new Date().getTime()).setHours(23, 59, 59, 59)),
          "yyyy-MM-dd hh:mm:ss"
        ),
      };
      // 获取账号权限
      getAccountPer();
      typeSelectData = {
        userName: user.username,
        clientId: null,
        adminId: null,
      };
      getStatisticsFun();
      // 获取首页公告
      getNotice();
      // 获取设备情况
      getMachineNum();
      if (user.type > 1) {
        // 查询设备是否有报警
        const queryParams = {
          adminId: user.id,
          todayDate: dateUtil.formateDate(new Date(), "yyyy-MM-dd"), // 当天时间
        };
        const { data } = await getIsAlarm(queryParams);
        if (data.data != null) {
          if (firstLogin.value == "true") {
            showAlarm.value = true;
          }
          alarmList.value = data.data;
        }
      }
      getDomainFunc();
    });

    const getDomainFunc = async () => {
      const currentDomain = window.location.href;
      console.log("href >>>", currentDomain);
      switch (true) {
        case currentDomain.includes("sskj.qxfoodom"): // 食神科技 sskj.qxfoodom.com
          sysTitle.value = "食神科技";
          break;
        default:
          sysTitle.value = t("public.sysName");
      }
    };

    const confirmAlarm = () => {
      localStorage.setItem("firstLogin", false);
    };

    const menuList = [];

    const showDataDiv = ref(true);

    const isOrderData = ref(true);

    // 获取账号权限
    const getAccountPer = async () => {
      const { data } = await getAdminRole({ adminId: user.id });
      if (data.code === "00000") {
        if (data.data.menuCodesJson !== null) {
          menuList.value = sortedArray(data.data.menuCodesJson);
        }
        // 子商家以上级别，默认可以看到订单详情
        if (user.type === 3 && !menuList.value.includes("M4")) {
          // 如果有数据概览权限 和 订单数据权限
          if (!menuList.value.includes("M4")) {
            showDataDiv.value = false;
          }
          if (!menuList.value.includes("M14")) {
            isOrderData.value = false;
          }
        }
        // 组合菜单权限
        menuList.value.forEach((item) => {
          // 设备管理M1，设备查看M2，订单数据M4，任务消息M6，销售排行M11，数据概览M14，订单退款M16，系统脱机M17 这些图标不用加载到底部菜单上
          if (
            item !== "M1" &&
            item !== "M2" && // M2本身就无logo
            item !== "M4" &&
            item !== "M6" &&
            item !== "M8" &&
            item !== "M11" &&
            item !== "M12" &&
            item !== "M13" &&
            item !== "M18" &&
            item !== "M14" &&
            item !== "M16" &&
            item !== "M17" &&
            item !== "M20"
          ) {
            pushToolList.value.push(item);
          }
        });
      }
    };

    // 解析 + 排序计算属性
    const sortedArray = (value) => {
      try {
        // 1. 安全解析JSON
        const parsed = JSON.parse(value);
        if (!Array.isArray(parsed)) return [];

        // 2. 自定义排序函数
        const getNumber = (str) => parseInt(str.match(/\d+/)?.[0] || 0);

        // 3. 执行排序（数字从小到大）
        return [...parsed].sort((a, b) => {
          return getNumber(a) - getNumber(b);
        });
      } catch (error) {
        console.error("解析失败:", error);
        return [];
      }
    };

    // 常用操作跳转页面
    const pushToolPage = (index) => {
      switch (index) {
        case "M1":
          router.push({ path: "/device" }); // 设备管理
          break;
        case "M3":
          router.push({ path: "/accountOperation" }); // 账户操作
          break;
        case "M4":
          router.push({ path: "/orderCenter" }); // 订单数据
          break;
        case "M5":
          router.push({ path: "/advertManage" }); // 广告管理
          break;
        case "M6":
          router.push({ path: "/taskMessage" });
          break;
        case "M7":
          router.push({ path: "/discountCode" });
          break;
        case "M8":
          router.push({ path: "/accountPer" });
          break;
        case "M9":
          router.push({ path: "/orderExport" });
          break;
        case "M10":
          router.push({ path: "/subLedgerManage" });
          break;
        case "M11":
          router.push({ path: "/robotranking" });
          break;
        case "M12":
          router.push({ path: "/joinpayMch" });
          break;
        case "M13":
          router.push({ path: "/shandeMch" });
          break;
        case "M15":
          router.push({ path: "/alarmHistory" }); // 报警历史
          break;
        case "M18":
          router.push({ path: "/labelMan" });
          break;
        case "M19":
          router.push({ path: "/apkManage" });
          break;
        case "M20":
          router.push({ path: "/merchantManage" });
          break;
      }
    };

    // 如果是空数据
    const noData = (volumes, nums) => {
      if (!volumes && !nums) {
        return true;
      }
      return false;
    };
    // 显示logo
    const showLogo = (url) => {
      return require(`../../assets/home/${url}.png`);
    };

    return {
      user,
      userName,
      update,
      upselectdata,
      chartBox,
      pushOrderCenter,
      pushToolList,
      pushToolPage,
      salesVolume,
      salesNumber,
      orderNumber,
      sys,
      noticeClk,
      confirmClk,
      kDialogRef,
      noData,
      equipStatus,
      noticeContent,
      showLogo,
      dateSelect,
      Format_time,
      showDataDiv,
      currencySymbol,
      showAlarm,
      alarmList,
      confirmAlarm,
      sysTitle,
    };
  },
};
</script>

<style lang="less" scoped>
@import "../../common/style/common";

.home-container {
  --primary-color: #2c87c8;
  --secondary-color: #07c160;
  --text-primary: #2d354d;
  --text-secondary: #666f8c;
  --background: #f5f7fa;
  --card-radius: 12px;
  --shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  --tabbar-height: 40px;
  --tabbar-padding: calc(var(--tabbar-height) + 20px);

  background: var(--background);
  min-height: 100vh;

  .app-header {
    box-shadow: var(--shadow);
  }

  .main-content {
    background-color: #f5f7fa;
    height: calc(100% - 95px);
    overflow: auto;
    overflow-x: hidden;
  }

  .smart-notice {
    border-radius: 8px;
    font-weight: 600;
  }

  .user-card {
    background: white;
    border-radius: var(--card-radius);
    padding: 16px;
    margin-bottom: 20px;
    margin: 10px;
    box-shadow: var(--shadow);

    .user-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .user-meta {
        flex: 1;

        .user-name {
          margin: 0 0 4px;
          font-size: 18px;
          color: var(--text-primary);
        }

        .device-status {
          display: flex;
          gap: 16px;
          font-size: 13px;

          .status-item {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 4px 8px;
            border-radius: 16px;
            background: #f5f7fa;

            &.total {
              color: var(--primary-color);
              background: rgba(77, 106, 221, 0.1);
            }

            &.running {
              color: var(--secondary-color);
              background: rgba(7, 193, 96, 0.1);
            }
          }
        }
      }
    }
  }

  .data-section {
    background: white;
    border-radius: var(--card-radius);
    padding: 16px;
    margin: 10px;
    box-shadow: var(--shadow);

    .section-header {
      .header-main {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        .section-title {
          position: relative;
          margin: 0;
          font-size: 16px;
          color: var(--text-primary);
          display: flex;
          align-items: center;

          .title-arrow {
            margin-left: 6px;
            font-size: 14px;
            transition: transform 0.2s;
          }

          &:hover .title-arrow {
            transform: translateX(2px);
          }
        }

        .data-entry {
          display: flex;
          align-items: center;
          color: var(--primary-color);
          font-size: 13px;
          cursor: pointer;
          transition: all 0.2s;
          padding: 4px 8px;
          border-radius: 16px;
          background: rgba(77, 106, 221, 0.05);

          .entry-arrow {
            margin-left: 4px;
            font-size: 12px;
            transition: transform 0.2s;
          }
        }
      }
    }

    .data-cards {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 12px;
      margin-bottom: 20px;

      .data-card {
        padding: 15px;
        border-radius: 8px;

        &.income {
          background: linear-gradient(
            135deg,
            var(--primary-color) 0%,
            #5ebcff 100%
          );
          color: white;
        }

        &.sales {
          background: linear-gradient(135deg, #ebc611 0%, #fce15b 100%);
          color: white;
        }

        .card-content {
          display: flex;
          align-items: center;

          .card-text {
            .value {
              font-size: 18px;
              font-weight: 600;
              line-height: 1.2;
            }

            .label {
              font-size: 13px;
              opacity: 0.9;
            }
          }
        }
      }
    }

    .chart-container {
      height: 300px;
      background: white;
      border-radius: 8px;

      .sales-chart {
        height: 270px;
        width: 100%;
      }
    }
  }

  .tools-section {
    padding: 10px 16px;
    background: #fff;
    border-radius: var(--card-radius);
    margin: 10px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

    .section-title {
      font-size: 16px;
      color: #333;
      // margin-bottom: 16px;
    }

    .tool-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 12px;
      margin-bottom: 12px;
      border-radius: 8px;
      transition: all 0.2s;

      &:active {
        background: #f1f3f5;
        transform: scale(0.98);
      }

      .tool-icon {
        width: 48px;
        height: 48px;
        margin-bottom: 8px;
        border-radius: 8px;
      }

      .tool-name {
        font-size: 12px;
        color: #666;
        text-align: center;
        line-height: 1.4;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
    }

    // 处理最后一行的边距
    :deep(.van-row) {
      margin-bottom: -12px;

      .van-col {
        margin-bottom: 12px;
      }
    }
  }

  .machine-sales {
    margin: 10px;

    .sales-list {
      display: grid;
      gap: 12px;

      .sales-item {
        background: white;
        border-radius: var(--card-radius);
        overflow: hidden;
        box-shadow: var(--shadow);

        .machine-header {
          padding: 12px 16px;
          font-weight: 500;
          color: var(--text-primary);
          border-bottom: 1px solid #eee;
          display: flex;
          align-items: center;

          .machine-icon {
            margin-right: 8px;
            font-size: 18px;
            color: var(--primary-color);
          }
        }

        .sale-cell {
          &:deep(.van-cell__title) {
            flex: none;
            width: 100px;
          }

          &:deep(.van-cell__value) {
            color: var(--text-primary);
            font-weight: 500;
          }
        }

        .total-cell {
          &:deep(.van-cell__value) {
            color: var(--primary-color);
            font-weight: 600;
          }
        }
      }
    }
  }
}
</style>
