<template>
  <div >
    <el-table :data="tableData"
              :height="700"
              :header-cell-style="{'text-align': 'center'}"
              border
              v-loading="loading" >
      <el-table-column type="selection" width="65" align="center" />

      <el-table-column prop="cardNo" label="卡号" align="center" width="160" fixed />

      <el-table-column prop="memberName" label="会员" align="center" width="120" fixed>
        <template slot-scope="scope">
          <div class="member-cell">
            <div class="member-name">{{ scope.row.memberName }}</div>
            <div class="member-phone">{{ scope.row.memberPhone }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="statusDesc" label="状态" align="center" width="80">
        <template slot-scope="scope">
          <el-tag :type="getStatusTagType(scope.row.status)" size="small">
            {{ scope.row.statusDesc }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="cardTypeName" label="卡类名称" align="center" width="160" />
      <el-table-column prop="price" label="实付价格" align="center" width="100">
        <template slot-scope="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="chargeType" label="扣费卡类" width="150">
        <template slot-scope="scope">
          <div v-if="scope.row.chargeType=='count'" class="item">
            <div class="item-name">次数卡</div>
            <div class="item-name">总次数: {{ scope.row.totalCount }} 次 </div>
            <div class="item-name">剩余次数: {{ scope.row.remainingCount }} 次</div>

          </div>
          <div v-if="scope.row.chargeType=='days'" class="item">
            <div class="item-name">周期卡</div>
            <div class="item-name">总天数: {{ scope.row.totalDays }} 天</div>
            <div class="item-name">剩余天数: {{ scope.row.remainingDays }} 天</div>

          </div>
          <div v-if="scope.row.chargeType=='total_fee'" class="item">
            <div class="item-name">储值卡 </div>
            <div class="item-name">储值金额: {{ scope.row.totalFee }} 元</div>
            <div class="item-name">剩余金额:  {{ scope.row.remainingTotalFee }} 元</div>

          </div>
        </template>
      </el-table-column>
      <el-table-column prop="chargeType" label="剩余价值" align="center" width="100">

        <template slot-scope="scope">
          <el-tooltip  effect="dark" content="计算方式：1.次卡会员（缴费金额➗️总次数✖️剩余次数）2. 周期卡会员（缴费金额➗️总天数✖️剩余天数）" placement="right">
          <div v-if="scope.row.chargeType=='count'" class="item">
            <div class="item-name">{{ scope.row.price==0?0:scope.row.price/scope.row.totalCount*scope.row.remainingCount  }} 元 </div>
          </div>
          <div v-if="scope.row.chargeType=='days'" class="item">
            <div class="item-name">{{ scope.row.price==0?0:scope.row.price/scope.row.totalDays*scope.row.remainingDays }} 元</div>
          </div>
          <div v-if="scope.row.chargeType=='total_fee'" class="item">
            <div class="item-name">{{ scope.row.remainingTotalFee }} 元</div>
          </div>
          </el-tooltip>
        </template>

      </el-table-column>
      <el-table-column prop="cardTypes" width="130" label="每节课扣次或费用">
        <template slot-scope="scope" >
          <div v-if="scope.row.chargeType=='days'">
            周期计费
          </div>
          <div v-else>
            <div v-if="scope.row.cardTypes.chargeType=='default'">
              默认<br>
              <span v-if="scope.row.chargeType=='count'">扣{{scope.row.cardTypes.defaultNum}}次 </span>
              <span v-if="scope.row.chargeType=='total_fee'">扣{{scope.row.cardTypes.defaultFee}}元 </span>
            </div>
            <div v-if="scope.row.cardTypes.chargeType=='customize'">
              <div>
                <ul>
                  <li v-for="item in scope.row.cardTypes.feeModeHourList" :key="item.courseTypeId">
                    {{ item.courseType }} -
                    <span v-if="scope.row.chargeType=='count'">扣{{item.cnt}}次 </span>
                    <span v-if="scope.row.chargeType=='total_fee'">扣{{item.totalFee}}元 </span>
                  </li>
                </ul>
              </div>

            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="cardTypes" width="180" label="限制课程">
        <template slot-scope="scope" >
          <div v-if="scope.row.cardTypes.restrictedCourses=='1'">
            全部允许<br>
          </div>
          <div v-if="scope.row.cardTypes.restrictedCourses=='2'">
            <div>
              <ul>
                <li v-for="item in scope.row.cardTypes.courses" :key="item.id">
                  {{ item.courseType }} - {{item.courseNames}}
                </li>
              </ul>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="cardTypes" width="100" label="限制教练" >
        <template slot-scope="scope" >
          {{scope.row.cardTypes.restrictedTeacher=='1'?'全部允许':scope.row.cardTypes.teachersName}}
        </template>
      </el-table-column>
      <el-table-column prop="cardTypes" align="center" width="120" label="预约次数限制" >
        <template slot-scope="scope" >
          {{ scope.row.cardTypes.restrictedNum=='1'?'不限预约次数':'限制预约次数'}}<br>
          <div v-if="scope.row.cardTypes.restrictedNum=='2'">
            {{scope.row.cardTypes.bookTime}}内只能预约{{scope.row.cardTypes.bookNum}}次
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="activationDate" label="激活日期" width="100">
        <template slot-scope="scope">
            <span >
              {{ scope.row.activationDate || '' }}
            </span>
        </template>
      </el-table-column>

      <el-table-column prop="expiryDate" label="到期时间" width="100">
        <template slot-scope="scope">
            <span :class="{'expiring': isExpiring(scope.row.expiryDate)}">
              {{ scope.row.expiryDate || '' }}
            </span>
        </template>
      </el-table-column>

      <el-table-column prop="purchaseDate" label="办理时间" width="100">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.purchaseDate) }}
        </template>
      </el-table-column>

    </el-table>
    <pagination
      v-show="pagination.total>0"
      :total="pagination.total"
      :page.sync="pagination.current"
      :limit.sync="pagination.size"
      @pagination="loadData(searchForm.memberId)"
    />
  </div>
</template>

<script>
import memberCardApi from '@/api/school/sc/memberCard'
import {select as selectCardType} from '@/api/school/sc/memberCardType'


export default {
  name: 'MemberCardList',
  props: {
    studentId: {
      type: String,
      default: undefined
    },
    queryParams: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      // 搜索表单
      searchForm: {
        memberId: null,
        status: null,        // 卡状态
        cardTypeId: null     // 卡类型ID
      },

      // 表格数据
      tableData: [],
      loading: false,

      // 分页
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },

      // 选项数据
      memberOptions: [],
      cardTypeOptions: [],

      // 选中的卡片
      selectedCard: null,
      selectedCardId: null,

      // 对话框控制
      detailDialogVisible: false,
      countDialogVisible: false,
      countDialogType: 'add' // add 或 deduct
    }
  },
  watch: {
    studentId: {
      handler(newValue) {
        this.searchForm.memberId = newValue
      },
      immediate: true
    },
    queryParams: {
      handler(newVal) {
        // this.searchForm = { ...this.searchForm, ...newVal }
        this.searchForm.memberId=newVal.studentId
        this.searchForm.status=newVal.status
        this.searchForm.cardTypeId=newVal.cardTypeId
        // 处理日期范围
        if (newVal.expiryDate && newVal.expiryDate.length === 2) {
          this.searchForm.startDate = newVal.expiryDate[0]
          this.searchForm.endDate = newVal.expiryDate[1]
        }
        // this.loadData() // 参数变化时重新加载数据
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    this.loadCardTypeOptions()
  },
  methods: {
    // 加载数据
    async loadData(studentId) {
      this.searchForm.memberId=studentId || this.searchForm.memberId
      this.loading = true
      try {
        const params = {
          ...this.searchForm,
          pageNum: this.pagination.current,
          pageSize: this.pagination.size
        }

        const response = await memberCardApi.getCardList(params)
        if (response.respCode === '0000') {
          this.tableData = response.data.rows || []
          this.pagination.total = response.data.total || 0
        } else {
          this.$message.error(response.message || '加载失败')
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('加载失败')
      } finally {
        this.loading = false
      }
    },

    // 加载会员选项
    // async loadMemberOptions() {
    //   try {
    //     const response = await getStudent('')
    //     this.memberOptions = response.data || []
    //   } catch (error) {
    //     console.error('加载会员选项失败:', error)
    //   }
    // },

    // 加载卡类型选项
    async loadCardTypeOptions() {
      try {
        const response = await selectCardType('')
        this.cardTypeOptions = response.data || []
      } catch (error) {
        console.error('加载卡类型选项失败:', error)
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadData()
    },

    // 重置搜索
    resetSearch() {
      this.$refs.searchForm.resetFields()
      this.pagination.current = 1
      this.loadData()
    },

    // 分页大小变化
    handleSizeChange(size) {
      this.pagination.size = size
      this.pagination.current = 1
      this.loadData()
    },

    // 当前页变化
    handleCurrentChange(current) {
      this.pagination.current = current
      this.loadData()
    },

    // 查看详情
    viewDetail(row) {
      this.selectedCardId = row.id
      this.detailDialogVisible = true
    },

    // 处理更多操作
    handleCommand(command, row) {
      this.selectedCard = row

      switch (command) {
        case 'activate':
          this.activateCard()
          break
        case 'suspend':
          this.suspendCard()
          break
        case 'renew':
          this.renewCard()
          break
        case 'addCount':
          this.showCountDialog('add')
          break
        case 'deductCount':
          this.showCountDialog('deduct')
          break
        case 'checkStatus':
          this.checkCardStatus()
          break
        case 'delete':
          this.deleteCard()
          break
      }
    },

    // 激活卡片
    async activateCard() {
      try {
        const confirm = await this.$confirm('确定要激活这张会员卡吗？', '提示', {
          type: 'warning'
        })

        if (confirm) {
          const response = await memberCardApi.activateCard(this.selectedCard.id)
          if (response.code === 200) {
            this.$message.success('激活成功')
            this.loadData()
          } else {
            this.$message.error(response.message || '激活失败')
          }
        }
      } catch (error) {
        console.error('激活失败:', error)
      }
    },

    // 暂停卡片
    async suspendCard() {
      try {
        const confirm = await this.$confirm('确定要暂停这张会员卡吗？', '提示', {
          type: 'warning'
        })

        if (confirm) {
          const response = await memberCardApi.suspendCard(this.selectedCard.id)
          if (response.code === 200) {
            this.$message.success('暂停成功')
            this.loadData()
          } else {
            this.$message.error(response.message || '暂停失败')
          }
        }
      } catch (error) {
        console.error('暂停失败:', error)
      }
    },


    // 显示增加/扣减次数对话框
    showCountDialog(type) {
      this.countDialogType = type
      this.countDialogVisible = true
    },

    // 检查卡片状态
    async checkCardStatus() {
      try {
        const response = await memberCardApi.checkCardStatus(this.selectedCard.id)
        if (response.code === 200) {
          this.$message.success(response.message || '卡片状态正常')
          this.loadData()
        } else {
          this.$message.warning(response.message || '卡片状态异常')
        }
      } catch (error) {
        console.error('检查状态失败:', error)
      }
    },



    // 获取状态标签类型
    getStatusTagType(status) {
      const typeMap = {
        'ACTIVE': 'success',
        'INACTIVE': 'info',
        'EXPIRED': 'warning',
        'SUSPENDED': 'danger',
        'DEPLETED': 'danger'
      }
      return typeMap[status] || 'info'
    },


    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      return dateTime.replace('T', ' ')
    },

    // 检查是否即将到期（7天内）
    isExpiring(expiryDate) {
      if (!expiryDate) return false

      const today = new Date()
      const expiry = new Date(expiryDate)
      const daysDiff = Math.floor((expiry - today) / (1000 * 60 * 60 * 24))

      return daysDiff >= 0 && daysDiff <= 7
    },


  }
}
</script>

<style scoped lang="scss">
.member-card-list {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: #333;
    }

    .header-actions {
      display: flex;
      gap: 10px;
    }
  }

  .search-card {
    margin-bottom: 20px;

    .el-form-item {
      margin-bottom: 10px;
    }
  }

  .table-card {
    .card-no-cell {
      display: flex;
      align-items: center;

      .card-no {
        margin-right: 8px;
      }

      .available-icon {
        color: #67c23a;
      }

      .unavailable-icon {
        color: #f56c6c;
      }
    }

    .member-cell {
      .member-name {
        font-weight: 500;
        margin-bottom: 2px;
      }

      .member-phone {
        font-size: 12px;
        color: #666;
      }
    }

    .expiring {
      color: #e6a23c;
      font-weight: 500;
    }

    .pagination {
      margin-top: 20px;
      text-align: right;
    }
  }
}
</style>
