<template>
  <!-- 主页 -->
  <div class="homePage flex-col">
    <div class="homeBox">
      <s-header :name="sys ? sys.title : $t('public.homePage')" :noback="true" :isFixed="false"></s-header>
      <!-- 新闻通知 -->
      <template v-if="noticeContent.title">
        <van-notice-bar @click="noticeClk" mode="link" :scrollable="true" color="#ff3456" background="#F2F9FC"
          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">
        </div>
      </div>
      <!-- 行情数据 -->
      <div class="titleBox flex-col">
        <div class="layer2 l-flex-RC">
          <div class="section5 flex-col"></div>
          <div class="TextGroup2 flex-col">
            <span class="txt4">行情数据</span>
          </div>
        </div>
      </div>

      <div style="width: 30%; margin: 0 auto;">
        <van-tabs type="card" swipeable @click-tab="onClickTab" color="#39a6fe">
          <van-tab title="日K"></van-tab>
          <van-tab title="月K"></van-tab>
        </van-tabs>
      </div>

      <!-- <div class="c-text-c c-text-18" style="color: #39a6fe;font-weight: bold ;">
        月K线图
      </div> -->
      <!-- ECharts -->
      <!-- <div v-if="!noData(salesVolume, salesNumber)"> -->
      <div v-if="!noData(stockPrice)">
        <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">买卖排行榜</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="top5-box">
      <div class="buy-box">
        <van-divider>买家Top5排行榜</van-divider>
        <van-row justify="center" class="bold-row">
          <van-col span="8">姓名</van-col>
          <van-col span="8">成交总量</van-col>
          <van-col span="8">总金额</van-col>
        </van-row>
        <van-row v-for="(item, index) in buyTop5List" :key="index" justify="center">
          <!-- <van-col span="8">买家{{ index + 1 }}</van-col> -->
          <van-col span="8">{{ item.userAnonymousName }}</van-col>
          <van-col span="8">{{ item.totalNum }}</van-col>
          <van-col span="8">{{ item.totalPrice }}</van-col>
        </van-row>
      </div>
      <div style="height: 20px;"></div>
      <div class="sell-box">
        <van-divider>卖家Top5排行榜</van-divider>
        <van-row justify="center" class="bold-row">
          <van-col span="8">姓名</van-col>
          <van-col span="8">成交总量</van-col>
          <van-col span="8">总金额</van-col>
        </van-row>
        <van-row v-for="(item, index) in sellTop5List" :key="index" justify="center">
          <van-col span="8">{{ item.userAnonymousName }}</van-col>
          <van-col span="8">{{ item.totalNum }}</van-col>
          <van-col span="8">{{ item.totalPrice }}</van-col>
        </van-row>
      </div>
    </div>


    <div style="height: 70px;"></div>


    <div>
      <!-- 分割线 -->
      <img class="pic1" src="../../assets/trading/line.png" />
      <br />
    </div>
    <!-- 新闻通知弹窗 -->
    <kDialog :dialogTitle="$t('home.notificationPop.notification')" cancelBtnTxt="确定" ref="kDialogRef">
      <template #content>
        <div class="o-w" style="max-height: 50vh; overflow-y: auto" v-html="noticeContent.content"></div>
      </template>
    </kDialog>

    <!-- 水印 -->
    <van-watermark :content="watermarkVal" opacity="0.2" :gap-x="70" :gap-y="50" :height="50" rotate="-22" />


    <van-number-keyboard safe-area-inset-bottom />
  </div>
</template>

<script setup>
// 导入无数据组件
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 { getLoginUser, styleUrl } from "@/common/js/utils";
import {
  getListStockInfoForMonth,
  getListStockInfoForDay,
  // Api_getNotice,
  getPageNotice,
  // Api_getUpdateNotice,
  getTop5List,
} from "../../service/home";
// import { showToast } from "vant";


const buyTop5List = ref([]);
const sellTop5List = ref([]);


async function getTop5Func() {
  const { data } = await getTop5List()
  if (data.code === '00000') {
    buyTop5List.value = data.data.buyTopList
    sellTop5List.value = data.data.sellTopList
  }
}

const noticeContent = ref({});
// 获取公告
const getNotice = () => {

  const params = {
    current: 1,
    size: 10
  }
  getPageNotice(params).then((res) => {
    noticeContent.value = res.data.data.records[0] || {};
  })

};
// 通知弹窗
const kDialogRef = ref(null);
// 点击通知栏
const noticeClk = () => {
  kDialogRef.value.openDialog();
};
// 点击右侧按钮
// const confirmClk = (e) => {
//   console.log(e, 2222);
//   Api_getUpdateNotice({
//     adminId: user.id,
//   }).then((res) => {
//     showToast(res.data.message);
//     setTimeout(() => {
//       getNotice();
//     }, 500);
//   });
// };
const firstLogin = ref(true);
const user = getLoginUser();
const userName = ref(user.userName);
const sys = ref(null);

const watermarkVal = ref('')
// 获取当前日期和时间
const date = new Date();

const year = date.getFullYear() % 100; // 获取年份的后两位
const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始计数，所以需要+1
const day = date.getDate().toString().padStart(2, '0'); // 获取日期
const hours = date.getHours().toString().padStart(2, '0'); // 获取小时
const minutes = date.getMinutes().toString().padStart(2, '0'); // 获取分钟

const formattedDate = `${year}${month}${day}${hours}${minutes}`;

watermarkVal.value = user.phone + "\n" + formattedDate;

// watermarkVal.value = user.phone + "~" + new Date().toISOString();
// console.log("watermark >>>", watermarkVal.value);


// 图表对象
const chartBox = ref();
let chartObj = null;

const showDay = ref(true);

const onClickTab = ({ title }) => {
  if (title === '日K') {
    showDay.value = true
    getListStockInfoForDayFunc()
  } else {
    showDay.value = false
    getListStockInfoForMonthFun()
  }
};

const getListStockInfoFunc = () => {
  if (showDay.value) {
    getListStockInfoForDayFunc()
  } else {
    getListStockInfoForMonthFun()
  }
}

const stockPrice = ref(0);

// 查询图表-日K
const getListStockInfoForDayFunc = async () => {
  const { data } = await getListStockInfoForDay();
  if (data.code === '00000' && data.data) {
    stockPrice.value = 0;
    data.data.series[0].data.forEach((item) => {
      stockPrice.value = parseInt(stockPrice.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",
          },
        },
        legend: { // 图例
          bottom: 0,
          right: 10,
          itemWidth: 10,
          itemHeight: 10,
          icon: "roundRect",
          orient: 'vertical', // 图例列表布局，vertical 垂直，horizontal 水平，当前只有一个无所谓
          top: 5,
        },
        grid: { // 网格
          top: "12%",
          left: "3%",
          right: "5%",
          bottom: "7%",
          containLabel: true, // 刻度标签
        },
        // 固定屏幕显示多少个，其余的滑动
        dataZoom: [
          {
            type: "inside",
            xAxisIndex: 0,
            filterMode: "none",
            startValue: null,
            endValue: null,
            zoomLock: true, // 锁定选择区域，只能平移，不能缩放。
          },
        ],
        xAxis: {
          type: "category",
          axisLabel: {
            rotate: 15, // 旋转角度
          },
          data: data.data.categories,
        },
        yAxis: {
          type: "value",
          // min: 20,
          // max: 120,
        },
        series: [
          {
            ...data.data.series[0],
            type: "line", // line折线图，bar柱状图
            // smooth: true, // 针对折线图，平滑曲线
            itemStyle: { color: "#ff5d88" },
            colorBy: 'series',
            name: "股价￥",
            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;
    }
  }
}



// 查询图表-月K
const getListStockInfoForMonthFun = async () => {
  const { data } = await getListStockInfoForMonth();
  if (data.code === '00000' && data.data) {
    stockPrice.value = 0;
    data.data.series[0].data.forEach((item) => {
      stockPrice.value = parseInt(stockPrice.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",
          },
        },
        legend: { // 图例
          bottom: 0,
          right: 10,
          itemWidth: 10,
          itemHeight: 10,
          icon: "roundRect",
          orient: 'vertical', // 图例列表布局，vertical 垂直，horizontal 水平，当前只有一个无所谓
          top: 5,
        },
        grid: { // 网格
          top: "12%",
          left: "3%",
          right: "5%",
          bottom: "7%",
          containLabel: true, // 刻度标签
        },
        // 固定屏幕显示多少个，其余的滑动
        dataZoom: [
          {
            type: "inside",
            xAxisIndex: 0,
            filterMode: "none",
            startValue: null,
            endValue: null,
            zoomLock: true, // 锁定选择区域，只能平移，不能缩放。
          },
        ],
        xAxis: {
          type: "category",
          axisLabel: {
            rotate: 15, // 旋转角度
          },
          data: data.data.categories,
        },
        yAxis: {
          type: "value",
          // min: 20,
          // max: 120,
        },
        series: [
          {
            ...data.data.series[0],
            type: "line", // line折线图，bar柱状图
            // smooth: true, // 针对折线图，平滑曲线
            itemStyle: { color: "#ff5d88" },
            colorBy: 'series',
            name: "股价￥",
            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;
    }
  }
};

// 页面初始化
onMounted(async () => {
  // 加载样式
  styleUrl('home');
  // if (localStorage.getItem("loginSys")) {
  //   const loginSysString = localStorage.getItem("loginSys");
  //   sys.value = JSON.parse(loginSysString);
  // }
  firstLogin.value = localStorage.getItem('firstLogin');

  // 获取日/周曲线
  // getListStockInfoForDayFunc();
  // 获取月度曲线
  // getListStockInfoForMonthFun();
  // 获取股票曲线
  getListStockInfoFunc();

  // 获取首页公告
  getNotice();

  getTop5Func();


});




// 如果是空数据
const noData = (stockPrice) => {
  if (!stockPrice) {
    return true;
  }
  return false;
};




</script>

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