<template>
  <div>
    <n-card
      :bordered="false"
      class="proCard"
      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 :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 { ExpeditionFloor } from '@/api/echarts/ExpeditionInfo';
  import Chart from '@/views/echarts/adv/components/Chart.vue';
  import {
    defaultStatisticsTimeOptions,
    defRangeShortcuts,
    timestampToDate,
  } from '@/utils/dateUtil';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  const useUserStore = useUserStoreWidthOut();
  let options3 = ref({});

  const message = useMessage();
  const formParams = reactive({
    startFloor: 1,
    endFloor: 60,
    day: '',
  });

  const params = ref<any>({
    pageSize: 10,
    day: 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: 'startFloor',
      component: 'NInput',
      label: '起始关卡',
      componentProps: {
        placeholder: '请输入关卡数',
        defaultValue: formParams.startFloor,
        onUpdateValue: (e: any) => {
          console.log(e);
          formParams.startFloor = e;
        },
      },
    },
    {
      field: 'endFloor',
      component: 'NInput',
      label: '结束关卡',
      componentProps: {
        placeholder: '请输入关卡数',
        defaultValue: formParams.endFloor,
        onUpdateValue: (e: any) => {
          formParams.endFloor = e;
          console.log('介入关卡值：', e, '--formParams.endFloor:', formParams.endFloor);
        },
      },
    },
    {
      field: 'formsDay',
      component: 'NDatePicker',
      label: '选择日期',
      defaultValue: defaultStatisticsTimeOptions(),
      componentProps: {
        type: 'date',
        clearable: true,
        shortcuts: defRangeShortcuts(),
        onUpdateValue: (e: any) => {
          console.log(e);
          params.value.day = timestampToDate(e);
        },
      },
    },
  ];

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

  const loadDataTable = async (res) => {
    new Promise((_resolve, _reject) => {
      ExpeditionFloor({ ...formParams, ...params.value, ...res })
        .then((res) => {
          draw(res);
        })
        .catch((error) => {
          message.error('loadDataTable:' + error.toString());
        });
    });
  };

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

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

  const xData = ref([]);
  const yData = ref([]);

  function findFloor(floor, arr) {
    for (let i = 0; i < arr.length; i++) {
      let item = arr[i];
      if (item.floor == floor) {
        return item.count;
      }
    }
    return false;
  }

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

    if (values.id === 0) {
      values = {};
    }

    // 结束关卡增加1关
    let endFloor = parseInt(formParams.endFloor) + 1;

    if (formParams.startFloor >= endFloor) {
      message.error('开始关卡必须小于结束关卡');
      return;
    }
    let count = endFloor - parseInt(formParams.startFloor);

    let failDatas = {};
    if (values.fail_data !== undefined && values.fail_data.length > 0) {
      failDatas = JSON.parse(values.fail_data);
    }
    xData.value = []; // 横坐标
    yData.value = []; // 数据

    for (let i = 0; i < count; i++) {
      let level = parseInt(formParams.startFloor) + i;
      xData.value.push(level + '关');
      let c = findFloor(level, failDatas);
      if (c === false) {
        c = 0;
      }
      yData.value.push(c);
    }

    options3.value = {};
    // 基本柱状图
    options3.value = {
      toolbox: {
        feature: {
          saveAsImage: {},
        },
      },
      xAxis: {
        data: xData.value,
      },
      yAxis: {},
      series: [
        {
          type: 'bar', //形状为柱状图
          data: yData.value,
          itemStyle: {
            normal: {
              label: {
                show: true, //开启显示数值
                position: 'top', //数值在上方显示
                textStyle: {
                  //数值样式
                  color: '#D1DBFF', //字体颜色
                  fontSize: 12, //字体大小
                },
              },
            },
          },
          colorBy: 'data', //每个颜色根据data不一样
          rippleEffect: {
            brushType: 'stroke', //波纹的绘制方式
          },
        },
      ],
    };
  }

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

  function handleReset(values: Recordable) {
    console.log(values);
    params.value = {
      pageSize: 10,
      day: timestampToDate(new Date() - 86400000),
      channel_id: '',
      server_id: null,
    };
    reloadTable();
  }
</script>

<style scoped></style>
