<template>
  <a-row>
    <a-col :flex="1">
      <a-form
        :model="searchForm"
        :label-col-props="{ span: 6 }"
        :wrapper-col-props="{ span: 18 }"
        label-align="left"
      >
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item field="name" label="分组名称">
              <a-input
                v-model="searchForm.name"
                placeholder="请输入分组名称"
                allow-clear
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item field="userId" label="创建人">
              <a-select v-model="searchForm.userId" allow-clear>
                <a-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.userName"
                  :value="item.id"
                />
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-col>
    <a-divider style="height: 42px" direction="vertical" />
    <a-col flex="172px" style="text-align: right">
      <a-space direction="horizontal" :size="18">
        <a-button type="primary" @click="handleSearch">
          <template #icon>
            <icon-search />
          </template>
          查询
        </a-button>
        <a-button @click="resetSearch">
          <template #icon>
            <icon-refresh />
          </template>
          重置
        </a-button>
      </a-space>
    </a-col>
  </a-row>
  <a-divider style="margin-top: 0" />
  <a-space direction="vertical" fill>
    <a-button v-if="checkTokenFromLogin()" type="primary" @click="handleAdd">
      新增
    </a-button>
    <a-table
      :data="tableData"
      :loading="loading"
      :pagination="pagination"
      @page-change="onPageChange"
      @page-size-change="onPageSizeChange"
    >
      <template #columns>
        <a-table-column title="ID" data-index="id" :width="80" />
        <a-table-column title="分组名称" data-index="name" />
        <a-table-column title="描述" data-index="notes" />
        <a-table-column title="创建时间" data-index="createdAt" :width="180" />
        <a-table-column title="更新时间" data-index="updatedAt" :width="180" />
        <a-table-column title="操作" :width="200" fixed="right">
          <template #cell="{ record }">
            <a-space>
              <a-button
                type="secondary"
                status="warning"
                size="mini"
                @click="handleStatistic(record)"
              >
                <template #icon>
                  <icon-edit />
                </template>
                统计
              </a-button>
              <a-button
                type="secondary"
                status="warning"
                size="mini"
                @click="handleEdit(record)"
              >
                <template #icon>
                  <icon-edit />
                </template>
                编辑
              </a-button>
              <a-button
                type="secondary"
                status="danger"
                size="mini"
                @click="handleDelete(record)"
              >
                <template #icon>
                  <icon-delete />
                </template>
                删除
              </a-button>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>
  </a-space>
  <a-modal
    v-model:visible="dialogVisible"
    :title="dialogTitle"
    @cancel="dialogVisible = false"
    @before-ok="handleSubmit"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-align="right"
      :label-col-props="{ span: 6 }"
      :wrapper-col-props="{ span: 18 }"
    >
      <a-form-item field="name" label="分组名称">
        <a-input v-model="form.name" placeholder="请输入分组名称" />
      </a-form-item>
      <a-form-item field="description" label="描述">
        <a-textarea
          v-model="form.description"
          placeholder="请输入描述"
          :auto-size="{ minRows: 3, maxRows: 5 }"
        />
      </a-form-item>
    </a-form>
  </a-modal>
  <statistics-drawer
    v-model:visible="statisticsVisible"
    :group-id="currentGroup?.id"
    :group-name="currentGroup?.name"
  />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { Message, Modal } from '@arco-design/web-vue';
import { apiClient } from '@/api/index.ts';
import {
  ApiCardInfoWalmartGroupListGetPageSizeEnum,
  KamiApiSysUserV1UserGetAllSimpleUser,
  KamiInternalModelEntityV1CardRedeemAccountGroup
} from '@/api/generated/index.ts';
import { checkTokenFromLogin } from '@/utils/auth';
import qs from 'query-string';
import StatisticsDrawer from './statistics/index.vue';

// 搜索表单
const searchForm = reactive({
  name: '',
  userId: null
});

// 表格数据
const tableData = ref<KamiInternalModelEntityV1CardRedeemAccountGroup[]>([]);
const loading = ref(false);

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50, 100]
});

// 对话框
const dialogVisible = ref(false);
const dialogTitle = ref('');
const formRef = ref();

// 表单
const form = reactive({
  id: null,
  name: '',
  description: ''
});

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入分组名称' },
    { minLength: 2, maxLength: 50, message: '长度在 2 到 50 个字符' }
  ]
};

// 查询数据
const handleSearch = () => {
  pagination.current = 1;
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  searchForm.name = '';
  pagination.current = 1;
  fetchData();
};

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const res = await apiClient.apiCardInfoWalmartGroupListGet(
      {
        current: pagination.current,
        pageSize:
          pagination.pageSize as ApiCardInfoWalmartGroupListGetPageSizeEnum,
        userId: searchForm.userId,
        name: searchForm.name
      },
      {
        paramsSerializer: obj => {
          return qs.stringify(obj, { arrayFormat: 'bracket' });
        }
      }
    );
    tableData.value = res.data.list;
    pagination.total = res.data.total;
  } catch (error) {
    console.error(error);
    Message.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增分组';
  form.id = '';
  form.name = '';
  form.description = '';
  dialogVisible.value = true;
};

// 编辑
const handleEdit = row => {
  dialogTitle.value = '编辑分组';
  form.id = row.id;
  form.name = row.name;
  form.description = row.description;
  dialogVisible.value = true;
};

// 统计
const handleStatistic = row => {
  currentGroup.value = row;
  statisticsVisible.value = true;
};

// 删除
const handleDelete = (row: KamiInternalModelEntityV1CardRedeemAccountGroup) => {
  Modal.warning({
    title: '提示',
    content: '确认删除该分组吗？',
    okText: '确定',
    cancelText: '取消',
    onOk: async () => {
      try {
        await apiClient.apiCardInfoWalmartGroupDeleteDelete({
          id: row.id
        });
        Message.success('删除成功');
        fetchData();
      } catch (error) {
        Message.error('删除失败');
      }
    }
  });
};

// 提交表单
const handleSubmit = async () => {
  const { validate } = formRef.value;
  try {
    await validate();
    if (form.id) {
      apiClient.apiCardInfoWalmartGroupUpdatePut({
        kamiApiCardInfoWalmartV1GroupUpdateReq: {
          id: form.id,
          name: form.name
        }
      });
    } else {
      await apiClient.apiCardInfoWalmartGroupAddPost({
        kamiApiCardInfoWalmartV1GroupAddReq: {
          name: form.name
        }
      });
    }
    Message.success(form.id ? '更新成功' : '创建成功');
    dialogVisible.value = false;
    fetchData();
    return true;
  } catch (error) {
    console.error(error);
    return false;
  }
};

// 分页处理
const onPageChange = current => {
  pagination.current = current;
  fetchData();
};

const onPageSizeChange = pageSize => {
  pagination.pageSize = pageSize;
  fetchData();
};

const userList = ref<KamiApiSysUserV1UserGetAllSimpleUser[]>([]);

// 获取所有分组
const getAllUserList = () => {
  apiClient.apiUserGetSimpleAllGet().then(res => {
    userList.value = res.data.list;
  });
};

// 在 script setup 中添加
const statisticsVisible = ref(false);
const currentGroup = ref(null);

onMounted(() => {
  fetchData();
  getAllUserList();
});
</script>

<style scoped>
.search-container {
  margin-bottom: 20px;
}
</style>
