<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="-200000"
      />
    </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 Chart from '@/views/echarts/adv/components/Chart.vue';
  import {defRangeShortcuts, timestampToDate} from '@/utils/dateUtil';
  import { reverse } from '@/utils/array';
  import { HelpCircleOutline } from '@vicons/ionicons5';
  import { GemLog } from '@/api/gem/gem';
  import {useUserStoreWidthOut} from "@/store/modules/user";

  const renderTooltip = (trigger, content) => {
    return h(NTooltip, null, {
      trigger: () => trigger,
      default: () => content,
    });
  };

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

  let options3 = ref({});
  const useUserStore = useUserStoreWidthOut();
  const columns = [
    {
      title: '日期',
      key: 'days',
      width: 100,
    },
    {
      key: 'validCount',
      width: 120,
      title(_column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '有效活跃', icon: renderIcon(HelpCircleOutline) }
          ),
          '当天老活跃玩家人数 + 当天内新注册玩家，且已完成新手引导关卡的人数'
        );
      },
    },
    {
      title: '获得宝石人数 / 占比',
      key: 'players',
      render(row) {
        let r = '-';

        if (row.validCount > 0 && row.players) {
          r = ((row.players / row.validCount) * 100).toFixed(2) + '%';
        }

        return row.players + ' / ' + r;
      },
      width: 150,
    },
    {
      title: '攻击宝石 / 人均',
      render(row) {
        return row.part1 + ' / ' + row.avgPart1;
      },
      width: 150,
    },
    {
      title: '减伤宝石 / 人均',
      render(row) {
        return row.part2 + ' / ' + row.avgPart2;
      },
      width: 150,
    },
    {
      title: '生命宝石 / 人均',
      render(row) {
        return row.part3 + ' / ' + row.avgPart3;
      },
      width: 150,
    },
    {
      title: '暴击宝石 / 人均',
      render(row) {
        return row.part4 + ' / ' + row.avgPart4;
      },
      width: 150,
    },
    {
      title: '暴伤宝石 / 人均',
      render(row) {
        return row.part5 + ' / ' + row.avgPart5;
      },
      width: 150,
    },
    {
      title: '换弹宝石 / 人均',
      render(row) {
        return row.part6 + ' / ' + row.avgPart6;
      },
      width: 150,
    },
  ];


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

  const dataSource = ref([]);
  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: '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: '',
  });


  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) => {
      GemLog({ ...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 () => {
    await loadDataTable({});
  });

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

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

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

    options3.value = {
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: [
          '获得宝石人数',
          '攻击宝石',
          '减伤宝石',
          '生命宝石',
          '暴击宝石',
          '暴伤宝石',
          '换弹宝石',
        ],
      },
      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.part1),
        },
        {
          name: '减伤宝石',
          type: 'line',
          data: reverse(values.part2),
        },
        {
          name: '生命宝石',
          type: 'line',
          data: reverse(values.part3),
        },
        {
          name: '暴击宝石',
          type: 'line',
          data: reverse(values.part4),
        },

        {
          name: '暴伤宝石',
          type: 'line',
          data: reverse(values.part5),
        },
        {
          name: '换弹宝石',
          type: 'line',
          data: reverse(values.part6),
        },
      ],
    };
  }

  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()),
      server_id: null,
    }
  }
</script>

<style scoped></style>
