<template>
  <div class="invite-page">
    <a-page-header title="我的邀请" class="page-header" />

    <div class="invite-content">
      <!-- 佣金概览卡片 -->
      <a-card class="commission-card" :bordered="false">
        <div class="commission-overview">
          <div class="commission-amount">
            <div class="amount-label">当前剩余佣金</div>
            <div class="amount-value">{{ currencySymbol }} {{ (info.commission_balance / 100).toFixed(2) }}</div>
          </div>
          <div class="commission-actions">
            <a-button type="primary" icon="swap" class="action-btn" @click="showTransferModal"> 划转 </a-button>
            <a-button type="default" icon="dollar" class="action-btn" @click="showWithdrawModal">
              推广佣金提现
            </a-button>
          </div>
        </div>
      </a-card>

      <!-- 统计信息 -->
      <div class="stats-grid">
        <a-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">已注册用户数</div>
            <div class="stat-value">{{ stat[0] }}人</div>
          </div>
        </a-card>

        <a-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">佣金比例</div>
            <div class="stat-value">{{ stat[3] }}%</div>
          </div>
        </a-card>

        <a-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">
              <span>确认中的佣金</span>
              <a-tooltip title="等待确认的佣金金额">
                <a-icon type="question-circle" class="help-icon" />
              </a-tooltip>
            </div>
            <div class="stat-value">{{ currencySymbol }} {{ (stat[2] / 100).toFixed(2) }}</div>
          </div>
        </a-card>

        <a-card class="stat-card">
          <div class="stat-item">
            <div class="stat-label">累计获得佣金</div>
            <div class="stat-value">{{ currencySymbol }} {{ (stat[1] / 100).toFixed(2) }}</div>
          </div>
        </a-card>
      </div>

      <!-- 邀请码管理 - 列表形式 -->
      <a-card class="invite-code-card" title="邀请码管理">
        <div class="invite-code-header">
          <a-button type="primary" @click="generateInviteCode" icon="plus"> 生成邀请码 </a-button>
        </div>

        <div v-if="inviteCodes.length === 0" class="empty-state">
          <a-empty description="暂无数据" />
        </div>

        <div v-else class="invite-code-list">
          <div v-for="(code, index) in inviteCodes" :key="code.id" class="invite-code-item">
            <div class="code-info">
              <div class="code-section">
                <div class="code-label">邀请码</div>
                <div class="code-value">
                  <span class="code-text">{{ code.code }}</span>
                  <a-button type="link" @click="copyInviteLink(code.code)" class="copy-btn"> 复制链接 </a-button>
                </div>
              </div>
              <div class="time-section">
                <div class="code-label">创建时间</div>
                <div class="code-time">{{ getTime(code.created_at) }}</div>
              </div>
            </div>
            <a-divider v-if="index < inviteCodes.length - 1" />
          </div>
        </div>
      </a-card>

      <!-- 佣金发放记录 -->
      <a-card class="commission-record-card" title="佣金发放记录">
        <a-table
          :columns="commissionColumns"
          :data-source="commissionData"
          :pagination="false"
          class="commission-table"
        >
          <template slot="emptyText">
            <a-empty description="暂无数据" />
          </template>
        </a-table>
      </a-card>
    </div>

    <!-- 划转账弹窗 -->
    <a-modal
      v-model="transferModalVisible"
      title="推广佣金划转至余额"
      ok-text="确认"
      cancel-text="取消"
      @ok="handleTransfer"
      @cancel="handleCancelTransfer"
    >
      <div class="transfer-modal-content">
        <p class="transfer-notice">划转后的余额仅用于加速乐消费使用</p>

        <div class="current-balance">
          <div class="balance-label">当前推广佣金余额</div>
          <div class="balance-amount">{{ currencySymbol }} {{ (info.commission_balance / 100).toFixed(2) }}</div>
        </div>

        <a-form :form="transferForm" layout="vertical">
          <a-form-item label="划转金额">
            <a-input
              v-decorator="[
                'transferAmount'
              ]"
              placeholder="请输入需要划转到余额的金额"
              type="number"
            />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>

    <!-- 提现弹窗 -->
    <a-modal
      v-model="withdrawModalVisible"
      title="申请提现"
      ok-text="确认"
      cancel-text="取消"
      @ok="handleWithdraw"
      @cancel="handleCancelWithdraw"
    >
      <a-form :form="withdrawForm" layout="vertical">
        <a-form-item label="提现方式">
          <a-select
            v-decorator="['withdrawMethod', { rules: [{ required: true, message: '请选择提现方式' }] }]"
            placeholder="请选择提现方式"
          >
            <a-select-option v-for="(item,index) in withdrawMethods" :key="index" :value="item">{{ item }}</a-select-option>
            
          </a-select>
        </a-form-item>

        <a-form-item label="提现账号">
          <a-input
            v-decorator="['withdrawAccount', { rules: [{ required: true, message: '请输入提现账号' }] }]"
            placeholder="请输入提现账号"
          />
        </a-form-item>

        <!-- <a-form-item label="提现金额">
          <a-input
            v-decorator="[
              'withdrawAmount',
              {
                rules: [{ required: true, message: '请输入提现金额' }, { validator: validateWithdrawAmount }],
              },
            ]"
            placeholder="请输入提现金额"
            type="number"
          />
        </a-form-item> -->
      </a-form>
    </a-modal>
  </div>
</template>

<script>
export default {
  name: 'InvitePage',
  data() {
    return {
      transferModalVisible: false,
      withdrawModalVisible: false,
      transferForm: this.$form.createForm(this),
      withdrawForm: this.$form.createForm(this),
      commissionColumns: [
        {
          title: '发放时间',
          dataIndex: 'created_at',
          key: 'created_at',
          align: 'center',
          width: '50%',
          customRender: (text) => `${this.getTime(text)}`,
        },
        {
          title: '佣金',
          dataIndex: 'get_amount',
          key: 'get_amount',
          align: 'center',
          width: '50%',
          customRender: (text) => `${this.currencySymbol} ${(text / 100).toFixed(2)}`,
        },
      ],
      commissionData: [], // 空数据，显示暂无数据
      inviteCodes: [],
      info: '',
      currencySymbol: '',
      stat: [],
      load: false,
      withdrawMethods:[],
      loading:false,
    }
  },
  created() {
    this.getInfo()
    this.getConfig()
    this.getInviteList()
    this.getInviteCode()
  },
  methods: {
    getTime(time) {
      const targetTimestamp = time * 1000 // 转换为毫秒
      const targetDate = new Date(targetTimestamp)
      const expired = targetDate.toLocaleString('zh-CN')
      return expired
    },
    getInviteCode() {
      this.$http.get('/user/invite/fetch').then((res) => {
        console.log('res', res)
        this.inviteCodes = res?.data?.codes ?? []
        this.stat = res?.data?.stat ?? []
      })
    },
    getInviteList() {
      this.$http.get('/user/invite/details').then((res) => {
        console.log('res', res)
        this.commissionData = res?.data ?? []
      })
    },
    getInfo() {
      this.$http.get('/user/info').then((res) => {
        console.log('res', res)
        this.info = res?.data ?? ''
      })
    },
    getConfig(id) {
      this.$http
        .get(`/user/comm/config`)
        .then((res) => {
          this.currencySymbol = res?.data?.currency_symbol ?? ''
          this.withdrawMethods = res?.data?.withdraw_methods??[]
        })
        .catch((error) => {
          console.error('获取失败:', error)
        })
        .finally(() => {})
    },
    // 显示划转弹窗
    showTransferModal() {
      this.transferModalVisible = true
      this.$nextTick(() => {
        this.transferForm.resetFields()
      })
    },

    // 显示提现弹窗
    showWithdrawModal() {
      this.withdrawModalVisible = true
      this.$nextTick(() => {
        this.withdrawForm.resetFields()
      })
    },

    // 处理划转
    handleTransfer() {
      this.transferForm.validateFields((err, values) => {
        if (!err) {
          console.log('划转信息:', values)
          if(this.load) return false
          this.load = true
          this.$http
            .post(`/user/transfer`, {
              transfer_amount: values.transferAmount * 100,
            })
            .then((res) => {
              if(res.data){
                this.$message.success('划转成功')
                this.transferModalVisible = false
                this.getInfo()
              }
              
            })
            .catch((error) => {
              console.error('失败:', error)
            })
            .finally(() => {
              this.load = false
            })
        }
      })
    },

    // 处理提现
    handleWithdraw() {
      this.withdrawForm.validateFields((err, values) => {
        if (!err) {
          console.log('提现信息:', values)
          if(this.loading) return false
          this.loading = true
          this.$http
            .post(`/user/ticket/withdraw`, {
              withdraw_account: values.withdrawAccount,
              withdraw_method: values.withdrawMethod 
            })
            .then((res) => {
              if(res.data){
                this.transferModalVisible = false
                this.getInfo()
              }
              
            })
            .catch((error) => {
              console.log('失败:', error)
            })
            .finally(() => {
              this.loading = false
            })
          this.$message.success('提现申请已提交')
          this.withdrawModalVisible = false
        }
      })
    },

    // 取消划转
    handleCancelTransfer() {
      this.transferModalVisible = false
    },

    // 取消提现
    handleCancelWithdraw() {
      this.withdrawModalVisible = false
    },

    // 生成邀请码
    generateInviteCode() {
      this.$http
        .get(`/user/invite/save`)
        .then((res) => {
          this.this.getInviteCode()
          this.$message.success('新邀请码已生成')
        })
        .catch((error) => {
          console.error('获取失败:', error)
        })
        .finally(() => {
          this.load = false
        })
      this.$message.success('新邀请码已生成')
    },

    // 复制邀请链接
    copyInviteLink(code) {
      const inviteLink = `${window.location.origin}/register?code=${code}`
      const textArea = document.createElement('textarea')
      textArea.value = inviteLink
      document.body.appendChild(textArea)
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
      this.$message.success('邀请链接已复制到剪贴板')
    },

    // 验证划转金额
    validateTransferAmount(rule, value, callback) {
      if (value && value <= 0) {
        callback('划转金额必须大于0')
      } else {
        callback()
      }
    },

    // 验证提现金额
    validateWithdrawAmount(rule, value, callback) {
      if (value && value <= 0) {
        callback('提现金额必须大于0')
      } else if (value && value > 0) {
        callback()
      } else {
        callback()
      }
    },
  },
}
</script>

<style scoped>
.invite-page {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  background: #fff;
  margin-bottom: 24px;
  border-radius: 8px;
  padding: 16px 24px;
}

.commission-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.commission-overview {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
}

.commission-amount {
  text-align: left;
}

.amount-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.amount-value {
  font-size: 32px;
  font-weight: 700;
  color: #1890ff;
}

.commission-actions {
  display: flex;
  gap: 12px;
}

.action-btn {
  height: 40px;
  padding: 0 20px;
  border-radius: 6px;
  font-weight: 500;
}

/* 统计信息网格 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-item {
  padding: 16px;
  text-align: center;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.stat-value {
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

.help-icon {
  color: #1890ff;
  cursor: pointer;
}

/* 邀请码管理和佣金发放记录卡片 */
.invite-code-card,
.commission-record-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
}

.invite-code-header {
  margin-bottom: 16px;
}

.empty-state {
  padding: 40px 0;
}

.invite-code-list {
  padding: 8px 0;
}

.invite-code-item {
  padding: 8px 0;
}

.code-info {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.code-section,
.time-section {
  flex: 1;
}

.code-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.code-value {
  display: flex;
  align-items: center;
  gap: 12px;
}

.code-text {
  font-family: 'Courier New', monospace;
  font-weight: 600;
  color: #1890ff;
  font-size: 16px;
}

.copy-btn {
  padding: 0;
  height: auto;
  font-size: 14px;
}

.code-time {
  color: #666;
  font-size: 14px;
}

/* 佣金发放记录表格 */
.commission-table {
  margin-top: 8px;
}

.commission-table >>> .ant-table-thead > tr > th {
  background-color: #fafafa;
  font-weight: 600;
  color: #262626;
  border-bottom: 1px solid #e8e8e8;
}

.commission-table >>> .ant-table-tbody > tr > td {
  border-bottom: 1px solid #e8e8e8;
  padding: 12px 8px;
}

.commission-table >>> .ant-table-tbody > tr:hover > td {
  background-color: #fafafa;
}

/* 弹窗内容样式 */
.transfer-modal-content {
  padding: 8px 0;
}

.transfer-notice {
  color: #666;
  margin-bottom: 20px;
  font-size: 14px;
}

.current-balance {
  background: #f5f5f5;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.balance-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.balance-amount {
  font-size: 20px;
  font-weight: 600;
  color: #1890ff;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .commission-overview {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .commission-actions {
    width: 100%;
    justify-content: center;
  }

  .code-info {
    flex-direction: column;
    gap: 12px;
  }

  .code-section,
  .time-section {
    width: 100%;
  }
}
</style>
