<template>
  <div class="equity-products">
    <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>
            <el-form-item label="权益编号:">
              <el-input v-model="searchForm.productId" placeholder="请输入" style="width: 150px"></el-input>
            </el-form-item>
            <el-form-item label="商品状态:">
              <el-select v-model="searchForm.shelfStatus" placeholder="全部" clearable style="width: 130px">
                <el-option label="未上架" value="未上架"></el-option>
                <el-option label="已上架" value="已上架"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="审核状态:">
              <el-select v-model="searchForm.auditStatus" placeholder="全部" clearable style="width: 150px">
                <el-option label="草稿" value="草稿"></el-option>
                <el-option label="上架待审核" value="上架待审核"></el-option>
                <el-option label="下架待审核" value="下架待审核"></el-option>
                <el-option label="审核通过" value="审核通过"></el-option>
              </el-select>
            </el-form-item>
            <div class="button-group" style="margin-left: 20px;">
              <el-button type="primary" @click="loadData">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </div>
          </el-form>
        </div>
        <div style="margin-top: 15px;">
          <el-button type="primary" @click="createProduct">
            <el-icon><Plus /></el-icon>添加权益
          </el-button>
        </div>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table :data="tableData" stripe style="width: 100%">
        <el-table-column label="操作" width="240" fixed="left">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button
              v-if="canEdit(scope.row)"
              type="text"
              size="small"
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              v-if="canRequestOffshelf(scope.row)"
              type="text"
              size="small"
              @click="handleOffshelf(scope.row)"
            >下架</el-button>
            <el-popover
              placement="bottom"
              trigger="click"
              :ref="`morePopover-${scope.$index}`"
            >
              <div class="more-actions-menu">
                <el-popover
                  placement="left"
                  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>
                    <div v-if="scope.row.shelfStatus === '已上架'" class="more-actions-item">调整显示顺序</div>
                  </template>
                </el-popover>
                <div
                  class="more-actions-item"
                  @click="handleCopyFromMore(scope.row, scope.$index)"
                >复制</div>
                <div
                  v-if="scope.row.shelfStatus === '已上架'"
                  class="more-actions-item"
                  @click="openLinkDialogFromMore(scope.row, scope.$index)"
                >生成链接</div>
                <div
                  v-if="scope.row.shelfStatus === '已上架' && scope.row.isPlatformExchange === '是' && scope.row.productType === '券码'"
                  class="more-actions-item"
                  @click="handleImportCouponsFromMore(scope.row, scope.$index)"
                >导入券码</div>
                <div
                  v-if="scope.row.shelfStatus === '已上架' && scope.row.isPlatformExchange === '是' && scope.row.productType === '券码'"
                  class="more-actions-item"
                  @click="handleManageCouponsFromMore(scope.row, scope.$index)"
                >券码管理</div>
                <div
                  v-if="canDelete(scope.row)"
                  class="more-actions-item more-actions-item-danger"
                  @click="handleDeleteFromMore(scope.row, scope.$index)"
                >删除</div>
              </div>
              <template #reference>
                <el-button type="text" size="small" style="margin-left: 8px;">
                  <el-icon><More /></el-icon>
                </el-button>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="equityName" label="权益名称" width="140" show-overflow-tooltip></el-table-column>
        <el-table-column label="商品状态" width="100">
          <template #default="scope">
            <el-tag :type="getShelfTagType(scope.row.shelfStatus)" size="small">{{ scope.row.shelfStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" width="120">
          <template #default="scope">
            <el-tag :type="getAuditTagType(scope.row.auditStatus)" size="small">{{ scope.row.auditStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否权益平台兑换" width="150">
          <template #default="scope">
            <el-tag :type="scope.row.isPlatformExchange === '是' ? 'success' : 'info'" size="small">{{ scope.row.isPlatformExchange }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="商品类型" width="120">
          <template #default="scope">
            <span v-if="scope.row.isPlatformExchange === '是'">{{ scope.row.productType }}</span>
            <span v-else class="empty-text">-</span>
          </template>
        </el-table-column>
        <el-table-column label="库存数" width="100" align="right">
          <template #default="scope">
            <span v-if="isPlatformProduct(scope.row) && hasStock(scope.row)">{{ scope.row.stockCount }}</span>
            <span v-else class="empty-text">-</span>
          </template>
        </el-table-column>
        <el-table-column label="外部权益链接" width="120">
          <template #default="scope">
            <span v-if="scope.row.isPlatformExchange === '否'">{{ scope.row.jumpLink }}</span>
            <span v-else class="empty-text">-</span>
          </template>
        </el-table-column>
        <el-table-column prop="productId" label="权益编号" width="100"></el-table-column>
        <el-table-column label="显示页面" min-width="220">
          <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-column prop="creator" label="创建人" width="100"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="170"></el-table-column>
        <el-table-column prop="reviewer" label="审核人" width="100"></el-table-column>
        <el-table-column prop="reviewTime" label="审核时间" width="170"></el-table-column>
      </el-table>

      <equity-link-dialog
        v-model="linkDialogVisible"
        :id="linkTargetId"
        path-name="equity/debit"
        title="生成借记卡权益链接"
      ></equity-link-dialog>

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

  </div>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'
import EquityLinkDialog from '@/components/EquityLinkDialog.vue'

export default {
  name: 'EquityProducts',
  components: { EquityLinkDialog },
  data() {
    return {
      searchForm: {
        equityName: '',
        productId: '',
        shelfStatus: '',
        auditStatus: ''
      },
      tableData: [],
      adjustOrderPosition: 1,
      linkDialogVisible: false,
      linkTargetId: ''
    }
  },
  created() {
    this.loadData()
  },
  activated() {
    this.loadData()
  },
  watch: {
    $route(to) {
      if (to.path === '/customization/hsbc/equity-products') {
        this.loadData()
      }
    }
  },
  methods: {
    loadData() {
      const params = new URLSearchParams()
      if (this.searchForm.equityName) params.append('equityName', this.searchForm.equityName)
      if (this.searchForm.productId) params.append('productId', this.searchForm.productId)
      if (this.searchForm.shelfStatus) params.append('shelfStatus', this.searchForm.shelfStatus)
      if (this.searchForm.auditStatus) params.append('auditStatus', this.searchForm.auditStatus)
      const qs = params.toString()
      request.get('/api/equity/list' + (qs ? `?${qs}` : '')).then(res => {
        this.tableData = res.data || []
      }).catch(() => {})
    },
    handleReset() {
      this.searchForm = { equityName: '', productId: '', shelfStatus: '', auditStatus: '' }
      this.loadData()
    },
    // 按钮可见性
    canEdit(row) {
      if (row.shelfStatus === '已下架') return true
      return row.shelfStatus === '未上架' && row.auditStatus === '草稿'
    },
    canRequestOffshelf(row) {
      return row.shelfStatus === '已上架' && row.auditStatus === '审核通过'
    },
    canDelete(row) {
      return row.shelfStatus === '未上架' && (row.auditStatus === '草稿' || row.auditStatus === '审核通过')
    },
    // Tag 样式
    getShelfTagType(s) {
      if (s === '已上架') return 'success'
      return 'info'
    },
    getAuditTagType(s) {
      if (s === '审核通过') return 'success'
      if (s === '草稿') return 'info'
      if (s === '上架待审核') return ''
      if (s === '下架待审核') return 'danger'
      return ''
    },
    isPlatformProduct(row) {
      return row.isPlatformExchange === '是' && (row.productType === '券码' || row.productType === '微信立减金')
    },
    hasStock(row) {
      return row.stockCount !== undefined && row.stockCount !== null && row.stockCount !== ''
    },
    visiblePages(row) {
      const pages = []
      if (row.showOnHome === '显示') pages.push('权益首页')
      if (row.showOnAssembly === '显示' && Array.isArray(row.assemblyPages)) {
        pages.push(...row.assemblyPages)
      }
      return pages
    },
    // 路由跳转
    createProduct() {
      this.$router.push('/customization/hsbc/equity-products/add')
    },
    handleView(row) {
      this.$router.push(`/customization/hsbc/equity-products/view/${row.productId}`)
    },
    handleEdit(row) {
      this.$router.push(`/customization/hsbc/equity-products/edit/${row.productId}`)
    },
    // 下架（提交下架审核）
    handleOffshelf(row) {
      ElMessageBox.confirm(`确定提交"${row.equityName}"的下架审核吗？审核通过后才会下架。`, '提示', {
        confirmButtonText: '提交',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.post('/api/equity/request-offshelf', {
          productId: row.productId
        }).then(() => {
          ElMessage.success('已提交下架审核')
          this.loadData()
        }).catch(() => {})
      }).catch(() => {})
    },
    // popover 工具方法
    getPopoverInstance(name) {
      const ref = this.$refs[name]
      if (!ref) return null
      return Array.isArray(ref) ? ref[0] : ref
    },
    onAdjustOrderShow(index) {
      this.adjustOrderPosition = index + 1
      const moreRef = this.getPopoverInstance(`morePopover-${index}`)
      if (moreRef) moreRef.hide()
    },
    closeAdjustOrder(index) {
      const adjustRef = this.getPopoverInstance(`adjustPopover-${index}`)
      if (adjustRef) adjustRef.hide()
      const moreRef = this.getPopoverInstance(`morePopover-${index}`)
      if (moreRef) moreRef.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)
    },
    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)
    },
    handleCopyFromMore(row, index) {
      const moreRef = this.getPopoverInstance(`morePopover-${index}`)
      if (moreRef) moreRef.hide()
      this.$router.push({
        path: '/customization/hsbc/equity-products/add',
        query: { copyFrom: row.productId }
      })
    },
    handleManageCouponsFromMore(row, index) {
      const moreRef = this.getPopoverInstance(`morePopover-${index}`)
      if (moreRef) moreRef.hide()
      window.open('https://uat.leagpoint.com/sipAdmin/coupon/inboundCouponList', '_blank')
    },
    handleImportCouponsFromMore(row, index) {
      const moreRef = this.getPopoverInstance(`morePopover-${index}`)
      if (moreRef) moreRef.hide()
      window.open('https://uat.leagpoint.com/sipAdmin/coupon/importCoupon', '_blank')
    },
    handleDeleteFromMore(row, index) {
      const moreRef = this.getPopoverInstance(`morePopover-${index}`)
      if (moreRef) moreRef.hide()
      ElMessageBox.confirm(`确定删除权益"${row.equityName}"吗？`, '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request.post('/api/equity/delete', { productId: row.productId }).then(() => {
          ElMessage.success('删除成功')
          this.loadData()
        }).catch(() => {})
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.equity-products {
  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;
}

.empty-text {
  color: #c0c4cc;
}
</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;
}

.more-actions-item-danger:hover {
  color: #f56c6c;
}

.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>
