<template>
  <div>
    <n-card
      title="玩家留存率"
      :content-style="{ padding: '10px' }"
      :header-style="{ padding: '10px' }"
    >
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>

      <Chart :loading="loading" :options="options3" style="width: 100%; min-height: 600px" />
    </n-card>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, reactive, ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { BasicRetention } from '@/api/echarts/ExpeditionInfo';
  import Chart from '@/views/echarts/adv/components/Chart.vue';
  import {defRangeShortcuts, timestampToDate} from '@/utils/dateUtil';
  import { useUserStoreWidthOut } from '@/store/modules/user';

  const useUserStore = useUserStoreWidthOut();

  let options3 = ref({});
  const params = ref<any>({
    pageSize: 10,
    day: timestampToDate(new Date() - 86400000 * 30),
    endDay: timestampToDate(new Date() - 86400000),
    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() - 86400000],
        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 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) => {
      BasicRetention({ ...formParams, ...params.value, ...res })
        .then((res) => {
          draw(res.info);
          loading.value = false;
        })
        .catch((error) => {
          message.error(error.toString());
          loading.value = false;
        });
    });
  };

  onMounted(async () => {
    await loadDataTable({});
  });

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

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

    options3.value = {
      tooltip: {
        trigger: 'axis',
      },
      legend: {
        data: ['次日留存率', '7日留存率', '14日留存率', '30日留存率'],
        selected: {
          '30日留存率': false, // 默认隐藏
        },
      },
      toolbox: {
        show: true,
        feature: {
          dataView: { readOnly: false },
          magicType: { type: ['line', 'bar'] },
          saveAsImage: {},
        },
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: values.days, //reverse(values.days),
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: '{value} %',
        },
      },
      series: [
        {
          name: '次日留存率',
          type: 'line',
          data: values.AvgActive1Day, //[10, 11, 13, 11, 12, 1, 9],
          markPoint: {
            data: [
              { type: 'max', name: 'Max' },
              // { type: 'min', name: 'Min' },
            ],
          },
          markLine: {
            data: [{ type: 'average', name: 'Avg' }],
          },
        },
        {
          name: '7日留存率',
          type: 'line',
          data: values.AvgActive7Day,
          markPoint: {
            data: [
              { type: 'max', name: 'Max' },
              // { type: 'min', name: 'Min' },
            ],
          },
          markLine: {
            data: [{ type: 'average', name: 'Avg' }],
          },
        },
        {
          name: '14日留存率',
          type: 'line',
          data: values.AvgActive14Day,
          showSymbol: false,
          markPoint: {
            data: [
              { type: 'max', name: 'Max' },
              // { type: 'min', name: 'Min' },
            ],
          },
          markLine: {
            data: [{ type: 'average', name: 'Avg' }],
          },
        },
        {
          name: '30日留存率',
          type: 'line',
          data: values.AvgActive30Day,
          showSymbol: false,
          markPoint: {
            data: [
              { type: 'max', name: 'Max' },
              // { type: 'min', name: 'Min' },
            ],
          },
          markLine: {
            data: [{ type: 'average', name: 'Avg' }],
          },
        },
      ],
    };
  }

  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() - 86400000),
      channel_id: '',
      server_id: null,
    };
    reloadTable();
  }
</script>

<style scoped></style>
