<template>
  <div>
    <n-card :bordered="false" class="proCard" title="游戏更新公告">
      <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: dialogWidth,
        }"
      >
        <n-form
          :model="formParams"
          :rules="rules"
          ref="formRef"
          label-placement="left"
          :label-width="80"
          class="py-4"
        >
          <n-form-item label="公告标题" path="content">
            <n-input
              type="textarea"
              rows="5"
              placeholder="请输入公告标题"
              v-model:value="formParams.title"
            />
          </n-form-item>
          <n-form-item label="公告内容" path="content">
            <n-input
              type="textarea"
              rows="5"
              placeholder="请输入公告内容"
              v-model:value="formParams.content"
            />
          </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 { List, Add, Del } from '@/api/announcement/announcement';
  import { columns } from './columns';

  const dialogWidth = ref('50%');

  function mapWidth() {
    let val = document.body.clientWidth;
    const def = 720; // 默认宽度
    if (val < def) {
      dialogWidth.value = '100%';
    } else {
      dialogWidth.value = def + 'px';
    }

    return dialogWidth.value;
  }

  const rules = {
    title: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入公告标题',
    },
    content: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入公告内容',
    },
  };

  const title = ref('新增公告');
  const formRef: any = ref(null);
  const message = useMessage();
  const actionRef = ref();

  const showModal = ref(false);
  const formBtnLoading = ref(false);
  const formParams = ref<any>({
    id: 0,
    content: '',
    send_interval: 1,
    notice_type: 1,
    start_at: null,
    end_at: null,
    date: null,
    server_ids: 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} 按钮`);
        },
      });
    },
  });

  function addTable() {
    title.value = '新增公告';
    formParams.value.title = '';
    formParams.value.content = '';
    showModal.value = true;
  }

  const loadDataTable = async (res) => {
    mapWidth();
    let data = await List({ ...formParams.value, ...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.value));
        if (formParams.value.title === null || formParams.value.title === '') {
          message.error('标题不能为空');
          return;
        }
        if (formParams.value.content === null || formParams.value.content === '') {
          message.error('内容不能为空');
          return;
        }

        formBtnLoading.value = true;
        Add(formParams.value)
          .then((_res) => {
            message.success('操作成功');
            setTimeout(() => {
              showModal.value = false;
              reloadTable();
            });
          })
          .catch((_error) => {
            // message.error(error.toString());
          });
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  function handleEdit(record: Recordable) {
    title.value = '编辑公告';
    formParams.value.title = record.title;
    formParams.value.content = record.content;
    showModal.value = true;

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

  function handleDelete() {
    Del()
      .then((_res) => {
        message.success('操作成功');
        setTimeout(() => {
          showModal.value = false;
          reloadTable();
        });
      })
      .catch((_error) => {
        message.error(_error.toString());
      });
  }
</script>

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