<template>
  <div class="agent-container">
    <el-card class="start">
      <h3>如何开始</h3>
      <div class="list">
        <div class="item">
          <el-icon color="#409eff">
            <CircleCheckFilled />
          </el-icon>
          <router-link to="/profile/kyc">实名认证</router-link>
        </div>
        <div class="line"></div>
        <div class="item">
          <el-icon color="#409eff">
            <CircleCheckFilled />
          </el-icon>
          <router-link to="/capital/rechange">存款</router-link>
        </div>
        <div class="line"></div>
        <div class="item">
          <el-icon color="#409eff">
            <CircleCheckFilled />
          </el-icon>
          <router-link to="/trade/exe">交易</router-link>
        </div>
      </div>
    </el-card>
    <el-card class="common">
      <h3>常用功能</h3>
      <div class="list">
        <router-link to="" class="item">
          <el-icon color="#409eff">
            <CircleCheckFilled />
          </el-icon>
          <router-link to="/capital/rechange">存款</router-link>
        </router-link>
        <router-link to="" class="item">
          <el-icon color="#409eff">
            <CircleCheckFilled />
          </el-icon>
          <router-link to="/capital/withdraw">取款</router-link>
        </router-link>
        <router-link to="" class="item">
          <el-icon color="#409eff">
            <CircleCheckFilled />
          </el-icon>
          <router-link to="/trade/exe">交易</router-link>
        </router-link>
      </div>
    </el-card>
    <el-card>
      <h3>我的钱包</h3>

      <el-popover placement="right" trigger="hover" class="wallet-popover">
        <div class="link">
          <router-link to="/capital/transfer" class="item">转账</router-link>
          <router-link to="/capital/withdraw" class="item">取款</router-link>
          <router-link to="/capital/fundFlow" class="item">资金明细</router-link>
        </div>
        <template #reference>
          <div class="wallet">
            <div class="item">
              <el-icon color="#409eff" size="40">
                <svg
                  t="1773987067376"
                  class="icon"
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="1663"
                  width="200"
                  height="200"
                >
                  <path
                    d="M512 97.52381c228.912762 0 414.47619 185.563429 414.47619 414.47619s-185.563429 414.47619-414.47619 414.47619S97.52381 740.912762 97.52381 512 283.087238 97.52381 512 97.52381z m96.060952 193.584761L512 387.120762l-96.060952-96.060952-51.687619 51.73638 96.036571 96.012191L329.142857 438.857143v73.142857h146.285714v60.952381h-146.285714v73.142857h146.285714v97.52381h73.142858v-97.52381h146.285714v-73.142857h-146.285714V512h146.285714v-73.142857h-131.145143l96.060952-96.060953-51.736381-51.687619z"
                    p-id="1664"
                  ></path>
                </svg>
              </el-icon>
            </div>
            <div class="item">
              <span>USD</span>
              <span>总金额</span>
              <span>可用资金</span>
              <span>冻结资金</span>
            </div>
            <div class="item">
              <span>主钱包</span>
              <span>{{ walletCapital.amount_total }}</span>
              <span>{{ walletCapital.amount }}</span>
              <span>{{ walletCapital.freeze }}</span>
            </div>
          </div>
        </template>
      </el-popover>
    </el-card>
    <el-card class="account">
      <h3 class="account-title">
        个人账户
        <el-button
          type="primary"
          size="small"
          @click="handleAddSubAccount"
          v-auth="'user_createAccount'"
          >添加子账户</el-button
        >
      </h3>
      <div class="account-list">
        <div class="list" v-for="item in accountList" :key="item.id">
          <div class="item item-setting">
            <div class="setting-content" v-if="isEdit !== item.account_id">
              <span>账户名称:</span>
              <span>{{ item.account_name }}</span>
            </div>
            <div class="setting-content" v-else>
              <span class="setting-label">账户名称:</span>
              <el-input
                v-model="editName"
                @blur="handleSave"
                @keyup.enter="handleSave"
                ref="inputRef"
                size="small"
              />
            </div>
            <div class="setting-group">
              <span>
                <el-icon @click="handleEdit(item.account_name, item.account_id)">
                  <EditPen />
                </el-icon>
              </span>
              <span>
                <el-icon @click="handleSetting(item.account_id)">
                  <Setting />
                </el-icon>
              </span>
            </div>
          </div>
          <div class="item">
            <span>账户号</span>
            <span>{{ item.account_id || '--' }}</span>
          </div>
          <div class="item">
            <span>净资产</span>
            <span>{{ item?.wallets_trade?.amount || '--' }}</span>
          </div>
          <div class="item">
            <span>余额</span>
            <span>{{ item?.wallets_trade?.amount || '--' }}</span>
          </div>
          <div class="item">
            <span>杠杆</span>
            <span>1:{{ item?.wallets_trade?.lever || '--' }}</span>
          </div>
        </div>
      </div>
    </el-card>
    <el-card class="qr-code" v-if="userInfo.type * 1 === 2 && userInfo.role_id * 1 === 5">
      <h3>
        推广
        <span>统计起始时间:2026-3-20</span>
      </h3>
      <div class="list">
        <div class="item">
          <span>推广链接</span>
          <div class="text">
            <span>{{ copyText }}</span>
            <el-icon @click="handleCopyUrl">
              <DocumentCopy />
            </el-icon>
          </div>
        </div>
        <div class="item">
          <span>推广二维码</span>
          <div class="text">
            <canvas ref="qrCanvas"></canvas>
          </div>
        </div>
      </div>
    </el-card>
  </div>
  <AgentDialog
    :visible="dialogVisible"
    :title="dialogTitle"
    :type="dialogType"
    @confirm="handleSubmit"
    @cancel="handleCancel"
    @close="handleClose"
  >
    <div class="tab" v-if="dialogType !== 'add'">
      <el-button
        :type="dialogType === 'setting' ? 'primary' : 'default'"
        @click="dialogType = 'setting'"
        >重置密码</el-button
      >
      <el-button
        :type="dialogType === 'leverage' ? 'primary' : 'default'"
        @click="handleChangeToLeverage"
        >修改杠杆</el-button
      >
    </div>
    <AgentForm
      :form-data="subAccountForm"
      :form-rules="subAccountRules"
      :form-items="subAccountFormItem"
      :options-map="subAccountFormOptionsMap"
      :row-gutter="rowGutter"
      :col-span="colSpan"
      ref="subAccountFormRef"
    />
  </AgentDialog>
</template>

<script setup lang="ts">

defineOptions({
  name: 'View'
})
import { CircleCheckFilled, EditPen, Setting, DocumentCopy } from '@element-plus/icons-vue'
//组件
import AgentDialog from '@/components/common/Dialog.vue'
import AgentForm from '@/components/common/Form.vue'

//配置
import { formItem, resetPasswordFormItem, leverageFormItem } from './options'
import { rules } from './rules'

//接口
import {
  getLeverOptionsApi,
  createAgentApi,
  editAgentNameApi,
  resetPasswordApi,
  leverageLeverApi,
} from '@/api/modules/agent'
import { getAllAccount, getWalletCapital, editAccountPass } from '@/api/modules/dashboard.ts'

//公共方法
import { getStorage, setStorage } from '@/utils/storage'
import { useUserStore } from '@/stores/modules/user.ts'

const userStore = useUserStore()

import QRCode from 'qrcode'

/**
 * @description: dialog数据
 */
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogType = ref('add')

const accountList = ref<any[]>([])
const getAccoundList = async () => {
  const res = await getAllAccount({ username: '' })
  console.log(res)
  accountList.value = res
}

const walletCapital = ref({})
const getWalletCapitaInfo = async () => {
  const res = await getWalletCapital()
  console.log('getWalletCapitaInfo', res)
  walletCapital.value = res
}

/**
 * @description: 添加子账户表单数据
 */
const subAccountForm = ref({
  password: '',
  leverage: null,
  //这是编辑密码的数据
  resetPassword: '',
  // 确认密码
  confirmPassword: '',
})
const subAccountFormRef = ref()
const subAccountRules = ref(rules(subAccountForm.value))
const subAccountFormItem = computed(() => {
  if (dialogType.value === 'setting') {
    return resetPasswordFormItem
  } else if (dialogType.value === 'leverage') {
    return leverageFormItem
  } else {
    return formItem
  }
})
const subAccountFormOptionsMap = ref({
  leverage: [],
})
const rowGutter = ref(20)
const colSpan = ref(12)

/**
 * @description: 编辑账户名称数据
 */
// 从本地存储获取账户名称
const userInfo = getStorage<any>('userInfo')
const accountName = ref(userInfo?.username || '')
const editName = ref('')
const isEdit = ref('')
const inputRef = ref<HTMLInputElement>()

/*
 * @description: 复制推广二维码和推广链接数据
 */
const copyText = ref(userInfo.invite_url)
const qrCanvas = ref()

/**
 * @description: 定义公共请求数据方法
 */
const getLeverOptions = async () => {
  try {
    const data: any = await getLeverOptionsApi()
    console.log(data)
    subAccountFormOptionsMap.value.leverage = data.map((item: any) => ({
      label: item.label,
      value: item.value,
    }))
  } catch (err) {
    console.error('获取杠杆选项失败:', err)
  }
}

const generateBasic = async () => {
  const userInfo = getStorage('userInfo')
  if (!userInfo?.invite_url || !qrCanvas.value) return

  await QRCode.toCanvas(qrCanvas.value, userInfo.invite_url, {
    width: 200,
    margin: 2,
  })
}

/**
 * @description: 页面加载完成需要请求的数据
 */
onMounted(() => {
  getLeverOptions()
  getAccoundList()
  getWalletCapitaInfo()
  generateBasic()
})

/**
 * @description: 添加子账户方法
 */
const handleAddSubAccount = () => {
  dialogVisible.value = true
  dialogTitle.value = '添加子账户'
  dialogType.value = 'add'
  console.log(dialogType.value)
}

/**
 * @description: dialog方法
 */
const handleSubmit = async () => {
  console.log(dialogType.value)
  await subAccountFormRef.value.validate()
  const params = {
    password: subAccountForm.value.password,
    lever: subAccountForm.value.leverage,
  }
  if (dialogType.value === 'add') {
    await createAgentApi(params)
    await getAccoundList()
    dialogVisible.value = false
  } else if (dialogType.value === 'setting') {
    const params = {
      account_id: account_id || '',
      user_password: subAccountForm.value.resetPassword,
      account_password: subAccountForm.value.confirmPassword,
    }
    await editAccountPass(params)
    await getAccoundList()
    subAccountForm.value.resetPassword = ''
    subAccountForm.value.confirmPassword = ''
    dialogVisible.value = false
  } else if (dialogType.value === 'leverage') {
    const params = {
      account_id: account_id || '',
      lever: subAccountForm.value.leverage,
    }
    await leverageLeverApi(params)
    await getAccoundList()
    dialogVisible.value = false
  }
}
const handleClose = () => {
  dialogVisible.value = false
}
const handleCancel = () => {
  dialogVisible.value = false
}

/**
 * @description: 编辑账户名称方法
 */

// 点击编辑图标方法
let account_id = ''
const handleEdit = async (name: string, id: string) => {
  if (isEdit.value) return (isEdit.value = '')
  isEdit.value = id
  editName.value = name
  account_id = id
}

// 保存编辑内容方法
const handleSave = async () => {
  if (account_id === '') return ElMessage.error('请先选择账户')
  if (editName.value === '') return ElMessage.error('请输入账号')
  editName.value.trim()
  await editAgentNameApi({
    account_id: account_id,
    account_name: editName.value,
  })
  await getAccoundList()

  isEdit.value = false
}

/**
 * @description: 设置方法
 */
const handleSetting = (id: string) => {
  dialogVisible.value = true
  account_id = id
  dialogTitle.value = '编辑账号'
  dialogType.value = 'setting'
}

/**
 * @description: 修改杠杆
 */
const handleChangeToLeverage = () => {
  // 切换到杠杆表单时，设置默认值为当前账户的杠杆值
  const currentAccount = accountList.value.find((item: any) => item.account_id === account_id)
  if (currentAccount?.wallets_trade?.lever) {
    subAccountForm.value.leverage = currentAccount.wallets_trade.lever
  }
  dialogType.value = 'leverage'
}

/**
 * @description: 复制推广二维码和推广链接方法
 */
const handleCopyUrl = async () => {
  const success = await copyToClipboard(copyText.value)
  if (success) {
    alert('复制成功')
  } else {
    alert('复制失败，请手动复制')
  }
}

async function copyToClipboard(text: string) {
  // 方案1: 优先使用现代 Clipboard API
  if (navigator.clipboard && navigator.clipboard.writeText) {
    try {
      await navigator.clipboard.writeText(text)
      return true
    } catch (err) {
      console.warn('Clipboard API 失败，尝试降级方案', err)
    }
  }

  // 方案2: 降级到 document.execCommand（兼容 HTTP 环境）
  const textarea = document.createElement('textarea')
  textarea.value = text
  textarea.style.position = 'fixed'
  textarea.style.left = '-9999px'
  textarea.style.top = '0'
  document.body.appendChild(textarea)
  textarea.focus()
  textarea.select()

  try {
    const success = document.execCommand('copy')
    document.body.removeChild(textarea)
    return success
  } catch (err) {
    document.body.removeChild(textarea)
    console.error('复制失败:', err)
    return false
  }
}
</script>

<style scoped lang="scss">
.agent-container {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  .el-card {
    margin-bottom: 20px;

    h3 {
      margin-bottom: 20px;
    }
  }

  .start {
    .list {
      display: flex;
      align-items: center;

      .item {
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #ccc;
        border-radius: 5px;
        padding: 10px;

        span {
          margin: 0 10px;
        }
      }

      .line {
        width: 100px;
        height: 2px;
        background-color: #409eff;
        position: relative;
        display: flex;
        align-items: center;

        &:before {
          content: '';
          display: block;
          width: 14px;
          height: 14px;
          border-radius: 50%;
          background-color: #409eff;
          position: absolute;
          left: 0;
        }

        &:after {
          content: '';
          display: block;
          width: 0;
          height: 0;
          border-top: 10px solid transparent;
          border-bottom: 10px solid transparent;
          border-left: 14px solid #409eff;
          position: absolute;
          right: 0;
        }
      }
    }
  }

  .common {
    .list {
      display: flex;
      gap: 60px;
    }

    .item {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding: 16px 24px;
      border: 1px solid #ccc;
      border-radius: 5px;
      text-decoration: none;
      color: #303133;

      .el-icon {
        font-size: 28px;
      }
    }
  }

  .wallet {
    display: flex;
    border: 1px solid #ccc;
    border-radius: 5px;
    width: fit-content;
    padding: 10px;
    cursor: pointer;
    gap: 10px;

    .item {
      display: flex;
      flex-direction: column;
      align-items: center;
    }
  }

  .account-title {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .account-list {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    column-gap: 12px;
    row-gap: 12px;
  }

  .account {
    .list {
      width: 300px;
      border: 1px solid #ccc;
      border-radius: 5px;
      padding: 10px;
      display: flex;
      flex-direction: column;
      gap: 10px;

      .item {
        display: flex;
        align-items: center;
        gap: 16px;
      }

      .item-setting {
        justify-content: space-between;

        .setting-content {
          display: flex;
          align-items: center;
          gap: 10px;

          .setting-label {
            width: 120px;
          }
        }

        .setting-group {
          display: flex;
          cursor: pointer;
          gap: 10px;
        }
      }
    }
  }

  .qr-code {
    h3 {
      span {
        font-size: 14px;
        font-weight: normal;
      }
    }

    .list {
      display: flex;
      gap: 20px;

      .item {
        display: flex;
        flex-direction: column;
        gap: 10px;

        .text {
          .el-icon {
            margin-left: 10px;
            cursor: pointer;
          }

          img {
            width: 100px;
            height: 100px;
          }
        }
      }
    }
  }
}

// 个人账户添加子账户按钮
.el-popper {
  width: 100px;

  .link {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;

    .item {
      width: fit-content;
      border: 1px solid #409eff;
      border-radius: 5px;
      padding: 4px;
    }

    .item {
      text-decoration: none;
      color: #303133;
    }
  }
}

.el-dialog {
  .tab {
    margin-bottom: 10px;
  }
}
</style>
