<template>
  <div class="equity-products">
    <el-card>
      <!-- 搜索区域 -->
      <div class="search-section" slot="header">
        <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.reviewStatus" placeholder="全部" clearable style="width: 150px">
                <el-option
                  v-for="opt in statusOptions"
                  :key="opt"
                  :label="opt"
                  :value="opt"
                />
              </el-select>
            </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 style="margin-top: 15px;">
          <el-button type="primary" icon="el-icon-plus" @click="createProduct">添加权益</el-button>
        </div>
      </div>

      <!-- 表格区域 -->
      <el-table :data="filteredTableData" stripe style="width: 100%">
        <el-table-column label="操作" width="240" fixed="left">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <el-button
                v-if="scope.row.reviewStatus === '待审核'"
                type="text"
                size="small"
                @click="handleAudit(scope.row)"
              >审核</el-button>
            <el-button
              v-if="scope.row.reviewStatus === '审核通过' || scope.row.reviewStatus === '已上架'"
              type="text"
              size="small"
              @click="handleOffline(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="mini"
                        :controls="false"
                        style="width: 70px;margin: 0 6px;"
                      />
                      <span>位</span>
                    </div>
                    <div class="adjust-order-actions">
                      <el-button size="mini" @click="closeAdjustOrder(scope.$index)">取消</el-button>
                      <el-button size="mini" type="primary" @click="confirmAdjustOrder(scope.$index)">确定</el-button>
                    </div>
                  </div>
                  <div slot="reference" class="more-actions-item">调整显示顺序</div>
                </el-popover>
                <div
                  class="more-actions-item"
                  @click="openLinkDialogFromMore(scope.row, scope.$index)"
                >生成链接</div>
                <div
                  v-if="scope.row.source === '银行自有' && scope.row.productType === '券码'"
                  class="more-actions-item"
                  @click="handleImportCouponsFromMore(scope.row, scope.$index)"
                >导入券码</div>
                <div
                  v-if="scope.row.source === '银行自有' && scope.row.productType === '券码'"
                  class="more-actions-item"
                  @click="handleManageCouponsFromMore(scope.row, scope.$index)"
                >券码管理</div>
                <div
                  v-if="scope.row.reviewStatus === '已下架'"
                  class="more-actions-item more-actions-item-danger"
                  @click="handleDelete(scope.row, scope.$index)"
                >删除</div>
              </div>
              <el-button slot="reference" type="text" size="small" icon="el-icon-more" style="margin-left: 8px;"></el-button>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="equityName" label="权益名称" width="120"></el-table-column>
        <el-table-column label="状态" width="100">
          <template slot-scope="scope">
            <el-tag
              :type="getStatusType(scope.row.reviewStatus)"
              size="small"
            >{{ scope.row.reviewStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="权益来源" width="100"></el-table-column>
        <el-table-column prop="jumpLink" label="外部权益链接" width="120"></el-table-column>
        <el-table-column prop="jumpMethod" label="是否有详情页" width="120"></el-table-column>
        <el-table-column prop="productId" label="权益编号" width="100"></el-table-column>
        <el-table-column label="显示页面" min-width="220">
          <template slot-scope="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="180"></el-table-column>
        <el-table-column prop="reviewer" label="审核人" width="100"></el-table-column>
        <el-table-column prop="reviewTime" label="审核时间" width="180"></el-table-column>
      </el-table>

      <show-pages-dialog
        :visible.sync="showPagesDialogVisible"
        :row="showPagesRow"
        @confirm="onShowPagesConfirm"
      ></show-pages-dialog>

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

      <!-- 分页 -->
      <div class="pagination-section">
        <span>Total 1000</span>
        <el-pagination
          layout="prev, pager, next, sizes, jumper"
          :page-size="100"
          :page-sizes="[100, 200, 500]"
          :total="1000"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import ShowPagesDialog from '@/components/ShowPagesDialog.vue'
import EquityLinkDialog from '@/components/EquityLinkDialog.vue'

export default {
  name: 'EquityProducts',
  components: { ShowPagesDialog, EquityLinkDialog },
  data() {
    return {
      searchForm: {
        equityName: '',
        productId: '',
        reviewStatus: ''
      },
      statusOptions: ['待审核', '已上架', '审核拒绝', '已下架'],
      adjustOrderPosition: 1,
      showPagesDialogVisible: false,
      showPagesRow: null,
      linkDialogVisible: false,
      linkTargetId: '',
      tableData: [
        {
          equityName: '权益A',
          reviewStatus: '待审核',
          source: '银行自有',
          jumpMethod: '-',
          jumpLink: '-',
          exchangeMethod: '权益平台',
          productId: '100001',
          skuNo: 'SKU001',
          merchantName: '商户A',
          productType: '券码',
          creator: '李运营',
          createTime: '2026-04-10 09:32:15',
          reviewer: '',
          reviewTime: ''
        },
        {
          equityName: '权益B',
          reviewStatus: '待审核',
          source: '第三方',
          jumpMethod: '没有',
          jumpLink: '太古地产',
          exchangeMethod: '第三方（列表跳转）',
          productId: '100002',
          skuNo: 'SKU002',
          merchantName: '商户B',
          creator: '王运营',
          createTime: '2026-04-12 14:08:42',
          reviewer: '张三',
          reviewTime: '2026-04-15 10:30:00'
        },
        {
          equityName: '权益C',
          reviewStatus: '已上架',
          source: '第三方',
          jumpMethod: '有',
          jumpLink: '龙腾',
          exchangeMethod: '第三方（详情页跳转）',
          productId: '100003',
          skuNo: 'SKU003',
          merchantName: '商户C',
          creator: '李运营',
          createTime: '2026-04-08 11:20:05',
          reviewer: '王五',
          reviewTime: '2026-04-14 16:45:00'
        },
        {
          equityName: '权益D',
          reviewStatus: '审核拒绝',
          source: '第三方',
          jumpMethod: '有',
          jumpLink: 'h5链接',
          exchangeMethod: '第三方（详情页跳转）',
          productId: '100004',
          skuNo: 'SKU004',
          merchantName: '商户D',
          creator: '陈运营',
          createTime: '2026-04-05 15:50:18',
          reviewer: '赵六',
          reviewTime: '2026-04-13 09:15:00'
        },
        {
          equityName: '权益E',
          reviewStatus: '已下架',
          source: '银行自有',
          jumpMethod: '-',
          jumpLink: '-',
          exchangeMethod: '权益平台',
          productId: '100005',
          skuNo: 'SKU005',
          merchantName: '商户E',
          productType: '券码',
          creator: '王运营',
          createTime: '2026-03-28 09:00:11',
          reviewer: '钱七',
          reviewTime: '2026-04-12 11:20:00'
        }
      ]
    }
  },
  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(row => {
        const f = this.searchForm
        if (f.equityName && !row.equityName.includes(f.equityName)) return false
        if (f.productId && !row.productId.includes(f.productId)) return false
        if (f.reviewStatus && row.reviewStatus !== f.reviewStatus) return false
        return true
      })
    }
  },
  methods: {
    handleSearch() {
      this.$message.success('已搜索')
    },
    handleReset() {
      this.searchForm = {
        equityName: '',
        productId: '',
        reviewStatus: ''
      }
    },
    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.doClose()
      }
    },
    closeAdjustOrder(index) {
      const adjustRef = this.getPopoverInstance(`adjustPopover-${index}`)
      if (adjustRef) {
        adjustRef.doClose()
      }
      const moreRef = this.getPopoverInstance(`morePopover-${index}`)
      if (moreRef) {
        moreRef.doClose()
      }
    },
    confirmAdjustOrder(index) {
      const target = Number(this.adjustOrderPosition)
      if (!target || target < 1 || target > this.tableData.length) {
        this.$message.warning('请输入有效的顺序位置')
        return
      }
      const targetIndex = target - 1
      if (targetIndex !== index) {
        const moved = this.tableData.splice(index, 1)[0]
        this.tableData.splice(targetIndex, 0, moved)
      }
      this.$message.success('顺序已调整')
      this.closeAdjustOrder(index)
    },
    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}`)
    },
    handleAudit(row) {
      this.$router.push(`/customization/hsbc/equity-products/audit/${row.productId}`)
    },
    showLinkDialog(row) {
      this.linkTargetId = row.productId
      this.linkDialogVisible = true
    },
    openLinkDialogFromMore(row, index) {
      const moreRef = this.getPopoverInstance(`morePopover-${index}`)
      if (moreRef) {
        moreRef.doClose()
      }
      this.showLinkDialog(row)
    },
    handleManageCoupons() {
      window.open('https://uat.leagpoint.com/sipAdmin/coupon/inboundCouponList', '_blank')
    },
    handleManageCouponsFromMore(row, index) {
      const moreRef = this.getPopoverInstance(`morePopover-${index}`)
      if (moreRef) {
        moreRef.doClose()
      }
      this.handleManageCoupons(row)
    },
    handleImportCoupons() {
      window.open('https://uat.leagpoint.com/sipAdmin/coupon/importCoupon', '_blank')
    },
    handleImportCouponsFromMore(row, index) {
      const moreRef = this.getPopoverInstance(`morePopover-${index}`)
      if (moreRef) {
        moreRef.doClose()
      }
      this.handleImportCoupons(row)
    },
    handleOffline(row) {
      this.$confirm(`确定要下架权益"${row.equityName}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success('下架成功')
      }).catch(() => {})
    },
    openShowPagesDialog(row, index) {
      const moreRef = this.getPopoverInstance(`morePopover-${index}`)
      if (moreRef) {
        moreRef.doClose()
      }
      this.showPagesRow = row
      this.showPagesDialogVisible = true
    },
    onShowPagesConfirm(values) {
      if (this.showPagesRow) {
        this.$set(this.showPagesRow, 'showOnHome', values.showOnHome)
        this.$set(this.showPagesRow, 'showOnAssembly', values.showOnAssembly)
        this.$set(this.showPagesRow, 'assemblyPages', [...values.assemblyPages])
        this.$message.success('显示页面已更新')
      }
    },
    handleDelete(row, index) {
      const moreRef = this.getPopoverInstance(`morePopover-${index}`)
      if (moreRef) {
        moreRef.doClose()
      }
      this.$confirm(`确定要删除权益"${row.equityName}"吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData.splice(index, 1)
        this.$message.success('删除成功')
      }).catch(() => {})
    },
    getStatusType(status) {
      switch (status) {
        case '待审核':
          return 'warning'
        case '已上架':
          return 'success'
        case '审核拒绝':
          return 'danger'
        case '已下架':
          return 'info'
        default:
          return ''
      }
    }
  }
}
</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>
