<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-col :span="3">
          <a-input v-model:value="keywords" placeholder="关键词"/>
        </a-col>
        <a-col :span="3">
            <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="创建应用，允许接入WebChat-Pay"
    @ok="handleRobotCreate"
    @cancel="handleRobotCancel"
    okText="创建"
    cancelText="取消"
  >
    <a-form :form="robotForm">
      <a-form-item label="上传Logo">
        <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">上传Logo</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="appName" placeholder="如：WebChat红包"/>
      </a-form-item>
      <a-form-item label="应用描述">
        <a-textarea v-model:value="description"  placeholder="WebChat-UGC服务申请加入WebChat支付"/>
      </a-form-item>
    </a-form>
  </a-modal>

  <!-- 凭证弹窗 -->
  <a-modal
    v-model:visible="credentialVisible"
    title="应用创建成功"
    :footer="null"
    :closable="false"
    width="450px"
    centered
  >
    <a-result
      status="success"
      title="应用创建成功！"
      sub-title="请立即复制身份凭证，关闭后将无法再次查看"
    >
      <div class="credential-box">
        <!-- 动态渲染凭证信息 -->
        <div v-for="item in credentialsDisplay" :key="item.key" class="credential-item">
          <div class="credential-label">{{ item.label }}</div>
          <a-input-group compact>
            <a-input 
              :value="item.value" 
              readonly 
              class="credential-value"
              :data-clipboard-text="item.value"
            />
            <a-tooltip title="复制">
              <a-button @click="copyText(item.value)" type="link">
                <template #icon><CopyOutlined /></template>
              </a-button>
            </a-tooltip>
          </a-input-group>
        </div>

        <!-- 一键复制按钮 -->
        <div class="copy-all">
          <a-button 
            type="primary" 
            size="large"
            @click="copyAllCredentials"
            icon="copy"
            block
          >
            一键复制全部凭证
          </a-button>
        </div>
      </div>
    </a-result>
  </a-modal>
  </div>
</template>

<script>
import { h } from 'vue';
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, Button } 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 keywords = ref(''); 
  const columns = [
    {
      title: '应用ID',
      dataIndex: 'id', 
      key: 'id',
    },
    {
      title: '应用图标',
      dataIndex: 'logo',
      customRender: ({ text: logo }) => { 
        return h('img', {
          src: logo,
          alt: '应用图标', 
          style: { 
            width: '40px',
            height: '40px',
            objectFit: 'cover' // 保持图片比例
          },
          onError: (e) => { // 处理图片加载失败
            e.target.style.display = 'none' // 隐藏损坏图片
            // 可选：显示默认占位图
            // e.target.src = 'default-logo.png'
          }
        });
      }
    },
    {
      title: '应用名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '身份凭证',
      dataIndex: 'accessKey',
      key: 'accessKey',
    },
    {
        title: '应用状态',
        dataIndex: 'status',
        customRender: ({ text }) => {
          const statusMap = {
            0: { text: '待发布', color: '#000' },
            1: { text: '正常', color: '#017D6F' },
            3: { text: '已删除', color: '#666' }
          };
          const status = statusMap[text] || {};
          return h('span', { style: { color: status.color } }, status.text);
        }
    },
    {
    title: '操作',
    key: 'action',
    customRender: ({ record }) => {
      const actions = [];
      // 根据状态显示不同按钮
      if (record.status === 0) {
        actions.push(
          h(
            Button,
            {
              style: { marginRight: '8px' },
              onClick: () => handlePublish(record.id)
            },
            '发布'
          )
        );
      }
      if (record.status !== 3) {
        actions.push(
          h(
            Button,
            {
              danger: true,
              onClick: () => handleDelete(record.id)
            },
            '删除'
          )
        );
      }
      return h('div', actions);
    }
  }
  ];
  const credentialVisible = ref(false);
  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 appName = ref(''); // 机器人账号
  const description = ref(''); // 机器人描述
  const robotForm = ref(null); // 机器人弹窗中的表单引用
  const uploadUrl = '/admin-service/file/upload'; // 上传头像的 URL
  // 格式化显示结构
  const credentialsDisplay = ref([]);
  const apiCredentials = ref({});


  // 复制单个
  const copyText = (text) => {
    navigator.clipboard.writeText(text)
      .then(() => message.success('复制成功'))
      .catch(() => message.error('请手动选择内容复制'));
  };

  // 复制全部（带格式）
  const copyAllCredentials = () => {
    const content = [
      `appId: ${apiCredentials.value.appId}`,
      `access-key: ${apiCredentials.value.accessKey}`,
      `secret-key: ${apiCredentials.value.secretKey}`
    ].join('\n');

    navigator.clipboard.writeText(content)
      .then(() => message.success('已复制全部凭证'))
      .catch(() => message.error('复制失败，请手动操作'));
  };

  const fetchData = async (page = 1, pageSize = 10, keywords = '') => {
    try {
      const response = await axios.get(`/admin-service/payment/app/page`, {
        params: {
          pageNo: page,
          pageSize: pageSize,
          keywords: keywords
        },
        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, keywords.value);
  };

  const handlePageChange = (page) => {
    fetchData(page, pageSize.value, keywords.value);
  };

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

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

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

  const handleRobotCreate = async () => {
      if (!robotAvatar.value) {
          message.error('请上传logo');
          return;
      }
      if (!appName.value) {
          message.error('应用名称');
          return;
      }
      if (!description.value) {
          message.error('应用描述');
          return;
      }
      try {
          const response = await axios.post('/admin-service/payment/app/create', {
              name: appName.value,
              description: description.value,
              logo: robotAvatar.value
          });
          if (response.data.code === 200) {
              robotModalVisible.value = false; // 关闭机器人弹窗
              message.success('应用创建成功');  // 正确调用 message 组件
              // 刷新列表
              fetchData(); 
              apiCredentials.value.appId = response.data.data.id;
              apiCredentials.value.accessKey = response.data.data.accessKey;
              apiCredentials.value.secretKey = response.data.data.secretKey;
              credentialsDisplay.value = [{ 
                                            key: 'appId',
                                            label: '应用 ID',
                                            value: response.data.data.id
                                          },
                                          { 
                                            key: 'accessKey',
                                            label: 'Access Key',
                                            value: response.data.data.accessKey
                                          },
                                          { 
                                            key: 'secretKey',
                                            label: 'Secret Key',
                                            value: response.data.data.secretKey
                                          }]
              // 显示凭证弹窗
              credentialVisible.value = true;
          } 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;
    };

    // 在setup函数中添加操作处理方法
const handlePublish = async (appId) => {
  try {
    const response = await axios.post(`/admin-service/payment/app/publish/${appId}`);
    if (response.data.code === 200) {
      message.success('发布成功');
      fetchData(currentPage.value, pageSize.value, keywords.value);
    }
  } catch (error) {
    message.error('操作失败');
  }
};

const handleDelete = async (appId) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除该应用吗？',
    onOk: async () => {
      try {
        const response = await axios.post(`/admin-service/payment/app/delete/${appId}`);
        if (response.data.code === 200) {
          message.success('删除成功');
          fetchData(currentPage.value, pageSize.value, keywords.value);
        }
      } catch (error) {
        message.error('删除失败');
      }
    }
  });
};


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

  return {
    credentialsDisplay,
    credentialVisible,
    dataSource,
    columns,
    keywords,
    formLayout,
    currentPage,
    pageSize,
    total,
    pageTotal,
    uploadUrl,
    robotModalVisible,
    robotAvatar,
    appName,
    description,
    robotForm,
    showRobotModal,
    handleRobotCancel,
    handleRobotCreate,
    beforeUpload,
    copyAllCredentials,
    copyText,
    handlePageChange,
    showTotal,
    fetchData,
    handleSearch
  };
},
});
</script>

<style scoped>
/* 样式优化 */
.credential-box {
  margin: 24px 0;
}

.credential-item {
  margin-bottom: 16px;
}

.credential-label {
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 8px;
  font-weight: 500;
}

.credential-value {
  width: 85%;
  font-family: monospace;
}

.copy-all {
  margin-top: 32px;
}

:deep(.ant-result-subtitle) {
  color: #ff4d4f;
  font-weight: 500;
}
</style>