<template>
  <div>
    <Summ />
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="广告位点击分布"> 根据广告点位去重人数 </n-card>
    </div>
    <n-card :bordered="false" class="proCard">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
        :canResize="true"
        :resizeHeightOffset="-10000"
        :pagination="false"
      />
    </n-card>
    <AdvEcharts ref="echartsModalRef" :positionId="positionId" :name="name" />
    <UserAdv />
    <FirstAdv />
  </div>
</template>

<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { NTag } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { AdSlotClick } from '@/api/echarts/AdSlotClick';
  import {
    defaultStatisticsTimeOptions,
    defRangeShortcuts,
    timestampToDate,
  } from '@/utils/dateUtil';
  import UserAdv from './components/UserAdv.vue';
  import AdvEcharts from './AdvEcharts.vue';
  import Summ from './summ.vue';
  import FirstAdv from './components/FirstAdv.vue';

  import { advPositions } from '@/convert/adv/map';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  const useUserStore = useUserStoreWidthOut();

  const columns = reactive([
    {
      title: '广告点id',
      dataIndex: 'position_id',
      key: 'position_id',
      width: 100,
    },
    {
      title: '广告点位置',
      dataIndex: 'position',
      key: 'position',
      render(row) {
        return h(
          NTag,
          {
            style: {
              marginRight: '6px',
            },
            type: 'info',
            bordered: false,
          },
          {
            default: () => advPositions[row.position_id] ?? '未知',
          }
        );
      },
      width: 150,
    },
    {
      dataIndex: 'show_times',
      key: 'show_times',
      title(_column) {
        return '展示次数( 累计：' + inGameShowTimes.value + ')';
      },
      width: 200,
    },
    {
      dataIndex: 'show_users',
      key: 'show_users',
      title(_column) {
        return '展示人数( 累计：' + inGameShowUsers.value + ')';
      },
      width: 200,
    },
    {
      dataIndex: 'click_times',
      key: 'click_times',
      title(_column) {
        return '点击次数( 累计：' + clickTimes.value + ')';
      },
      width: 200,
    },
    {
      dataIndex: 'click_users',
      key: 'click_users',
      title(_column) {
        return '点击人数( 累计：' + clickUsers.value + ')';
      },
      width: 200,
    },
    {
      dataIndex: 'reward_times',
      key: 'reward_times',
      title(_column) {
        return '领取次数( 累计：' + getRewardTimes.value + ')';
      },
      width: 200,
    },
    {
      dataIndex: 'reward_users',
      key: 'reward_users',
      title(_column) {
        return '领取人数( 累计：' + gameRewardUsers.value + ')';
      },
      width: 200,
    },
  ]);

  const params = ref<any>({
    pageSize: 100,
    day: timestampToDate(defaultStatisticsTimeOptions()),
    channel_id: '',
    server_id: null,
    flag: -1,
  });

  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: 'flag',
      component: 'NSelect',
      label: '玩家分类',
      componentProps: {
        placeholder: '请选择玩家分类',
        options: useUserStore.config.flag_option,
        onUpdateValue: (e: any) => {
          console.log(e);
          params.value.flag = e;
        },
      },
    },
    {
      field: 'makeDate',
      component: 'NDatePicker',
      label: '选择日期',
      defaultValue: defaultStatisticsTimeOptions(),
      componentProps: {
        type: 'date',
        clearable: true,
        shortcuts: defRangeShortcuts(),
        onUpdateValue: (e: any) => {
          console.log(e);
          params.value.day = timestampToDate(e);
        },
      },
    },
  ];

  const actionRef = ref();
  const formParams = reactive({
    day: '',
    channel_id: '',
  });

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

  const inGameShowTimes = ref(0);
  const getRewardTimes = ref(0);
  const inGameShowUsers = ref(0);
  const gameRewardUsers = ref(0);
  const clickTimes = ref(0);
  const clickUsers = ref(0);

  function mysort(a, b) {
    return a.show_times > b.show_times ? -1 : 1;
  }

  const loadDataTable = (res) => {
    let data = AdSlotClick({ ...formParams, ...params.value, ...res });
    inGameShowTimes.value = 0;
    getRewardTimes.value = 0;
    inGameShowUsers.value = 0;
    gameRewardUsers.value = 0;
    clickTimes.value = 0;
    clickUsers.value = 0;

    data.then((res) => {
      if (res.list === null) {
        return;
      }
      if (res.list.length > 0) {
        res.list.forEach((info) => {
          console.log(info.reward_times);
          inGameShowTimes.value += info.show_times;
          getRewardTimes.value += info.reward_times;
          inGameShowUsers.value += info.show_users;
          gameRewardUsers.value += info.reward_users;
          clickTimes.value += info.click_times;
          clickUsers.value += info.click_users;
        });
        res.list.sort(mysort);
      }
    });

    return data;
  };

  const actionColumn = reactive({
    width: 150,
    title: '操作',
    key: 'action',
    // fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            type: 'default',
            label: '查看趋势',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
          },
        ],
      });
    },
  });

  function handleEdit(record: Recordable) {
    openEchartsModal(record.position_id);
  }

  const echartsModalRef = ref();
  const positionId = ref(0);
  const name = ref('');

  function openEchartsModal(id) {
    positionId.value = id;
    name.value = advPositions[id] ?? '';
    const { openDrawer } = echartsModalRef.value;
    openDrawer();
  }

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

  function reloadTable() {
    actionRef.value.reload();
  }

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

  function handleReset(values: Recordable) {
    console.log(values);
    params.value = {
      pageSize: 100,
      day: timestampToDate(defaultStatisticsTimeOptions()),
      channel_id: '',
      server_id: null,
      flag: -1,
    };
    reloadTable();
  }
</script>

<style scoped></style>
