<template>
  <div>
    <a-breadcrumb>
      <a-breadcrumb-item>WebChat</a-breadcrumb-item>
      <a-breadcrumb-item>控制台</a-breadcrumb-item>
      <a-breadcrumb-item>钱包管理</a-breadcrumb-item>
    </a-breadcrumb>

    <a-form :layout="formLayout" style="margin: 20px 0px 10px 0px; width: 100%">
      <a-row :gutter="20"> 
          <a-select v-model:value="transType" style="width: 120px; margin-left: 10px;">
            <a-select-option value="">全部类型</a-select-option>
            <a-select-option value="1">收入</a-select-option>
            <a-select-option value="-1">支出</a-select-option>
          </a-select>
        <a-select v-model:value="eventType" style="width: 120px; margin-left: 10px;">
            <a-select-option value="">全部事件</a-select-option>
            <a-select-option value="1">系统发放</a-select-option>
            <a-select-option value="2">发红包</a-select-option>
            <a-select-option value="3">收红包</a-select-option>
            <a-select-option value="4">参与抽奖</a-select-option>
          </a-select>
          <a-auto-complete 
            style="margin-left: 10px; width: 200px;"
            v-model:value="searchUserId"
            :options="suggestUserOptions"
            placeholder="请输入用户名称"
            @select="handleSuggestUserSelect"
            @change="handleSuggestUserChange"
          />
        <a-col :span="5">
          <a-button @click="resetSearch">重置</a-button>
          <a-button type="primary" @click="handleSearch" style="margin-left: 20px; background-color: black;">搜索</a-button>
        </a-col>
        <a-col :span="3">
          <a-button type="primary" @click="showGiveModal" style="margin-left: 50px; background-color: black;">系统发放</a-button>
        </a-col>
      </a-row>
    </a-form>

    <a-table :dataSource="dataSource" :columns="columns" :pagination="false" />
    <a-pagination
      :current="currentPage"
      :pageSize="pageSize"
      :total="total"
      :showTotal="showTotal"
      @change="handlePageChange"
      style="float: right; margin-top: 20px"
    />

    <!-- 机器人弹窗组件 -->
  <a-modal
    v-model:visible="giveModalVisible"
    title="系统发放"
    @ok="handleGiveCreate"
    @cancel="handleGiveCancel"
    okText="发放"
    cancelText="取消"
  >
    <a-form :form="giveForm">
      <a-form-item label="授予用户">
        <a-input v-model:value="giveMoneyCount" placeholder="如：授予用户"/>
      </a-form-item>
      <a-form-item label="授予金额">
        <a-input v-model:value="giveMoneyCount" placeholder="如：1000"/>
      </a-form-item>
    </a-form>
  </a-modal>
  </div>
</template>

<script>
import axios from 'axios';
import { defineComponent, ref, onMounted, watch, nextTick } from 'vue';
import { useRoute } from 'vue-router';
import { Avatar, Modal, Form, FormItem, Input, Upload, message } from 'ant-design-vue';

export default defineComponent({
  setup() {
    const route = useRoute();
    const oauthCode = ref(route.query.oauthCode || new URLSearchParams(window.location.search).get('oauthCode'));
    const dataSource = ref([]);
    const searchUserId = ref('');
    const suggestUserOptions = ref([]);
    const selectedUserId = ref('');
    const userId = ref(''); 
    const userName = ref(''); 
    const mobile = ref(''); 
    const transType = ref('');
    const eventType = ref('');
    const giveForm = ref(null);
    const giveModalVisible = ref(false);
    const formLayout = 'horizontal'; 
    const currentPage = ref(1); // 当前页码
    const pageSize = ref(10); // 每页显示的记录数
    const total = ref(0); // 总记录数
    const pageTotal = ref(0); // 总页数
    const columns = [
      {
        title: '账号ID',
        dataIndex: 'userId', 
        key: 'userId',
      },
      {
        title: '用户名',
        customRender: ({ text, record }) => {
          // 使用 record.user.userName 来访问嵌套属性
          return record.user?.userName || '';
        }
      },
      {
        title: '交易事件',
        dataIndex: 'eventName',
        key: 'eventName',
      },
      {
        title: '交易类型',
        dataIndex: 'typeName',
        key: 'typeName',
      },
      {
        title: '金额',
        dataIndex: 'money',
        key: 'money',
      },
      {
        title: '交易时间',
        dataIndex: 'timeStr',
        key: 'timeStr',
      }
    ];
    const fetchData = async (page = 1, pageSize = 10, userId = '', userName = '', mobile = '') => {
      try {
        console.log("Fetching data with params:", userId, userName, mobile); 
        const response = await axios.get(`/admin-service/wallet/page`, {
          params: {
            pageNo: page,
            pageSize: pageSize,
            transType: transType.value, 
            eventType: eventType.value 
          },
          headers: {
            'oauth-code': oauthCode.value,
            'origin-url': window.location.href
          }
        });
        if (response.data.code === 40001) {
          // 未登录
          window.location.href = response.data.redirect_url;
        }
        dataSource.value = response.data.data;
        // 更新分页信息
        total.value = response.data.total;
        pageTotal.value = response.data.pageTotal;
        currentPage.value = response.data.pageNo;
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    const handleSearch = async () => {
      await nextTick();
      await fetchData(1, pageSize.value, userId.value, userName.value, mobile.value);
    };

    const resetSearch = () => {
      eventType.value = '';
      transType.value = '';
      handleSearch();
    };

    const handlePageChange = (page) => {
      fetchData(page, pageSize.value, userId.value, userName.value, mobile.value);
    };

    const showTotal = (total) => {
      return `共 ${total} 条`;
    };

    const showGiveModal = () => {
      giveModalVisible.value = true; // 显示机器人弹窗
    };

    const handleGiveCancel = () => {
      giveModalVisible.value = false; // 关闭机器人弹窗
    };

    const handleGiveCreate = async () => {
        try {
            const response = await axios.post('/admin-service/account/createRobot', {
                
            });
            if (response.data.code === 200) {
              giveModalVisible.value = false; // 关闭机器人弹窗
                message.success('发放成功');  // 正确调用 message 组件
                // 刷新列表
                fetchData(); 
            } else {
                message.error(response.data.message || '机器人创建失败，请检查输入信息');
            }
        } catch (error) {
            message.error('机器人创建失败，请稍后重试');
        }
    };

    const handleSuggestUser = async (searchText) => {
      try {
        // 使用 axios 进行请求
        const response = await axios.get('/admin-service/account/suggest', {
          params: { keyword: searchText }
        });
        // 假设后端返回的数据结构为 [{ id: 'user1', name: 'User One' }, { id: 'user2', name: 'User Two' }]
        suggestUserOptions.value = response.data.map(user => ({ value: user.name, label: user.name }));
      } catch (error) {
        console.error('搜索用户时出错：', error);
      }
    };

    const handleSuggestUserChange = (val) => {
      // 使用绑定的 searchUserId 作为搜索关键词
      handleSuggestUser(searchUserId.value);
    };

    const handleSuggestUserSelect = (value) => {
      // 查找选中用户的 ID
      const selectedOption = suggestUserOptions.value.find(option => option.value === value);
      if (selectedOption) {
        selectedUserId.value = selectedOption.id;
        // 将选中用户的 ID 存储到 userId 中，以便后续作为搜索条件使用
        userId.value = selectedUserId.value;
        console.log('选中用户的 ID:', selectedUserId.value);
      }
    };

    onMounted(() => {
      fetchData();
    });

    watch([userId, userName, mobile], ([newUserId, newUserName, newMobile]) => {
      console.log("Input values changed:", newUserId, newUserName, newMobile);
    }, { immediate: true });

    return {
      transType,
      eventType,
      dataSource,
      columns,
      giveForm,
      userId,
      userName,
      mobile,
      formLayout,
      currentPage,
      pageSize,
      total,
      pageTotal,
      giveModalVisible,
      searchUserId,
      suggestUserOptions,
      selectedUserId,
      fetchData,
      handleSearch,
      resetSearch, 
      showGiveModal,
      handleGiveCancel,
      handleGiveCreate,
      handlePageChange,
      showTotal,
      handleSuggestUser,
      handleSuggestUserChange,
      handleSuggestUserSelect
    };
  },
});
</script>

<style scoped>

</style>