<template>
  <div>
    <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>-->
      <n-alert :show-icon="false">
        渠道统计数据时间从2022年10月26日开始，数据来源于广告渠道埋点，实时同步
      </n-alert>
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        @update:checked-row-keys="onCheckedRow"
        :actionColumn="actionColumn"
        :scroll-x="1090"
        :pagination="{ pageSize: 10 }"
        :resizeHeightOffset="-20000"
      />
    </n-card>

    <n-modal
      v-model:show="showModal"
      style="width: 60%"
      :show-icon="false"
      preset="dialog"
      :title="'正在编辑渠道(' + channelData.channel_id + ')'"
    >
      <n-form ref="formRef" label-placement="left" :label-width="80" class="py-4">
        <n-form-item label="渠道名称" path="name">
          <n-input placeholder="" v-model:value="channelData.name" />
        </n-form-item>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click="() => (showModal = false)">取消</n-button>
          <n-button
            type="info"
            :loading="formBtnLoading"
            :disabled="formBtnDisabled"
            @click="confirmForm"
            >修改</n-button
          >
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { FormSchema, useForm } from '@/components/Form/index';
  import { defaultStatisticsTimeOptions, timestampToDate, timestampToTime } from '@/utils/dateUtil';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import { Stat, StatEdit } from '@/api/channel/channel';
  import { useMessage } from 'naive-ui';
  const useUserStore = useUserStoreWidthOut();
  const formBtnLoading = ref(false);
  const formBtnDisabled = ref(false);
  const showModal = ref(false);
  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '渠道ID',
      dataIndex: 'channel_id',
      key: 'channel_id',
    },
    {
      title: '渠道名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '累计登录次数',
      dataIndex: 'totalLogin',
      key: 'totalLogin',
    },
    {
      title: '累计新用户',
      dataIndex: 'totalNewUser',
      key: 'totalNewUser',
    },
    {
      title: '最后上报时间',
      dataIndex: 'lastAt',
      key: 'lastAt',
      render: (rows, _) => {
        if (rows.lastAt <= 0) {
          return `-`;
        }
        return timestampToTime(rows.lastAt);
      },
    },
  ];

  const schemas: FormSchema[] = [
    {
      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: 'makeDate',
      component: 'NDatePicker',
      label: '选择日期',
      defaultValue: defaultStatisticsTimeOptions(),
      componentProps: {
        type: 'date',
        clearable: true,
        onUpdateValue: (e: any) => {
          console.log(e);
          params.value.day = timestampToDate(e);
        },
      },
    },
  ];

  const actionRef = ref();

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

  const params = ref({
    channel_id: '',
    pageSize: 10,
    day: timestampToDate(defaultStatisticsTimeOptions()),
  });

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

  const loadDataTable = async (res) => {
    return await Stat({ ...formParams, ...params.value, ...res });
  };

  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 = {
      channel_id: '',
      pageSize: 10,
      day: timestampToDate(defaultStatisticsTimeOptions()),
    };
    reloadTable();
  }

  const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    // fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
          },
        ],
      });
    },
  });
  const formRef: any = ref(null);
  const message = useMessage();
  function confirmForm(e) {
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate((errors) => {
      if (!errors) {
        console.log('formParams:' + JSON.stringify(formParams));

        showModal.value = false;
        StatEdit(channelData.value)
          .then((_res) => {
            // dataSource.value = res.rows;
            message.success('操作成功');
          })
          .catch((error) => {
            message.error(error.toString());
          });

        setTimeout(function () {
          reloadTable();
        }, 200);
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  const channelData = ref({
    id: 0,
    channel_id: 0,
    name: '',
  });
  async function handleEdit(record: Recordable) {
    showModal.value = true;
    channelData.value.id = record.id;
    channelData.value.channel_id = record.channel_id;
    channelData.value.name = record.name;
    // console.log('handleEdit :' + JSON.stringify(record));
  }
</script>

<style scoped></style>
