<template>
  <div class="panel">
    <h2 class="panel-title page-title">钱包绑定</h2>
    <div class="panel-body" v-loading="loading">
      <el-form :model="form" label-width="120px" class="config-form">
        <el-form-item label="选择链/币种">
          <el-cascader
            style="width: 420px;"
            v-model="value"
            :options="options"
            :props="cascaderProps"
            :show-all-levels="false"
            clearable
            filterable
            @change="handleChange"
            @expand-change="handleExpandChange"
          >
            <template slot-scope="{ node, data }">
              <span class="custom-node" aria-label="cascader-item" tabindex="0" @click.stop="handleItemClick(node, data)">
                <span class="node-label">{{ data.label }}</span>
                <span v-if="node.isLeaf && node.checked" class="leaf-checked" aria-hidden="true">✓</span>
              </span>
            </template>
          </el-cascader>

        </el-form-item>

        <el-form-item label="已选择币种">
          <div class="selected-coins" aria-label="selected-coins" tabindex="0">
            <el-tag
              v-for="coin in selectedCoins"
              :key="coin"
              type="warning"
              effect="light"
              closable
              disable-transitions
              @close="handleRemoveSelectedCoin(coin)"
            >
              {{ coin }}
            </el-tag>
            <span v-if="selectedCoins.length === 0" class="placeholder">未选择</span>
          </div>
        </el-form-item>


        <el-form-item label="收款钱包地址">
        
          <el-input
            v-model="form.payAddress"
            placeholder="请输入"
          />
        </el-form-item>



        <el-form-item>
          <el-button style="width: 200px;" type="primary" @click="handleSave">确认绑定</el-button>
      
        </el-form-item>
      </el-form>
      <!-- 绑定前预检测弹窗：若存在关联商品，先提示用户再继续绑定 -->
      <el-dialog :visible.sync="preCheck.visible" width="80vw" :close-on-click-modal="false" title="检测到关联商品" @close="handlePreCheckClose">
        <div style="margin-bottom:10px;">
          <el-alert
            type="warning"
            :closable="false"
            show-icon
            description="检测到以下商品与本次绑定的链/币相关。继续绑定后，可能需要为这些商品配置该新链下的价格。是否继续？"
          />
        </div>
   
        <p style="color: red; font-size: 12px; margin-top: 6px;text-align: right;">* 请填写每个商品对应币种的价格,商品包含机器统一设置价格，如需单台修改请在商品列表-详情页操作</p>
        <el-table :data="preCheck.rows" height="360" border :header-cell-style="{ textAlign: 'left' }" :cell-style="{ textAlign: 'left' }">
          <el-table-column label="商品名称" min-width="160">
            <template #default="scope">{{ scope.row.name || scope.row.productName || scope.row.title || scope.row.product || '-' }}</template>
          </el-table-column>
          <el-table-column label="链" min-width="120">
            <template #default> {{ (form.chain || '').toUpperCase() }} </template>
          </el-table-column>
          <el-table-column label="币种" min-width="120">
            <template #default> {{ form.payCoin.split(',').map(s=>s.trim().toUpperCase()).join('，') }} </template>
          </el-table-column>
          <el-table-column label="总矿机数" min-width="100">
            <template #default="scope">{{ scope.row.totalMachineNumber != null ? scope.row.totalMachineNumber : (scope.row.total || scope.row.totalMachines || '-') }}</template>
          </el-table-column>
          <el-table-column label="商品状态" min-width="100">
            <template #default="scope">{{ Number(scope.row.state) === 1 ? '下架' : '上架' }}</template>
          </el-table-column>
          <el-table-column v-for="sym in coinsForBind" :key="'price-'+sym" :label="sym + ' 价格'" min-width="160">
            <template #default="scope">
              <el-input
                v-model="preCheck.rowPrices[getRowKey(scope.row, scope.$index)][sym]"
                size="mini"
                class="price-input"
                placeholder="请输入"
                inputmode="decimal"
              >
                <template #append>{{ sym }}</template>
              </el-input>
            </template>
          </el-table-column>
        </el-table>

        <template #footer>
          <el-button @click="preCheck.visible = false">取消</el-button>
          <el-button type="primary" :disabled="!canSubmitPreCheck" @click="handleConfirmBindAfterPreview">继续绑定</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getMyShop } from "@/api/shops";
import { getChainAndList, addWalletShopConfig,getProductListForShopWalletConfig,updateProductListForShopWalletConfig } from "../../api/wallet";
import { rsaEncrypt, rsaEncryptSync } from "../../utils/rsaEncrypt";

export default {
  name: "AccountShopConfig",
  data() {
    return {
      productOptions: [],
      form: {
        chain: "",
        payAddress: "",
        payCoin: "",
      
      },
      shop: {
        id: 0,
        name: "",
        image: "",
        description: "",
        del: true,
        state: 0,
      },
      // 级联多选值：形如 [[chain, coin], [chain, coin2]]
      value: [],
      currentChain: '',
      cascaderProps: { multiple: true, checkStrictly: false, emitPath: true, value: 'value', label: 'label', children: 'children' },
      options: [
        // {
        //   value: "Tron (TRC20)",
        //   label: "Tron (TRC20)",
        //   children: [
        //     {
        //       value: "USDT",
        //       label: "USDT (TRC20)",
        //     },
        //     {
        //       value: "币种2",
        //       label: "币种2",
        //     },
        //   ],
        // },
        // {
        //   value: "ETH",
        //   label: "ETH",
        //   children: [
        //     {
        //       value: "USDT",
        //       label: "USDT (TRC20)",
        //     },
        //   ],
        // },
      ],
      loading: false,
      // 绑定前预检测弹窗数据
      preCheck: { visible: false, rows: [], prices: {}, rowPrices: {} },
    };
  },
  mounted() {
  
    this.getChainAndList();
  },
  methods: {
    /**
     * 关闭标签 -> 移除对应币种
     */
    handleRemoveSelectedCoin(coinUpper) {
      const coin = String(coinUpper || '').toLowerCase()
      const next = (this.value || []).filter(v => Array.isArray(v) && String(v[1]).toLowerCase() !== coin)
      this.handleChange(next)
    },
    // 允许点击整行触发选择/展开，提升“可点文字即可选”的体验
    handleItemClick(node, data) {
      if (!node) return
      if (node.isLeaf) {
        // 叶子：切换选中
        const path = node.path.map(n => n.value)
        const chain = path[0]
        const coin = path[1]
        this.currentChain = String(chain || '')
        let next = Array.isArray(this.value) ? this.value.slice() : []
        // 始终以最后点击的链为准：如果链不同，清空旧链
        const last = next.length ? next[next.length - 1] : null
        const lastChain = Array.isArray(last) ? last[0] : null
        if (lastChain && lastChain !== chain) next = []
        const idx = next.findIndex(v => Array.isArray(v) && v[0] === chain && v[1] === coin)
        if (idx >= 0) next.splice(idx, 1)
        else next.push([chain, coin])
        this.handleChange(next)
      } else {
        // 父级：以最后点击为准，清空旧链选择并切换到当前链
        const chain = data && data.value
        if (!node.expanded) node.expand()
        if (chain) {
          this.currentChain = String(chain)
          this.value = []
          this.form.chain = String(chain)
          this.form.payCoin = ''
        }
      }
    },
    handleExpandChange(nodes) {
      // 记录当前展开的链，供 @change 过滤依据
      const chain = Array.isArray(nodes) ? (nodes[0] || '') : ''
      if (chain) this.currentChain = String(chain)
    },
    /**
     * 根据选择的链校验钱包地址格式（参考钱包页面规则）
     * - tron: 以 T 开头的 34 位字符
     * - ethereum/bsc/polygon 等 EVM: 0x 开头 + 40 位十六进制
     * - 其他：长度 > 10 的宽松校验
     */
    validateAddressByChain(chain, address) {
      const c = String(chain || '').toLowerCase()
      const addr = String(address || '').trim()
      if (!addr) return { ok: false, message: '请输入收款地址' }

      if (c.includes('tron') || c === 'tron') {
        const ok = /^T[A-Za-z1-9]{33}$/.test(addr)
        return ok
          ? { ok: true }
          : { ok: false, message: '请输入正确的 TRON 地址：以 T 开头的 34 位字符' }
      }

      if (
        c.includes('ethereum') || c === 'ethereum' ||
        c.includes('eth') ||
        c.includes('bsc') || c === 'bsc' ||
        c.includes('polygon') || c === 'polygon' ||
        c.includes('erc') || c.includes('bep')
      ) {
        const ok = /^0x[a-fA-F0-9]{40}$/.test(addr)
        return ok
          ? { ok: true }
          : { ok: false, message: '请输入正确的以太坊/EVM 兼容链地址：以 0x 开头 + 40 位十六进制' }
      }

      if (addr.length <= 10) {
        return { ok: false, message: '请输入正确的收款地址格式' }
      }
      return { ok: true }
    },
    async getChainAndList() {
      this.loading = true;
      const res = await getChainAndList();
      if (res && (res.code === 0 || res.code === 200) && res.data) {
        this.options = this.toUpperOptions(res.data);
      }

      this.loading = false;
    },
    /**
     * 将级联选项的 label 文本统一转为大写（不修改 value）
     * @param {Array} list
     * @returns {Array}
     */
    toUpperOptions(list) {
      const arr = Array.isArray(list) ? list : []
      return arr.map(item => {
        const next = { ...item }
        const src = (item && (item.label != null ? item.label : item.value)) || ''
        next.label = String(src).toUpperCase()
        if (Array.isArray(item && item.children)) {
          next.children = this.toUpperOptions(item.children)
        }
        return next
      })
    },
    async FetchAddWalletShopConfig(params) {
      this.loading = true;
      
      // 使用 RSA 加密钱包地址
      let encryptedPayAddress = params.payAddress
      if (params.payAddress) {
        // 优先使用同步版本（如果 JSEncrypt 已加载）
        const syncEncrypted = rsaEncryptSync(params.payAddress)
        if (syncEncrypted) {
          encryptedPayAddress = syncEncrypted
        } else {
          // 如果同步版本失败，使用异步版本
          const asyncEncrypted = await rsaEncrypt(params.payAddress)
          if (asyncEncrypted) {
            encryptedPayAddress = asyncEncrypted
          } else {
            this.$message.error('钱包地址加密失败，请重试')
            this.loading = false
            return
          }
        }
      }
      
      const encryptedParams = {
        ...params,
        payAddress: encryptedPayAddress
      }
      
      const res = await addWalletShopConfig(encryptedParams);
      if (res && (res.code === 0 || res.code === 200)) {
        this.$message.success("绑定成功");
        this.$router.push("/account/shops");
      } 
      this.loading = false;
    },

    handleChange(value) {
      // 仅允许同一链下多选；无提示，始终以“最后一次点击”的链为准
      const selections = Array.isArray(value) ? value : []
      if (selections.length === 0) {
        this.form.chain = ""
        this.form.payCoin = ""
        this.value = []
        return
      }
      const last = selections[selections.length - 1]
      const lastChain = Array.isArray(last) ? last[0] : ''
      const targetChain = this.currentChain || lastChain
      const filtered = selections.filter(v => Array.isArray(v) && v[0] === targetChain)
      this.value = filtered
      this.form.chain = targetChain || ""
      this.form.payCoin = filtered.map(v => v[1]).filter(Boolean).join(',')
    },

    handleSave() {
      // 从多选值同步 chain 与 payCoin（英文逗号隔开）
      const selections = Array.isArray(this.value) ? this.value : []
      this.form.chain = selections.length ? (selections[0] && selections[0][0]) : ''
      this.form.payCoin = selections.map(v => v && v[1]).filter(Boolean).join(',')

      if (!this.form.chain) {
        this.$message.warning("请选择链");
        return;
      }
      if (!this.form.payCoin) {
        this.$message.warning("请选择币种");
        return;
      }
      if (!this.form.payAddress) {
        this.$message.warning("请输入钱包地址");
        return;
      }

      // 链路格式校验
      const { ok, message } = this.validateAddressByChain(this.form.chain, this.form.payAddress)
      if (!ok) {
        this.$message.warning(message || '钱包地址格式不正确')
        return
      }

      // 新增步骤：绑定前预检测商品列表
      this.preCheckBeforeBind()
    },
    /**
     * 绑定前预检测：若接口返回有关联商品，则弹窗展示；否则直接走绑定流程
     */
    async preCheckBeforeBind() {
      try {
        this.loading = true
        // 先关闭弹窗，确保不会显示旧数据
        this.preCheck.visible = false
        this.preCheck.rows = []
        
        const params = { chain: this.form.chain, payCoin: this.form.payCoin }
        const res = await getProductListForShopWalletConfig(params)
        
        // 检查接口是否成功（code === 0 或 code === 200）
        const isSuccess = res && (res.code === 0 || res.code === 200)
        if (!isSuccess) {
          // 接口失败，直接走绑定流程，不显示弹窗
          await this.submitBindWithPrice([])
          return
        }
        
        // 接口成功，提取数据
        const rows = Array.isArray(res && res.data) ? res.data : (Array.isArray(res && res.rows) ? res.rows : [])
        // 确保 rows 是有效数组且有数据
        if (Array.isArray(rows) && rows.length > 0) {
          this.preCheck.rows = rows
          // 初始化各币种价格输入
          const coins = (this.form.payCoin || '').split(',').map(s => s.trim().toUpperCase()).filter(Boolean)
          const map = {}
          coins.forEach(c => { if (!(c in this.preCheck.prices)) map[c] = '' })
          this.preCheck.prices = { ...map, ...this.preCheck.prices }
          // 初始化每行的价格容器
          this.preCheck.rowPrices = this.preCheck.rowPrices || {}
          this.preCheck.rows.forEach((r, idx) => {
            const key = this.getRowKey(r, idx)
            if (!this.preCheck.rowPrices[key]) this.$set(this.preCheck.rowPrices, key, {})
            coins.forEach(c => { if (!(c in this.preCheck.rowPrices[key])) this.$set(this.preCheck.rowPrices[key], c, '') })
          })
          this.preCheck.visible = true
        } else {
          // 无关联商品或数据为空，直接绑定并设置（机器列表为空），不显示弹窗
          this.preCheck.visible = false
          this.preCheck.rows = []
          await this.submitBindWithPrice([])
        }
      } catch (e) {
        // 接口异常不阻塞绑定流程，直接走绑定，不显示弹窗
        this.preCheck.visible = false
        this.preCheck.rows = []
        await this.submitBindWithPrice([])
      } finally {
        this.loading = false
      }
    },
    handleConfirmBindAfterPreview() {
      // 校验价格必填
      const coins = (this.form.payCoin || '').split(',').map(s => s.trim().toUpperCase()).filter(Boolean)
      // 逐行校验
      for (let i = 0; i < this.preCheck.rows.length; i++) {
        const row = this.preCheck.rows[i]
        const key = this.getRowKey(row, i)
        const priceMap = (this.preCheck.rowPrices && this.preCheck.rowPrices[key]) || {}
        for (const c of coins) {
          const v = priceMap[c]
          if (!v || Number(v) <= 0) {
            this.$message.warning(`请填写第 ${i + 1} 行 ${c} 的价格`)
            return
          }
        }
      }
      const groups = this.collectMachineGroups(this.preCheck.rows)
      this.preCheck.visible = false
      this.submitBindWithPrice(groups)
    },
    /** 收集每一行对应的机器ID分组（兼容不同返回结构） */
    collectMachineGroups(rows) {
      const groups = []
      const pushId = (arr, id) => { if (id != null && id !== '') arr.push(id) };
      (rows || []).forEach((r, idx) => {
        const ids = []
        // 兼容多种返回结构，优先使用接口包含的 machineList（每台矿机对象含 productMachineId）
        if (Array.isArray(r && r.machineList)) r.machineList.forEach(m => pushId(ids, m && (m.productMachineId != null ? m.productMachineId : m.id)))
        if (Array.isArray(r && r.productMachineIdList)) r.productMachineIdList.forEach(id => pushId(ids, id))
        if (r && r.productMachineId != null) pushId(ids, r.productMachineId)
        if (Array.isArray(r && r.productMachineDtoList)) r.productMachineDtoList.forEach(m => pushId(ids, (m && (m.productMachineId != null ? m.productMachineId : m.id))))
        if (Array.isArray(r && r.machines)) r.machines.forEach(m => pushId(ids, (m && (m.productMachineId != null ? m.productMachineId : m.id))))
        if (Array.isArray(r && r.items)) r.items.forEach(m => pushId(ids, (m && (m.productMachineId != null ? m.productMachineId : m.id))))
        const key = this.getRowKey(r, idx)
        groups.push({ key, machineIds: ids })
      })
      return groups
    },
    /** 生成某一行的 key（优先 productId/id） */
    getRowKey(row, index) {
      if (row && row.productId != null) return String(row.productId)
      if (row && row.id != null) return `p-${row.id}`
      return `idx-${index}`
    },
    /** 提交绑定：使用 updateProductListForShopWalletConfig 完成绑定与价格设置 */
    async submitBindWithPrice(machineGroups) {
      try {
        this.loading = true
        const coins = (this.form.payCoin || '').split(',').map(s => s.trim().toUpperCase()).filter(Boolean)
        const list = []
        if (Array.isArray(machineGroups) && machineGroups.length) {
          machineGroups.forEach(g => {
            const priceMap = (this.preCheck.rowPrices && this.preCheck.rowPrices[g.key]) || {}
            const priceStr = coins.map(c => priceMap[c] || '').join(',');
            (g.machineIds || []).forEach(id => { list.push({ productMachineId: id, price: priceStr }) })
          })
        }
        
        // 使用 RSA 加密钱包地址
        let encryptedPayAddress = this.form.payAddress
        if (this.form.payAddress) {
          // 优先使用同步版本（如果 JSEncrypt 已加载）
          const syncEncrypted = rsaEncryptSync(this.form.payAddress)
          if (syncEncrypted) {
            encryptedPayAddress = syncEncrypted
          } else {
            // 如果同步版本失败，使用异步版本
            const asyncEncrypted = await rsaEncrypt(this.form.payAddress)
            if (asyncEncrypted) {
              encryptedPayAddress = asyncEncrypted
            } else {
              this.$message.error('钱包地址加密失败，请重试')
              this.loading = false
              return
            }
          }
        }
        
        const payload = {
          chain: this.form.chain,
          symbol: this.form.payCoin,
          // payAddress: this.form.payAddress,//使用未加密地址
          payAddress: encryptedPayAddress, // 使用加密后的地址
          productMachineForWalletConfigVoList: list
        }
        const res = await updateProductListForShopWalletConfig(payload)
        if (res && (res.code === 0 || res.code === 200)) {
          this.preCheck.visible = false
          this.resetPreCheckPrices()
          this.$message.success('绑定成功')
          this.$router.push('/account/shops')
        } else {
          // 绑定失败，关闭弹窗并显示错误消息
          this.preCheck.visible = false
          this.resetPreCheckPrices()
         
        }
      } catch (e) {
        // 错误交由全局拦截或简单提示
      } finally {
        this.loading = false
      }
    },
    handleReset() {
      this.form = { chain: "", payAddress: "", payCoin: "" };
      this.value = []
    },
    // 清空预检测中的价格输入
    resetPreCheckPrices() {
      try {
        this.preCheck.prices = {}
        this.preCheck.rowPrices = {}
      } catch (e) { /* noop */ }
    },
    // 弹窗关闭时清空价格输入
    handlePreCheckClose() {
      this.resetPreCheckPrices()
    },
  },
  computed: {
    coinsForBind() {
      return (this.form.payCoin || '').split(',').map(s => s.trim().toUpperCase()).filter(Boolean)
    },
    canSubmitPreCheck() {
      if (!this.preCheck || !this.preCheck.visible) return false
      const coins = this.coinsForBind
      if (!coins.length) return false
      // 所有行都需要填写
      for (let i = 0; i < (this.preCheck.rows || []).length; i++) {
        const row = this.preCheck.rows[i]
        const key = this.getRowKey(row, i)
        const priceMap = (this.preCheck.rowPrices && this.preCheck.rowPrices[key]) || {}
        for (const c of coins) {
          const v = priceMap[c]
          if (!v || Number(v) <= 0) return false
        }
      }
      return true
    },
    /**
     * 已选择币种的可读展示（中文顿号分隔）
     */
    selectedCoinsDisplay() {
      const arr = Array.isArray(this.value) ? this.value : []
      const coins = arr.map(v => v && v[1]).filter(Boolean).map(s => String(s).toUpperCase())
      return coins.join('、')
    },
    /**
     * 标签列表数据
     */
    selectedCoins() {
      const arr = Array.isArray(this.value) ? this.value : []
      return arr.map(v => v && v[1]).filter(Boolean).map(s => String(s).toUpperCase())
    },
  },
};
</script>

<style scoped>
.page-title {
  text-align: left;
  margin-bottom: 16px;
  font-size: 20px;
  padding-left: 4px;
}
.config-form {
  max-width: 720px;
  margin: 0;
  background: #fff;
  padding: 8px 12px;
}
.config-form .el-form-item {
  margin-bottom: 18px;
}
.config-form .el-select,
.config-form .el-input {
  width: 420px;
}
.radio-group {
  display: inline-flex;
  align-items: center;
  gap: 24px;
  width: 420px; /* 与上方输入框等宽 */
  height: 40px; /* 与输入框高度接近，视觉更整齐 */
  padding-left: 12px; /* 留出与输入框一致的内边距感 */
  box-sizing: border-box;
}
.tip {
  color: #999;
  font-size: 12px;
  margin-top: 6px;
}

/* 自定义级联节点样式：叶子被选中时显示勾选 */
.custom-node { display: inline-flex; align-items: center; gap: 8px; }
.leaf-checked { color: #409EFF; font-weight: 700; }
.node-label { line-height: 20px; }

/* 已选择币种标签样式 */
.selected-coins { display: flex; flex-wrap: wrap; gap: 8px; min-height: 32px; align-items: center; margin-left: 79px;}
.selected-coins .el-tag { border-radius: 4px; }
.selected-coins .placeholder { color: #c0c4cc; }

/* 价格输入框获得焦点时高亮为红色，提示用户输入 */
.price-input :deep(.el-input__inner:focus) {
  border-color: #f56c6c !important;
  box-shadow: 0 0 0 1px #f56c6c inset;
}
</style>

