<template>
  <div class="credit-card-equity">
    <el-card>
      <template #header>
        <div class="search-section">
        <div class="search-row">
          <el-form :model="searchForm" label-width="80px" inline>
            <el-form-item label="权益名称:">
              <el-input v-model="searchForm.equityName" placeholder="请输入" style="width: 150px"></el-input>
            </el-form-item>
            <div class="button-group" style="margin-left: 20px;">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </div>
          </el-form>
        </div>
        </div>
      </template>

      <el-table :data="filteredTableData" stripe style="width: 100%">
        <el-table-column label="操作" width="280" fixed="left">
          <template #default="scope">
            <div class="row-actions">
              <el-popover
                placement="bottom"
                trigger="click"
                width="240"
                @show="onAdjustOrderShow(scope.$index)"
                :ref="`adjustPopover-${scope.$index}`"
              >
                <div class="adjust-order-form">
                  <div class="adjust-order-title">调整显示顺序</div>
                  <div class="adjust-order-tip">移动端权益首页和列表页按照该顺序展示</div>
                  <div class="adjust-order-input">
                    <span>调整到第</span>
                    <el-input-number
                      v-model.number="adjustOrderPosition"
                      :min="1"
                      :max="tableData.length"
                      size="small"
                      :controls="false"
                      style="width: 70px;margin: 0 6px;"
                    />
                    <span>位</span>
                  </div>
                  <div class="adjust-order-actions">
                    <el-button size="small" @click="closeAdjustOrder(scope.$index)">取消</el-button>
                    <el-button size="small" type="primary" @click="confirmAdjustOrder(scope.$index)">确定</el-button>
                  </div>
                </div>
                <template #reference>
                  <el-button v-if="scope.row.shelfStatus === '已上架'" type="text" size="small">调整显示顺序</el-button>
                </template>
              </el-popover>
              <el-button type="text" size="small" @click="openShowPagesDialog(scope.row)">设置显示页面</el-button>
              <el-popover
                placement="bottom"
                trigger="click"
                :ref="`morePopover-${scope.$index}`"
              >
                <div class="more-actions-menu">
                  <div
                    v-if="scope.row.shelfStatus === '已上架'"
                    class="more-actions-item"
                    @click="openLinkDialogFromMore(scope.row, scope.$index)"
                  >生成链接</div>
                </div>
                <template #reference>
                  <el-button type="text" size="small"><el-icon><More /></el-icon></el-button>
                </template>
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="equityName" label="权益名称" min-width="220" show-overflow-tooltip></el-table-column>
        <el-table-column label="显示页面" min-width="240">
          <template #default="scope">
            <template v-if="visiblePages(scope.row).length">
              <el-tag
                v-for="page in visiblePages(scope.row)"
                :key="page"
                size="small"
                style="margin-right: 4px;"
              >{{ page }}</el-tag>
            </template>
            <span v-else class="empty-text">-</span>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-section">
        <span>Total {{ filteredTableData.length }}</span>
        <el-pagination
          layout="prev, pager, next, sizes, jumper"
          :page-size="10"
          :page-sizes="[10, 20, 50]"
          :total="filteredTableData.length"
        ></el-pagination>
      </div>
    </el-card>

    <show-pages-dialog
      v-model="showPagesDialogVisible"
      :row="showPagesRow"
      @confirm="onShowPagesConfirm"
    ></show-pages-dialog>

    <equity-link-dialog
      v-model="linkDialogVisible"
      :id="linkTargetId"
      path-name="equity/credit"
      title="生成信用卡权益链接"
    ></equity-link-dialog>
  </div>
</template>

<script>
import ShowPagesDialog from '@/components/ShowPagesDialog.vue'
import EquityLinkDialog from '@/components/EquityLinkDialog.vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'CreditCardEquity',
  components: { ShowPagesDialog, EquityLinkDialog },
  data() {
    return {
      searchForm: {
        equityName: ''
      },
      showPagesDialogVisible: false,
      showPagesRow: null,
      linkDialogVisible: false,
      linkTargetId: '',
      adjustOrderPosition: 1,
      tableData: [
        {
          equityName: '白金卡机场贵宾厅',
          productId: 'CC001',
          skuNo: 'CCSKU001',
          merchantName: '环亚机场贵宾',
          createTime: '2026-01-10 09:32:15',
          showOnHome: '显示',
          showOnAssembly: '不显示',
          assemblyPages: []
        },
        {
          equityName: '钻石卡高尔夫体验',
          productId: 'CC002',
          skuNo: 'CCSKU002',
          merchantName: '尊享高尔夫俱乐部',
          createTime: '2026-01-15 14:08:42',
          showOnHome: '显示',
          showOnAssembly: '不显示',
          assemblyPages: []
        },
        {
          equityName: '金卡洗车服务',
          productId: 'CC003',
          skuNo: 'CCSKU003',
          merchantName: '车之家精洗服务',
          createTime: '2026-02-01 11:20:05',
          showOnHome: '显示',
          showOnAssembly: '不显示',
          assemblyPages: []
        }
      ]
    }
  },
  computed: {
    visiblePages() {
      return row => {
        const pages = []
        if (row.showOnHome === '显示') pages.push("权益首页")
        if (row.showOnAssembly === '显示' && Array.isArray(row.assemblyPages)) {
          pages.push(...row.assemblyPages)
        }
        return pages
      }
    },
    filteredTableData() {
      return this.tableData.filter(item => {
        if (this.searchForm.equityName && !item.equityName.includes(this.searchForm.equityName)) return false
        return true
      })
    }
  },
  methods: {
    handleSearch() {
      ElMessage.success('已搜索')
    },
    handleReset() {
      this.searchForm = {
        equityName: ''
      }
    },
    openShowPagesDialog(row) {
      this.showPagesRow = row
      this.showPagesDialogVisible = true
    },
    showLinkDialog(row) {
      this.linkTargetId = row.productId
      this.linkDialogVisible = true
    },
    openLinkDialogFromMore(row, index) {
      const moreRef = this.getPopoverInstance(`morePopover-${index}`)
      if (moreRef) {
        moreRef.hide()
      }
      this.showLinkDialog(row)
    },
    onShowPagesConfirm(values) {
      if (this.showPagesRow) {
        this.showPagesRow.showOnHome = values.showOnHome
        this.showPagesRow.showOnAssembly = values.showOnAssembly
        this.showPagesRow.assemblyPages = [...values.assemblyPages]
        ElMessage.success('显示页面已更新')
      }
    },
    getPopoverInstance(name) {
      const ref = this.$refs[name]
      if (!ref) return null
      return Array.isArray(ref) ? ref[0] : ref
    },
    onAdjustOrderShow(index) {
      this.adjustOrderPosition = index + 1
    },
    closeAdjustOrder(index) {
      const adjustRef = this.getPopoverInstance(`adjustPopover-${index}`)
      if (adjustRef) {
        adjustRef.hide()
      }
    },
    confirmAdjustOrder(index) {
      const target = Number(this.adjustOrderPosition)
      if (!target || target < 1 || target > this.tableData.length) {
        ElMessage.warning('请输入有效的顺序位置')
        return
      }
      const targetIndex = target - 1
      if (targetIndex !== index) {
        const moved = this.tableData.splice(index, 1)[0]
        this.tableData.splice(targetIndex, 0, moved)
      }
      ElMessage.success('顺序已调整')
      this.closeAdjustOrder(index)
    }
  }
}
</script>

<style scoped>
.credit-card-equity {
  padding: 0;
}

.search-section {
  display: flex;
  flex-direction: column;
}

.search-row {
  margin-bottom: 15px;
}

.search-row .el-form {
  display: flex;
  flex-wrap: wrap;
  gap: 0;
}

.search-row .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
}

.button-group {
  display: flex;
  gap: 5px;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
  margin-top: 20px;
}

.row-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.empty-text {
  color: #c0c4cc;
}

.row-actions .el-button + .el-button {
  margin-left: 0;
}
</style>

<style>
.more-actions-menu {
  display: flex;
  flex-direction: column;
  margin: -12px;
}

.more-actions-item {
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
}

.more-actions-item:hover {
  background: #f5f7fa;
  color: #409eff;
}

.adjust-order-form {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.adjust-order-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.adjust-order-tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  padding: 8px 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.adjust-order-input {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

.adjust-order-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}
</style>
