<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="notice_type">
            <n-select
              :default-value="formParams.notice_type"
              :options="typeList"
              @update:value="handleUpdateTypeValue"
            />
            <template #feedback>
              普通广播只会定期发送广播，停服广播在结束前会发送关服命令</template
            > </n-form-item
          ><br />

          <n-form-item label="服务器" path="server_ids">
            <n-select
              multiple
              v-model:value="formParams.server_ids"
              :options="serverOptions"
              @update:value="handleUpdateValue"
            />
          </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-item label="时间区间" path="date">
            <n-date-picker
              type="datetimerange"
              placeholder="请选择开始结束时间"
              v-model:value="formParams.date"
            />
          </n-form-item>
          <n-form-item label="发送间隔" path="send_interval">
            <n-input-number
              :show-button="false"
              placeholder="请输入间隔分钟"
              v-model:value="formParams.send_interval"
              :min="1"
            >
              <template #suffix> 分钟 </template>
            </n-input-number>
          </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 { SelectOption, useMessage, useDialog } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { FormSchema, useForm } from '@/components/Form/index';
  import { List, Cancel, Add } from '@/api/notice/notice';
  import { columns } from './columns';
  import { useUserStoreWidthOut } from '@/store/modules/user';

  const useUserStore = useUserStoreWidthOut();
  const dialog = useDialog();
  const dialogWidth = ref('50%');
  const serverOptions = useUserStore.config.server_option;

  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 typeList = ref([
    {
      value: 1,
      label: '普通广播',
    },
    {
      value: 2,
      label: '停服广播',
    },
  ]);
  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 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: [
          {
            type: 'warning',
            label: '提前终止',
            onClick: handleCancel.bind(null, record),
          },
          {
            label: '编辑',
            onClick: handleEdit.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() {
    title.value = '新增广播';
    formParams.value.date = null;
    formParams.value.start_at = null;
    formParams.value.end_at = null;
    formParams.value.content = '';
    formParams.value.notice_type = 1;
    formParams.value.send_interval = 1;
    formParams.value.id = 0;
    formParams.value.server_ids = null;
    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.date == null ||
          formParams.value.date[0] === undefined ||
          formParams.value.date[1] === undefined
        ) {
          message.error('开始时间结束时间不能为空');
          return;
        }

        formParams.value.start_at = parseInt(formParams.value.date[0] / 1000);
        formParams.value.end_at = parseInt(formParams.value.date[1] / 1000);

        if (formParams.value.start_at + 120 > formParams.value.end_at) {
          message.error('开始时间和结束时间间隔太短(<120秒)');
          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.date = [record.start_at * 1000, record.end_at * 1000];
    formParams.value.content = record.content;
    formParams.value.send_interval = record.send_interval;
    formParams.value.notice_type = record.notice_type;
    formParams.value.id = record.id;
    showModal.value = true;

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

  function handleUpdateTypeValue(
    value: string | number | Array<string | number> | null,
    option: SelectOption | null | Array<SelectOption | null>
  ) {
    console.log(value, option);
    formParams.value.notice_type = value;
  }

  function handleCancel(record: Recordable) {
    dialog.warning({
      title: '警告',
      content: '你确定要提前终止该广播吗？\r\n如果是停服广播终止后将不会发送关服命令',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        Cancel(record)
          .then((_res) => {
            console.log('_res:' + JSON.stringify(_res));
            message.success('操作成功');
            reloadTable();
          })
          .catch((_e: Error) => {
            // message.error(_e.message ?? '操作失败');
          });
      },
      onNegativeClick: () => {
        // message.error('取消');
      },
    });
  }

  function handleUpdateValue(value: string, _option) {
    let arr = value.toString().split(',');
    if (arr.length > 1 && arr.includes('0')) {
      message.error('选择全服时不能再选择其他服务器');
      return;
    }
  }
</script>

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