<template>
  <!-- 主页 -->
  <div class="homePage flex-col">
    <div class="homeBox">
      <s-header :name="sys ? sys.title : sysTitle" :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"
          style="font-size: 0.375rem;" 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 justify-between">
          <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> -->
      <typeDownMenu v-if="showDataDiv" :isHome="true" @upselectdata="upselectdata($event)"></typeDownMenu>
      <!-- 订单数据 -->
      <div v-if="showDataDiv" class="o-plr-8 o-pt-10">
        <div class="salesData flex-col" @click="pushOrderCenter">
          <!-- <div class="block5 flex-col"> -->
          <div class="topTitle flex-row justify-end" v-if="isOrderData">
            <span class="txt10">{{ $t("home.orderData") }}</span>
            <div class="layer4 flex-col"></div>
          </div>
          <div class="salesDataBox flex-row">
            <div class="dataGroup flex-col">
              <div class="dataGroupBox l-flex-RC justify-center">
                <!-- 首页 - 订单数据 - 收入总额￥ -->
                <!-- <span class="word8">&yen;</span> -->
                <span class="currencySymbol o-pr-2">{{ currencySymbol }}</span>
                <span class="dataNum">{{ salesVolume.toFixed(2) }}</span>
              </div>
              <span class="dataText">{{ $t("home.totalIncome") }}</span>
            </div>
            <div class="dataGroup flex-col">
              <div class="dataGroupBox flex-col justify-between">
                <span class="dataNum">{{ salesNumber }}</span>
                <span class="dataText">{{ $t("home.productNum") }}</span>
              </div>
            </div>
            <div class="dataGroup flex-col">
              <div class="dataGroupBox flex-col justify-between">
                <span class="dataNum">{{ orderNumber }}</span>
                <span class="dataText">{{ $t("home.numberOfOrders") }}</span>
              </div>
            </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>
      <!-- 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 v-if="user.type === 0">
        <div class="outer9 flex-col justify-center">
          <div class="main24 flex-col ">
            <div class="ImageText10 flex-col">
              <div class="wrap2 flex-row l-flex-RC">
                <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>

      <div v-if="showDataDiv && user.ifForeign === '1'">
        <!-- 机器销售额 -->
        <div class="outer9 flex-col justify-center">
          <div class="main24 flex-col">
            <div class="ImageText10 flex-col">
              <div class="wrap2 flex-row l-flex-RC">
                <div class="outer10 flex-col"></div>
                <div class="TextGroup13 flex-col">
                  <span class="txt13">{{ $t("home.machineSales") }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 各支付方式总额 -->
        <van-list offset="100" :immediate-check="false">
          <div v-for="item in combinedList" :key="item" class="o-ptb-10">
            <div>
              <van-cell-group inset class="machineSaleBox">
                <!-- 设备名称 -->
                <div class="contentWord kBordBott">{{ item.machineName }}
                </div>
                <!-- <van-row class="layer5" justify="space-between">
            <van-col span="12">总销售额: {{ item.totalSales }}</van-col>
            <van-col span="12">总现金: {{ item.totalCash }}</van-col>
          </van-row> -->
                <van-row class="layer5" justify="space-between">
                  <!-- 硬币 -->
                  <!-- <van-col span="8">{{ $t("home.coins") }}: {{ item.coins }}</van-col> -->
                  <!-- 纸币 -->
                  <!-- <van-col span="8">{{ $t("home.bills") }}: {{ item.bills }}</van-col> -->
                  <!-- 硬币+纸币 -->
                  <van-col span="12">{{ $t("home.coinsBills") }}: {{ item.coinsBills !== undefined ? item.coinsBills :
        '0'
                    }}</van-col>
                  <!-- 信用卡 -->
                  <van-col span="12">{{ $t("home.creditCard") }}: {{ item.creditCard !== undefined ? item.creditCard :
        '0'
                    }}</van-col>
                  <!-- 电子支付 -->
                  <!-- <van-col span="8">{{ $t("home.electronicPayment") }}: {{ item.electronicPayment }}</van-col> -->
                  <!-- 所有支付方式合计 -->
                  <van-col span="12">{{ $t("home.allPayTypeTotal") }}: {{ calculateTotal(item) }}</van-col>
                </van-row>
              </van-cell-group>
            </div>
          </div>
        </van-list>
      </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>
    <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>
    <template v-if="isShowRobot">
      <van-floating-bubble v-model:offset="offset" axis="xy" :icon="robotIcon" magnetic="x"
        @offset-change="onOffsetChange" @click="onClickBot">
      </van-floating-bubble>
      <van-popup v-model:show="popupVisible" position="bottom" :style="{ height: '90%' }" round @click="onClose">
        <iframe :src="aiUrl" sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
          style="width: 100%; height: 100%;"></iframe>
      </van-popup>
    </template>

  </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 typeSelectList from "../../components/typeSelectList";
import typeDownMenu from "../../components/typeDownMenu";
import { getLoginUser, $M_Menus, Format_time, styleUrl } from "../../common/js/utils";
import { useRouter } from "vue-router";
import {
  getStatistics,
  Api_getNotice,
  Api_postMachineNum,
  Api_getUpdateNotice,
  getIsAlarm,
  Api_getEquipmentPageStatistics,
} from "../../service/home";
import dateUtil from "../../utils/dateUtil";
import { useI18n } from "vue-i18n";
import { showFailToast, showToast } from "vant";
import RobotIcon from '@/assets/home/robot.png';
import { getLocal, setLocal, navigatorLanguage } from "@/common/js/utils";

export default {
  name: "home",
  components: {
    sHeader,
    // navBar,
    dateSelectList,
    // typeSelectList,
    typeDownMenu,
    kDialog,
    kNoData,
    // [Popup.name]: Popup,
  },
  setup() {
    // 是否显示机器人
    const isShowRobot = ref(false);
    // 设备状况
    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 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 = "￥";
    }

    // 图表对象
    const chartBox = ref();
    let chartObj = null;
    // 跳转订单中心
    const pushOrderCenter = () => {
      router.push({ path: "/orderCenter" });
    };
    const dateSelect = ref({});
    const update = (uDate) => {
      dateSelect.value = uDate;
      getStatisticsFun();
      getMachineNameListFunc()
    };
    let typeSelectData = {};
    const upselectdata = (uSData) => {
      typeSelectData = uSData;
      getStatisticsFun();
      getMachineNameListFunc()
    };
    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: "#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 - 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 () => {
      // 加载样式
      styleUrl('home');
      // 检测语言是否有缓存
      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"
        ),
      };
      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;
        }
      }

      if (localStorage.getItem('curLang') == 'zh') { // 机器人仅在中文环境下使用
        isShowRobot.value = true;
      }

      getTitleFunc();

      if (user) {
        getMachineNameListFunc();
      }

    });

    const finished = ref(false);
    const loading = ref(true);


    // 设备销售数据 
    const combinedList = ref([]); // 设备销额集合
    const calculateTotal = (item) => {
      let total = 0;
      // total += item.coins;
      // total += item.bills;
      // total += item.coinsBills;
      // total += item.creditCard;
      if (typeof item.coinsBills === 'number' && !isNaN(item.coinsBills)) {
        total += item.coinsBills;
      }

      if (typeof item.creditCard === 'number' && !isNaN(item.creditCard)) {
        total += item.creditCard;
      }
      // total += item.electronicPayment;
      return total;
    }

    const getMachineNameListFunc = async () => {

      combinedList.value = [];
      const searchParams = {
        adminId: user.id,
        ...dateSelect.value,
      }
      try {
        const { data } = await Api_getEquipmentPageStatistics(Object.assign({}, searchParams));
        if (data.code === "00000" && data.data) {

          for (let i = 0; i < data.data.categories.length; i++) {
            const machineNameVal = data.data.categories[i];  // 设备名称
            const coinsVal = data.data.series[0].data[i];  // 硬币销额
            const billsVal = data.data.series[1].data[i];  // 纸币销额
            const coinsBillsVal = data.data.series[2].data[i];  // 硬币+纸币销额
            const creditCardVal = data.data.series[3].data[i];  // 信用卡销额
            const electronicPaymentVal = data.data.series[4].data[i];  // 电子支付销额


            const machineSalesData = {
              // totalSales: totalSalesVal,
              // totalCash: totalCashVal,
              machineName: machineNameVal,
              coins: coinsVal,
              bills: billsVal,
              coinsBills: coinsBillsVal,
              creditCard: creditCardVal,
              electronicPayment: electronicPaymentVal
            }

            combinedList.value.push(machineSalesData);
          }

        } else {
          showFailToast(data.message);
        }
      } catch (error) {
        console.error("Error", error)
      }
    }

    const getTitleFunc = async () => {
      const currentDomain = window.location.href;
      // const currentDomain = window.location.hostname;
      switch (true) {
        // case currentDomain.includes('/shenze/'):
        //   sysTitle.value = 'AETI GLOBAL';
        //   break;
        case currentDomain.includes('/aeti/'):
          sysTitle.value = 'AETI GLOBAL';
          break;
        default:
          sysTitle.value = t('public.sysName');
      }
    }

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

    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，销售排行M11，数据概览M14，订单退款M16，系统脱机M17 这些图标不用加载到底部菜单上
          if (
            item === key &&
            (
              item !== "M1" &&
              item !== "M2" && // M2本身就无logo
              item !== "M4" &&
              item !== "M6" &&
              item !== "M11" &&
              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 (user.type === 0) {
        pushToolList.value.push({
          label: t("role.mqtt"),
          value: "M21"
        });
      }

      // 如果没有账号权限
      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) {
          showDataDiv.value = true;
        }
      }

    };

    // 常用操作跳转页面
    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;
        case "M21":
          router.push({ path: "/mqtt" });
          break;
      }
    };


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

    // const aiDialog = showDialog();
    const offset = ref({ x: Math.floor(window.innerWidth * 0.8), y: Math.floor(window.innerHeight * 0.75) });

    const popupVisible = ref(false);
    // const token = getLocal("token");
    // const openid = "f45sdFu2eXPtjeyzhUmcJ9wZiOSfPr";
    // const avatar = "用户头像";

    // 构建带有动态 token 和 openid 的 AI URL
    // const aiUrl = `https://chatbot.weixin.qq.com/webapp/auth/${token.value}?openid=${userName.value}&nickname=${userName.value}&avatar=${userName.value}&robotName=${"显示在页面顶部的title信息"}`;

    // const aiUrl = "https://chatbot.weixin.qq.com/webapp/f45sdFu2eXPtjeyzhUmcJ9wZiOSfPr?robotName=Ritchie"; // 微信对话-test
    // const aiUrl = "https://chatbot.aliyuncs.com/intl/index.htm?locale=zh-CN&from=0x0R41zuRE"; // 阿里云智能对话机器人
    const aiUrl = "https://chatbot.weixin.qq.com/webapp/c3thmydLGYWDugrgtfAj5I0Ng3sniv?robotName=Cotton%20Candy%20Robot"; // 阿里云智能对话机器人-ccbot

    // AI小助手
    const onClickBot = () => {
      popupVisible.value = true;
    }

    const onOffsetChange = (offset) => {
      offset.value = offset;
    }

    const onClose = () => {
      popupVisible.value = false;
    }
    // const onClickOverlay = () => {
    //   popupVisible.value = false;
    // };
    // const onClickCloseIcon = () => {
    //   popupVisible.value = false;
    // };

    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,
      firstLogin,
      pic1,
      showAlarm,
      alarmList,
      confirmAlarm,
      onOffsetChange,
      robotIcon: RobotIcon,
      aiUrl,
      popupVisible,
      // onClickOverlay,
      // onClickCloseIcon,
      onClose,
      onClickBot,
      offset,
      isShowRobot,
      sysTitle,
      finished,
      loading,
      // machineName,
      // coins,
      // bills,
      // coinsBills,
      // creditCard,
      // electronicPayment,
      combinedList,
      isOrderData,
      calculateTotal
    };
  },

};
</script>

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