<template>
  <div>
    <n-card :bordered="false" class="proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        :scroll-x="1090"
      >
        <template #tableTitle>
          <n-button type="primary" @click="addTable"> 新增广播（旧） </n-button>
        </template>
      </BasicTable>

      <n-modal
        v-model:show="showModal"
        :show-icon="false"
        preset="dialog"
        :title="title"
        style="width: 620px"
      >
        <n-form
          :model="formParams"
          :rules="rules"
          ref="formRef"
          label-placement="left"
          :label-width="80"
          class="py-4"
        >
          <n-form-item label="key" path="name" v-show="mode === 2">
            <n-input :disabled="disabled" placeholder="key" v-model:value="formParams.key" />
            <!--            <template #feedback> 新增广播时不需要填写key </template>-->
          </n-form-item>
          <n-form-item label="广播内容" path="name">
            <n-input
              type="textarea"
              placeholder="请输入广播内容"
              v-model:value="formParams.content"
            />
          </n-form-item>
          <n-form-item label="时间区间" path="date">
            <n-date-picker
              type="datetimerange"
              placeholder="请选择开始结束时间"
              v-model:value="formParams.date"
            />
          </n-form-item>
          <n-form-item label="间隔分钟" path="interval">
            <n-input-number
              placeholder="请输入间隔分钟"
              v-model:value="formParams.interval"
              :min="1"
            />
          </n-form-item>
        </n-form>

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

<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { FormSchema, useForm } from '@/components/Form/index';
  import { noticeTable, addNotice, delNotice } from '@/api/echarts/noticeTable';
  import { columns } from './columns';

  const mode = ref(1); //1新增  2编辑
  const rules = {
    content: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入广播内容',
    },
    key: {
      trigger: ['blur', 'input'],
      message: '请输入key',
    },
  };

  const schemas: FormSchema[] = [
    {
      field: 'mobile',
      component: 'NInputNumber',
      label: '玩家ID',
      componentProps: {
        placeholder: '请输入玩家ID',
        showButton: false,
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'type',
      component: 'NSelect',
      label: '下单渠道',
      componentProps: {
        placeholder: '请选择下单渠道',
        options: [
          {
            label: '安卓平台',
            value: 1,
          },
          {
            label: '苹果平台',
            value: 2,
          },
        ],
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'createtime',
      component: 'NDatePicker',
      label: '选择日期',
      componentProps: {
        type: 'datetimerange',
        clearable: true,
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
  ];

  const disabled = ref(true);
  const title = ref('');
  const formRef: any = ref(null);
  const message = useMessage();
  const actionRef = ref();

  const showModal = ref(false);
  const formBtnLoading = ref(false);
  let formParams = reactive({
    content: '',
    interval: 1,
    key: '',
    date: null,
  });

  const params = ref({
    pageSize: 10,
  });

  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),
          },
          {
            label: '删除',
            onClick: handleDelete.bind(null, record),
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

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

  function addTable() {
    mode.value = 1;
    title.value = '新增广播';
    formParams.date = null;
    formParams.content = '';
    formParams.interval = 1;
    formParams.key = '';
    showModal.value = true;
  }

  const loadDataTable = async (res) => {
    let data = await noticeTable({ ...formParams, ...params.value, ...res });

    data.list.sort((a, b) => {
      return a.create_at > b.create_at ? -1 : 1;
    });
    return data;
  };

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

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

  function confirmForm(e) {
    e.preventDefault();

    formRef.value.validate((errors) => {
      if (!errors) {
        console.log('formParams:' + JSON.stringify(formParams));
        if (
          formParams.date == null ||
          formParams.date[0] === undefined ||
          formParams.date[1] === undefined
        ) {
          message.error('开始时间结束时间不能为空');
          return;
        }

        let req = {};
        req.start_at = formParams.date[0] / 1000;
        req.end_at = formParams.date[1] / 1000;

        if (req.start_at + 120 > req.end_at) {
          message.error('开始时间和结束时间间隔太短(<120秒)');
          return;
        }

        req.content = formParams.content;
        if (req.content === null || req.content === '') {
          message.error('内容不能为空');
          return;
        }

        req.interval = formParams.interval;

        req.key = formParams.key;
        let msg = req.key == '' ? '记录添加成功' : '记录更新成功';
        formBtnLoading.value = true;
        addNotice(req)
          .then((_res) => {
            message.success(msg);
          })
          .catch((error) => {
            message.error(error.toString());
          });

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

  function handleEdit(record: Recordable) {
    mode.value = 2;
    title.value = '编辑广播';
    formParams.date = [record.start_at * 1000, record.end_at * 1000];
    formParams.content = record.content;
    formParams.interval = record.interval;
    formParams.key = record.key;
    showModal.value = true;

    console.log('点击了编辑', record);
  }

  function handleDelete(record: Recordable) {
    console.log('点击了删除', record);
    let req = {};
    req.id = record.key;
    delNotice(req)
      .then((_res) => {
        message.success('删除成功');
      })
      .catch((error) => {
        message.error(error.toString());
      });

    setTimeout(() => {
      reloadTable();
    });
  }
</script>

<style lang="less" scoped></style>
