<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-item>机器人账号</a-breadcrumb-item>
      </a-breadcrumb>
  
      <a-form :layout="formLayout" style="margin: 20px 0px 10px 0px; width: 100%">
        <a-row :gutter="20"> 
          <a-col :span="3">
            <a-input v-model:value="userId" placeholder="用户ID"/>
          </a-col>
          <a-col :span="3">
            <a-input v-model:value="mobile" placeholder="账号" />
          </a-col>
          <a-col :span="3">
            <a-input v-model:value="userName" placeholder="用户名"/>
          </a-col>
          <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="showRobotModal" 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="robotModalVisible"
      title="创建公众号"
      @ok="handleRobotCreate"
      @cancel="handleRobotCancel"
      okText="创建"
      cancelText="关闭"
    >
      <a-form :form="robotForm">
        <a-form-item label="上传头像">
          <a-upload
            name="avatar"
            :action="uploadUrl"
            list-type="picture-card"
            :show-upload-list="false"
            :before-upload="beforeUpload"
          >
            <div v-if="!robotAvatar">
              <a-icon type="plus" />
              <div style="margin-top: 8px">上传头像</div>
            </div>
            <div v-else>
              <img :src="robotAvatar" alt="avatar" style="width: 100%; display: block" />
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="创建账号">
          <a-input v-model:value="robotAccount" placeholder="如：gzh_java"/>
        </a-form-item>
        <a-form-item label="账号名称">
          <a-input v-model:value="robotAccountName" placeholder="如：Java技术分享"/>
        </a-form-item>
        <a-form-item label="账号描述">
          <a-textarea v-model:value="robotDescription"  placeholder="如：分享Java技术公众号"/>
        </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 userId = ref(''); 
    const userName = ref(''); 
    const mobile = ref(''); 
    const columns = [
      {
        title: '账号ID',
        dataIndex: 'userId', 
        key: 'userId',
      },
      {
        title: '账号',
        dataIndex: 'mobile',
        key: 'mobile',
      },
      {
        title: '用户名',
        dataIndex: 'userName',
        key: 'userName',
      },
      {
        title: '签名',
        dataIndex: 'signature',
        key: 'signature',
      }
    ];
    const formLayout = 'horizontal'; 
    const currentPage = ref(1); // 当前页码
    const pageSize = ref(10); // 每页显示的记录数
    const total = ref(0); // 总记录数
    const pageTotal = ref(0); // 总页数
    const robotModalVisible = ref(false); // 机器人弹窗的可见性
    const robotAvatar = ref(null); // 机器人头像
    const robotAccount = ref(''); // 机器人账号
    const robotAccountName = ref(''); // 机器人名称
    const robotDescription = ref(''); // 机器人描述
    const robotForm = ref(null); // 机器人弹窗中的表单引用
    const uploadUrl = '/admin-service/file/upload'; // 上传头像的 URL
    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/account/page`, {
          params: {
            roleCode: 6,
            pageNo: page,
            pageSize: pageSize,
            userId: userId, 
            userName: userName, 
            mobile: mobile 
          },
          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 = () => {
      userId.value = '';
      userName.value = '';
      mobile.value = '';
      handleSearch();
    };

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

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

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

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

    const handleRobotCreate = async () => {
        if (!robotAvatar.value) {
            message.error('请上传头像');
            return;
        }
        if (!robotAccount.value) {
            message.error('请设置公众号账号');
            return;
        }
        if (!robotAccountName.value) {
            message.error('公众号名称为空');
            return;
        }
        if (!robotDescription.value) {
            message.error('公众号描述为空');
            return;
        }
        try {
            const response = await axios.post('/admin-service/account/createPublicAccount', {
                account: robotAccount.value,
                accountName: robotAccountName.value,
                signature: robotDescription.value,
                accountPhoto: robotAvatar.value
            });
            if (response.data.code === 200) {
                robotModalVisible.value = false;
                message.success('公众号创建成功');
                // 刷新列表
                fetchData(); 
            } else {
                message.error(response.data.message || '公众号创建失败，请检查输入信息');
            }
        } catch (error) {
            message.error('公众号创建失败，请稍后重试');
        }
    };

    const handleAvatarUpload = async (file) => {
        const formData = new FormData();
        formData.append('file', file);
        try {
          const response = await axios.post(uploadUrl, formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              'oauth-code': oauthCode.value,
              'origin-url': window.location.href,
              'upload-path': 'images/avatar'
            }
          });
          if (response.data.code === 40001) {
            window.location.href = response.data.redirect_url;
          }
          // 假设服务器返回头像的 URL
          robotAvatar.value = response.data.data.url; 
        } catch (error) {
          console.error('Error uploading avatar:', error);
        }
      };

      const beforeUpload = async (file) => {
        // 文件验证逻辑，例如限制文件大小和类型
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJpgOrPng) {
          message.error('请上传 JPG 或 PNG 格式的图片');
          return false;
        }
        if (!isLt2M) {
          message.error('图片大小不能超过 2MB');
          return false;
        }
        await handleAvatarUpload(file);
        return false;
      };


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

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


    return {
      dataSource,
      columns,
      fetchData,
      handleSearch,
      resetSearch, 
      userId,
      userName,
      mobile,
      formLayout,
      currentPage,
      pageSize,
      total,
      pageTotal,
      handlePageChange,
      showTotal,
      robotModalVisible,
      robotAvatar,
      robotAccount,
      robotAccountName,
      robotDescription,
      robotForm,
      showRobotModal,
      handleRobotCancel,
      handleRobotCreate,
      beforeUpload,
      uploadUrl
    };
  },
});
  </script>
  
  <style scoped>
  
  </style>