<template>
  <div>
    <n-modal
      v-model:show="showModal"
      style="width: 80%"
      :show-icon="false"
      preset="dialog"
      :title="title"
    >
      <n-card :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>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, watch } from 'vue';
  import { useMessage } from 'naive-ui';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { AdvEcharts } from '@/api/echarts/AdSlotClick';
  import Chart from '@/views/echarts/adv/components/Chart.vue';
  import {defRangeShortcuts, timestampToDate} from '@/utils/dateUtil';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  const useUserStore = useUserStoreWidthOut();
  interface Props {
    positionId?: number;
    name: string;
  }
  const props = withDefaults(defineProps<Props>(), { positionId: 0, name: '' });

  let options3 = 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: 'NSelect',
      label: '推广渠道',
      componentProps: {
        placeholder: '请选择推广渠道',
        options: useUserStore.config.channel_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 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) => {
      AdvEcharts({ ...formParams, ...params.value, ...res, ...{ position_id: props.positionId } })
        .then((res) => {
          draw(res.info);
          loading.value = false;
        })
        .catch((error) => {
          message.error(error.toString());
          loading.value = false;
        });
    });
  };

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

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

    options3.value = {
      tooltip: {
        trigger: 'axis',
      },
      legend: {},
      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.ShowTimes, //[10, 11, 13, 11, 12, 1, 9],
          markPoint: {
            data: [
              { type: 'max', name: 'Max' },
              // { type: 'min', name: 'Min' },
            ],
          },
          markLine: {
            data: [{ type: 'average', name: 'Avg' }],
          },
        },
        {
          name: '展示人数',
          type: 'line',
          data: values.ShowUsers,
          markPoint: {
            data: [
              { type: 'max', name: 'Max' },
              // { type: 'min', name: 'Min' },
            ],
          },
          markLine: {
            data: [{ type: 'average', name: 'Avg' }],
          },
        },
        {
          name: '点击次数',
          type: 'line',
          data: values.ClickTimes, //[10, 11, 13, 11, 12, 1, 9],
          markPoint: {
            data: [
              { type: 'max', name: 'Max' },
              // { type: 'min', name: 'Min' },
            ],
          },
          markLine: {
            data: [{ type: 'average', name: 'Avg' }],
          },
        },
        {
          name: '点击人数',
          type: 'line',
          data: values.ClickUsers,
          markPoint: {
            data: [
              { type: 'max', name: 'Max' },
              // { type: 'min', name: 'Min' },
            ],
          },
          markLine: {
            data: [{ type: 'average', name: 'Avg' }],
          },
        },
        {
          name: '领取次数',
          type: 'line',
          data: values.RewardTimes,
          markPoint: {
            data: [
              { type: 'max', name: 'Max' },
              // { type: 'min', name: 'Min' },
            ],
          },
          markLine: {
            data: [{ type: 'average', name: 'Avg' }],
          },
        },
        {
          name: '领取人数',
          type: 'line',
          data: values.RewardUsers,
          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()),
      channel_id: '',
      server_id: null,
    };
    reloadTable();
  }

  const showModal = ref(false);
  const title = ref('广告点位趋势');

  function openDrawer() {
    params.value.day = timestampToDate(new Date() - 86400000 * 30);
    params.value.endDay = timestampToDate(new Date());
    showModal.value = true;
  }

  watch(props, (_newVal, _oldVal) => {
    refresh();
  });

  function refresh() {
    if (showModal.value === true) {
      if (props.name !== '') {
        title.value = props.name + ' 点击趋势';
      }
      params.value.day = timestampToDate(new Date() - 86400000 * 30);
      params.value.endDay = timestampToDate(new Date());

      loadDataTable({});
    }
  }

  defineExpose({ openDrawer });
</script>

<style scoped></style>
