<script setup lang="ts">
import { Page } from '@vben/common-ui';
import { Button, Card, Space, Image, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';
import type { VbenFormProps } from '#/adapter/form';
import type { MailData } from '#/api/core/mail';
import { getServerListApi, getAppListApi } from '#/api/core/server';
import { getMailListApi, deleteMailApi } from '#/api/core/mail';
import type { AppData, ServerData } from '#/api/core/server';
import { useVbenModal } from '@vben/common-ui';
import { onMounted, ref } from 'vue';
import AddMailModal from './mail-info.vue';
import DetailMailModal from './mail-detail.vue';
import { getItemUrl } from '#/store/util';
const appList = ref<AppData[]>([]);
const ServerList = ref<ServerData[]>([]);

const formOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  schema: [
    {
      component: 'Select',
      defaultValue: 1,
      componentProps: {
        onChange: async (value: number) => {
          const serverResponse = await getServerListApi({
            AppId: value,
            Type: 1,
          });
          ServerList.value = Array.isArray(serverResponse)
            ? serverResponse
            : [];
          GridApi.formApi.updateSchema([
            {
              component: 'Select',
              componentProps: {
                options: ServerList.value.map((item) => ({
                  label: item.ServerName,
                  value: item.ServerId,
                })),
              },
              fieldName: 'ServerId',
            },
          ]);
        },
        filterOption: true,
        options: [],
        placeholder: '请选择',
        showSearch: true,
      },
      fieldName: 'AppId',
      label: 'APP：',
    },
    {
      component: 'Select',
      defaultValue: 1,
      componentProps: {
        options: [],
      },
      fieldName: 'ServerId',
      label: '区服',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};
const gridOptions: VxeGridProps<MailData> = {
  columns: [
    { field: 'mail_id', title: 'id' },
    { field: 'title', title: '邮件标题' },
    // { field: 'title_en', title: '英文邮件标题' },
    { field: 'subtitle', title: '邮件副标题' },
    // { field: 'subtitleEN', title: '英文邮件副标题' },
    { field: 'content', title: '邮件内容' },
    // { field: 'content_en', title: '英文邮件内容' },
    { field: 'items', title: '道具', slots: { default: 'items' } },
     {
       field: 'start_time',
       title: '开始时间',
       formatter: ({ cellValue }) =>
         cellValue ? new Date(cellValue * 1000).toLocaleString() : '',
    },
    {
      field: 'mail_type',
      title: '邮件类型',
      formatter: ({ cellValue }) => (cellValue == 1 ? '普通邮件' : '节日邮件'),
    },
    {
      field: 'send_type',
      title: '邮件发送类型',
      formatter: ({ cellValue }) => (cellValue == 1 ? '全服邮件' : '个人邮件'),
    },
    { field: 'to_uids', title: '接收者' },
    { field: 'create_time', title: '创建时间' },
    { slots: { default: 'action' }, title: '操作', width: 100 },
  ],
  height: 'auto',
  pagerConfig: {},
  proxyConfig: {
    response: {
      total: 'total',
      result: 'data',
    },
    ajax: {
      query: async ({ page }, formValues) => {
        let AppId = parseInt(formValues.AppId, 10);
        return await getMailListApi({
          AppId: AppId,
          ServerId: formValues.ServerId,
          PageSize: page.pageSize,
          CurrentPage: page.currentPage,
        });
      },
    },
  },
  showOverflow: false,
  rowConfig: {
    isHover: true,
  },
};
const gridEvents: VxeGridListeners<MailData> = {
  cellClick: ({ row }) => {
    AddMailApi2.setData(row);
    AddMailApi2.open();
    // message.info(`cell-click: ${row.title}`);
  },
};
const [Grid, GridApi] = useVbenVxeGrid({
  gridEvents,
  formOptions,
  gridOptions,
});
const [AddMailM, AddMailApi] = useVbenModal({
  connectedComponent: AddMailModal,
  onClosed: async () => {
    AddMailApi.close();
    GridApi.query();
    //console.log("close")
  },
});

const [AddMailM2, AddMailApi2] = useVbenModal({
  connectedComponent: DetailMailModal,
});
onMounted(async () => {
  try {
    const response = await getAppListApi();
    appList.value = Array.isArray(response) ? response : [];
    const app = appList.value[0];
    if (!app) return;
    GridApi.formApi.updateSchema([
      {
        component: 'Select',
        componentProps: {
          options: appList.value.map((item) => ({
            label: item.AppName,
            value: item.AppId,
          })),
        },
        fieldName: 'AppId',
      },
    ]);
    const serverResponse = await getServerListApi({
      AppId: app.AppId,
      Type: 1,
    });
    ServerList.value = Array.isArray(serverResponse) ? serverResponse : [];
    GridApi.formApi.updateSchema([
      {
        component: 'Select',
        componentProps: {
          options: ServerList.value.map((item) => ({
            label: item.ServerName,
            value: item.ServerId,
          })),
        },
        fieldName: 'ServerId',
      },
    ]);
  } catch (e) {
    appList.value = [];
    //console.log(e);
  }
});

async function addMail() {
  //console.log('addMail');
  const Value = await GridApi.formApi.getValues();
  AddMailApi.setData({ AppId: Value.AppId, ServerId: Value.ServerId });
  AddMailApi.open();
}

async function deleteRow(row: MailData) {
  //console.log(row);
  GridApi.setLoading(true);
  if (typeof row.mail_id == 'number') {
    await deleteMailApi(row.AppId, row.ServerId, row.mail_id);
  } else {
    //console.error('Invalid mail_id:', row.mail_id);
  }
  GridApi.setLoading(false);
  GridApi.query();
}

function fromatItems(items: string) {
  try {
    const itemList = JSON.parse(items);
    const r =  itemList.map((item: { Id: number; Num: number }) => ({
      ...item,
      url: getItemUrl(item.Id),
    }));
    return r;
  } catch (e) {
    //console.error('Failed to parse items:', e);
    return [];
  }
}
</script>

<template>
  <Page auto-content-height class="h-[800px]">
    <AddMailM class="w-[50%]" />
    <AddMailM2 class="w-[50%]" />
    <Card class="mb-5" title="邮件操作">
      <Space>
        <Button @click="addMail">新增邮件</Button>
      </Space>
    </Card> 
    <Grid> 
      <template #items="{ row }">
        <div class="flex flex-wrap items-center justify-center">
          <div v-for="item in fromatItems(row.items)" :key="item.Id" class="flex items-center gap-1">
            <template v-if="item.url">
              <Image :src="item.url" width="30px" />
            </template>
            <template v-else>
              <Tag class="w-[45px] h-[30px] flex items-center justify-center text-xs">
               {{item.Id}}
              </Tag>
            </template>
            <span>x{{ item.Num }}</span>
          </div>
        </div>
      </template>
      <template #action="{ row }">
        <Button type="link" @click="deleteRow(row)" style="color: #cc0000">删除</Button>
      </template>
    </Grid>
  </Page>
</template>
