<template>
  <el-container class="notification-view panel-block">
    <el-header class="sa-header">
      <!-- 简化搜索组件 -->
      <div class="search-container">
        <sa-search-simple :searchFields="searchFields" :defaultValues="defaultSearchValues"
          v-model="currentSearchParams" @search="handleSearch" @reset="handleReset">
        </sa-search-simple>
      </div>
      <div class="sa-title sa-flex sa-row-between">
        <div class="label sa-flex">{{ t('modules.notification.title') }}</div>
        <div>
          <el-button class="sa-button-refresh" icon="RefreshRight" @click="getData()"></el-button>
          <el-button icon="Plus" type="primary" @click="addRow">{{ t('modules.notification.create') }}</el-button>
        </div>
      </div>
    </el-header>
    <el-main class="sa-p-0">
      <div class="sa-table-wrap panel-block panel-block--bottom" v-loading="loading">
        <el-table height="100%" class="sa-table" :data="table.data" @sort-change="fieldFilter" row-key="id" stripe>
          <template #empty>
            <sa-empty />
          </template>

          <el-table-column prop="id" label="ID" min-width="100" sortable="custom">
          </el-table-column>
          <el-table-column :label="t('modules.notification.messageTitle')" min-width="150">
            <template #default="scope">
              <span class="sa-table-line-1">
                {{ scope.row.title || '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.notification.messageContent')" min-width="200">
            <template #default="scope">
              <span class="sa-table-line-2">
                {{ scope.row.message || '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.notification.pagePath')" min-width="150">
            <template #default="scope">
              <span class="sa-table-line-1">
                {{ scope.row.pages || '-' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.notification.createTime')" min-width="160">
            <template #default="scope">
              {{ scope.row.createTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column :label="t('modules.notification.updateTime')" min-width="160">
            <template #default="scope">
              {{ scope.row.updateTime || '-' }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" :label="t('modules.notification.actions')" min-width="180">
            <template #default="scope">
              <el-button class="is-link" type="primary" @click="editRow(scope.row)">{{ t('modules.notification.edit')
              }}</el-button>
              <el-button class="is-link" type="success" @click="sendRow(scope.row)">{{ t('modules.notification.send')
              }}</el-button>
              <el-popconfirm width="fit-content" :confirm-button-text="t('modules.notification.confirm')"
                :cancel-button-text="t('modules.notification.cancel')" :title="t('modules.notification.confirmDelete')"
                @confirm="deleteApi(scope.row.id)">
                <template #reference>
                  <el-button class="is-link" type="danger">{{ t('modules.notification.delete') }}</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
    <sa-view-bar>
      <template #right>
        <sa-pagination :pageData="pageData" @updateFn="getData" />
      </template>
    </sa-view-bar>
  </el-container>
</template>
<script setup>
import { onMounted, reactive, ref, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { api } from '../content.service';
import { ElMessage } from 'element-plus';
import { useModal } from '@/sheep/hooks';
import { usePagination } from '@/sheep/hooks';
import notificationEdit from './edit.vue';
import notificationSend from './send.vue';

const { t } = useI18n();
const { pageData } = usePagination();

// 搜索字段配置 - 使用计算属性以支持语言切换
const searchFields = computed(() => ({
  title: {
    type: 'input',
    label: t('modules.notification.messageTitle'),
    placeholder: t('modules.notification.enterMessageTitle'),
    width: 200,
  },
}));
// 默认搜索值
const defaultSearchValues = reactive({
  title: '',
});

// 当前搜索条件 - 使用 ref 支持双向绑定
const currentSearchParams = ref({});

// 列表
const table = reactive({
  data: [],
  order: '',
  sort: '',
});
const loading = ref(true);
// 获取数据
async function getData(page, searchParams = null) {
  if (page) pageData.page = page;
  loading.value = true;

  // 构建请求参数 - 优先使用传入的参数，否则使用双向绑定的搜索条件
  const finalSearchParams = searchParams !== null ? searchParams : currentSearchParams.value;

  try {
    const { code, data } = await api.notification.list({
      page: pageData.page,
      size: pageData.size,
      queryStr: finalSearchParams.title || '',
    });
    if (code == 200) {
      table.data = data.list;
      pageData.page = data.pageNum;
      pageData.size = data.pageSize;
      pageData.total = data.total;
    }
  } catch (error) {
    console.error('获取数据失败:', error);
    ElMessage.error(t('modules.notification.getDataFailed'));
    table.data = [];
  }
  loading.value = false;
}
// table 字段排序
function fieldFilter({ prop, order }) {
  table.order = order == 'ascending' ? 'asc' : 'desc';
  table.sort = prop;
  getData();
}

function addRow() {
  useModal(
    notificationEdit,
    { title: t('modules.notification.createMessage'), type: 'add' },
    {
      confirm: () => {
        getData();
      },
    },
  );
}
function editRow(row) {
  useModal(
    notificationEdit,
    {
      title: t('modules.notification.editMessage'),
      type: 'edit',
      id: row.id,
    },
    {
      confirm: () => {
        getData();
      },
    },
  );
}

function sendRow(row) {
  useModal(
    notificationSend,
    {
      title: t('modules.notification.sendMessage'),
      id: row.id,
      templateData: row,
    },
    {
      confirm: () => {
        // 发送成功后可以刷新数据或显示提示
        console.log(t('modules.notification.messageSendComplete'));
      },
    },
  );
}
// 删除api
async function deleteApi(id) {
  try {
    const { code } = await api.notification.delete(id);
    if (code == 200) {
      getData();
    }
  } catch (error) {
    console.error('删除失败:', error);
    ElMessage.error(t('modules.notification.deleteFailed'));
  }
}


// 搜索处理
const handleSearch = () => {
  // 由于使用了 v-model，currentSearchParams 会自动更新
  // 直接调用 getData，会自动使用当前的搜索条件
  getData(1);
};

// 重置处理
const handleReset = () => {
  // 由于使用了 v-model，currentSearchParams 会自动清空
  // 直接调用 getData，会自动使用当前的搜索条件
  getData(1, {});
};

onMounted(() => {
  getData();
});
</script>
<style lang="scss" scoped>
.notification-view {
  .el-header {
    height: auto;
  }

  .el-main {
    .sa-table-wrap {
      height: 100%;
    }
  }
}
</style>
