<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 { BossInfo } from '@/api/echarts/ExpeditionInfo';
  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 { useUserStoreWidthOut } from '@/store/modules/user';
  const useUserStore = useUserStoreWidthOut();
  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 columns = [
    {
      title: '日期',
      key: 'days',
      width: 120,
    },
    {
      title: '参与人数',
      key: 'players',
      width: 120,
    },
    {
      title: '最大击退阶数',
      key: 'maxStage',
      width: 150,
    },
    {
      title: '挑战次数 / 人均',
      render(row) {
        return row.challengeCount + ' / ' + row.avgChallengeCount;
      },
      width: 150,
    },
    // {
    //   title: '复活次数 / 人均',
    //   render(row) {
    //     return row.reviveCount + ' / ' + row.avgReviveCount;
    //   },
    //   width: 150,
    // },
    {
      title: '查看击退奖励 / 人均',
      render(row) {
        return row.repelCount + ' / ' + row.avgRepelCount;
      },
      width: 150,
    },
    {
      title: '查看排行榜 / 人均',
      render(row) {
        return row.awardCount + ' / ' + row.avgAwardCount;
      },
      width: 150,
    },
    {
      key: 'minuteMix1Count',
      title(_column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '1分钟 / 占比', icon: renderIcon(HelpCircleOutline) }
          ),
          '1分钟及以下结算的挑战次数（存在少量误差）'
        );
      },
      render(row) {
        return row.minuteMix1Count + ' / ' + row.avgMinuteMix1Count + '%';
      },
      width: 150,
    },
    {
      key: 'minuteMix2Count',
      title(_column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '1~2分钟 / 占比', icon: renderIcon(HelpCircleOutline) }
          ),
          '1分钟到2分钟之间结算的挑战次数（存在少量误差）'
        );
      },
      width: 150,
      render(row) {
        return row.minuteMix2Count + ' / ' + row.avgMinuteMix2Count + '%';
      },
    },
    {
      key: 'minuteMix3Count',
      title(_column) {
        return renderTooltip(
          h(
            NButton,
            {
              ghost: true,
              strong: true,
              tertiary: true,
              size: 'small',
              text: true,
              iconPlacement: 'right',
            },
            { default: () => '2分钟以上 / 占比', icon: renderIcon(HelpCircleOutline) }
          ),
          '2分钟以上结算的挑战次数（存在少量误差）'
        );
      },
      width: 150,
      render(row) {
        return row.minuteMix3Count + ' / ' + row.avgMinuteMix3Count + '%';
      },
    },
    {
      title: '总战斗时长 / 人均（秒）',
      render(row) {
        return row.minuteCount + ' / ' + row.avgMinuteCount;
      },
      width: 180,
    },
    {
      title: '兑换物品',
      render(row) {
        return row.exchangeData;
      },
      width: 100,
    },
  ];

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

  const schemas: FormSchema[] = [
    {
      field: 'server_id',
      component: 'NSelect',
      label: '服务器',
      componentProps: {
        placeholder: '请选择服务器',
        defaultValue: params.value.server_id,
        options: useUserStore.config.server_simple_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) => {
      BossInfo({ ...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: [
          '参与玩家',
          '挑战次数',
          '复活次数',
          '查看击退奖励',
          '查看排行榜',
          '1分钟时长',
          '1~2分钟',
          '2分钟以上',
          // '总战斗时长',
          // '人均战斗时长',
        ],
      },
      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.challengeCount),
        },
        {
          name: '复活次数',
          type: 'line',
          data: reverse(values.reviveCount),
        },
        {
          name: '查看击退奖励',
          type: 'line',
          data: reverse(values.repelCount),
        },
        {
          name: '查看排行榜',
          type: 'line',
          data: reverse(values.awardCount),
        },

        {
          name: '1分钟时长',
          type: 'line',
          data: reverse(values.minuteMix1Count),
        },
        {
          name: '1~2分钟',
          type: 'line',
          data: reverse(values.minuteMix2Count),
        },
        {
          name: '2分钟以上',
          type: 'line',
          data: reverse(values.minuteMix3Count),
        },
        // {
        //   name: '总战斗时长',
        //   type: 'line',
        //   data: reverse(values.minuteCount),
        // },
        // {
        //   name: '人均战斗时长',
        //   type: 'line',
        //   data: reverse(values.avgMinuteCount),
        // },
      ],
    };
  }

  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: 1,
    };
    reloadTable();
  }
</script>

<style scoped></style>
