<script setup lang="ts">
import { Page } from '@vben/common-ui';
import { useAccess } from '@vben/access';
import { Button, Card, Image, message, Modal, Space, Tag } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import type { 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 {
  approveMailApi,
  deleteMailApi,
  getMailListApi,
  rejectMailApi,
} 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, formatUTC8Time } from '#/store/util';
import { $t } from '#/locales';

const appList = ref<AppData[]>([]);
const ServerList = ref<ServerData[]>([]);
const { hasAccessByRoles } = useAccess();

function getStatusText(status?: number) {
  if (status === 1) {
    return '待审核';
  }
  if (status === 2) {
    return '已通过';
  }
  if (status === 3) {
    return '已驳回';
  }
  return '已发送';
}

function getStatusColor(status?: number) {
  if (status === 1) {
    return 'processing';
  }
  if (status === 2) {
    return 'success';
  }
  if (status === 3) {
    return 'error';
  }
  return 'default';
}

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：',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};
const gridOptions: VxeGridProps<MailData> = {
  columns: [
    { field: 'audit_id', title: '审核单ID', width: 100 },
    { field: 'mail_id', title: '邮件ID', width: 100 },
    { field: 'title', title: '邮件标题' },
    { field: 'content', title: '邮件内容' },
    { field: 'items', title: '道具', slots: { default: 'items' } },
    {
      field: 'status',
      title: '审核状态',
      slots: { default: 'status' },
    },
    {
      field: 'applicant',
      title: '申请人',
    },
    {
      field: 'reviewer',
      title: '审核人',
    },
    {
      field: 'review_time',
      title: '审核时间',
      formatter: ({ cellValue }) =>
        cellValue ? formatUTC8Time(cellValue) : '-',
    },
    {
      field: 'start_time',
      title: '开始时间',
      formatter: ({ cellValue }) =>
        cellValue ? formatUTC8Time(cellValue) : '',
      slots: { header: 'time_header' },
    },
    {
      field: 'mail_type',
      title: '邮件类型',
      formatter: ({ cellValue }) => (cellValue == 1 ? '普通邮件' : '节日邮件'),
    },
    {
      field: 'send_type',
      title: '邮件发送类型',
      formatter: ({ cellValue }) => (cellValue == 1 ? '全服邮件' : '个人邮件'),
    },
    {
      field: 'min_level',
      title: '最低等级',
      formatter: ({ cellValue }) => (cellValue ? cellValue : 0),
    },
    { field: 'to_uids', title: '接收者' },
    {
      field: 'create_time',
      title: '申请时间',
      formatter: ({ cellValue }) =>
        cellValue ? formatUTC8Time(cellValue) : '-',
    },
    { slots: { default: 'action' }, title: '操作', width: 280, fixed: 'right' },
  ],
  minHeight: '650px',
  pagerConfig: {},
  proxyConfig: {
    response: {
      total: 'total',
      result: 'data',
    },
    ajax: {
      query: async ({ page }, formValues) => {
        const AppId = Number(formValues.AppId || appList.value[0]?.AppId || 1);
        return await getMailListApi({
          AppId: AppId,
          ServerId: Number(formValues.ServerId || 1),
          PageSize: page.pageSize,
          CurrentPage: page.currentPage,
        });
      },
    },
  },
  showOverflow: true,
  rowConfig: {
    isHover: true,
  },
};
const [Grid, GridApi] = useVbenVxeGrid({
  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: $t('page.server.' + item.AppName),
            value: item.AppId,
          })),
        },
        fieldName: 'AppId',
      },
    ]);
    
  } catch (e) {
    appList.value = [];
    //console.log(e);
  }
});

async function addMail() {
  const Value = await GridApi.formApi.getValues();
  AddMailApi.setData({
    AppId: Number(Value.AppId || appList.value[0]?.AppId || 1),
    ServerId: Number(Value.ServerId || 1),
  });
  AddMailApi.open();
}

function showDetail(row: MailData) {
  AddMailApi2.setData(row);
  AddMailApi2.open();
}

async function refreshGrid() {
  await GridApi.query();
}

function approveRow(row: MailData) {
  const auditId = row.audit_id;
  if (!auditId) {
    message.error('缺少审核单ID');
    return;
  }
  Modal.confirm({
    title: '确认通过这条邮件审核吗？',
    async onOk() {
      await approveMailApi(auditId);
      message.success('审核通过');
      await refreshGrid();
    },
  });
}

function rejectRow(row: MailData) {
  const auditId = row.audit_id;
  if (!auditId) {
    message.error('缺少审核单ID');
    return;
  }
  Modal.confirm({
    title: '确认驳回这条邮件申请吗？',
    async onOk() {
      await rejectMailApi(auditId);
      message.success('已驳回');
      await refreshGrid();
    },
  });
}

async function deleteRow(row: MailData) {
  Modal.confirm({
    title: '确认删除这条邮件记录吗？',
    async onOk() {
      GridApi.setLoading(true);
      try {
        await deleteMailApi({
          AppId: row.AppId,
          ServerId: row.ServerId,
          audit_id: row.audit_id,
          mail_id: row.mail_id,
        });
        message.success('删除成功');
        await refreshGrid();
      } finally {
        GridApi.setLoading(false);
      }
    },
  });
}

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>
    <AddMailM class="w-[50%]" />
    <AddMailM2 class="w-[50%]" />
    <Card class="mb-5" title="邮件审核">
      <Space>
        <Button v-if="hasAccessByRoles(['super', 'AC7001'])" @click="addMail">新增邮件申请</Button>
      </Space>
    </Card>
    <Grid>
      <template #time_header>
        开始时间 <span style="color: red">(UTC+8)</span>
      </template>
      <template #status="{ row }">
        <Tag :color="getStatusColor(row.status)">{{ getStatusText(row.status) }}</Tag>
      </template>
      <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 }">
        <Space>
          <Button type="primary" @click="showDetail(row)">详情</Button>
          <Button
            v-if="row.status === 1 && hasAccessByRoles(['super', 'AC7004'])"
            type="primary"
            @click="approveRow(row)"
          >
            通过
          </Button>
          <Button
            v-if="row.status === 1 && hasAccessByRoles(['super', 'AC7005'])"
            danger
            type="primary"
            @click="rejectRow(row)"
          >
            驳回
          </Button>
          <Button
            v-if="hasAccessByRoles(['super', 'AC7003'])"
            danger
            type="primary"
            @click="deleteRow(row)"
          >
            删除
          </Button>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
