<template>
  <div>
    <n-card :bordered="false" class="proCard" title="邮件通知">
      <BasicForm
        @register="register"
        @submit="handleSubmit"
        @reset="handleReset"
        @keyup.enter="handleSubmit"
        ref="searchFormRef"
      >
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>

      <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="error" @click="addTable(1)"> 发送全服邮件</n-button>
          <n-button type="warning" @click="addTable(2)" class="left-2"> 发送指定服邮件</n-button>
          <n-button type="primary" @click="addTable(3)" class="left-4"> 发送指定玩家邮件</n-button>
          <n-button type="primary" @click="exportMail" class="left-6" :loading="loadingRef"
            >导出数据</n-button
          >
        </template>
      </BasicTable>

      <n-modal
        v-model:show="showModal"
        :show-icon="false"
        preset="dialog"
        :title="title"
        style="width: 780px"
      >
        <n-form
          :model="formParams"
          :rules="rules"
          ref="formRef"
          label-placement="left"
          :label-width="80"
          class="py-4"
        >
          <n-form-item label="收件服务器" path="serverIds" v-if="formParams.receiptType == 2">
            <n-select multiple v-model:value="formParams.serverIds" :options="serverOptions" />
          </n-form-item>

          <n-form-item label="收件玩家ID" path="playerIds" v-if="formParams.receiptType == 3">
            <n-input
              type="textarea"
              placeholder="请填写玩家ID，多个请用,(英文逗号)隔开"
              v-model:value="formParams.playerIds"
            />
          </n-form-item>

          <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"
            />
          </n-form-item>

          <n-form-item label="附件材料" path="ext">
            <n-dynamic-input
              v-model:value="formParams.ext"
              item-style="margin-bottom: 0;"
              :on-create="onCreate"
              #="{ index, value }"
            >
              <div style="display: flex">
                <n-form-item
                  ignore-path-change
                  :show-label="false"
                  :path="`dynamicInputValue[${index}].name`"
                >
                  <n-input
                    v-model:value="formParams.ext[index].key"
                    placeholder="材料或装备ID"
                    @keydown.enter.prevent
                    @change="handleExtChange(index, formParams.ext[index])"
                    @input="handleExtChange(index, formParams.ext[index])"
                  />
                </n-form-item>
                <div style="height: 34px; line-height: 34px; margin: 0 8px"></div>
                <n-form-item
                  ignore-path-change
                  :show-label="false"
                  :path="`dynamicInputValue[${index}].value`"
                >
                  <n-input
                    v-model:value="formParams.ext[index].value"
                    placeholder="数量"
                    @keydown.enter.prevent
                    @change="handleExtChange(index, formParams.ext[index])"
                    @input="handleExtChange(index, formParams.ext[index])"
                  />
                </n-form-item>
                <div
                  :style="{
                    height: '34px',
                    'line-height': '34px',
                    margin: '0 8px',
                    'font-size': '12px',
                    color: formParams.ext[index].color,
                    'font-weight': '550',
                    width: '180px',
                  }"
                >
                  {{ formParams.ext[index].label }}
                </div>
              </div>
            </n-dynamic-input>
          </n-form-item>

          <n-form-item label="备注" path="remark">
            <n-input
              type="textarea"
              placeholder="请输入备注信息"
              v-model:value="formParams.remark"
            />
          </n-form-item>

          <n-form-item label="发送方式" path="sendType">
            <n-space>
              <n-radio
                :checked="formParams.sendType === 1"
                value="1"
                name="sendType"
                @change="handleChange"
                :disabled="disabled"
              >
                立即发送
              </n-radio>
              <n-radio
                :checked="formParams.sendType === 2"
                value="2"
                name="sendType"
                @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>

        <template #action>
          <n-space>
            <n-button @click="() => (showModal = false)">取消</n-button>
            <n-button type="info" @click="preview">提交预览</n-button>
          </n-space>
        </template>
      </n-modal>
    </n-card>

    <n-modal
      v-model:show="showModal2"
      :show-icon="false"
      preset="dialog"
      :title="title"
      style="width: 620px"
    >
      <n-thing>
        <template #header>
          <n-card title="邮件标题" size="small" :bordered="false" :embedded="true">
            {{ formParams.title }}
          </n-card>
        </template>

        <template #default>
          <n-space vertical>
            <n-card title="收件人" size="small" :bordered="false" :embedded="true">
              <span style="color: red; font-weight: 550; font-size: 18px">{{
                getReceivFormat()
              }}</span>
            </n-card>

            <n-card title="发放道具" size="small" :bordered="false" :embedded="true">
              <n-table :single-line="false">
                <thead>
                  <tr>
                    <th>道具名称</th>
                    <th>数量</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="item in formParams.ext" :key="item">
                    <td>{{ item.label }}</td>
                    <td>{{ item.value }}</td>
                  </tr>
                </tbody>
              </n-table>
            </n-card>

            <n-card title="备注" size="small" :bordered="false" :embedded="true">
              {{ formParams.remark }}
            </n-card>
          </n-space>
        </template>

        <template #footer>
          <n-space vertical>
            <n-card title="邮件内容" size="small" :bordered="false" :embedded="true">
              {{ formParams.content }}
            </n-card>
          </n-space>
        </template>

        <template #action>
          <n-card title="发送方式" size="small" :bordered="false" :embedded="true">
            {{ formParams.sendType == 1 ? '立即发送' : '延迟发送' }}
            {{ formParams.sendType == 1 ? '' : ' - 发送时间：' + format(formParams.sentAt) }}
          </n-card>
        </template>
      </n-thing>

      <template #action>
        <n-space v-if="!formParams.isView">
          <n-button @click="() => (showModal2 = false)">取消</n-button>
          <n-button type="info" :loading="formBtnLoading" @click="confirmForm"
            >{{ formBtnLabel }}
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { h, onMounted, reactive, ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { FormSchema, useForm } from '@/components/Form/index';
  import { columns } from './columns';
  import moment from 'moment';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import { getAllEquipments, getAllMaterials } from '@/api/account/list';
  import { Add, List, Verify } from '@/api/email';
  import { delNullProperty, encodeParams } from '@/utils/array';

  const useUserStore = useUserStoreWidthOut();
  const serverOptions = useUserStore.config.server_simple_option;

  const showModal2 = ref<Boolean>(false);

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

  const schemas: FormSchema[] = [
    {
      field: 'operatorId',
      component: 'NInputNumber',
      label: '发件人Id',
      componentProps: {
        placeholder: '请输入发件人Id',
        showButton: false,
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'sender',
      component: 'NInput',
      label: '发件人名字',
      componentProps: {
        placeholder: '请输入发件人名字',
        showButton: false,
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'createdAt',
      component: 'NDatePicker',
      label: '选择日期',
      componentProps: {
        type: 'datetimerange',
        clearable: true,
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
  ];

  const title = ref('');
  const formBtnLabel = ref('确认发送');
  const disabled = ref(false);
  const subStatus = ref(0); //0提交审核 1确认发送 2取消发送
  const formRef: any = ref(null);
  const loadingRef = ref(false);

  const message = useMessage();
  const actionRef = ref();

  const showModal = ref(false);
  const formBtnLoading = ref(false);

  let formParams = ref<any>({
    id: 0,
    content: '',
    title: '',
    ext: null,
    sendType: 1,
    sendAt: null,
    receiptType: 1,
    serverIds: null,
    playerIds: '',
    keys: '',
    isView: false,
    remark: '',
  });

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

  const actionColumn = reactive({
    width: 260,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            type: 'default',
            label: '查看',
            onClick: handleEdit.bind(null, record),
          },
          {
            type: 'success',
            label: '同意发送',
            onClick: handleVerify.bind(null, record, 1),
            ifShow: () => {
              return record.status == 3;
            },
          },
          {
            type: 'error',
            label: '取消发送',
            onClick: handleVerify.bind(null, record, 2),
            ifShow: () => {
              return record.status == 3;
            },
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 95,
    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 !== 2;
    formParams.value.sendType = checkedValueRef.value;
    console.log('handleChange formParams.sendType:' + formParams.value.sendType);
  }

  function handleSubmit(values: Recordable) {
    console.log('handleSubmit values:' + JSON.stringify(values));
    params.value = { ...values, pageSize: 10 };
    reloadTable();
  }

  function exportMail() {
    loadingRef.value = true;
    window.location.href =
      '/api/email/list?' +
      encodeParams(
        delNullProperty({ ...params.value, isExport: 1, ...{ authorization: useUserStore.token } })
      );
    setTimeout(() => {
      loadingRef.value = false;
    }, 2000);
  }

  function addTable(receiptType) {
    formBtnLabel.value = '确认无误，提交发送';
    title.value = '发送邮件';
    if (receiptType === 1) {
      title.value = '发送全服邮件';
      if (!useUserStore.info.isSuper) {
        formBtnLabel.value = '确认无误，提交审核';
      }
    }
    if (receiptType === 2) {
      title.value = '发送指定服邮件';
      if (!useUserStore.info.isSuper) {
        formBtnLabel.value = '确认无误，提交审核';
      }
    }

    if (receiptType === 3) {
      title.value = '发送指定玩家邮件';
      if (!useUserStore.info.isSuper) {
        formBtnLabel.value = '确认无误，提交审核';
      }
    }

    formParams.value.id = 0;
    formParams.value.content = '';
    formParams.value.title = '';
    formParams.value.ext = null;
    formParams.value.sendType = 1;
    formParams.value.sendAt = null;
    formParams.value.receiptType = receiptType;
    formParams.value.serverIds = null;
    formParams.value.playerIds = '';
    formParams.value.isView = false;
    formParams.value.remark = '';
    delaySendShow.value = true;
    showModal.value = true;
  }

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

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

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

  function handleReset(values: Recordable) {
    params.value = { ...values, pageSize: 10 };
    reloadTable();
  }

  function conversionParameters(req) {
    if (
      formParams.value.ext === undefined ||
      formParams.value.ext === null ||
      formParams.value.ext.length === 0
    ) {
      formParams.value.ext = [];
    }

    req.id = formParams.value.id;
    req.ext = [];
    req.keys = [...new Array(formParams.value.ext.length).keys()];
    console.log('formParams.value.ext:', formParams.value.ext);
    for (let i = 0; i < formParams.value.ext.length; i++) {
      let typ = findItemTypeById(formParams.value.ext[i].key);
      console.log('conversionParameters typ:' + typ);
      req.ext[i] = {
        id: formParams.value.ext[i].key,
        type: typ,
        num: formParams.value.ext[i].value,
      };
    }

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

    req.title = formParams.value.title;
    if (req.title === null || req.title === '') {
      message.error('标题不能为空');
      return;
    }

    if (
      formParams.value.receiptType == 2 &&
      (!formParams.value.serverIds || formParams.value.serverIds.length < 1)
    ) {
      message.error('请选择收件服务器');
      return;
    }

    if (formParams.value.receiptType == 3 && formParams.value.playerIds == '') {
      message.error('请填写收件人');
      return;
    }

    if (formParams.value.sendType == 2) {
      if (formParams.value.sendAt === null || formParams.value.sendAt === undefined) {
        message.error('延迟发送时间不能为空');
        return;
      }
    }

    req.expired = formParams.value.expired;
    req.serverIds = formParams.value.serverIds;
    req.playerIds = formParams.value.playerIds.split(',').map(String);
    req.remark = formParams.value.remark;
    req.sendType = formParams.value.sendType;
    req.sendAt = formParams.value.sendAt;
    if (req.sendAt > 0) {
      req.sendAt = req.sendAt / 1000;
    }
    req.receiptType = formParams.value.receiptType;
    req.ok = true;
    return req;
  }

  function confirmForm(e) {
    console.log('发送');
    if (subStatus.value != 0) {
      Verify({
        id: formParams.value.id,
        verifyStatus: subStatus.value,
      }).then((_res) => {
        message.success('操作成功');
        showModal.value = false;
        showModal2.value = false;
        reloadTable();
      });
      return;
    }

    e.preventDefault();

    formRef.value.validate((errors) => {
      if (!errors) {
        let req = {};
        req = conversionParameters(req);
        if (!req.ok) {
          return;
        }

        console.log('confirmForm req:' + JSON.stringify(req));

        formBtnLoading.value = true;

        Add(req)
          .then((_res) => {
            message.success('操作成功');
            console.log('操作成功');
          })
          .catch((error) => {
            message.error(error.toString());
          });

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

  function handleEdit(record: Recordable) {
    title.value = '查看邮件';
    showModal2.value = true;
    formParams.value.isView = true;
    formParams.value.expired = record.expired;
    formParams.value.receiptType = record.receipt_type;
    formParams.value.sendAt = record.send_at;
    formParams.value.sendType = record.send_type;
    formParams.value.title = record.title;
    formParams.value.content = record.content;
    formParams.value.id = record.id;
    formParams.value.serverIds = JSON.parse(record.server_ids);
    formParams.value.playerIds = record.player_ids;
    formParams.value.remark = record.remark;

    formParams.value.ext = [];

    let ext = JSON.parse(record.ext);
    if (ext.length > 0) {
      for (let i = 0; i < ext.length; i++) {
        let label = getItemLabel(ext[i].id);
        if (!label) {
          label = '道具不存在';
        }
        formParams.value.ext[i] = { key: ext[i].id, value: ext[i].num, label: label };
      }
    }
  }

  function handleVerify(record: Recordable, st: number) {
    title.value = '您确定同意发送该邮件吗？';
    formBtnLabel.value = '确认发送';
    subStatus.value = 1;
    if (st == 2) {
      title.value = '您确定取消发送该邮件吗？';
      formBtnLabel.value = '确认取消';
      subStatus.value = 2;
    }

    formParams.value.isView = false;
    formParams.value.expired = record.expired;
    formParams.value.receiptType = record.receipt_type;
    formParams.value.sendAt = record.send_at;
    formParams.value.sendType = record.send_type;
    formParams.value.title = record.title;
    formParams.value.content = record.content;
    formParams.value.id = record.id;
    formParams.value.serverIds = JSON.parse(record.server_ids);
    formParams.value.playerIds = record.player_ids;
    formParams.value.remark = record.remark;

    formParams.value.ext = [];
    let ext = JSON.parse(record.ext);
    if (ext.length > 0) {
      for (let i = 0; i < ext.length; i++) {
        let label = getItemLabel(ext[i].id);
        if (!label) {
          label = '道具不存在';
        }
        formParams.value.ext[i] = { key: ext[i].id, value: ext[i].num, label: label };
      }
    }
    showModal2.value = true;
  }

  const allEquipments = ref<any>([]);
  const allMaterials = ref<any>([]);

  onMounted(async () => {
    // getAllEquipments({}).then((res) => {
    //   allEquipments.value = res.list;
    // });

    getAllMaterials({}).then((res) => {
      allMaterials.value = res;
    });
  });

  function onCreate() {
    return {
      key: '',
      value: '',
      label: '',
      color: '#2080f0',
    };
  }

  function handleExtChange(index, item) {
    const name = getItemLabel(item.key);
    if (!name) {
      formParams.value.ext[index].label = '道具不存在';
      formParams.value.ext[index].color = 'red';
    } else {
      formParams.value.ext[index].color = '#2080f0';
      if (item.value > 0) {
        formParams.value.ext[index].label = name + ' * ' + item.value;
      } else {
        formParams.value.ext[index].label = name;
      }
    }
  }

  function findItemNameById(itemId) {
    for (const index in allMaterials.value) {
      const item = allMaterials.value[index];
      for (let i = 0; i < item.length; i++) {
        if (item[i].ItemId == itemId) {
          return item[i].ItemName;
        }
      }
    }
    return null;
  }

  function findItemTypeById(itemId: String) {
    console.log('findItemTypeById itemId:' + itemId);

    for (const index in allMaterials.value) {
      const items = allMaterials.value[index];
      console.log('findItemTypeById items:' + JSON.stringify(items));
      for (let i = 0; i < items.length; i++) {
        if (items[i].ItemId === Number(itemId)) {
          return items[i].ItemType;
        }
      }
    }
    return null;
  }

  function getItemLabel(key) {
    // const eq = allEquipments.value[key];
    // if (eq) {
    //   return eq.name + ' 星级:' + eq.star;
    // }

    const name = findItemNameById(key);
    if (name) {
      return name;
    }
    return null;
  }

  function preview(e) {
    let req = { opt: 'send' };
    req = conversionParameters(req);
    if (req.ok === undefined) {
      return;
    }
    subStatus.value = 0;
    showModal2.value = true;
  }

  function format(d) {
    return moment(d).format('YYYY-MM-DD HH:mm:ss');
  }

  function getReceivFormat() {
    let str = '';
    if (formParams.value.receiptType === 1) {
      str = '发送给全服玩家';
    }

    if (formParams.value.receiptType === 2) {
      str = '发送给指定服务器玩家，';
      str += ' 服务器ID：' + JSON.stringify(formParams.value.serverIds);
    }

    if (formParams.value.receiptType === 3) {
      str = '发送给指定玩家，';
      str += ' 玩家ID：' + formParams.value.playerIds;
    }
    return str;
  }
</script>

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