<template>
  <div>
    <n-card
      title="玩家古玩参与情况统计"
      :content-style="{ padding: '10px' }"
      :header-style="{ padding: '10px' }"
    >
      <Chart :loading="loading" :options="options3" style="width: 100%; min-height: 600px" />
    </n-card>

    <n-card :bordered="false" class="proCard" title="古玩每日均值数据">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>

      <BasicTable
        :loading="loading"
        :columns="columns"
        :dataSource="dataSource"
        :row-key="(row) => row.id"
        ref="actionRef"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
        :resizeHeightOffset="-2000"
      />
    </n-card>
  </div>
</template>

<script lang="ts" setup>
  import { Component, h, onMounted, reactive, ref } from 'vue';
  import { NButton, NIcon, NTooltip, useMessage } from 'naive-ui';
  import { BasicTable } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { gudongTable } from '@/api/echarts/gudongTable';
  import Chart from '@/views/echarts/adv/components/Chart.vue';
  import {defRangeShortcuts, timestampToDate} from '@/utils/dateUtil';
  import { reverse } from '@/utils/array';
  import { UtilsTool } from '@/utils/macd/UtilsTool';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import { HelpCircleOutline } from '@vicons/ionicons5';

  const useUserStore = useUserStoreWidthOut();
  let options3 = ref({});
  const renderTooltip = (trigger, content) => {
    return h(NTooltip, null, {
      trigger: () => trigger,
      default: () => content,
    });
  };

  function renderIcon(icon: Component) {
    return () => h(NIcon, null, { default: () => h(icon) });
  }

  const columns = [
    {
      title: '日期',
      key: 'days',
      width: 150,
    },
    {
      title: '参与人数',
      key: 'players',
      width: 150,
    },
    {
      title: '获取物品 / 人均',
      key: 'avgGetGoods',
      render(rows) {
        return rows.getGoods + ' / ' + rows.avgGetGoods;
      },
      width: 200,
    },
    {
      title: '获取精力 / 人均',
      key: 'avgAdJinglis',
      render(rows) {
        return h('p', { id: 'app' }, [
          h('div', {
            innerHTML: '<div>广告：' + rows.adJinglis + ' / ' + rows.avgAdJinglis + '</div>',
          }),
          h('div', {
            innerHTML:
              '<div>钻石：' + rows.diamondJinglis + ' / ' + rows.avgDiamondJinglis + '</div>',
          }),
        ]);
      },
      width: 200,
    },
    {
      // title: '获取钻石 / 人均',
      title(_column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '获取钻石 / 人均', icon: renderIcon(HelpCircleOutline) }
          ),
          '通过古玩页面顶部钻石，补充钻石时会统计该数据'
        );
      },
      key: 'adDiamonds',
      width: 200,
      render(rows) {
        return h('p', { id: 'app' }, [
          h('div', {
            innerHTML: '<div>广告：' + rows.adDiamonds + ' / ' + rows.avgAdDiamonds + '</div>',
          }),
          h('div', {
            innerHTML: '<div>RMB：' + rows.rmbDiamonds + ' / ' + rows.avgRmbDiamonds + '</div>',
          }),
        ]);
      },
    },
    {
      title: '宝箱加速 / 人均',
      key: 'avgSpeedUps',
      render(rows) {
        return rows.speedUps + ' / ' + rows.avgSpeedUps;
      },
      width: 200,
    },
    {
      title: '古玩鉴定 / 人均',
      key: 'avgIdentifyGoods',
      render(rows) {
        return rows.identifyGoods + ' / ' + rows.avgIdentifyGoods;
      },
      width: 200,
    },
    {
      title: '古玩升级 / 人均',
      key: 'avgUpgradeGoods',
      render(rows) {
        return rows.upgradeGoods + ' / ' + rows.avgUpgradeGoods;
      },
      width: 200,
    },
    {
      title: '展览收益 / 人均',
      key: 'avgShowRevenues',
      render(rows) {
        return (
          UtilsTool.unitConversion(rows.showRevenues) +
          ' / ' +
          UtilsTool.unitConversion(rows.avgShowRevenues)
        );
      },
      width: 200,
    },
    {
      title: '出售物品 / 人均',
      key: 'avgSellGoods',
      render(rows) {
        return rows.sellGoods + ' / ' + rows.avgSellGoods;
      },
      width: 200,
    },
    {
      title: '排行榜 / 人均',
      key: 'adDiamonds',
      render(rows) {
        return h('p', { id: 'app' }, [
          h('div', {
            innerHTML: '<div>查看榜单：' + rows.rankings + ' / ' + rows.avgRankings + '</div>',
          }),
          h('div', {
            innerHTML:
              '<div>查看收益：' + rows.rankingBenifit + ' / ' + rows.avgRankingBenifit + '</div>',
          }),
        ]);
      },
      width: 200,
    },
    {
      title: '古玩兑换(总值)',
      // width: 200,
      key: 'exchangeGoods',
      render(row) {
        if (row.exchangeGoods == null || row.exchangeGoods == 'null') {
          return '-';
        }
        return row.exchangeGoods;
      },
      width: 200,
    },
    {
      title: '物品获取(总值)',
      // width: 200,
      key: 'getGoodsDetail',
      render(row) {
        if (row.getGoodsDetail == null || row.getGoodsDetail == 'null') {
          return '-';
        }
        return row.getGoodsDetail;
      },
      width: 200,
    },
  ];

  const dataSource = ref([]);
  const params = ref<any>({
    pageSize: 10,
    day: timestampToDate(new Date() - 86400000 * 30),
    endDay: timestampToDate(new Date()),
    channel_id: '',
    server_id: null,
  });

  const schemas: FormSchema[] = [
    {
      field: 'server_id',
      component: 'NSelect',
      label: '服务器',
      componentProps: {
        placeholder: '请选择服务器',
        defaultValue: params.value.server_id,
        options: useUserStore.config.server_option,
        onUpdateValue: (e: any) => {
          console.log(e);
          params.value.server_id = e;
        },
      },
    },
    {
      field: 'channel_id',
      component: 'NTreeSelect',
      label: '推广渠道',
      componentProps: {
        placeholder: '请选择推广渠道',
        clearFilterAfterSelect: true,
        clearable: true,
        filterable: true,
        defaultExpandAll: true,
        options: useUserStore.config.channel_tree_option,
        onUpdateValue: (e: any) => {
          console.log(e);
          params.value.channel_id = e;
        },
      },
    },
    {
      field: 'createtime',
      component: 'NDatePicker',
      label: '选择日期',
      componentProps: {
        type: 'daterange',
        clearable: true,
        shortcuts: defRangeShortcuts(),
        defaultValue: [new Date() - 86400000 * 30, new Date()],
        onUpdateValue: (e: any) => {
          console.log(e);
          params.value.day = timestampToDate(e[0]);
          params.value.endDay = timestampToDate(e[1]);
        },
      },
    },
  ];

  const loading = ref(false);
  const message = useMessage();
  const actionRef = ref();
  const formParams = reactive({
    day: '',
    endDay: '',
    channel_id: '',
  });

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas,
  });

  const loadDataTable = async (res) => {
    loading.value = true;
    new Promise((_resolve, _reject) => {
      gudongTable({ ...formParams, ...params.value, ...res })
        .then((res) => {
          dataSource.value = res.rows;
          draw(res.info);
          loading.value = false;
        })
        .catch((error) => {
          message.error(error.toString());
          loading.value = false;
        });
    });
  };
  onMounted(async () => {
    loadDataTable({});
  });

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function reloadTable() {
    loadDataTable({});
  }

  function draw(values) {
    if (values == undefined) {
      values = {};
    }

    options3.value = {
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: [
          '参与玩家',
          '获取物品次数',
          '精力获取(ad)次数',
          '精力获取(钻石)次数',
          '钻石获取(ad)次数',
          '钻石获取(rmb)次数',
          '宝箱加速次数',
          '古玩鉴定次数',
          '古玩升级次数',
          '展览收益',
          '出售物品次数',
          '查看排行榜次数',
          '查看排行榜收益次数',
        ],
        selected: {
          展览收益: false,
          获取物品次数: false,
        },
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true,
      },
      toolbox: {
        feature: {
          saveAsImage: {},
        },
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: reverse(values.days),
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          name: '参与玩家',
          type: 'line',
          data: reverse(values.players),
        },
        {
          name: '获取物品次数',
          type: 'line',
          data: reverse(values.getGoods),
        },
        {
          name: '精力获取(ad)次数',
          type: 'line',
          data: reverse(values.adJinglis),
        },
        {
          name: '精力获取(钻石)次数',
          type: 'line',
          data: reverse(values.diamondJinglis),
        },
        {
          name: '钻石获取(ad)次数',
          type: 'line',
          data: reverse(values.adDiamonds),
        },
        {
          name: '钻石获取(rmb)次数',
          type: 'line',
          data: reverse(values.rmbDiamonds),
        },
        {
          name: '宝箱加速次数',
          type: 'line',
          data: reverse(values.speedUps),
        },
        {
          name: '古玩鉴定次数',
          type: 'line',
          data: reverse(values.identifyGoods),
        },
        {
          name: '古玩升级次数',
          type: 'line',
          data: reverse(values.upgradeGoods),
        },
        {
          name: '展览收益',
          type: 'line',
          data: reverse(values.showRevenues),
        },
        {
          name: '出售物品次数',
          type: 'line',
          data: reverse(values.sellGoods),
        },
        {
          name: '查看排行榜次数',
          type: 'line',
          data: reverse(values.rankings),
        },
        {
          name: '查看排行榜收益次数',
          type: 'line',
          data: reverse(values.rankingBenifit),
        },
      ],
    };
  }

  function handleSubmit(values: Recordable) {
    console.log(values);
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
    params.value = {
      pageSize: 10,
      day: timestampToDate(new Date() - 86400000 * 30),
      endDay: timestampToDate(new Date()),
      channel_id: '',
      server_id: null,
    };
    reloadTable();
  }
</script>

<style scoped></style>
