<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"
        :canResize="true"
        :resizeHeightOffset="-10000"
      >
        <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="邮件标题" path="title">
            <n-input placeholder="%字符会被自动过滤掉" v-model:value="formParams.title" />
          </n-form-item>
          <n-form-item label="邮件内容" path="content">
            <n-input
              type="textarea"
              placeholder="%字符会被自动过滤掉"
              v-model:value="formParams.content"
              :maxlength="200"
            />
          </n-form-item>
          <!--          <n-form-item label="发件人" path="sender">-->
          <!--            <n-input placeholder="发件人" v-model:value="formParams.sender" />-->
          <!--          </n-form-item>-->

          <n-form-item label="附件材料" path="ext">
            <n-dynamic-input
              v-model:value="formParams.ext"
              preset="pair"
              key-placeholder="材料或装备ID"
              value-placeholder="数量"
            />
          </n-form-item>

          <n-form-item label="发送方式" path="sendWay">
            <n-space>
              <n-radio
                :checked="checkedValueRef === 1"
                value="1"
                name="sendWay"
                @change="handleChange"
                :disabled="disabled"
              >
                立即发送
              </n-radio>
              <n-radio
                :checked="checkedValueRef === 0"
                value="0"
                name="sendWay"
                @change="handleChange"
                :disabled="disabled"
              >
                延时发送
              </n-radio>
            </n-space>
          </n-form-item>

          <n-form-item label="延时发送" path="sendAt" :hidden="delaySendShow">
            <n-date-picker
              type="datetime"
              placeholder="请选择延时发送时间"
              v-model:value="formParams.sendAt"
            />
          </n-form-item>

          <n-form-item label="有效时长" path="interval">
            <n-input-number
              placeholder="请输入有效时长"
              v-model:value="formParams.expired"
              :min="1"
            />
            <template #feedback>
              发送 {{ formParams.expired }} 天后如果邮件未被查看，则会删除
            </template>
          </n-form-item>

          <n-form-item label="收件类型" path="recieverType">
            <n-radio-group v-model:value="formParams.recieverType" name="radiogroup">
              <n-space>
                <n-radio v-for="song in recieveTypeOpts" :key="song.value" :value="song.value">
                  {{ song.label }}
                </n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item>

          <n-form-item label="收件方" path="recievers" :hidden="formParams.recieverType === 1">
            <n-input
              type="textarea"
              placeholder="如发送指定服请填写服务器ID，指定玩家请填写玩家ID，多个请用,(英文逗号)隔开"
              v-model:value="formParams.recievers"
              :maxlength="200"
            />
          </n-form-item>
        </n-form>

        <template #action>
          <n-space>
            <n-button @click="() => (showModal = false)">取消</n-button>
            <n-button type="info" :loading="formBtnLoading" @click="draftMail">存草稿</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 { mailTable, addMail, delMail } from '@/api/echarts/mailTable';
  import { columns } from './columns';
  import { useRouter } from 'vue-router';
  import moment from 'moment';

  const recieveTypeOpts = [
    {
      value: 1,
      label: '全服',
    },
    {
      value: 2,
      label: '指定服',
    },
    {
      value: 3,
      label: '指定玩家',
    },
  ];

  const rules = {
    content: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入邮件内容',
    },
    title: {
      required: true,
      trigger: ['blur', 'input'],
      message: '请输入邮件标题',
    },
    // sender: {
    //   required: true,
    //   trigger: ['blur', 'input'],
    //   message: '请输入发件人',
    // },
    // recievers: {
    //   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 disabled = ref(false);
  const router = useRouter();
  const formRef: any = ref(null);
  const message = useMessage();
  const actionRef = ref();

  const showModal = ref(false);
  const formBtnLoading = ref(false);
  let formParams = reactive<any>({
    id: 0,
    content: '',
    title: '',
    // sender: '',
    ext: null,
    sendWay: 1,
    sendAt: null,
    expired: 1,
    recieverType: 1,
    recievers: '',
    keys: '',
  });

  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),
            ifShow: () => {
              return record.status == '';
            },
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

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

  const checkedValueRef = ref(1);
  const delaySendShow = ref(true);
  function handleChange(e: Event) {
    checkedValueRef.value = Number((e.target as HTMLInputElement).value);
    delaySendShow.value = checkedValueRef.value !== 0;
    formParams.sendWay = checkedValueRef.value;
  }

  function addTable() {
    title.value = '发送邮件';
    formParams.id = 0;
    formParams.content = '';
    formParams.title = '';
    // formParams.sender = '';
    formParams.ext = null;
    formParams.sendWay = 1;
    formParams.sendAt = null;
    formParams.expired = 1;
    formParams.recievers = '';
    formParams.recieverType = 1;
    formParams.keys = '';
    showModal.value = true;
  }

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

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

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

  function conversionParameters(req) {
    if (formParams.ext === undefined || formParams.ext === null || formParams.ext.length === 0) {
      message.error('至少添加一个材料');
      return;
    }

    req.id = formParams.id;
    req.ext = [];
    req.keys = [...new Array(formParams.ext.length).keys()];
    for (let i = 0; i < formParams.ext.length; i++) {
      req.ext[i] = { id: formParams.ext[i].key, count: formParams.ext[i].value };
    }

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

    if (formParams.recieverType !== 1 && formParams.recievers === '') {
      message.error('非全服邮件，请填写收件人');
      return;
    }

    if (formParams.sendWay == 0) {
      if (formParams.sendAt === null || formParams.sendAt === undefined) {
        message.error('延迟发送时间不能为空');
        return;
      }
      req.sendAt = moment(formParams.sentAt).format();
    }

    req.expired = formParams.expired;
    req.recievers = formParams.recievers;
    req.sendWay = formParams.sendWay;
    // req.sender = formParams.sender;
    req.title = formParams.title;
    req.recieverType = formParams.recieverType;
    req.ok = true;
    return req;
  }

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

    formRef.value.validate((errors) => {
      if (!errors) {
        let req = { opt: 'send' };
        console.log('formParams:' + JSON.stringify(formParams));

        req = conversionParameters(req);
        if (req.ok === undefined) {
          return;
        }
        formBtnLoading.value = true;
        addMail(req)
          .then((_res) => {
            message.success('操作成功');
          })
          .catch((error) => {
            message.error(error.toString());
          });

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

  function draftMail(e) {
    e.preventDefault();
    formRef.value.validate((errors) => {
      if (!errors) {
        console.log('formParams222:' + JSON.stringify(formParams));
        let req = { opt: 'draft' };
        req = conversionParameters(req);
        if (req.ok === undefined) {
          return;
        }
        formBtnLoading.value = true;
        addMail(req)
          .then((_res) => {
            message.success('添加草稿成功');
          })
          .catch((error) => {
            message.error(error.toString());
          });

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

  function handleEdit(record: Recordable) {
    title.value = '查看邮件';
    showModal.value = true;

    formParams.expired = record.expired;
    formParams.recievers = record.recievers;
    formParams.sendAt = record.sendAt;
    formParams.sendWay = record.sendWay;
    // formParams.sender = record.sender;
    formParams.title = record.title;
    formParams.content = record.content;
    formParams.id = record.id;

    // 兼容老模式
    if (record.recieverType === 0) {
      if (record.recievers == '全员') {
        record.recieverType = 1;
      } else {
        record.recieverType = 3;
      }
    }

    formParams.recieverType = record.recieverType;

    formParams.ext = [];
    console.log('record.ext:' + JSON.stringify(record.ext));
    if (record.ext.length > 0) {
      for (let i = 0; i < record.ext.length; i++) {
        formParams.ext[i] = { key: record.ext[i].id, value: record.ext[i].count };
      }
    }
    console.log('formParams.ext:' + JSON.stringify(formParams.ext));
    console.log('点击了编辑', record);
  }

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

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

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