<template>
  <!-- 主页 -->
  <div class="homePage flex-col">
    <div class="homeBox">
      <s-header :name="sys ? sys.title : $t('public.sysName')" :noback="true" :isFixed="false"></s-header>
      <!-- 留言滚动条 -->
      <template v-if="noticeContent.title">
        <van-notice-bar @click="noticeClk" mode="link" :scrollable="true" color="rgba(64,77,116,1)" background="#fff"
          left-icon="volume-o" :text="noticeContent.title" />
      </template>
      <div class="intervalRow"></div>
      <div class="nameDeviceRow flex-col">
        <span class="txt3">{{ userName }}</span>
        <div class="l-flex-RC">
          <span class="info3" style="color: #4d6add;">{{ $t("home.totalEquipment") }} : {{ equipStatus.machineTotalNum
          }}</span>
          <div class="lineCon o-mlr-6"></div>
          <span class="word2" style="color: #07c160;">{{ $t("home.running") }} : {{ equipStatus.machineUseNum }}</span>
        </div>
      </div>
      <!-- 没有数据概览M14权限的人看不到数据概览和ECharts -->
      <!-- 数据概览 -->
      <div v-if="showDataDiv" class="titleBox flex-col">
        <div class="layer2 flex-row">
          <div class="section5 flex-col"></div>
          <div class="TextGroup2 flex-col">
            <span class="txt4">{{ $t("home.dataOverview") }}</span>
          </div>
        </div>
      </div>
      <!-- 时间选择 -->
      <dateSelectList v-if="showDataDiv" @update="update($event)"></dateSelectList>
      <typeSelectList v-if="showDataDiv" :isHome="true" @upselectdata="upselectdata($event)"></typeSelectList>
      <!-- 订单数据 -->
      <div v-if="showDataDiv" class="o-plr-8 o-pt-10">
        <div class="outer5 flex-col" @click="pushOrderCenter">
          <div class="block5 flex-col">
            <div class="topTitle flex-row justify-end">
              <span class="txt10">{{ $t("home.orderData") }}</span>
              <div class="layer4 flex-col"></div>
            </div>
            <div class="outerBox flex-row">
              <div class="main4 flex-col justify-between">
                <div class="main5 flex-row justify-center">
                  <!-- 首页 - 订单数据 - 收入总额￥ -->
                  <!-- <span class="word8">&yen;</span> -->
                  <span class="word8">{{ currencySymbol }}</span>
                  <span class="word9">{{ salesVolume.toFixed(0) }}</span>
                </div>
                <span class="info5">{{ $t("home.totalIncome") }}</span>
              </div>
              <div class="TextGroup7 flex-col">
                <div class="mod3 flex-col justify-between">
                  <span class="txt8">{{ salesNumber }}</span>
                  <span class="info6">{{ $t("home.productNum") }}</span>
                </div>
              </div>
              <div class="TextGroup8 flex-col">
                <div class="outer6 flex-col justify-between">
                  <span class="txt9">{{ orderNumber }}</span>
                  <span class="word10">{{ $t("home.numberOfOrders") }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 时间 -->
      <div v-if="showDataDiv" class="c-text-c c-text-18">
        {{ Format_time(dateSelect.startDate, 'YYYY-MM-DD') }}--{{ Format_time(dateSelect.endDate, 'YYYY-MM-DD') }}
      </div>
      <!-- ECharts
      <template v-if="showDataDiv && !noData(salesVolume, salesNumber)">
        <div ref="chartBox" class="Chart1 flex-col"></div>
      </template>
      <template v-else>
        <kNoData v-if="showDataDiv"></kNoData>
      </template> -->
      <!-- <div> -->
      <div v-if="showDataDiv && !noData(salesVolume, salesNumber)">
        <div ref="chartBox" class="Chart1 flex-col"></div>
      </div>
      <kNoData v-else></kNoData>
      <!-- </div> -->
      <!-- 常用工具 -->
      <div class="outer9 flex-col justify-center">
        <div class="main24 flex-col justify-between">
          <div class="ImageText10 flex-col">
            <div class="wrap2 flex-row justify-between">
              <div class="outer10 flex-col"></div>
              <div class="TextGroup13 flex-col">
                <span class="txt13">{{ $t("home.commonTools") }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="outer11 flex-row">
        <div class="main25 flex-col" v-for="(item, index) in pushToolList" :key="index" @click="pushToolPage(item.value)">
          <img class="mod7 flex-col" :src="showLogo(item.value)" />
          <div class="TextGroup14 flex-col">
            <!-- <span class="info15" v-html="item.label"></span> -->
            <span class="info15">{{ $t(item.label) }}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 通知弹窗 -->
    <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>
    <!-- <nav-bar></nav-bar> -->
    <!-- <van-dialog v-model:show="firstLogin" title="标题" show-cancel-button style="">
      <div style="max-height: 60vh; overflow-y: auto;">
        <van-image v-model="pic1" src="https://fastly.jsdelivr.net/npm/@vant/assets/apple-3.jpeg"/>
        <van-image src="https://fastly.jsdelivr.net/npm/@vant/assets/apple-3.jpeg" />
        <van-image src="https://fastly.jsdelivr.net/npm/@vant/assets/apple-3.jpeg" />
      </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 navBar from "../../components/NavBar";
import dateSelectList from "../../components/dateSelectList";
import typeSelectList from "../../components/typeSelectList";
import { getLoginUser, $M_Menus, Format_time, styleUrl } from "../../common/js/utils";
import { useRouter } from "vue-router";
import {
  getStatistics,
  Api_getNotice,
  Api_postMachineNum,
  Api_getUpdateNotice,
} from "../../service/home";
import dateUtil from "../../utils/dateUtil";
import { useI18n } from "vue-i18n";
import { showToast } from "vant";

export default {
  name: "home",
  components: {
    sHeader,
    // navBar,
    dateSelectList,
    typeSelectList,
    kDialog,
    kNoData,
  },
  setup() {
    // 设备状况
    const equipStatus = ref({});
    // 获取设备情况
    const getMachineNum = () => {
      Api_postMachineNum({ adminId: user.id }).then((res) => {
        // console.log("res", res);
        equipStatus.value = res.data.data || {};
      });
    };
    const noticeContent = ref({});
    // 获取公告
    const getNotice = () => {
      Api_getNotice({ adminId: user.id }).then((res) => {
        // console.log("res", res);
        noticeContent.value = res.data.data || {};
      });
    };
    const { t } = useI18n();
    // 通知弹窗
    const kDialogRef = ref(null);
    // 点击通知栏
    const noticeClk = () => {
      kDialogRef.value.openDialog();
    };
    // 点击右侧按钮
    const confirmClk = (e) => {
      console.log(e, 2222);
      Api_getUpdateNotice({
        adminId: user.id,
      }).then((res) => {
        // console.log("res", res);
        showToast(res.data.message);
        setTimeout(() => {
          getNotice();
        }, 500);
      });
    };
    const user = getLoginUser();
    const router = useRouter();
    const userName = ref(user.name);
    const sys = ref(null);

    const firstLogin = ref(true);
    const pic1 = ref([
      { url: 'https://fastly.jsdelivr.net/npm/@vant/assets/apple-3.jpeg', isImage: true },
      // Uploader 根据文件后缀来判断是否为图片文件
      // 如果图片 URL 中不包含类型信息，可以添加 isImage 标记来声明
    ]);

    // 自定义货币符号
    const currencySymbol = ref("￥");
    if (user.currencySymbol) {
      currencySymbol.value = user.currencySymbol;
    } else {
      currencySymbol.value = "￥";
    }
    // console.log("currencySymbol是》》》" + user.currencySymbol);

    // 图表对象
    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,
        // ...typeSelectData,
        adminId: user.id,
        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: {
              left: "3%",
              right: "4%",
              bottom: "10%",
              containLabel: true,
            },
            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: null,
                endValue: null,
                zoomLock: true,
              },
            ],
            xAxis: {
              type: "category",
              axisLabel: {
                rotate: 45,
              },
              data: data.data.categories,
            },
            yAxis: {
              type: "value",
            },
            series: [
              {
                ...data.data.series[0],
                type: "bar",
                itemStyle: { color: "#e59a6d" },
                name: t("home.productNum"),
                label: {
                  show: true,
                  position: "top",
                },
              },
              {
                ...data.data.series[1],
                type: "bar",
                itemStyle: { color: "#4d6add" },
                name: t("home.salesAmount"),
                label: {
                  show: true,
                  position: "top",
                },
              },
            ],
          };

          option.dataZoom[0]["startValue"] =
            data.data.categories[data.data.categories.length - 5];
          option.dataZoom[0]["endValue"] =
            data.data.categories[data.data.categories.length - 1];
          chartObj && chartObj.setOption(option);
          //图形宽度随屏幕宽度改变而改变
          window.onresize = chartObj.resize;
        }
      }
    };
    const pushToolList = ref([]);
    // 页面初始化
    onMounted(() => {
      // 加载样式
      styleUrl('home');
      if (localStorage.getItem("loginSys")) {
        const loginSysString = localStorage.getItem("loginSys");
        sys.value = JSON.parse(loginSysString);
      }
      // 设置菜单权限
      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"
        ),
      };
      typeSelectData = {
        userName: user.username,
        clientId: null,
      };
      getStatisticsFun();
      // 获取首页公告
      getNotice();
      // 获取设备情况
      getMachineNum();

    });

    const menuList = [];

    const showDataDiv = ref(false);

    const isOrderData = ref(false);

    // 设置菜单权限
    const menuSet = () => {

      // 清空菜单列表
      menuList.length = 0;

      // 组合菜单权限
      user.menuCodeList.forEach((item) => {
        for (const key in $M_Menus) {
          // 设备管理M1，设备查看M2，订单数据M4，任务消息M6，数据概览M14，订单退款M16，系统脱机M17 这些图标不用加载到底部菜单上
          if (
            item === key &&
            (
              item !== "M1" &&
              item !== "M2" && // M2本身就无logo
              item !== "M4" &&
              item !== "M6" &&
              item !== "M14" &&
              item !== "M16" &&
              item !== "M17"
            )
          ) {
            menuList.push({
              label: $M_Menus[key],
              value: item
            });
          }
        }

      });

      // 赋值菜单
      pushToolList.value = menuList;

      // 查询是否有apk管理权限
      const isApkMan = user.menuCodeList.some((item) => {
        return item === "M19";
      });

      // 查询是否有账号权限
      const isAccount = user.menuCodeList.some((item) => {
        return item === "M8";
      });

      // 查询是否有订单数据权限
      isOrderData.value = user.menuCodeList.some((item) => {
        return item === "M4";
      })

      // 查询是否有订单导出权限
      // const isOrderExport = user.menuCodeList.some((item) => {
      //   return item === "M9";
      // })

      // 查询是否有数据概览权限
      const isDataOverview = user.menuCodeList.some((item) => {
        return item === "M14";
      })

      // 如果没有apk管理
      if (!isApkMan) {
        // 如果是公司人，要把apk添加上去
        // if (user.type === 0 || user.type === 1) {
        //   pushToolList.value.push({
        //     label: t("home.apkMan"),
        //     value: "M19"
        //   });
        // }
      }

      // 如果没有账号权限
      if (!isAccount) {
        //  如果是公司人type=0，要把账号权限添加上去
        if (user.type === 0) {
          pushToolList.value.push({
            label: t("home.accountPermission"),
            value: "M8"
          });
        }
      }

      // 子商家以上级别，默认可以看到订单详情
      if (user.type === 0 || user.type === 2) {
        showDataDiv.value = true;
      } else {
        // 如果有数据概览权限 和 订单数据权限
        if (isDataOverview && isOrderData.value) {
          showDataDiv.value = true;
        }
      }

    };

    // 常用操作跳转页面
    const pushToolPage = (index) => {
      // console.log("常用操作跳转页面menuList >>> " + menuList);
      switch (index) {
        case "M1":
          router.push({ path: "/device" }); // 设备管理
          break;
        case "M3":
          // router.push({ path: "/distributionSet" });
          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 {
      userName,
      update,
      upselectdata,
      chartBox,
      pushOrderCenter,
      pushToolList,
      pushToolPage,
      salesVolume,
      salesNumber,
      orderNumber,
      sys,
      noticeClk,
      confirmClk,
      kDialogRef,
      noData,
      equipStatus,
      noticeContent,
      showLogo,
      dateSelect,
      Format_time,
      showDataDiv,
      currencySymbol,
      firstLogin,
      pic1
    };
  },

};
</script>

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