<template>
  <SimpleScrollbar>
    <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
      <ACard
        :title="t('page.wlan.title')"
        :bordered="false"
        :body-style="{ flex: 1, overflow: 'hidden' }"
        class="flex-col-stretch sm:flex-1-hidden card-wrapper"
      >
        <template #extra>
          <div class="flex items-center gap-4">
            <!-- 站点选择 -->
            <a-select
              v-model:value="selectedSiteId"
              :loading="siteLoading"
              :placeholder="t('page.wlan.selectSite')"
              style="width: 200px"
              @change="handleSiteChange"
            >
              <a-select-option
                v-for="site in siteList"
                :key="site.siteId"
                :value="site.siteId"
              >
                {{ site.name }}
              </a-select-option>
            </a-select>

            <!-- 群组选择 -->
            <a-select
              v-model:value="selectedGroupId"
              :loading="groupLoading"
              :placeholder="t('page.wlan.selectGroup')"
              style="width: 200px"
              :disabled="!selectedSiteId"
              @change="handleGroupChange"
            >
              <a-select-option
                v-for="group in groupList"
                :key="group.wlanId"
                :value="group.wlanId"
              >
                {{ group.name }}
              </a-select-option>
            </a-select>

            <!-- 添加表格操作组件 -->
            <TableHeaderOperation
              v-model:columns="columnChecks"
              :loading="tableLoading"
              :show-delete="false"
              @add="handleAdd"
              @refresh="getData"
            />
          </div>
        </template>

        <!-- 添加表格 -->
        <ATable
          :columns="columns"
          :data-source="tableData"
          :loading="tableLoading"
          :pagination="{
            ...mobilePagination,
            total: mobilePagination.total,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            showTotal: (total: number) => `${t('page.wlan.total')} ${total} `
          }"
          @change="(pagination) => {
            searchParams.pageNum = pagination.current;
            searchParams.pageSize = pagination.pageSize;
            getData();
          }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'operate'">
              <div class="flex items-center justify-center gap-2">
                <a-tooltip :title="t('common.edit')">
                  <a-button
                    type="link"
                    size="small"
                    @click="() => handleEdit(record)"
                  >
                    <template #icon>
                      <EditOutlined />
                    </template>
                  </a-button>
                </a-tooltip>

                <a-tooltip :title="t('common.delete')">
                  <a-button
                    type="link"
                    size="small"
                    class="text-red-500"
                    @click="() => handleDelete(record)"
                  >
                    <template #icon>
                      <DeleteOutlined />
                    </template>
                  </a-button>
                </a-tooltip>
              </div>
            </template>
          </template>
        </ATable>
      </ACard>

      <!-- 添加无线网络对话框 -->
      <a-modal
        v-model:visible="addVisible"
        :title="t('page.wlan.addSsid')"
        @ok="handleAddConfirm"
        width="600px"
      >
        <a-form
          :model="addForm"
          :rules="addRules"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
          layout="horizontal"
          ref="formRef"
        >
          <a-form-item name="name" :label="t('page.wlan.name')">
            <a-input v-model:value="addForm.name" />
          </a-form-item>

          <a-form-item name="deviceType" :label="t('page.wlan.deviceType')">
            <a-space>
              <a-checkbox v-model:checked="addForm.deviceType.eap">EAP</a-checkbox>
              <a-checkbox v-model:checked="addForm.deviceType.gateway">Gateway</a-checkbox>
            </a-space>
          </a-form-item>

          <a-form-item name="band" :label="t('page.wlan.band')">
            <a-space>
              <a-checkbox v-model:checked="addForm.band.band24G">2.4GHz</a-checkbox>
              <a-checkbox v-model:checked="addForm.band.band5G">5GHz</a-checkbox>
              <a-checkbox v-model:checked="addForm.band.band6G">6GHz</a-checkbox>
            </a-space>
          </a-form-item>

          <a-form-item name="guestNetEnable" :label="t('page.wlan.guestNetwork')">
            <a-checkbox v-model:checked="addForm.guestNetEnable" />   {{t('page.wlan.open')}}
          </a-form-item>

          <a-form-item name="security" :label="t('page.wlan.security.security')">
            <a-select v-model:value="addForm.security">
              <a-select-option :value="0">{{ t('page.wlan.none') }}</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item name="broadcast" :label="t('page.wlan.broadcast')">
            <a-checkbox v-model:checked="addForm.broadcast" /> {{t('page.wlan.open')}}
          </a-form-item>

          <a-form-item name="vlanEnable" :label="t('page.wlan.vlan')">
            <a-radio-group v-model:value="addForm.vlanEnable">
              <a-radio :value="false">{{ t('page.wlan.default') }}</a-radio>
              <a-radio :value="true">{{ t('page.wlan.custom') }}</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item
            v-if="addForm.vlanEnable"
            name="vlanId"
            :label="t('page.wlan.vlanId')"
          >
            <a-input-number v-model:value="addForm.vlanId" :min="1" :max="4094" style="width: 100%" />
          </a-form-item>
        </a-form>
      </a-modal>

      <!-- 修改无线网络对话框 -->
      <a-modal
        v-model:visible="editVisible"
        :title="t('page.wlan.editSsid')"
        @ok="handleEditConfirm"
        width="600px"
      >
        <a-form
          :model="editForm"
          :rules="addRules"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 16 }"
          layout="horizontal"
          ref="editFormRef"
        >
          <a-form-item name="name" :label="t('page.wlan.name')">
            <a-input v-model:value="editForm.name" />
          </a-form-item>

          <a-form-item name="deviceType" :label="t('page.wlan.deviceType')">
            <a-space>
              <a-checkbox v-model:checked="editForm.deviceType.eap">EAP</a-checkbox>
              <a-checkbox v-model:checked="editForm.deviceType.gateway">Gateway</a-checkbox>
            </a-space>
          </a-form-item>

          <a-form-item name="band" :label="t('page.wlan.band')">
            <a-space>
              <a-checkbox v-model:checked="editForm.band.band24G">2.4GHz</a-checkbox>
              <a-checkbox v-model:checked="editForm.band.band5G">5GHz</a-checkbox>
              <a-checkbox v-model:checked="editForm.band.band6G">6GHz</a-checkbox>
            </a-space>
          </a-form-item>

          <a-form-item name="guestNetEnable" :label="t('page.wlan.guestNetwork')">
            <a-checkbox v-model:checked="editForm.guestNetEnable" />   {{t('page.wlan.open')}}
          </a-form-item>

          <a-form-item name="security" :label="t('page.wlan.security.security')">
            <a-select v-model:value="editForm.security">
              <a-select-option :value="0">{{ t('page.wlan.none') }}</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item name="broadcast" :label="t('page.wlan.broadcast')">
            <a-checkbox v-model:checked="editForm.broadcast" /> {{t('page.wlan.open')}}
          </a-form-item>

          <a-form-item name="vlanEnable" :label="t('page.wlan.vlan')">
            <a-radio-group v-model:value="editForm.vlanEnable">
              <a-radio :value="false">{{ t('page.wlan.default') }}</a-radio>
              <a-radio :value="true">{{ t('page.wlan.custom') }}</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item
            v-if="editForm.vlanEnable"
            name="vlanId"
            :label="t('page.wlan.vlanId')"
          >
            <a-input-number v-model:value="editForm.vlanId" :min="1" :max="4094" style="width: 100%" />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </SimpleScrollbar>
</template>

<script setup lang="ts">
import { SimpleScrollbar } from '~/packages/materials/src';
import { ref, onMounted } from 'vue';
import { Card as ACard, Table as ATable, message, Modal } from 'ant-design-vue';
import { useI18n } from 'vue-i18n';
import { fetchSiteList, fetchWlanGroups, fetchWlanSsidList, addWlanSsid, deleteWlanSsid, updateWlanSsid, getWlanSsidConfig } from '@/service/api/auth';
import { useTable } from '@/hooks/common/table';
import { DeleteOutlined, EditOutlined } from '@ant-design/icons-vue';
import {centerAlign} from "consola/utils";

const { t } = useI18n();

// 站点相关
const siteList = ref<Api.Site.SiteInfo[]>([]);
const selectedSiteId = ref<string>('');
const siteLoading = ref(false);

// 群组相关
const groupList = ref<Api.Wlan.WlanGroup[]>([]);
const selectedGroupId = ref<string>('');
const groupLoading = ref(false);

// 使用 useTable hook
const {
  columns,
  columnChecks,
  data: tableData,
  loading: tableLoading,
  getData,
  mobilePagination,
  searchParams,
} = useTable<Api.Wlan.WlanSsid, Api.Wlan.WlanSsidParams>({
  apiFn: async (params:any) => {
    if (!selectedSiteId.value || !selectedGroupId.value) {
      return {
        data: {
          rows: [],
          total: 0
        }
      };
    }
    return fetchWlanSsidList(
      selectedSiteId.value,
      selectedGroupId.value,
      {
        pageNum: params.pageNum || 1,
        pageSize: params.pageSize || 10
      }
    );
  },
  columns: () => [
    {
      title: t('page.wlan.name'),
      dataIndex: 'name',
      key: 'name',
      width: 150
    },
    {
      title: t('page.wlan.security.security'),
      dataIndex: 'security',
      key: 'security',
      width: 100,
      customRender: ({ text }: { text: number }) => {
        const securityMap: Record<number, string> = {
          0: t('page.wlan.none'),
          2: t('page.wlan.security.wpaEnterprise'),
          3: t('page.wlan.security.wpaPersonal'),
          4: t('page.wlan.security.ppskWithoutRadius'),
          5: t('page.wlan.security.ppskWithRadius')
        };
        return securityMap[text] || text;
      }
    },
    {
      title: t('page.wlan.band'),
      dataIndex: 'band',
      key: 'band',
      width: 100,
      customRender: ({ text }: { text: number }) => {
        const bands = [];
        if (text & 1) bands.push('2.4G');
        if (text & 2) bands.push('5G');
        if (text & 4) bands.push('6G');
        return bands.join('/') || '-';
      }
    },
    {
      title: t('page.wlan.guestNetwork'),
      dataIndex: 'guestNetEnable',
      key: 'guestNetEnable',
      width: 100,
      customRender: ({ text }: { text: boolean }) => {
        return text ? t('page.wlan.enable') : t('page.wlan.disable');
      }
    },
    {
      title: t('page.wlan.portalEnable'),
      dataIndex: 'portalEnable',
      key: 'portalEnabel',
      width: 120,
      customRender: ({ text }: { text: boolean }) => {
        return text ? '√' : '-';
      }
    },
    {
      title: t('page.wlan.portalName'),
      dataIndex: 'portalName',
      key: 'portalName',
      width: 120,
      customRender: ({ text, record }: { text: string | null, record: Api.Wlan.WlanSsid }) => {
        return record.portalEnable ? (text || '-') : '-';
      }
    },
    {
      title: 'VLAN',
      dataIndex: 'vlanId',
      key: 'vlanId',
      width: 120,
      customRender: ({ text, record }: { text: number | null, record: Api.Wlan.WlanSsid }) => {
        return record.vlanEnable ? (text || '-') : '-';
      }
    },
    {
      title: t('common.operate'),
      key: 'operate',
      width: 120,
      fixed: 'right',
      align: 'center'
    }
  ]
});

// 获取站点列表
const getSiteList = async () => {
  siteLoading.value = true;
  const { data, error } = await fetchSiteList({
    pageNum: 1,
    pageSize: 100
  });

  if (!error) {
    siteList.value = data.rows || [];

    // 如果有站点数据，默认选择第一个
    if (siteList.value.length > 0) {
      selectedSiteId.value = siteList.value[0].siteId;
      // 获取第一个站点的群组列表
      await getGroupList(selectedSiteId.value);
    }
  }

  siteLoading.value = false;
};

// 获取群组列表
const getGroupList = async (siteId: string) => {
  groupLoading.value = true;
  const { data, error } = await fetchWlanGroups(siteId);

  if (!error) {
    groupList.value = data || [];

    // 如果有群组数据，默认选择第一个
    if (groupList.value.length > 0) {
      selectedGroupId.value = groupList.value[0].wlanId;
      // 这里可以调用获取其他数据的方法
      await getData();
    } else {
      selectedGroupId.value = '';
    }
  }

  groupLoading.value = false;
};

// 处理站点变更
const handleSiteChange = async (value: string) => {
  selectedSiteId.value = value;
  selectedGroupId.value = ''; // 清空群组选择
  groupList.value = []; // 清空群组列表
  await getGroupList(value);
};

// 处理群组变更
const handleGroupChange = async (value: string) => {
  selectedGroupId.value = value;
  // 这里可以调用获取其他数据的方法
  await getData();
};

// 添加对话框相关
const addVisible = ref(false);
const formRef = ref();
const addForm = ref<Api.Wlan.WlanSsidForm>({
  name: '',
  deviceType: {
    eap: true,
    gateway: false
  },
  band: {
    band24G: true,
    band5G: true,
    band6G: false
  },
  guestNetEnable: false,
  security: 0,
  broadcast: true,
  vlanEnable: false,
  vlanId: undefined
});

// 表单验证规则
const addRules = {
  name: [
    { required: true, message: t('page.wlan.nameRequired') },
    { min: 1, max: 32, message: t('page.wlan.nameLength') }
  ],
  vlanId: [
    {
      required: true,
      message: t('page.wlan.vlanIdRequired'),
      validator: (_: any, value: number) => {
        if (!addForm.value.vlanEnable) return Promise.resolve();
        if (!value) return Promise.reject();
        return Promise.resolve();
      }
    }
  ]
};

// 处理添加按钮点击
const handleAdd = () => {
  addVisible.value = true;
};

// 处理添加确认
const handleAddConfirm = async () => {
  await formRef.value?.validate();

  const hide = message.loading(t('common.loading'), 0);

  // 转换表单数据为API参数
  const params: Api.Wlan.AddWlanSsidParams = {
    name: addForm.value.name,
    deviceType: (addForm.value.deviceType.eap ? 1 : 0) | (addForm.value.deviceType.gateway ? 2 : 0),
    band: (addForm.value.band.band24G ? 1 : 0) |
      (addForm.value.band.band5G ? 2 : 0) |
      (addForm.value.band.band6G ? 4 : 0),
    guestNetEnable: addForm.value.guestNetEnable,
    security: addForm.value.security,
    broadcast: addForm.value.broadcast,
    vlanEnable: addForm.value.vlanEnable,
    vlanId: addForm.value.vlanEnable ? addForm.value.vlanId : undefined,
    // 固定值字段
    mloEnable: false,
    pmfMode: 1,
    enable11r: false,
    hidePwd: false,
    greEnable:false,
  };

  const { error } = await addWlanSsid(selectedSiteId.value, selectedGroupId.value, params);

  hide();
  if (!error) {
    message.success(t('page.wlan.addSuccess'));
    addVisible.value = false;
    addForm.value = { ...addForm.value, name: '' }; // 重置表单
    getData(); // 刷新列表
  }
};

// 添加修改相关的响应式变量
const editVisible = ref(false);
const editFormRef = ref();
const currentSsid = ref<string>('');
const editForm = ref<Api.Wlan.WlanSsidForm>({
  name: '',
  deviceType: {
    eap: true,
    gateway: false
  },
  band: {
    band24G: true,
    band5G: true,
    band6G: false
  },
  guestNetEnable: false,
  security: 0,
  broadcast: true,
  vlanEnable: false,
  vlanId: undefined
});

// 处理编辑按钮点击
const handleEdit = async (record: Api.Wlan.WlanSsid) => {
  const hide = message.loading(t('common.loading'), 0);

  // 获取当前配置
  const { data, error } = await getWlanSsidConfig(
    selectedSiteId.value,
    selectedGroupId.value,
    record.ssidId
  );

  hide();
  if (!error && data) {
    // 保存当前编辑的 ssidId
    currentSsid.value = record.ssidId;

    // 转换后端数据为表单数据
    editForm.value = {
      name: data.name,
      deviceType: {
        eap: !!(data.deviceType & 1),
        gateway: !!(data.deviceType & 2)
      },
      band: {
        band24G: !!(data.band & 1),
        band5G: !!(data.band & 2),
        band6G: !!(data.band & 4)
      },
      guestNetEnable: data.guestNetEnable,
      security: data.security,
      broadcast: data.broadcast,
      vlanEnable: data.vlanEnable,
      vlanId: data.vlanId,
    };

    editVisible.value = true;
  }
};

// 处理修改确认
const handleEditConfirm = async () => {
  await editFormRef.value?.validate();

  const hide = message.loading(t('common.loading'), 0);

  // 转换表单数据为API参数
  const params: Api.Wlan.AddWlanSsidParams = {
    name: editForm.value.name,
    deviceType: (editForm.value.deviceType.eap ? 1 : 0) | (editForm.value.deviceType.gateway ? 2 : 0),
    band: (editForm.value.band.band24G ? 1 : 0) |
      (editForm.value.band.band5G ? 2 : 0) |
      (editForm.value.band.band6G ? 4 : 0),
    guestNetEnable: editForm.value.guestNetEnable,
    security: editForm.value.security,
    broadcast: editForm.value.broadcast,
    vlanEnable: editForm.value.vlanEnable,
    vlanId: editForm.value.vlanEnable ? editForm.value.vlanId : undefined,
    // 固定值字段
    mloEnable: false,
    pmfMode: 1,
    enable11r: false,
    hidePwd: false,
    greEnable: false,
  };

  const { error } = await updateWlanSsid(
    selectedSiteId.value,
    selectedGroupId.value,
    currentSsid.value,
    params
  );

  hide();
  if (!error) {
    message.success(t('page.wlan.updateSuccess'));
    editVisible.value = false;
    getData(); // 刷新列表
  }
};

const handleDelete = (record: Api.Wlan.WlanSsid) => {
  Modal.confirm({
    title: t('page.wlan.confirmDelete'),
    content: t('page.wlan.deleteConfirmContent', { name: record.name }),
    okText: t('common.confirm'),
    cancelText: t('common.cancel'),
    onOk: async () => {
      const hide = message.loading(t('common.loading'), 0);

      const { error } = await deleteWlanSsid(
        selectedSiteId.value,
        selectedGroupId.value,
        record.ssidId
      );

      hide();
      if (!error) {
        message.success(t('page.wlan.deleteSuccess'));
        getData(); // 刷新列表
      }
    }
  });
};

// 组件挂载时获取站点列表
onMounted(() => {
  getSiteList();
});
</script>

<style scoped>
.card-wrapper {
  margin-top: 16px;
}

:deep(.ant-form-item) {
  margin-bottom: 12px;  /* 减小表单项之间的间距 */
}

:deep(.ant-modal-body) {
  padding: 16px 24px;  /* 调整弹窗内边距 */
}
</style>

