<template>
  <div class="account-products" >
    <!-- 标题与操作栏 -->
    <div class="toolbar">
      <div class="left-area">
        <h2 class="page-title">商品列表</h2>
      </div>
      <div class="right-area">
        <el-select
          v-model="listParams.type"
          placeholder="矿机种类"
          size="small"
          class="mr-12"
          style="width: 140px"
          @change="handleTypeChange"
        >
          <el-option :label="'ASIC'" :value="0" />
          <el-option :label="'GPU'" :value="1" />
        </el-select>
        <el-input
          v-model="searchKeyword"
          :placeholder="searchPlaceholder"
          size="small"
          clearable
          class="mr-12"
          style="width: 280px"
          @keyup.enter.native="handleSearch"
          @clear="handleClear"
        />
        <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>
        <el-button size="small" class="ml-8" @click="handleReset">重置</el-button>
      </div>
    </div>

    <!-- 全局支持结算方式展示 -->
    <div class="paytypes-bar" v-if="payTypes && payTypes.length">
      <span class="pt-label">支持结算方式：</span>
      <div class="pt-icons">
            <el-tooltip
          v-for="(pt, idx) in payTypes"
              :key="idx"
          :content="formatPayTypeHead(pt)"
              placement="top"
              :open-delay="80"
          
            >
          <img :src="getPayImage(pt)" :alt="formatPayTypeHead(pt)" class="paytype-icon" />
            </el-tooltip>
          </div>
    </div>

    <!-- 售价展示币种选择（影响 ASIC 表格“售价”列展示） -->
    <div
      v-if="listParams.type === 0 && payTypes && payTypes.length"
      class="price-select-bar"
      style="margin:8px 0 4px; display:flex; justify-content:flex-end; align-items:center;"
    >
      <span style="margin-right:8px;color:#606266;font-size: 14px;">筛选售价：</span>
      <el-select
        v-model="selectedPayKey"
        size="small"
        style="width: 220px"
        placeholder="选择价格展示币种"
        @change="handlePayTypeChange"
      >
        <template slot="prefix">
          <img
            v-if="getSelectedPayImage()"
            :src="getSelectedPayImage()"
            class="paytype-icon"
             style="width:16px;height:16px;border-radius:3px;margin-right:6px;"
          />
        </template>
        <el-option
          v-for="(pt, idx) in payTypes"
          :key="'pt-opt-top-' + idx"
          :label="formatPayTypeHead(pt)"
          :value="buildPayKey(pt)"
        >
          <span style="display:inline-flex;align-items:center;gap:6px;">
            <img :src="getPayImage(pt)" class="paytype-icon" />
            <span>{{ formatPayTypeHead(pt) }}</span>
          </span>
        </el-option>
      </el-select>
    </div>

    <!-- 表格列表（ASIC） -->
    <el-table
      :key="'asic-table'"
      v-if="listParams.type === 0"
      :data="shopMachineList || []"
      v-loading="loading"
      border
      stripe
      style="width: 100%"
    >
      <!-- 矿机类型：type 0 ASIC / 1 GPU -->
      <el-table-column label="矿机类型" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.type == 0 ? 'warning' : 'success'">
            {{ scope.row.type == 0 ? 'ASIC' : 'GPU' }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 币种（来自 coinAndAlgoList，多项用逗号拼接；兜底 row.coin） -->
      <el-table-column label="币种" min-width="140" show-overflow-tooltip>
        <template #default="scope">
          <div class="ellipsis-cell">{{ getRowCoinText(scope.row) }}</div>
        </template>
      </el-table-column>
      <!-- 算法（来自 coinAndAlgoList，多项用逗号拼接；兜底 row.algorithm） -->
      <el-table-column label="算法" min-width="160" show-overflow-tooltip>
        <template #default="scope">
          <div class="ellipsis-cell">{{ getRowAlgorithmText(scope.row) }}</div>
        </template>
      </el-table-column>
      <!-- 矿机型号 -->
      <el-table-column prop="name" label="矿机型号" />
       <!-- 理论算力（附带单位） -->
       <el-table-column label="理论算力" min-width="170" show-overflow-tooltip>
        <template #default="scope">
          <div class="ellipsis-cell">{{ getTheoryText(scope.row) }}</div>
        </template>
      </el-table-column>
      <!-- 功耗(kw/h) -->
      <el-table-column label="功耗(kw/h)">
        <template #default="scope">
          <span>{{ getPowerDissText(scope.row) }}</span>
        </template>
      </el-table-column>
      <!-- 该商品总机器数量 -->
      <el-table-column prop="saleNumbers" label="总机器数量" />
      <!-- 已售数量 -->
      <el-table-column prop="saleOutNumbers" label="已售数量" />
     
      <!-- 最大租赁天数 -->
      <el-table-column prop="maxLeaseDays" label="最大租赁天数" />
      <!-- 售价（根据选择的结算方式展示对应价格） -->
      <el-table-column>
        <template slot="header">
          <div style="display:flex;align-items:center;gap:8px;">
            <span>售价</span>
          </div>
        </template>
        <template slot-scope="scope">
          <span class="price-strong">{{ getRowPriceText(scope.row) }}</span>
        </template>
      </el-table-column>
      <!-- 状态：0 上架 1 下架 -->
      <el-table-column label="状态" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.state === 0 ? 'success' : 'info'">
            {{ scope.row.state === 0 ? '上架' : '下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 操作：去掉详情与添加出售机器 -->
      <el-table-column label="操作" fixed="right" width="140">
        <template #default="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="text" size="small" style="color:#f56c6c" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格列表（GPU） -->
    <el-table
      :key="'gpu-table-' + String(listParams.type)"
      v-else
      :data="shopMachineList || []"
      border
      stripe
      style="width: 100%"
    >
      <el-table-column label="矿机类型" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.type == 1 ? 'success' : 'warning'">
            {{ scope.row.type == 1 ? 'GPU' : 'ASIC' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="miner" label="矿机编号">
        <template #default="scope">
          <span>{{ scope.row.miner || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="显卡型号">
        <template #default="scope">
          <span>{{ scope.row.name || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="180">
        <template #default="scope">
          <div class="gpu-state">
            <el-switch
              :active-value="0"
              :inactive-value="1"
              :value="(updateMap[getRowId(scope.row)] && updateMap[getRowId(scope.row)].state) != null ? updateMap[getRowId(scope.row)].state : 1"
              @change="handleToggleState(scope.row, $event)"
            />
            <span
              class="gpu-state-text"
              :class="{ on: ((updateMap[getRowId(scope.row)] && updateMap[getRowId(scope.row)].state) === 0) }"
            >
              {{ ((updateMap[getRowId(scope.row)] && updateMap[getRowId(scope.row)].state) === 0) ? '上架' : '下架' }}
            </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="售价" min-width="300">
        <template #default="scope">
          <div class="gpu-price-row">
            <div
              v-for="(pt, idx) in payTypes"
              :key="idx"
              class="gpu-price-item"
            >
              <span class="gpu-price-label">{{ formatPayTypeHead(pt) }}</span>
              <el-input
                size="small"
                class="gpu-price-input"
                :value="getPriceValue(getRowId(scope.row), pt)"
                placeholder="价格"
                @input="handlePriceInput(scope.row, pt, $event)"
                @blur="handlePriceBlur(scope.row, pt)"
              />
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="最大租赁天数" width="160">
        <template #default="scope">
          <el-input
            size="small"
            :value="String((updateMap[getRowId(scope.row)] && updateMap[getRowId(scope.row)].maxLeaseDays) || '')"
            placeholder="1-365"
            style="width: 120px"
            @input="handleMaxLeaseDaysInput(scope.row, $event)"
          />
        </template>
      </el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作" fixed="right" width="120">
        <template #default="scope">
          <el-button type="text" size="small" style="color:#f56c6c" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination" v-if="listParams.type === 0">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :current-page.sync="pagination.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size.sync="pagination.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- GPU 操作 -->
    <div v-else style="margin-top: 12px; display:flex; justify-content: space-between; align-items: center;">
      <el-button type="primary" @click="handleUpdateGpu">更新商品信息</el-button>
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :current-page.sync="pagination.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size.sync="pagination.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑弹窗（ASIC 修改） -->
    <el-dialog
      :visible.sync="editDialog.visible"
      :close-on-click-modal="false"
      width="70VW"
      :title="'编辑商品 - ' + ((editDialog.form && editDialog.form.name) ? editDialog.form.name : '')"
    >
      <el-form
        v-if="editDialog.form"
        :model="editDialog.form"
        label-width="160px"
        ref="editForm"
        class="edit-form"
      >
        <el-form-item label="矿机型号">
          <el-input v-model.trim="editDialog.form.name" maxlength="60" />
        </el-form-item>
        <!-- 编辑：币种/算法/理论算力/单位（可增删，最多10行） -->
        <el-form-item label="币种/算法/算力/单位">
          <div class="coin-algo-rows">
            <div
              class="coin-algo-line"
              v-for="(row, idx) in editDialog.form.coinAndAlgoList"
              :key="'edit-ca-' + idx"
            >
              <el-input
                v-model="row.coin"
                placeholder="币种"
                class="coin-input"
                @input="editHandleCoinInput(idx)"
              />
              <el-input
                v-model="row.algorithm"
                placeholder="算法"
                class="algo-input"
                @input="editHandleAlgorithmInput(idx)"
              />
              <el-input
                v-model="row.theoryPower"
                placeholder="理论算力"
                inputmode="decimal"
                class="power-input"
                @input="editHandleRowTheoryInput(idx)"
              />
              <el-select
                v-model="row.unit"
                placeholder="单位"
                class="unit-select"
                @change="editHandleRowUnitChange(idx, $event)"
              >
                <el-option label="KH/S" value="KH/S" />
                <el-option label="MH/S" value="MH/S" />
                <el-option label="GH/S" value="GH/S" />
                <el-option label="TH/S" value="TH/S" />
                <el-option label="PH/S" value="PH/S" />
              </el-select>
              <el-button
                class="op-btn"
                type="primary"
                icon="el-icon-plus"
                circle
                @click="editHandleAddRow"
                :aria-label="'新增一行'"
              />
              <el-button
                v-if="(editDialog.form.coinAndAlgoList || []).length > 1"
                class="op-btn"
                icon="el-icon-minus"
                circle
                @click="editHandleRemoveRow(idx)"
                :aria-label="'删除该行'"
              />
            </div>
          </div>
        </el-form-item>
        <el-form-item label="最大租赁天数">
          <el-input
            v-model="editDialog.form.maxLeaseDays"
            placeholder="1-365"
            @input="editDialog.form.maxLeaseDays = (String(editDialog.form.maxLeaseDays||'').replace(/[^\d]/g,''))"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="状态" class="align-like-input">
          <el-radio-group v-model="editDialog.form.state">
            <el-radio :label="0">上架</el-radio>
            <el-radio :label="1">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="功耗(kw/h)">
          <el-input
            v-model="editDialog.form.powerDissipation"
            placeholder="功耗"
            @input="editDialog.form.powerDissipation = (String(editDialog.form.powerDissipation||'').replace(/[^\\d.]/g,''))"
            style="width: 200px"
          />
        </el-form-item>
        <!-- 理论算力与单位已合并到上方多行编辑 -->
        <el-form-item label="出售数量(台)">
          <el-input
            v-model="editDialog.form.saleNumbers"
            placeholder="整数"
            @input="editDialog.form.saleNumbers = (String(editDialog.form.saleNumbers||'').replace(/[^\d]/g,''))"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="售价（多币种）">
          <div class="gpu-price-row">
            <div
              v-for="(pl, idx) in editDialog.priceList"
              :key="'ep-' + idx"
              class="gpu-price-item"
            >
              <span class="gpu-price-label">{{ formatPayTypeHead(pl) }}</span>
              <el-input
                size="small"
                class="gpu-price-input"
                :value="pl.price"
                placeholder="价格"
                @input="handleEditPriceInput(idx, $event)"
              />
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="editDialog.saving" @click="handleSaveEdit">确认修改</el-button>
      </template>
    </el-dialog>
  </div>
  
</template>

<script>
/**
 * 商品列表管理页（账户侧）
 * - 表格展示，通过 getProductList 获取数据
 * - 支持查看详情、修改、删除
 */
import { updateProduct,deleteMachine, deleteProduct, getMachineInfo,getShopMachineListForSeller,getPayTypes, updateGpuMachine,updateAsicMachine} from '../../api/products'

// 本页用户偏好存储键：记住矿机种类（ASIC/GPU）
const MACHINE_TYPE_KEY = 'account_products_machine_type'

export default {
  name: 'AccountProducts',
  data() {
    return {
      loading: false,
      searchKeyword: '',
      tableData: [],
  
      payTypes: [],
      selectedPayKey: '',
      shopMachineList: [],
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      coinOptions: [],
      editDialog: {
        visible: false,
        saving: false,
        form: null,
        priceList: []
      },
      total: 0,
      userEmail:"",
      listParams:{
        type: 0,  // 0: ASIC, 1: GPU（默认 ASIC）
        pageNum: 1,
        pageSize: 10,
      
      },
      // GPU 编辑草稿：数组与映射
      updateArr: [],
      updateMap: {},
      unitCoin: ''

    }
  },
  created() {
    this.initOptions()
    // 读取上次选择（未选择则保持默认 ASIC=0）
    try {
      const saved = localStorage.getItem(MACHINE_TYPE_KEY)
      const t = saved != null ? parseInt(saved, 10) : null
      if (t === 0 || t === 1) {
        this.listParams.type = t
      }
    } catch (e) {}
    // 顺序请求，逻辑更简单：先列表，后支付方式
    this.fetchTableData()
    this.getPayTypesList().then(() => {
      if (!this.selectedPayKey && Array.isArray(this.payTypes) && this.payTypes.length) {
        this.selectedPayKey = this.buildPayKey(this.payTypes[0])
      }
    })
  },
  watch: {
    'listParams.type'(val) {
      // 类型切换时清理旧数据，避免残留
      this.shopMachineList = []
      this.updateMap = {}
      this.updateArr = []
      this.ensureGpuDraft()
    },
    payTypes: {
      handler() {
        this.ensureGpuDraft()
        this.computeUnitFromFirstRow()
      },
      deep: true
    },
    shopMachineList: {
      handler() {
        this.ensureGpuDraft()
        this.computeUnitFromFirstRow()
      },
      deep: true
    },
    selectedPayKey() {
      // 选择售价发生变化时，刷新单位：从首行价格推断
      this.computeUnitFromFirstRow()
    }
  },
  computed: {
    /** 搜索框占位文案：GPU 与 ASIC 区分 */
    searchPlaceholder() {
      return this.listParams.type === 1 ? '输入显卡型号搜索' : '输入币种或算法关键字后回车/搜索'
    },
    /** 表头展示用的币种单位（优先从选择的结算方式解析） */
    headerCoinSymbol() {
      // 1) 优先从 selectedPayKey 直接解析
      if (this.selectedPayKey) {
        const parts = String(this.selectedPayKey).split('|')
        const coin = (parts[1] || '').trim().toUpperCase()
        if (coin) return coin
      }
      // 2) 其次从支付方式的第一项取
      if (Array.isArray(this.payTypes) && this.payTypes.length) {
        const first = this.payTypes[0] || {}
        const coin = (first.payCoin || first.coin || '').toString().trim().toUpperCase()
        if (coin) return coin
      }
      // 3) 最后从首行价格列表取
      const rows = Array.isArray(this.shopMachineList) ? this.shopMachineList : []
      if (rows.length) {
        const list = Array.isArray(rows[0].priceList) ? rows[0].priceList : []
        if (list.length) {
          const first = list[0] || {}
          const coin = (first.coin || first.payCoin || '').toString().trim().toUpperCase()
          if (coin) return coin
        }
      }
      return ''
    }
  },
  methods: {
    /** 编辑弹窗：币种输入过滤（仅字母数字，转大写） */
    editHandleCoinInput(index) {
      const r = this.editDialog.form.coinAndAlgoList[index]
      let v = String(r.coin || '')
      v = v.replace(/[\u4e00-\u9fa5]/g, '').replace(/[^A-Za-z0-9]/g, '')
      this.$set(this.editDialog.form.coinAndAlgoList[index], 'coin', v.toUpperCase())
    },
    /** 编辑弹窗：算法输入过滤（仅字母数字和-，转大写） */
    editHandleAlgorithmInput(index) {
      const r = this.editDialog.form.coinAndAlgoList[index]
      let v = String(r.algorithm || '')
      v = v.replace(/[\u4e00-\u9fa5]/g, '').replace(/[^A-Za-z0-9-]/g, '')
      this.$set(this.editDialog.form.coinAndAlgoList[index], 'algorithm', v.toUpperCase())
    },
    /** 编辑弹窗：理论算力限制（6整数+4小数） */
    editHandleRowTheoryInput(index) {
      let v = String(this.editDialog.form.coinAndAlgoList[index].theoryPower ?? '')
      v = v.replace(/[^0-9.]/g, '')
      const firstDot = v.indexOf('.')
      if (firstDot !== -1) {
        v = v.slice(0, firstDot + 1) + v.slice(firstDot + 1).replace(/\./g, '')
      }
      const endsWithDot = v.endsWith('.')
      const parts = v.split('.')
      let intPart = parts[0] || ''
      let decPart = parts[1] || ''
      if (intPart.length > 6) intPart = intPart.slice(0, 6)
      if (decPart) decPart = decPart.slice(0, 4)
      v = decPart.length ? `${intPart}.${decPart}` : (endsWithDot ? `${intPart}.` : intPart)
      this.$set(this.editDialog.form.coinAndAlgoList[index], 'theoryPower', v)
    },
    /** 编辑弹窗：单位变更 */
    editHandleRowUnitChange(index, value) {
      this.$set(this.editDialog.form.coinAndAlgoList[index], 'unit', value)
    },
    /** 编辑弹窗：新增一行（最多10行） */
    editHandleAddRow() {
      const list = this.editDialog.form.coinAndAlgoList || []
      if (list.length >= 10) {
        this.$message.warning('最多添加 10 行')
        return
      }
      const last = list[list.length - 1] || { unit: 'TH/S' }
      list.push({ coin: '', algorithm: '', theoryPower: '', unit: last.unit || 'TH/S', coinAndPowerId: null })
      this.$set(this.editDialog.form, 'coinAndAlgoList', list)
    },
    /** 编辑弹窗：删除一行（至少保留1行） */
    editHandleRemoveRow(index) {
      const list = this.editDialog.form.coinAndAlgoList || []
      if (list.length <= 1) return
      list.splice(index, 1)
      this.$set(this.editDialog.form, 'coinAndAlgoList', list)
    },
    /** 行：币种（来自 coinAndAlgoList，去重后用中文逗号拼接；兜底 row.coin） */
    getRowCoinText(row) {
      try {
        const list = Array.isArray(row && row.coinAndAlgoList) ? row.coinAndAlgoList : []
        if (list.length) {
          const coins = list.map(i => String(i && i.coin ? i.coin : '').trim()).filter(Boolean)
          const uniq = Array.from(new Set(coins))
          if (uniq.length) return uniq.join('，')
        }
        const fallback = String(row && row.coin ? row.coin : '').trim()
        return fallback || '-'
      } catch (e) {
        return String(row && row.coin ? row.coin : '').trim() || '-'
      }
    },
    /** 行：算法（来自 coinAndAlgoList，去重后用中文逗号拼接；兜底 row.algorithm） */
    getRowAlgorithmText(row) {
      try {
        const list = Array.isArray(row && row.coinAndAlgoList) ? row.coinAndAlgoList : []
        if (list.length) {
          const algos = list.map(i => String(i && i.slogithm ? i.slogithm : (i && i.algorithm ? i.algorithm : '')).trim()).filter(Boolean)
          const uniq = Array.from(new Set(algos))
          if (uniq.length) return uniq.join('，')
        }
        const fallback = String(row && row.algorithm ? row.algorithm : '').trim()
        return fallback || '-'
      } catch (e) {
        return String(row && row.algorithm ? row.algorithm : '').trim() || '-'
      }
    },
    /** 从首行 priceList 推断表头单位（优先按 selectedPayKey 匹配） */
    computeUnitFromFirstRow() {
      try {
        const rows = Array.isArray(this.shopMachineList) ? this.shopMachineList : []
        if (!rows.length) { this.unitCoin = ''; return }
        const first = rows[0] || {}
        const list = Array.isArray(first.priceList) ? first.priceList : []
        if (!list.length) { this.unitCoin = ''; return }
        let selChain = '', selCoin = ''
        if (this.selectedPayKey) {
          const parts = String(this.selectedPayKey).split('|')
          selChain = (parts[0] || '').trim().toUpperCase()
          selCoin = (parts[1] || '').trim().toUpperCase()
        }
        let match = null
        if (selChain || selCoin) {
          match = list.find(p => {
            const c1 = String(p.chain || p.payChain || '').trim().toUpperCase()
            const c2 = String(p.coin || p.payCoin || '').trim().toUpperCase()
            return (!selChain || c1 === selChain) && (!selCoin || c2 === selCoin)
          }) || null
        }
        if (!match) match = list[0] || null
        const coin = match ? (match.coin || match.payCoin || '') : ''
        this.unitCoin = String(coin || '').trim().toUpperCase()
      } catch (e) {
        this.unitCoin = ''
      }
    },
    /** 生成 payKey: CHAIN|COIN */
    buildPayKey(pt) {
      const chain = (pt && (pt.payChain || pt.chain) ? String(pt.payChain || pt.chain) : '').trim().toUpperCase()
      const coin = (pt && (pt.payCoin || pt.coin) ? String(pt.payCoin || pt.coin) : '').trim().toUpperCase()
      return [chain, coin].filter(Boolean).join('|')
    },
    /** 选择结算方式变化（无需额外处理，价格随 selectedPayKey 自动变化） */
    handlePayTypeChange() {},
    /** 通过 key 找到支付方式对象 */
    getPayTypeByKey(key) {
      try {
        if (!key) return null
        const parts = String(key).split('|')
        const chain = (parts[0] || '').trim().toUpperCase()
        const coin = (parts[1] || '').trim().toUpperCase()
        return (this.payTypes || []).find(pt =>
          String(pt.payChain || pt.chain || '').trim().toUpperCase() === chain &&
          String(pt.payCoin || pt.coin || '').trim().toUpperCase() === coin
        ) || null
      } catch (e) {
        return null
      }
    },
    /** 当前选择的支付方式图标 */
    getSelectedPayImage() {
      const obj = this.getPayTypeByKey(this.selectedPayKey)
      if (!obj) return ''
      const img = obj.payCoinImage || obj.image || ''
      return String(img || '').trim()
    },
    /** 当前选择的币种符号 */
    getSelectedCoinSymbol() {
      try {
        const obj = this.getPayTypeByKey(this.selectedPayKey)
        if (obj) {
          const coin = obj.payCoin || obj.coin || ''
          return String(coin || '').trim().toUpperCase()
        }
        // 兜底：直接从 selectedPayKey 解析
        if (this.selectedPayKey) {
          const parts = String(this.selectedPayKey).split('|')
          const coin = (parts[1] || '').trim().toUpperCase()
          if (coin) return coin
        }
        // 再兜底：默认取第一个支付方式
        if (Array.isArray(this.payTypes) && this.payTypes.length) {
          const first = this.payTypes[0]
          const coin = first && (first.payCoin || first.coin)
          return String(coin || '').trim().toUpperCase()
        }
        return ''
      } catch (e) {
        return ''
      }
    },
    /** 根据当前选择的结算方式，获取行的对应价格 */
    getRowPriceBySelected(row) {
      try {
        const list = Array.isArray(row && row.priceList) ? row.priceList : []
        if (!list.length) return '-'
        let chain = ''
        let coin = ''
        if (this.selectedPayKey) {
          const parts = String(this.selectedPayKey).split('|')
          chain = (parts[0] || '').toUpperCase()
          coin = (parts[1] || '').toUpperCase()
        }
        // 若未选择，则默认用第一个
        if (!chain && !coin) {
          const first = list[0] || {}
          const p = first && first.price != null ? String(first.price) : ''
          return p || '-'
        }
        const hit = list.find(p => {
          const c1 = String(p.chain || p.payChain || '').toUpperCase()
          const c2 = String(p.coin || p.payCoin || '').toUpperCase()
          return c1 === chain && c2 === coin
        })
        if (hit && hit.price != null) return String(hit.price)
        return '-'
      } catch (e) {
        return '-'
      }
    },
    /** 行内文案：价格 后跟 币种单位（来自行的 priceList；优先匹配已选结算方式，其次取首个） */
    getRowPriceText(row) {
      try {
        const list = Array.isArray(row && row.priceList) ? row.priceList : []
        if (!list.length) return '-'
        let selChain = '', selCoin = ''
        if (this.selectedPayKey) {
          const parts = String(this.selectedPayKey).split('|')
          selChain = (parts[0] || '').trim().toUpperCase()
          selCoin = (parts[1] || '').trim().toUpperCase()
        }
        let item = null
        if (selChain || selCoin) {
          item = list.find(p => {
            const c1 = String(p.chain || p.payChain || '').trim().toUpperCase()
            const c2 = String(p.coin || p.payCoin || '').trim().toUpperCase()
            return (!selChain || c1 === selChain) && (!selCoin || c2 === selCoin)
          }) || null
        }
        if (!item) item = list[0] || null
        if (!item) return '-'
        const price = item.price != null ? String(item.price) : ''
        const coin = (item.coin || item.payCoin || '').toString().trim().toUpperCase()
        if (!price) return '-'
        return coin ? `${price} ${coin}` : price
      } catch (e) {
        return '-'
      }
    },
    /** 取 ASIC 行的首个价格文本 */
    getFirstPriceText(row) {
      try {
        const list = Array.isArray(row && row.priceList) ? row.priceList : []
        if (!list.length) return '-'
        const first = list[0] || {}
        const price = first.price != null ? first.price : (first.amount != null ? first.amount : '')
        if (price === '' || price == null) return '-'
        return String(price)
      } catch (e) {
        return '-'
      }
    },
    /** 展示理论算力（来自 coinAndAlgoList：每项“值 单位”，多项以中文逗号拼接；兜底 row.theoryPower + row.unit） */
    getTheoryText(row) {
      try {
        const list = Array.isArray(row && row.coinAndAlgoList) ? row.coinAndAlgoList : []
        if (list.length) {
          const parts = list.map(i => {
            const power = (i && i.theoryPower != null) ? String(i.theoryPower) : ''
            const unit = (i && (i.unit || i.Unit)) ? String(i.unit || i.Unit).trim().toUpperCase() : ''
            const text = power ? (unit ? `${power} ${unit}` : power) : ''
            return text
          }).filter(Boolean)
          if (parts.length) return parts.join('， ')
        }
        const val = row && row.theoryPower != null ? String(row.theoryPower) : ''
        if (!val) return '-'
        const unit = (row && row.unit ? String(row.unit) : '').trim().toUpperCase()
        return unit ? `${val} ${unit}` : val
      } catch (e) {
        const val = row && row.theoryPower != null ? String(row.theoryPower) : ''
        if (!val) return '-'
        const unit = (row && row.unit ? String(row.unit) : '').trim().toUpperCase()
        return unit ? `${val} ${unit}` : val
      }
    },
    /** 展示功耗（kw/h） */
    getPowerDissText(row) {
      const val = row && row.powerDissipation != null ? String(row.powerDissipation) : ''
      return val ? val : '-'
    },
    /** 统一取得行唯一ID（兼容多字段） */
    getRowId(row) {
      if (!row) return undefined
      if (row.id != null) return row.id
      if (row.productMachineId != null) return row.productMachineId
      if (row.produceMachineId != null) return row.produceMachineId
      if (row.machineId != null) return row.machineId
      if (row.__key != null) return row.__key
      return undefined
    },
    /** 提交 GPU 更新 */
    async updateGpuMachineInfo(params) {
      const res = await updateGpuMachine(params)
      if (res && (res.code === 0 || res.code === 200)) {
        this.$message.success('更新成功')
        await this.fetchTableData()
      }
    },
    async getPayTypesList() {
      const res = await getPayTypes()
      if (res && (res.code === 0 || res.code === 200)) {
        const list = Array.isArray(res.data) ? res.data : []
        this.payTypes = list
        // 初始化默认选择（若未选择）
        if (!this.selectedPayKey && this.payTypes.length) {
          this.selectedPayKey = this.buildPayKey(this.payTypes[0])
        }
      }
    },
    //获取店铺机器列表
    async fetchShopMachineListForSeller(params) {
      const res = await getShopMachineListForSeller(params)
      console.log(res,'res');
      
      if (res && (res.code === 0 || res.code === 200)) {
        this.shopMachineList = Array.isArray(res.rows) ? res.rows : []
        this.total = Number(res.total || (res.data && res.data.total) || (res.data && res.data.totalCount) || 0)
        // 立即同步生成/合并 GPU 草稿，避免首屏不展示
        this.ensureGpuDraft()
        // 同步根据首行价格推断单位
        this.computeUnitFromFirstRow()
      }
    },
    /** 切换矿机种类 */
    handleTypeChange(val) {
      // 列表联动
      this.pagination.pageNum = 1
      this.listParams.type = val
      this.listParams.pageNum = 1
      this.listParams.keyword = (this.searchKeyword || '').trim() || undefined
      // 持久化用户选择
      try { localStorage.setItem(MACHINE_TYPE_KEY, String(val)) } catch (e) {}
      // 清理旧状态，防闪烁与残留
      this.shopMachineList = []
      this.updateMap = {}
      this.updateArr = []
      this.fetchTableData()
    },
    /** 保障 GPU 草稿存在且与当前数据一致 */
    ensureGpuDraft() {
      if (this.listParams.type !== 1) return
      if (!Array.isArray(this.shopMachineList) || !this.shopMachineList.length) return
      if (!Array.isArray(this.payTypes) || !this.payTypes.length) return
      const nextMap = {}
      const template = this.payTypes.map(pt => ({
        chain: (pt.payChain || pt.chain || '').toString(),
        coin: (pt.payCoin || pt.coin || '').toString()
      }))
      const normalizePriceList = (sourceList = [], prevList = []) => {
        return template.map(t => {
          const fromSource = (Array.isArray(sourceList) ? sourceList : []).find(p => p.chain === t.chain && p.coin === t.coin)
          const fromPrev = (Array.isArray(prevList) ? prevList : []).find(p => p.chain === t.chain && p.coin === t.coin)
          return {
            chain: t.chain,
            coin: t.coin,
            price: fromSource ? (fromSource.price ?? '') : (fromPrev ? (fromPrev.price ?? '') : ''),
            payTypeId: fromSource ? (fromSource.payTypeId ?? '') : (fromPrev ? (fromPrev.payTypeId ?? '') : '')
          }
        })
      }
      this.shopMachineList.forEach((m, idx) => {
        let key = this.getRowId(m)
        if (key == null) {
          // 兜底：构造一个稳定 key 并写回行对象
          key = `k_${idx}_${m && (m.name || m.miner || '')}`
          this.$set(m, '__key', key)
        }
        const exist = this.updateMap[key]
        if (exist) {
          const merged = { ...exist }
          // 覆盖为后端最新状态/天数（若存在）
          if (m && typeof m.maxLeaseDays !== 'undefined') merged.maxLeaseDays = m.maxLeaseDays
          // 如果接口有返回 state，使用接口返回的值；否则保持现有值
          if (m && (m.state === 0 || m.state === 1)) {
            merged.state = m.state
          } else {
            // 如果接口没有返回 state，默认下架（state = 1）
            merged.state = 1
          }
          // 保存 effect 字段（从原始数据获取）
          if (m && (m.effect === 0 || m.effect === 1)) {
            merged.effect = m.effect
          } else if (merged.effect === undefined) {
            // 如果原始数据没有 effect，默认设为 1（能上架）
            merged.effect = 1
          }
          merged.priceList = normalizePriceList(m && m.priceList, exist.priceList)
          nextMap[key] = merged
        } else {
          // 如果接口没有返回 state，默认下架（state = 1）
          const defaultState = (m && (m.state === 0 || m.state === 1)) ? m.state : 1
          nextMap[key] = {
            id: key,
            maxLeaseDays: (m && typeof m.maxLeaseDays !== 'undefined') ? m.maxLeaseDays : '',
            priceList: normalizePriceList(m && m.priceList, []),
            state: defaultState,
            effect: (m && (m.effect === 0 || m.effect === 1)) ? m.effect : 1 // 保存 effect 字段，默认1（能上架）
          }
        }
      })
      this.updateMap = nextMap
      this.updateArr = Object.values(this.updateMap)
    },
    /** 获取价格值（表格渲染） */
    getPriceValue(rowId, pt) {
      const item = this.updateMap[rowId]
      if (!item || !Array.isArray(item.priceList)) return ''
      const chain = (pt.payChain || pt.chain || '').toString()
      const coin = (pt.payCoin || pt.coin || '').toString()
      const obj = item.priceList.find(p => p.chain === chain && p.coin === coin)
      return obj ? obj.price : ''
    },
    /** 确保有价格对象 */
    ensurePriceObj(rowId, chain, coin) {
      const item = this.updateMap[rowId]
      if (!item) return null
      let target = item.priceList.find(p => p.chain === chain && p.coin === coin)
      if (!target) {
        target = { chain, coin, price: '', payTypeId: '' }
        item.priceList.push(target)
      }
      return target
    },
    /** 规范化 GPU 价格输入：整数最多10位，最多6位小数；移除多余前导0；仅保留首个小数点 */
    normalizeGpuPrice(val, isBlur = false) {
      if (val == null) return ''
      let v = String(val).replace(/[^\d.]/g, '')
      // 仅保留一个小数点
      const firstDot = v.indexOf('.')
      if (firstDot !== -1) {
        // 移除后续的所有点
        v = v.slice(0, firstDot + 1) + v.slice(firstDot + 1).replace(/\./g, '')
      }
      const hasDot = firstDot !== -1
      const trailingDot = hasDot && v.endsWith('.')
      // 拆分整数/小数
      let [intPart, decPart = ''] = v.split('.')
      // 移除整数前导零（保留单个0用于 0.xxx 场景）
      if (intPart.length > 1) intPart = intPart.replace(/^0+/, '')
      if (intPart === '') intPart = '0'
      // 限制整数最多10位
      if (intPart.length > 10) intPart = intPart.slice(0, 10)
      // 限制小数最多6位
      if (decPart.length > 6) decPart = decPart.slice(0, 6)
      // 组装
      let out
      if (hasDot) {
        if (decPart) {
          out = `${intPart}.${decPart}`
        } else {
          // 输入中保留尾随小数点，便于继续输入
          out = isBlur ? intPart : `${intPart}.`
        }
      } else {
        out = intPart
      }
      if (isBlur) {
        const n = Number(out)
        // 必须大于0
        if (!(Number.isFinite(n) && n > 0)) return ''
        // 不能是以0开头的整数（多位）
        if (!decPart && String(intPart).length > 1 && String(intPart).startsWith('0')) {
          const fixedInt = String(intPart).replace(/^0+/, '') || '0'
          out = fixedInt
        }
      }
      return out
    },
    /** 输入 - 售价（GPU） */
    handlePriceInput(row, pt, val) {
      const rowId = this.getRowId(row) || row.__key
      const chain = (pt.payChain || pt.chain || '').toString()
      const coin = (pt.payCoin || pt.coin || '').toString()
      const price = this.normalizeGpuPrice(val, false)
      const obj = this.ensurePriceObj(rowId, chain, coin)
      if (obj) obj.price = price
      this.updateArr = Object.values(this.updateMap)
    },
    /** 失焦 - 售价（GPU）严格校验（@blur 无值参数，这里从已存储的 price 读取） */
    handlePriceBlur(row, pt) {
      const rowId = this.getRowId(row) || row.__key
      const chain = (pt.payChain || pt.chain || '').toString()
      const coin = (pt.payCoin || pt.coin || '').toString()
      const obj = this.ensurePriceObj(rowId, chain, coin)
      const current = obj ? obj.price : ''
      const normalized = this.normalizeGpuPrice(current, true)
      if (obj) obj.price = normalized
      if (normalized === '') {
        this.$message.warning('价格需为>0，整数最多10位，小数最多6位，且整数部分不可以0开头')
      }
      this.updateArr = Object.values(this.updateMap)
    },
    /** 输入 - 最大租赁天数（仅整数 1-365） */
    handleMaxLeaseDaysInput(row, val) {
      const rowId = this.getRowId(row) || row.__key
      const v = String(val || '').replace(/[^\d]/g, '')
      let num = v ? parseInt(v, 10) : ''
      if (typeof num === 'number' && !Number.isNaN(num)) {
        if (num < 1) num = 1
        if (num > 365) num = 365
      }
      if (this.updateMap[rowId]) this.updateMap[rowId].maxLeaseDays = num
      this.updateArr = Object.values(this.updateMap)
    },
    /** 切换状态（0 上架 1 下架） */
    handleToggleState(row, val) {
      const rowId = this.getRowId(row) || row.__key
      // 如果要上架（val === 0），需要检查 effect 字段
      if (val === 0) {
        // 从原始数据或 updateMap 中获取 effect 字段
        let effect = 1 // 默认能上架
        if (row && (row.effect === 0 || row.effect === 1)) {
          effect = row.effect
        } else if (this.updateMap[rowId] && (this.updateMap[rowId].effect === 0 || this.updateMap[rowId].effect === 1)) {
          effect = this.updateMap[rowId].effect
        }
        
        if (effect === 0) {
          // effect = 0 表示不能上架，提示用户
          this.$message.warning('本网站暂时不支持该矿机币种及算法，暂时不能上架！')
          // 恢复为下架状态
          if (this.updateMap[rowId]) {
            this.updateMap[rowId].state = 1
          }
          this.updateArr = Object.values(this.updateMap)
          return
        }
      }
      // 允许切换状态
      if (this.updateMap[rowId]) {
        this.updateMap[rowId].state = val
        // 确保 effect 字段被保存（从原始数据获取）
        if (row && (row.effect === 0 || row.effect === 1)) {
          this.updateMap[rowId].effect = row.effect
        }
      }
      this.updateArr = Object.values(this.updateMap)
    },
    /** 提交 GPU 更新（触发按钮） */
    handleUpdateGpu() {
      if (this.listParams.type !== 1) return
      const payload = Object.values(this.updateMap).map(it => ({
        id: it.id,
        maxLeaseDays: it.maxLeaseDays,
        priceList: Array.isArray(it.priceList)
          ? it.priceList.map(p => ({
              chain: p.chain,
              coin: p.coin,
              price: p.price,
              payTypeId: p.payTypeId || ''
            }))
          : [],
        state: it.state
      }))
      // 校验：售价不能为空（需覆盖所有支付方式）
      const expectedPriceCount = Array.isArray(this.payTypes) ? this.payTypes.length : 0
      if (expectedPriceCount > 0) {
        const priceMissing = payload.some(it => {
          if (!Array.isArray(it.priceList) || it.priceList.length !== expectedPriceCount) return true
          return it.priceList.some(p => {
            const v = (p && p.price != null) ? String(p.price).trim() : ''
            if (v === '') return true
            const norm = this.normalizeGpuPrice(v, true)
            return norm === ''
          })
        })
        if (priceMissing) {
          this.$message.warning('请填写合法售价（>0，整数最多10位，小数最多6位，且每种支付方式均需填写）')
          return
        }
      }
      const invalid = payload.some(it => !(Number.isInteger(it.maxLeaseDays) && it.maxLeaseDays >= 1 && it.maxLeaseDays <= 365))
      if (invalid) {
        this.$message.warning('请检查最大租赁天数（1-365天的整数）')
        return
      }
      this.updateGpuMachineInfo(payload)
    },
    /** 格式化支持结算币种的展示，如 TRON-USDT */
    formatPayType(item) {
      try {
        const chain = (item && item.chain ? String(item.chain) : '').toUpperCase()
        const coin = (item && item.coin ? String(item.coin) : '').toUpperCase()
        if (chain && coin) return `${chain}-${coin}`
        return chain || coin || ''
      } catch (e) {
        return ''
      }
    },
    /** 顶部结算方式格式：兼容 payChain/payCoin */
    formatPayTypeHead(item) {
      try {
        const chain = (item && (item.payChain || item.chain) ? String(item.payChain || item.chain) : '').toUpperCase()
        const coin = (item && (item.payCoin || item.coin) ? String(item.payCoin || item.coin) : '').toUpperCase()
        if (chain && coin) return `${chain}-${coin}`
        return chain || coin || ''
      } catch (e) {
        return ''
      }
    },
    getPayImage(item) {
      const img = item && (item.payCoinImage || item.image) ? String(item.payCoinImage || item.image) : ''
      return img.trim()
    },
    /** 初始化筛选选项 */
    initOptions() {
      try {
        // 动态导入，避免打包时循环引用
        const { coinList } = require('../../utils/coinList')
        this.coinOptions = Array.isArray(coinList) ? coinList : []
      } catch (e) {
        this.coinOptions = []
      }
    },
   async fetchMachineInfo(params) {
      const res = await getMachineInfo(params)
      if (res && (res.code === 0 || res.code === 200)) {
        this.editDialog.form = res.data
        console.log(res.data,'res.data');
        
      }
    },
    /**
     * 获取商品表格数据
     */
    async fetchTableData() {
      this.loading = true
      try {
        // 统一使用卖家矿机列表接口，参数仅来自 this.listParams
        await this.fetchShopMachineListForSeller(this.listParams)
        } catch (error) {
        console.error('获取列表失败', error)
      } finally {
        this.loading = false
      }
    },

    /** 搜索 */
    handleSearch() {
      this.pagination.pageNum = 1
      this.listParams.pageNum = 1
      this.listParams.keyword = (this.searchKeyword || '').trim() || undefined
      this.fetchTableData()
    },

    /** 重置 */
    handleReset() {
      this.searchKeyword = ''
      this.pagination.pageNum = 1
      this.pagination.pageSize = 10
      this.listParams = { type: this.listParams.type, pageNum: 1, pageSize: 10, keyword: undefined }
      this.fetchTableData()
    },



    /** 查看详情 */
    handleView(row) {
      if (!row || !row.id) {
        this.$message({
          message: '缺少商品ID',
          type: 'warning',
          showClose: true
        })
        return
      }
      this.$router.push(`/account/product-detail/${row.id}`)
    },

    /** 编辑 */
    handleEdit(row) {
      // coinAndAlgoList：从后端 coinAndAlgoList 转换；若没有则用旧字段构造单行
      const srcList = Array.isArray(row.coinAndAlgoList) ? row.coinAndAlgoList : []
      const coinAndAlgoList = srcList.length
        ? srcList.map(it => ({
            coin: String(it && (it.coin || '')).trim(),
            algorithm: String(it && (it.slogithm || it.algorithm || '')).trim(),
            theoryPower: (it && it.theoryPower != null) ? String(it.theoryPower) : '',
            unit: String(it && (it.unit || '')).trim() || 'TH/S',
            coinAndPowerId: it && (it.coinAndPowerId != null) ? it.coinAndPowerId : null
          }))
        : [{
            coin: String(row.coin || '').trim(),
            algorithm: String(row.algorithm || '').trim(),
            theoryPower: (row && row.theoryPower != null) ? String(row.theoryPower) : '',
            unit: String(row.unit || 'TH/S').trim(),
            coinAndPowerId: null
          }]
      const form = {
        id: row.id,
        name: row.name || '',
        coinAndAlgoList,
        maxLeaseDays: row.maxLeaseDays || '',
        powerDissipation: row.powerDissipation || row.powerDissipation || '',
        saleNumbers: row.saleNumbers || '',
        state: (row && (row.state === 0 || row.state === 1)) ? row.state : 0
      }
      // 构建可编辑的价格列表：以支持的支付方式为模板
      const priceSrc = Array.isArray(row.priceList) ? row.priceList : []
      const template = (this.payTypes || []).map(pt => ({
        chain: (pt.payChain || pt.chain || '').toString(),
        coin: (pt.payCoin || pt.coin || '').toString(),
        payTypeId: pt.payTypeId || pt.id || 0
      }))
      this.editDialog.priceList = template.map(t => {
        const hit = priceSrc.find(p =>
          String(p.chain || p.payChain || '') === t.chain &&
          String(p.coin || p.payCoin || '') === t.coin
        )
        return {
          chain: t.chain,
          coin: t.coin,
          price: hit ? (hit.price ?? '') : '',
          payTypeId: hit ? (hit.payTypeId ?? t.payTypeId ?? 0) : (t.payTypeId ?? 0),
          productMachineId: row.productMachineId || row.id || 0
        }
      })
      this.editDialog.form = form
      this.editDialog.visible = true
    },

    /** 保存编辑 */
    handleEditPriceInput(idx, val) {
      const v = String(val || '').replace(/[^\d.]/g, '')
      if (this.editDialog.priceList && this.editDialog.priceList[idx]) {
        this.$set(this.editDialog.priceList[idx], 'price', v)
      }
    },
    async handleSaveEdit() {
      if (!this.editDialog.form) return
      const f = this.editDialog.form
      // 基础校验
      if (!String(f.name || '').trim()) { this.$message.warning('矿机型号不能为空'); return }
      // 校验 coinAndAlgoList
      const list = Array.isArray(f.coinAndAlgoList) ? f.coinAndAlgoList : []
      if (!list.length) { this.$message.warning('请至少添加一行币种/算法/算力/单位'); return }
      const coinPattern = /^[A-Za-z0-9]{1,10}$/
      const algoPattern = /^[A-Za-z0-9-]{2,20}$/
      const powerPattern = /^\d{1,6}(\.\d{1,4})?$/
      for (let i = 0; i < list.length; i += 1) {
        const r = list[i] || {}
        const coin = String(r.coin || '').trim()
        const algo = String(r.algorithm || '').trim()
        const power = String(r.theoryPower || '').trim()
        const unit = String(r.unit || '').trim()
        if (!coin) { this.$message.warning(`第 ${i + 1} 行：请输入币种`); return }
        if (!coinPattern.test(coin)) { this.$message.warning(`第 ${i + 1} 行：币种仅允许字母或数字，1-10 位`); return }
        if (!algo) { this.$message.warning(`第 ${i + 1} 行：请输入算法`); return }
        if (!algoPattern.test(algo)) { this.$message.warning(`第 ${i + 1} 行：算法仅允许字母/数字/“-”，2-20 位`); return }
        if (!power || !powerPattern.test(power) || Number(power) <= 0) {
          this.$message.warning(`第 ${i + 1} 行：理论算力需大于0，整数最多6位，小数最多4位`); return
        }
        if (!unit) { this.$message.warning(`第 ${i + 1} 行：请选择算力单位`); return }
      }
      const days = parseInt(String(f.maxLeaseDays || '').replace(/[^\d]/g, ''), 10)
      if (!(Number.isInteger(days) && days >= 1 && days <= 365)) { this.$message.warning('最大租赁天数需为1-365的整数'); return }
      const sale = parseInt(String(f.saleNumbers || '').replace(/[^\d]/g, ''), 10)
      if (!Number.isInteger(sale) || sale < 0) { this.$message.warning('出售数量应为非负整数'); return }
      const payload = {
        id: f.id,
        coinAndAlgoList: (f.coinAndAlgoList || []).map(it => ({
          coin: String(it.coin || '').trim().toUpperCase(),
          algorithm: String(it.algorithm || '').trim().toUpperCase(),
          theoryPower: Number(it.theoryPower) || 0,
          unit: it.unit,
          coinAndPowerId: it.coinAndPowerId || null
        })),
        maxLeaseDays: days,
        name: String(f.name || '').trim(),
        powerDissipation: Number(String(f.powerDissipation || '0').replace(/[^\d.]/g, '')) || 0,
        priceList: (this.editDialog.priceList || []).map(p => ({
          chain: p.chain,
          coin: p.coin,
          payTypeId: p.payTypeId || 0,
          price: Number(String(p.price || '0').replace(/[^\d.]/g, '')) || 0,
          productMachineId: p.productMachineId || f.id || 0
        })),
        saleNumbers: sale,
        state: (f && (f.credentials ? f.state : f.state)) ?? 0
      }
      // 价格至少有一个填写
      const hasAnyPrice = Array.isArray(payload.priceList) && payload.priceList.some(i => i.price > 0)
      if (!hasAnyPrice) { this.$message.warning('请至少填写一种支付方式的售价'); return }
      this.editDialog.saving = true
      try {
        const res = await updateAsicMachine(payload)
        if (res && (res.code === 0 || res.code === 200)) {
          this.$message.success('修改成功')
          this.editDialog.visible = false
          await this.fetchTableData()
        } else {
          this.$message.error(res?.msg || '修改失败')
        }
      } catch (error) {
        console.error('更新失败', error)
        this.$message.error('修改失败')
      } finally {
        this.editDialog.saving = false
      }
    },

    /** 删除 */
    handleDelete(row) {
      if (!row) return
      const id = this.getRowId(row) || row.id
      if (id == null || id === '') {
        this.$message.warning('缺少可删除的ID')
        return
      }
      this.$confirm('确认删除该商品吗？删除后不可恢复', '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await deleteMachine({ id })
          if (res && (res.code === 0 || res.code === 200)) {
            this.$message.success('删除成功')
            // 若当前页仅一条且删除后为空，回退一页
            if (this.tableData.length === 1 && this.pagination.pageNum > 1) {
              this.pagination.pageNum -= 1
            }
            this.fetchTableData()
          } 
        } catch (error) {
          console.error('删除商品失败', error)
          console.log('删除失败')
        }
      }).catch(() => {})
    },

    /** 分页 - 每页条数变化 */
    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.pagination.pageNum = 1
      this.listParams.pageSize = size
      this.listParams.pageNum = 1
      this.fetchTableData()
    },

    /** 分页 - 当前页变化 */
    handleCurrentChange(page) {
      this.pagination.pageNum = page
      this.listParams.pageNum = page
      this.fetchTableData()
    },

    /** 清空搜索框时恢复默认列表 */
    handleClear() {
      this.searchKeyword = ''
      this.pagination.pageNum = 1
      this.listParams.pageNum = 1
      this.listParams.keyword = undefined
      this.fetchTableData()
    },

    /** 跳转添加出售机器 */
    handleAddMachine(row) {
      if (!row || !row.id) {
        this.$message.warning('缺少商品ID')
        return
      }
      let payTypesParam = ''
      try {
        const pts = Array.isArray(row.payTypes) ? row.payTypes : []
        payTypesParam = encodeURIComponent(JSON.stringify(pts))
      } catch (e) {
        payTypesParam = ''
      }
      this.$router.push({
        path: '/account/product-machine-add',
        query: {
          productId: row.id,
          coin: row.coin,
          name: row.name,
          payTypes: payTypesParam
        }
      })
    }
  }
}
</script>

<style scoped>
.account-products {
  padding: 4px;
}
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.left-area {
  display: flex;
  align-items: center;
}
.right-area {
  display: flex;
  align-items: center;
}
.paytypes-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #f5f7fa;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  padding: 8px 12px;
  margin-bottom: 8px;
}
.pt-label {
  color: #666;
  margin-right: 6px;
  font-size: 12px;
}
.pt-icons {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}
.page-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}
.mr-12 { margin-right: 12px; }
.ml-8 { margin-left: 8px; }

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}

/* 编辑弹窗内：让下拉/单选与输入框左边缘对齐 */
.edit-form .align-like-input .el-form-item__content {
  padding-left: 12px; /* 对齐到上方 el-input 的内边距视觉效果 */
}

/* 编辑弹窗：左侧标签不换行（长文本保持单行，可溢出隐藏省略） */
.edit-form :deep(.el-form-item__label) {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

::v-deep .el-form-item__content{
   text-align: left;
}

/* 支持结算币种的小图标样式 */
.paytypes { display: inline-flex; align-items: center; gap: 8px; }
.paytype-icon { width: 22px; height: 22px; border-radius: 4px; display: inline-block; }

.gpu-price-row {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr)); /* 两列并排，减少单元格高度 */
  gap: 10px 16px;
}
.gpu-price-item {
  display: grid;
  grid-template-columns: 100px 1fr; /* 左侧标签固定宽度，右侧输入自适应 */
  align-items: center;
}
.gpu-price-label {
  color: #666;
  white-space: nowrap;
  text-align: right;
  padding-right: 8px;
}
.gpu-price-input {
  width: 100%;
}
.gpu-state {
  display: inline-flex;
  align-items: center;
  gap: 8px;
}
.gpu-state-text {
  color: #909399;
  user-select: none;
}
.gpu-state-text.on {
  color: #67C23A;
  font-weight: 600;
}

/* 售价高亮（加粗标红） */
.price-strong {
  color: #f56c6c;
  font-weight: 700;
}

/* 表格单元格文本溢出省略，hover 显示完整（依赖列的 show-overflow-tooltip） */
.ellipsis-cell {
  display: block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 编辑弹窗：币种/算法/算力/单位 多行布局 */
.coin-algo-rows { display: grid; gap: 8px; width: 100%; }
.coin-algo-line { display: flex; align-items: center; gap: 8px; }
.coin-algo-line .coin-input { width: 18%; min-width: 140px; }
.coin-algo-line .algo-input { width: 24%; min-width: 160px; }
.coin-algo-line .power-input { width: 20%; min-width: 140px; }
.coin-algo-line .unit-select { width: 16%; min-width: 120px; }
.coin-algo-line .op-btn { flex: 0 0 auto; }

::v-deep .el-input__prefix, .el-input__suffix{
  top:24%;
}

::v-deep .el-input--mini .el-input__icon{
  line-height: 0px;
}

</style>

