<template>
  <div class="NCC-common-layout">
    <div class="NCC-common-layout-center">
      <!-- 筛选条件 -->
      <el-row class="NCC-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item label="会员" required>
              <el-select
                :style='{"width":"100%"}'
                v-model="query.memberId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入关键词"
                :remote-method="remoteMethod"
                :loading="kdhyLoading">
                <el-option
                  v-for="item in kdhyOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开始时间">
              <el-date-picker 
                v-model="query.startTime" 
                type="date" 
                value-format="yyyy-MM-dd" 
                placeholder="开始时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束时间">
              <el-date-picker 
                v-model="query.endTime" 
                type="date" 
                value-format="yyyy-MM-dd" 
                placeholder="结束时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
              <el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>

      <!-- 数据表格 -->
      <div class="NCC-common-layout-main NCC-flex-main">
        <NCC-table v-loading="listLoading" :data="list" has-c>
          <el-table-column type="expand">
            <template slot-scope="props">
              <div class="expand-container">
                <div class="expand-title">项目明细</div>
                <el-table :data="props.row.ItemDetails" border size="small">
                  <el-table-column prop="ItemName" label="项目名称" align="left" width="150" />
                  <el-table-column prop="ItemId" label="项目编号" align="left" width="120" />
                  <el-table-column prop="UnitPrice" label="单价" align="right" width="100">
                    <template slot-scope="scope">
                      <span class="amount-value">¥{{ formatMoney(scope.row.UnitPrice) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="ProjectNumber" label="项目次数" align="right" width="100">
                    <template slot-scope="scope">
                      {{ scope.row.ProjectNumber || 0 }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="TotalPrice" label="总价" align="right" width="100">
                    <template slot-scope="scope">
                      <span class="amount-value">¥{{ formatMoney(scope.row.TotalPrice) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="SourceType" label="来源类型" align="left" width="100">
                    <template slot-scope="scope">
                      <el-tag 
                        :type="getSourceTypeTagType(scope.row.SourceType)" 
                        size="small"
                      >
                        {{ scope.row.SourceType || '无' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="CreateTime" label="创建时间" align="left" width="160">
                    <template slot-scope="scope">
                      {{ formatTime(scope.row.CreateTime) }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="MemberId" label="会员号" align="left" width="140" />
          <el-table-column prop="MemberName" label="会员姓名" align="left" width="100" />
          <el-table-column prop="StoreName" label="门店名称" align="left" width="120" />
          <el-table-column prop="UsageDate" label="耗卡日期" align="left" width="160">
            <template slot-scope="scope">
              {{ formatTime(scope.row.UsageDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="TotalAmount" label="总金额" align="right" width="120">
            <template slot-scope="scope">
              <span class="amount-value">¥{{ formatMoney(scope.row.TotalAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="Remarks" label="备注" align="left" min-width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ parseRemarks(scope.row.Remarks) }}
            </template>
          </el-table-column>
          <el-table-column prop="CreateTime" label="创建时间" align="left" width="160">
            <template slot-scope="scope">
              {{ formatTime(scope.row.CreateTime) }}
            </template>
          </el-table-column>
        </NCC-table>

        <!-- 分页组件 -->
        <pagination 
          v-show="total > 0" 
          :total="total" 
          :page.sync="query.currentPage"
          :limit.sync="query.pageSize" 
          @pagination="getList" 
        />
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import Pagination from '@/components/Pagination'

export default {
  name: 'CardUsageRecord',
  components: {
    Pagination
  },
  data() {
    return {
      kdhyLoading: false,
      kdhyOptions: [],
      query: {
        memberId: '',
        startTime: '',
        endTime: '',
        currentPage: 1,
        pageSize: 20
      },
      list: [],
      total: 0,
      listLoading: false
    }
  },
  created() {
    this.getkdhyOptions()
  },
  methods: {
    // 获取会员选项（初始）
    getkdhyOptions() {
      request({
        url: '/api/Extend/LqKhxx?page=1&pageSize=10',
        method: 'GET',
      }).then((res) => {
        if (res.code == 200 && res.data.list.length > 0) {
          this.kdhyOptions = res.data.list.map(item => ({
            value: item.id,
            label: `${item.khmc}` + '(' + item.sjh + ')',
          }));
        } else {
          this.kdhyOptions = [];
        }
      })
    },
    // 远程搜索会员
    async remoteMethod(query) {
      if (query !== '') {
        this.kdhyLoading = true;
        await request({
          url: '/api/Extend/LqKhxx?page=1&pageSize=20&keyword=' + query,
          method: 'GET',
        }).then((res) => {
          this.kdhyLoading = false;
          if (res.code == 200 && res.data.list.length > 0) {
            this.kdhyOptions = res.data.list.map(item => ({
              value: item.id,
              label: `${item.khmc}` + '(' + item.sjh + ')',
            }));
          } else {
            this.kdhyOptions = [];
          }
        })
      }
    },
    // 获取耗卡记录列表
    getList() {
      if (!this.query.memberId) {
        this.$message({
          type: 'warning',
          message: '请选择会员',
          duration: 1500
        })
        return
      }

      this.listLoading = true

      const params = {
        MemberId: this.query.memberId,
        currentPage: this.query.currentPage,
        pageSize: this.query.pageSize
      }

      if (this.query.startTime) {
        params.StartTime = this.query.startTime
      }
      if (this.query.endTime) {
        params.EndTime = this.query.endTime
      }

      request({
        url: '/api/Extend/lqxhhyhk/GetMemberCardUsageRecord',
        method: 'GET',
        data: params
      }).then(res => {
        if (res.data && res.data.list) {
          this.list = res.data.list
          this.total = (res.data.pagination && res.data.pagination.total) || res.data.list.length || 0
        } else {
          this.list = []
          this.total = 0
        }
        this.listLoading = false
      }).catch(err => {
        console.error('查询失败:', err)
        this.$message({
          type: 'error',
          message: '查询失败，请重试',
          duration: 1500
        })
        this.listLoading = false
      })
    },

    // 查询
    search() {
      this.query.currentPage = 1
      this.getList()
    },

    // 重置查询条件
    reset() {
      this.query = {
        memberId: '',
        startTime: '',
        endTime: '',
        currentPage: 1,
        pageSize: 20
      }
      this.list = []
      this.total = 0
      this.getkdhyOptions()
    },

    // 获取来源类型标签类型
    getSourceTypeTagType(sourceType) {
      if (sourceType === '购买') {
        return 'success'
      } else if (sourceType === '赠送') {
        return 'warning'
      } else if (sourceType === '体验') {
        return 'info'
      }
      return ''
    },

    // 解析备注（处理JSON字符串）
    parseRemarks(remarks) {
      if (!remarks || remarks === '[]') return '无'
      try {
        const parsed = JSON.parse(remarks)
        if (Array.isArray(parsed) && parsed.length > 0) {
          return parsed.join('; ')
        }
        return '无'
      } catch (e) {
        return remarks
      }
    },

    // 格式化金额
    formatMoney(amount) {
      if (!amount && amount !== 0) return '0.00'
      return Number(amount).toFixed(2)
    },

    // 格式化时间
    formatTime(timestamp) {
      if (!timestamp) return '无'
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  }
}
</script>

<style lang="scss" scoped>
.expand-container {
  padding: 16px;
  background: #fafafa;
  
  .expand-title {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 12px;
  }
}

.amount-value {
  color: #409EFF;
  font-weight: 500;
}

.amount-paid {
  color: #67C23A;
  font-weight: 500;
}

.amount-debt {
  color: #F56C6C;
  font-weight: 500;
}
</style>

