<template>
  <div>
    <obj-modal
      ref="modal"
      labelWidth="150px"
      :modalCols="modalCols"
      :modalConfig="modalConfig"
      :modalData="modalData"
      :modalHandles="modalHandles"
    >
      <template slot="dialog__after">
        <!-- 用户信息顶部展示 -->
        <div class="user-info-header">
          <div class="user-basic-info">
            <div class="info-row">
              <div class="info-item">
                <span class="label">会员姓名：</span>
                <span class="value">{{ modalData.username || "-" }}</span>
              </div>
              <div class="info-item">
                <span class="label">系统编号：</span>
                <span class="value">{{ modalData.id || "-" }}</span>
              </div>
              <div class="info-item">
                <span class="label">手机号：</span>
                <span class="value">{{ maskMobile(modalData.mobile) }}</span>
              </div>
            </div>
            <div class="info-row">
              <div class="info-item">
                <span class="label">生日：</span>
                <span class="value">{{ modalData.birthday || "-" }}</span>
              </div>
            </div>
          </div>
          <div class="user-stats">
            <div class="stat-card">
              <div class="stat-number">{{ modalData.growthValue || 0 }}</div>
              <div class="stat-label">会员成长值</div>
            </div>
            <div class="stat-card">
              <div class="stat-number">
                {{ modalData.availablePoints || 0 }}
              </div>
              <div class="stat-label">会员积分</div>
            </div>
            <div class="stat-card">
              <div class="stat-number">{{ modalData.couponCount || 0 }}</div>
              <div class="stat-label">会员优惠券</div>
            </div>
          </div>
        </div>

        <!-- Tab分页内容 -->
        <div class="tab-content">
          <el-tabs v-model="activeTab" @tab-click="handleTabClick">
            <el-tab-pane label="会员成长值明细" name="growth">
              <el-table
                :data="growthList"
                border
                style="width: 100%"
                v-loading="growthLoading"
              >
                <el-table-column
                  prop="changeTime"
                  label="变化时间"
                  width="180"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="changeType"
                  label="变动类型"
                  width="120"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="changeValue"
                  label="成长值变动"
                  width="120"
                  align="center"
                >
                  <template slot-scope="scope">
                    <span
                      :style="{
                        color: scope.row.changeValue > 0 ? '#67C23A' : '#F56C6C'
                      }"
                    >
                      {{ scope.row.changeValue > 0 ? "+" : ""
                      }}{{ scope.row.changeValue }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="shopOrderNo"
                  label="关联订单"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="shopName"
                  label="所属店铺"
                  width="120"
                  align="center"
                >
                </el-table-column>
                <el-table-column label="详情" width="100" align="center">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="small"
                      @click="viewGrowthDetail(scope.row)"
                    >
                      查看详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                @size-change="handleGrowthSizeChange"
                @current-change="handleGrowthCurrentChange"
                :current-page="growthPagination.currentPage"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="growthPagination.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="growthPagination.total"
                style="margin-top: 20px; text-align: center"
              >
              </el-pagination>
            </el-tab-pane>

            <el-tab-pane label="会员积分明细" name="points">
              <el-table
                :data="pointsList"
                border
                style="width: 100%"
                v-loading="pointsLoading"
              >
                <el-table-column
                  prop="changeTime"
                  label="变化时间"
                  width="180"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="changeType"
                  label="变动类型"
                  width="120"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="changeValue"
                  label="积分变动"
                  width="120"
                  align="center"
                >
                  <template slot-scope="scope">
                    <span
                      :style="{
                        color: scope.row.changeValue > 0 ? '#67C23A' : '#F56C6C'
                      }"
                    >
                      {{ scope.row.changeValue > 0 ? "+" : ""
                      }}{{ scope.row.changeValue }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="shopOrderNo"
                  label="关联订单"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="exchangeProductName"
                  label="兑换商品"
                  width="120"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  prop="shopName"
                  label="所属店铺"
                  width="120"
                  align="center"
                >
                </el-table-column>
                <el-table-column label="详情" width="100" align="center">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      size="small"
                      @click="viewPointsDetail(scope.row)"
                    >
                      查看详情
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                @size-change="handlePointsSizeChange"
                @current-change="handlePointsCurrentChange"
                :current-page="pointsPagination.currentPage"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="pointsPagination.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pointsPagination.total"
                style="margin-top: 20px; text-align: center"
              >
              </el-pagination>
            </el-tab-pane>

            <el-tab-pane label="会员优惠券" name="coupons">
              <el-table
                :data="couponsList"
                border
                style="width: 100%"
                v-loading="couponsLoading"
              >
                <el-table-column prop="name" label="优惠券名称" align="center">
                </el-table-column>
                <el-table-column
                  prop="couponType"
                  label="类型"
                  width="100"
                  align="center"
                >
                  <template slot-scope="scope">
                    {{ getCouponTypeText(scope.row.couponType) }}
                  </template>
                </el-table-column>
                <el-table-column label="面额" width="100" align="center">
                  <template slot-scope="scope">
                    <span v-if="scope.row.couponType === 'DISCOUNT'">
                      {{ scope.row.discount }}折
                    </span>
                    <span v-else-if="scope.row.couponType === 'MONEY'">
                      ¥{{ scope.row.money }}
                    </span>
                    <span v-else>
                      {{ scope.row.money || scope.row.discount || "-" }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="minPrice"
                  label="使用条件"
                  width="120"
                  align="center"
                >
                  <template slot-scope="scope">
                    <span v-if="scope.row.minPrice > 0">
                      满{{ scope.row.minPrice }}元可用
                    </span>
                    <span v-else>无门槛</span>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="createTime"
                  label="获得时间"
                  width="180"
                  align="center"
                >
                </el-table-column>
                <el-table-column label="有效期" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.useStartTime }} 至 {{ scope.row.useEndTime }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="status"
                  label="使用状态"
                  width="100"
                  align="center"
                >
                  <template slot-scope="scope">
                    <el-tag
                      :type="getCouponStatusTagType(scope.row.status)"
                      size="small"
                    >
                      {{ getCouponStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination
                @size-change="handleCouponsSizeChange"
                @current-change="handleCouponsCurrentChange"
                :current-page="couponsPagination.currentPage"
                :page-sizes="[10, 20, 50, 100]"
                :page-size="couponsPagination.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="couponsPagination.total"
                style="margin-top: 20px; text-align: center"
              >
              </el-pagination>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
    </obj-modal>

    <!-- 成长值详情弹框 -->
    <growth-detail ref="growthDetail"></growth-detail>

    <!-- 积分详情弹框 -->
    <points-detail ref="pointsDetail"></points-detail>
  </div>
</template>
<script>
import { cloneDeep } from "lodash";
import GrowthDetail from "./growth-detail.vue";
import PointsDetail from "./points-detail.vue";
export default {
  components: {
    GrowthDetail,
    PointsDetail
  },
  data() {
    return {
      isAdd: true,
      //表格属性
      modalConfig: {
        title: "用户详情",
        show: false,
        width: "80%"
      },
      modalData: {},
      // Tab相关数据
      activeTab: "growth",
      couponCount: 0,
      // 成长值明细
      growthList: [],
      growthLoading: false,
      growthPagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 积分明细
      pointsList: [],
      pointsLoading: false,
      pointsPagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 优惠券
      couponsList: [],
      couponsLoading: false,
      couponsPagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    };
  },
  watch: {
    "modalConfig.show"(newVal) {
      if (newVal) {
        //关闭弹窗清空校验
        setTimeout(() => {
          this.$refs.modal.resetFields();
        });
      }
    }
  },
  methods: {
    // 手机号脱敏处理
    maskMobile(mobile) {
      if (!mobile || mobile.length !== 11) {
        return mobile;
      }
      return mobile.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
    },
    queryTableData() {},
    toggle(e) {
      if (this.modalConfig.show == false) {
        this.modalConfig.show = true;
      } else {
        this.modalConfig.show = false;
      }
      if (e) {
        this.init(cloneDeep(e));
      }
      return {
        add: () => {
          this.modalConfig.title = "用户详情";
          this.isAdd = true;
        },
        update: () => {
          this.isAdd = false;
        }
      };
    },
    init(row) {
      this.modalData = row;
      this.loadTabData();
    },
    // Tab切换处理
    handleTabClick(tab) {
      this.activeTab = tab.name;
      this.loadTabData();
    },
    // 加载Tab数据
    loadTabData() {
      switch (this.activeTab) {
        case "growth":
          this.loadGrowthData();
          break;
        case "points":
          this.loadPointsData();
          break;
        case "coupons":
          this.loadCouponsData();
          break;
      }
    },
    // 加载成长值明细数据
    loadGrowthData() {
      this.growthLoading = true;

      const params = {
        membershipId: this.modalData.id || 0,
        pageNumber: this.growthPagination.currentPage,
        pageSize: this.growthPagination.pageSize
      };

      this.$api.marketing
        .growthValueChangePage(params)
        .then(res => {
          if (res.data.code === "200") {
            this.growthList = res.data.data.data || [];
            this.growthPagination.total = res.data.data.total || 0;
          } else {
            this.growthList = [];
            this.growthPagination.total = 0;
            this.$message.error(res.data.message || "获取成长值明细失败");
          }
        })
        .catch(error => {
          console.error("获取成长值明细失败:", error);
          this.growthList = [];
          this.growthPagination.total = 0;
          this.$message.error("获取成长值明细失败");
        })
        .finally(() => {
          this.growthLoading = false;
        });
    },
    // 加载积分明细数据
    loadPointsData() {
      this.pointsLoading = true;

      const params = {
        membershipId: this.modalData.id || 0,
        pageNumber: this.pointsPagination.currentPage,
        pageSize: this.pointsPagination.pageSize
      };

      this.$api.marketing
        .pointsChangePage(params)
        .then(res => {
          if (res.data.code === "200") {
            this.pointsList = res.data.data.data || [];
            this.pointsPagination.total = res.data.data.total || 0;
          } else {
            this.pointsList = [];
            this.pointsPagination.total = 0;
            this.$message.error(res.data.message || "获取积分明细失败");
          }
        })
        .catch(error => {
          console.error("获取积分明细失败:", error);
          this.pointsList = [];
          this.pointsPagination.total = 0;
          this.$message.error("获取积分明细失败");
        })
        .finally(() => {
          this.pointsLoading = false;
        });
    },
    // 加载优惠券数据
    loadCouponsData() {
      this.couponsLoading = true;

      const params = {
        shopId: this.modalData.shopId || 0,
        userId: this.modalData.userId || 0,
        pageNumber: this.couponsPagination.currentPage,
        pageSize: this.couponsPagination.pageSize
      };

      this.$api.marketing
        .memberCouponPage(params)
        .then(res => {
          if (res.data.code === "200") {
            this.couponsList = res.data.data.data || [];
            this.couponsPagination.total = res.data.data.total || 0;
          } else {
            this.couponsList = [];
            this.couponsPagination.total = 0;
            this.$message.error(res.data.message || "获取优惠券列表失败");
          }
        })
        .catch(error => {
          console.error("获取优惠券列表失败:", error);
          this.couponsList = [];
          this.couponsPagination.total = 0;
          this.$message.error("获取优惠券列表失败");
        })
        .finally(() => {
          this.couponsLoading = false;
        });
    },
    // 成长值分页处理
    handleGrowthSizeChange(val) {
      this.growthPagination.pageSize = val;
      this.loadGrowthData();
    },
    handleGrowthCurrentChange(val) {
      this.growthPagination.currentPage = val;
      this.loadGrowthData();
    },
    // 积分分页处理
    handlePointsSizeChange(val) {
      this.pointsPagination.pageSize = val;
      this.loadPointsData();
    },
    handlePointsCurrentChange(val) {
      this.pointsPagination.currentPage = val;
      this.loadPointsData();
    },
    // 优惠券分页处理
    handleCouponsSizeChange(val) {
      this.couponsPagination.pageSize = val;
      this.loadCouponsData();
    },
    handleCouponsCurrentChange(val) {
      this.couponsPagination.currentPage = val;
      this.loadCouponsData();
    },
    // 查看详情方法
    viewGrowthDetail(row) {
      this.$refs.growthDetail.show(row);
    },
    viewPointsDetail(row) {
      this.$refs.pointsDetail.show(row);
    },
    // 获取状态标签类型（保留原有方法，用于兼容）
    getStatusTagType(status) {
      switch (status) {
        case "可使用":
          return "success";
        case "已使用":
          return "info";
        case "已过期":
          return "danger";
        default:
          return "";
      }
    },
    // 获取优惠券状态标签类型
    getCouponStatusTagType(status) {
      switch (status) {
        case 0: // 可使用
          return "success";
        case 1: // 已使用
          return "info";
        case 2: // 已过期
          return "danger";
        default:
          return "";
      }
    },
    // 获取优惠券状态文本
    getCouponStatusText(status) {
      switch (status) {
        case 0:
          return "可使用";
        case 1:
          return "已使用";
        case 2:
          return "已过期";
        default:
          return "未知";
      }
    },
    // 获取优惠券类型中文文本
    getCouponTypeText(couponType) {
      switch (couponType) {
        case "MONEY":
          return "满减券";
        case "DISCOUNT":
          return "折扣券";
        default:
          return couponType || "未知";
      }
    }
  },
  computed: {
    modalCols() {
      return [];
    },
    modalHandles() {
      return [
        {
          label: "关闭",
          handle: () => {
            this.toggle();
          }
        }
      ];
    }
  },
  asyncComputed: {}
};
</script>
<style lang="scss" scoped>
.user-info-header {
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.user-basic-info {
  flex: 1;
}

.info-row {
  display: flex;
  margin-bottom: 15px;
}

.info-item {
  margin-right: 40px;
}

.label {
  color: #606266;
  font-weight: 500;
}

.value {
  color: #303133;
  margin-left: 5px;
}

.user-stats {
  display: flex;
  gap: 20px;
}

.stat-card {
  text-align: center;
  padding: 15px 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  min-width: 100px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}
</style>
