<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"
            >{{ equipStatus.machineTotalNum }}
            {{ $t("home.totalEquipment") }}</span
          >
          <div class="lineCon o-mlr-6"></div>
          <span class="word2"
            >{{ equipStatus.machineUseNum }} {{ $t("home.running") }}</span
          >
        </div>
      </div>
	  <!-- 数据概览 -->
      <div 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 @update="update($event)"></dateSelectList>
      <typeSelectList :isHome="true" @upselectdata="upselectdata($event)"></typeSelectList>
	  <!-- 订单数据 -->
      <div class="o-plr-8">
        <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="word9">{{ salesVolume }}</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 class="c-text-c c-text-18">
        {{$M_FormatTime(dateSelect.startDate,'YYYY-MM-DD')}}--{{$M_FormatTime(dateSelect.endDate,'YYYY-MM-DD')}}
      </div>
      <div v-if="!noData(salesVolume, salesNumber)">
        <div ref="chartBox" class="Chart1 flex-col"></div>
      </div>
      <kNoData v-else></kNoData>
      <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>
          </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>
  </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,$M_FormatTime } 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 { Toast } 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({ id: 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,
        noticeId: noticeContent.value.id,
      }).then((res) => {
        console.log("res", res);
        Toast(res.data.message);
        setTimeout(() => {
          getNotice();
        }, 500);
      });
    };
    const user = getLoginUser();
    const router = useRouter();
    const userName = ref(user.name);
    const sys = ref(null);
    // 图表对象
    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: user.ifForeign,
        payType: typeSelectData.payType,
        clientId: typeSelectData.clientId,
        username: typeSelectData.userName, // 商家
        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 = parseInt(salesVolume.value + item);
        });
		    data.data.series[2].data.forEach((item) => {
		      orderNumber.value = parseInt(orderNumber.value + item);
		    });
        // 解决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" },
                label: {
                  show: true,
                  position: "top",
                },
              },
              {
                ...data.data.series[1],
                type: "bar",
                itemStyle: { color: "#4D6ADD" },
                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(() => {
      if (localStorage.getItem("loginSys")) {
        const loginSysString = localStorage.getItem("loginSys");
        sys.value = JSON.parse(loginSysString);
      }
      // 设置菜单权限
      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 menuSet = () => {
      const menuList = [];
      // 组合菜单权限
      user.menuCodeList.forEach((item) => {
        for (const key in $M_Menus) {
          // 除了设备查看M2，数据概况M14，订单退款M16，系统脱机M17不用加在菜单上
          if (
            item === key &&
            (item !== "M2" &&
              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";
      });
      // 如果没有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"
          });
        }
      }
    };
    // 常用操作跳转页面
    const pushToolPage = (index) => {
      switch (index) {
        case "M1":
          router.push({ path: "/device" });
          break;
        case "M3":
          router.push({ path: "/distributionSet" });
          break;
        case "M4":
          router.push({ path: "/alarmHistory" });
          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: "/orderCenter" });
          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,
      $M_FormatTime,
    };
  },
};
</script>

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