<template>
  <SimpleScrollbar>
    <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
      <DeviceSearch
        v-model:model="searchParams"
        :loading="loading"
        @reset="handleReset"
        @search="handleSearch"
      />
      <ACard
        :title="t('page.apdevice.aptitle')"
        :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.apdevice.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>


            <TableHeaderOperation
            v-model:columns="columnChecks"
            :loading="loading"
            :show-delete="false"
            @add="handleAdd"
            @refresh="getData"
          />
          </div>
        </template>

        <ATable
          ref="wrapperEl"
          :columns="columns"
          :data-source="data"
          :loading="loading"
          row-key="id"
          size="small"
          :pagination="{
            ...mobilePagination,
            total: mobilePagination.total,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            showTotal: (total: number) => `${t('page.apdevice.total')} ${total} `
          }"
          :scroll="scrollConfig"
          class="h-full"
          @change="(pagination) => {
            searchParams.pageNum = pagination.current;
            searchParams.pageSize = pagination.pageSize;
            getData();
          }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'status'">
              <ATag :color="record.status === 1 ? 'success' : 'error'">
                {{ record.status === 1 ? t('page.apdevice.online') : t('page.apdevice.outline') }}
              </ATag>
            </template>

            <template v-if="column.key === 'operate'">
              <div class="flex items-center justify-center gap-2">
                <a-tooltip :title="t('page.apdevice.editConfig')">
                  <a-button type="link" size="small" @click="handleEditConfig(record)">
                    <template #icon>
                      <setting-outlined />
                    </template>
                  </a-button>
                </a-tooltip>

                <a-tooltip :title="t('page.apdevice.forget')">
                  <a-button type="link" size="small" @click="handleForgetDevice(record)">
                    <template #icon>
                      <delete-outlined />
                    </template>
                  </a-button>
                </a-tooltip>

                <template v-if="record.status === 1">
                  <a-tooltip :title="t('page.apdevice.restart')">
                    <a-button type="link" size="small" @click="handleRestart(record)">
                      <template #icon>
                        <reload-outlined />
                      </template>
                    </a-button>
                  </a-tooltip>
                </template>

                <template v-if="record.status === 0">
                  <a-tooltip :title="t('page.apdevice.adopt')">
                    <a-button type="link" size="small" @click="handleAdopt(record)">
                      <template #icon>
                        <plus-outlined />
                      </template>
                    </a-button>
                  </a-tooltip>
                </template>

              </div>
            </template>
          </template>
        </ATable>
      </ACard>
      <!-- 添加设备对话框 -->
      <a-modal
        v-model:visible="addDeviceVisible"
        :title="t('page.apdevice.addDevice')"
        @ok="handleAddConfirm"
      >
        <a-form
          :model="addDeviceForm"
          :rules="addDeviceRules"
          layout="vertical"
          ref="formRef"
        >
          <a-form-item name="sn" :label="t('page.apdevice.sn')">
            <a-input v-model:value="addDeviceForm.sn" autocomplete="off"/>
          </a-form-item>
          <a-form-item name="name" :label="t('page.apdevice.name')">
            <a-input v-model:value="addDeviceForm.name" autocomplete="off"/>
          </a-form-item>
          <a-form-item name="username" :label="t('page.apdevice.username')">
            <a-input v-model:value="addDeviceForm.username" autocomplete="off"/>
          </a-form-item>
          <a-form-item name="password" :label="t('page.apdevice.password')">
            <a-input-password v-model:value="addDeviceForm.password" autocomplete="new-password"/>
          </a-form-item>
        </a-form>
      </a-modal>
      <!-- 修改配置对话框 -->
      <a-modal
        v-model:visible="configVisible"
        :title="t('page.apdevice.editConfig')"
        @ok="handleConfigConfirm"
      >
        <a-form
          :model="configForm"
          :rules="configRules"
          layout="vertical"
          ref="configFormRef"
        >
          <a-form-item name="name" :label="t('page.apdevice.name')">
            <a-input v-model:value="configForm.name" />
          </a-form-item>

          <a-form-item name="ledSetting" :label="t('page.apdevice.led')">
            <a-radio-group v-model:value="configForm.ledSetting">
              <a-radio :value="2">{{ t('page.apdevice.useSiteSettings') }}</a-radio>
              <a-radio :value="1">{{ t('page.apdevice.on') }}</a-radio>
              <a-radio :value="0">{{ t('page.apdevice.off') }}</a-radio>
            </a-radio-group>
          </a-form-item>

<!--          <a-form-item name="tagIds" :label="t('page.apdevice.deviceTags')">-->
<!--            <a-select-->
<!--              v-model:value="configForm.tagIds"-->
<!--              mode="multiple"-->
<!--              :placeholder="t('page.apdevice.selectTags')"-->
<!--            >-->
<!--              <a-select-option v-for="tag in tagsList" :key="tag.id" :value="tag.id">-->
<!--                {{ tag.name }}-->
<!--              </a-select-option>-->
<!--            </a-select>-->
<!--          </a-form-item>-->

          <a-form-item name="longitude" :label="t('page.apdevice.longitude')">
            <a-input-number
              v-model:value="configForm.longitude"
              :precision="6"
              style="width: 100%"
            />
          </a-form-item>

          <a-form-item name="latitude" :label="t('page.apdevice.latitude')">
            <a-input-number
              v-model:value="configForm.latitude"
              :precision="6"
              style="width: 100%"
            />
          </a-form-item>

          <a-form-item name="address" :label="t('page.apdevice.address')">
            <a-textarea
              v-model:value="configForm.address"
              :auto-size="{ minRows: 2, maxRows: 6 }"
            />
          </a-form-item>
        </a-form>
      </a-modal>
      <!-- 纳管设备对话框 -->
      <a-modal
        v-model:visible="adoptVisible"
        :title="t('page.apdevice.adopt')"
        @ok="handleAdoptConfirm"
      >
        <a-form
          :model="adoptForm"
          :rules="adoptRules"
          layout="vertical"
          ref="adoptFormRef"
        >
          <a-form-item name="username" :label="t('page.apdevice.username')">
            <a-input v-model:value="adoptForm.username" autocomplete="off"/>
          </a-form-item>
          <a-form-item name="password" :label="t('page.apdevice.password')">
            <a-input-password v-model:value="adoptForm.password" autocomplete="new-password"/>
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </SimpleScrollbar>
</template>

<script setup lang="ts">
import { useTable } from '@/hooks/common/table';
import { SimpleScrollbar } from '~/packages/materials/src';
import { computed, shallowRef } from 'vue';
import { useElementSize } from '@vueuse/core';
import { fetchApDeviceList,forgetApDevice, addApDevice } from '@/service/api/auth';
import {Card as ACard, Table as ATable, Tag as ATag, Modal, message } from 'ant-design-vue';
import DeviceSearch from './modules/device-search.vue';
import { useI18n } from 'vue-i18n';
import { SettingOutlined, DeleteOutlined, ReloadOutlined,PlusOutlined } from '@ant-design/icons-vue';
import {Rule} from "ant-design-vue/es/form";
const { t } = useI18n();

const wrapperEl = shallowRef<HTMLElement | null>(null);
const { height: wrapperElHeight } = useElementSize(wrapperEl);

const scrollConfig = computed(() => ({
  y: wrapperElHeight.value - 72,
  x: 800
}));

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

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

    // 适配新的响应格式
    siteList.value = response.data.rows || [];

    // 如果有站点数据，默认选择第一个
    if (siteList.value.length > 0) {
      selectedSiteId.value = siteList.value[0].siteId; // 使用 siteId 而不是 id
      await getData();
    }
  } catch (error) {
    console.error('Get site list error:', error);
    message.error(t('page.apdevice.getSiteError'));
  } finally {
    siteLoading.value = false;
  }
};

// 处理站点变更
const handleSiteChange = async (value: string) => {
  selectedSiteId.value = value;
  await getData();
};

const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  mobilePagination,
  searchParams,
} = useTable({
  apiFn: async (params: { searchKey?: string; pageNum: number; pageSize: number }) => {
    if (!selectedSiteId.value) {
      return {
        data: {
          rows: [],
          total: 0
        }
      };
    }

    try {
      const response = await fetchApDeviceList(selectedSiteId.value, params);
      return {
        data: {
          rows: response.data.rows,
          total: response.data.total
        }
      };
    } catch (error) {
      console.error('API Error:', error);
      return {
        data: {
          rows: [],
          total: 0
        },
        error
      };
    }
  },
  immediate: false,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    name: '',
    mac: ''
  } as Api.Device.ApDeviceParams,
  rowKey: 'id',
  pagination: true,
  columns: (): AntDesign.TableColumn<Api.Device.ApDevice>[] => [
    {
      key: 'name',
      dataIndex: 'name',
      title: t('page.apdevice.apname'),
      align: 'center',
      width: 150
    },
    {
      key: 'ip',
      dataIndex: 'ip',
      title: t('page.apdevice.ip'),
      align: 'center',
      width: 150
    },
    {
      key: 'mac',
      dataIndex: 'mac',
      title: t('page.apdevice.mac'),
      align: 'center',
      width: 180
    },
    {
      key: 'model',
      dataIndex: 'model',
      title: t('page.apdevice.model'),
      align: 'center',
      width: 150
    },
    {
      key: 'uptime',
      dataIndex: 'uptime',
      title: t('page.apdevice.uptime'),
      align: 'center',
      width: 180
    },
    {
      key: 'status',
      dataIndex: 'status',
      title: t('page.apdevice.status'),
      align: 'center',
      width: 100
    },
    {
      key: 'operate',
      title: t('common.operate'),
      align: 'center',
      width: 100,
      fixed: 'right'
    }
  ]
});

// 监听搜索参数变化并打印日志
watch(
  () => searchParams,
  (newParams) => {
    console.log('Search params changed:', JSON.stringify(newParams, null, 2));
  },
  { deep: true, immediate: true }
);

// 添加搜索处理函数
const handleSearch = () => {
  console.log('Searching with params:', JSON.stringify(searchParams, null, 2));
  getData();
};

// 修改重置处理函数
const handleReset = () => {
  // 保存当前的 pageSize
  const currentPageSize = searchParams.pageSize;

  // 重置搜索参数
  searchParams.searchKey = '';
  searchParams.pageNum = 1;
  searchParams.pageSize = currentPageSize;

  // 重新获取数据
  getData();
};


// 添加相关的处理函数
// 处理打开配置对话框
const handleEditConfig = async (record: Api.Device.ApDevice) => {
  try {
    if (!selectedSiteId.value) {
      throw new Error('No site selected');
    }

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

    // 先获取设备当前的配置
    const response = await getApDeviceConfig(selectedSiteId.value, record.mac);

    hide();

    // 保存当前编辑的设备信息
    currentDevice.value = record;

    // 使用获取到的配置更新表单，处理 null 和嵌套对象
    configForm.value = {
      name: response.data?.name || record.name,
      ledSetting: response.data?.ledSetting ?? 2, // 如果没有设置，默认使用站点设置
      // tagIds: response.data?.tagIds || [], // 暂时注释掉
      longitude: response.data?.location?.longitude,
      latitude: response.data?.location?.latitude,
      address: response.data?.location?.address || ''
    };

    // 显示配置对话框
    configVisible.value = true;
  } catch (error) {
    console.error('Get device config error:', error);
    message.error(t('page.apdevice.getConfigError'));
  }
};

const handleForgetDevice = (record: Api.Device.ApDevice) => {
  Modal.confirm({
    title: t('common.confirm'),
    content: t('page.apdevice.forgetConfirm'),
    onOk: async () => {
      try {
        const hide = message.loading(t('common.loading'), 0);
        console.log('Forgetting device:', record);

        if (!selectedSiteId.value || !record.mac) {
          throw new Error('Missing required parameters: siteId or mac');
        }

        // 使用当前选中的 siteId
        const response = await forgetApDevice(selectedSiteId.value, record.mac);
        console.log('Forget device response:', response);

        hide();
        message.success(t('page.apdevice.forgetSuccess'));

        // 重新获取列表数据
        getData();
      } catch (error) {
        console.error('Forget device error:', error);
        message.error(t('page.apdevice.forgetError'));
        throw error;
      }
    }
  });
};

const handleRestart = (record: Api.Device.ApDevice) => {
  // 处理重启设备
  Modal.confirm({
    title: t('common.confirm'),
    content: t('page.apdevice.restartConfirm'),
    onOk: async () => {
      // 调用重启设备 API
      console.log('Restart device:', record);
    }
  });
};

// 纳管表单数据
const adoptForm = ref({
  username: '',
  password: ''
});

// 纳管对话框可见性
const adoptVisible = ref(false);

// 当前要纳管的设备
const adoptingDevice = ref<Api.Device.ApDevice | null>(null);

// 处理纳管按钮点击
const handleAdopt = (record: Api.Device.ApDevice) => {
  adoptingDevice.value = record;
  adoptForm.value = {
    username: '',
    password: ''
  };
  adoptVisible.value = true;
};

// 处理纳管确认
const handleAdoptConfirm = async () => {
  try {
    if (!adoptingDevice.value || !selectedSiteId.value) {
      throw new Error('Missing device or site information');
    }

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

    // 构造请求参数，只有在有值时才包含
    const params: { username?: string; password?: string } = {};
    if (adoptForm.value.username) {
      params.username = adoptForm.value.username;
    }
    if (adoptForm.value.password) {
      params.password = adoptForm.value.password;
    }

    await adoptApDevice(selectedSiteId.value, adoptingDevice.value.mac, params);

    hide();
    message.success(t('page.apdevice.adoptSuccess'));
    adoptVisible.value = false;

    // 重新获取列表数据
    getData();
  } catch (error) {
    console.error('Adopt device error:', error);
    message.error(t('page.apdevice.adoptError'));
  }
};


// 修改表单验证规则的定义
const addDeviceRules = {
  sn: [
    { required: true, message: t('page.apdevice.snRequired'), trigger: 'blur' },
    {
      pattern: /^[A-Z0-9]{13}$/,
      message: t('page.apdevice.snFormatError'),
      trigger: 'blur'
    }
  ] as Rule[],
  name: [
    {
      pattern: /^[^ \+\-\@\=]$|^[^ \+\-\@\=].{0,126}[^ ]$/,
      message: t('page.apdevice.nameFormatError'),
      trigger: 'blur'
    }
  ] as Rule[]
};

// 添加设备的表单数据
const addDeviceForm = ref({
  sn: '',
  name: '',
  username: '',
  password: ''
});

// 添加设备对话框的可见性
const addDeviceVisible = ref(false);

// 处理添加设备
const handleAdd = () => {
  addDeviceVisible.value = true;
};

// 处理添加设备的确认
const handleAddConfirm = async () => {
  try {
    // 先验证表单
    await formRef.value?.validate();

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

    // 构造请求参数，即使所有字段都为空也要发送一个空对象
    // 构造请求参数，确保 sn 字段存在
    const deviceParams: Api.Device.AddApDeviceItem = {
      sn: addDeviceForm.value.sn  // sn 是必填的
    };

    // 只添加其他有值的字段
    if (addDeviceForm.value.name) {
      deviceParams.name = addDeviceForm.value.name;
    }
    if (addDeviceForm.value.username) {
      deviceParams.username = addDeviceForm.value.username;
    }
    if (addDeviceForm.value.password) {
      deviceParams.password = addDeviceForm.value.password;
    }

    await addApDevice(selectedSiteId.value, deviceParams);

    hide();
    message.success(t('page.apdevice.addSuccess'));
    addDeviceVisible.value = false;

    // 清空表单
    addDeviceForm.value = {
      sn: '',
      name: '',
      username: '',
      password: ''
    };

    // 重新获取列表数据
    getData();
  } catch (error) {
    console.error('Add device error:', error);
    message.error(t('page.apdevice.addError'));
  }
};
// 添加表单引用
const formRef = ref();
// 配置表单的数据
const configForm = ref<Api.Device.ApDeviceConfigForm>({
  name: '',
  ledSetting: 2,
  // tagIds: [],
  longitude: undefined,
  latitude: undefined,
  address: ''
});

// 配置对话框的可见性
const configVisible = ref(false);

// 配置表单的验证规则
const configRules = {
  name: [
    {
      pattern: /^[^ \+\-\@\=]$|^[^ \+\-\@\=].{0,126}[^ ]$/,
      message: t('page.apdevice.nameFormatError'),
      trigger: 'blur'
    }
  ] as Rule[],
  longitude: [
    {
      type: 'number',
      min: -180,
      max: 180,
      message: t('page.apdevice.longitudeError'),
      trigger: 'change'
    }
  ] as Rule[],
  latitude: [
    {
      type: 'number',
      min: -90,
      max: 90,
      message: t('page.apdevice.latitudeError'),
      trigger: 'change'
    }
  ] as Rule[]
};

// 当前编辑的设备
const currentDevice = ref<Api.Device.ApDevice | null>(null);

// 处理配置确认
const handleConfigConfirm = async () => {
  try {
    await configFormRef.value?.validate();

    if (!currentDevice.value || !selectedSiteId.value) {
      throw new Error('Missing device or site information');
    }

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

    await updateApDeviceConfig(
      selectedSiteId.value,
      currentDevice.value.mac,
      configForm.value
    );

    hide();
    message.success(t('page.apdevice.configSuccess'));
    configVisible.value = false;

    // 重新获取列表数据
    getData();
  } catch (error) {
    console.error('Update config error:', error);
    message.error(t('page.apdevice.configError'));
  }
};

// 配置表单引用
const configFormRef = ref();
// 在组件挂载时获取站点列表
onMounted(() => {
  getSiteList();
});
</script>

<style scoped>
.h-full {
  height: 100%;
}

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