<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="门店">
              <el-select
                v-model="query.StoreId"
                placeholder="请选择门店"
                filterable
                clearable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="store in storeOptions"
                  :key="store.id"
                  :label="store.dm"
                  :value="store.id">
                </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"
                format="yyyy-MM-dd"
                placeholder="开始日期"
                :style='{"width":"100%"}'
              />
            </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"
                format="yyyy-MM-dd"
                placeholder="结束日期"
                :style='{"width":"100%"}'
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="品项">
              <el-select
                v-model="query.ItemId"
                placeholder="请选择品项"
                filterable
                clearable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="item in itemOptions"
                  :key="item.id"
                  :label="item.xmmc"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="品项分类">
              <el-select
                v-model="query.ItemCategory"
                placeholder="请选择品项分类"
                filterable
                clearable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="item in itemCategoryOptions"
                  :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-input-number
                v-model="query.MinAmount"
                placeholder="请输入最小金额"
                :min="0"
                :precision="2"
                :style='{"width":"100%"}'
                clearable>
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="最大金额">
              <el-input-number
                v-model="query.MaxAmount"
                placeholder="请输入最大金额"
                :min="0"
                :precision="2"
                :style='{"width":"100%"}'
                clearable>
              </el-input-number>
            </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="statistics-cards" v-if="pageStatistics && pageStatistics.totalCount > 0">
        <el-row :gutter="16">
          <el-col :span="8">
            <div class="statistics-card">
              <div class="card-icon">
                <i class="el-icon-document"></i>
              </div>
              <div class="card-content">
                <div class="card-title">总记录数</div>
                <div class="card-value">{{ pageStatistics.totalCount || 0 }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="statistics-card">
              <div class="card-icon">
                <i class="el-icon-money"></i>
              </div>
              <div class="card-content">
                <div class="card-title">总金额</div>
                <div class="card-value">¥{{ formatMoney(pageStatistics.totalAmount) }}</div>
              </div>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="statistics-card">
              <div class="card-icon">
                <i class="el-icon-goods"></i>
              </div>
              <div class="card-content">
                <div class="card-title">总项目数</div>
                <div class="card-value">{{ pageStatistics.totalProjectNumber || 0 }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 数据表格 -->
      <div class="NCC-common-layout-main NCC-flex-main">
        <NCC-table v-loading="listLoading" :data="list" has-c>
          <el-table-column prop="Id" label="储扣记录ID" width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.Id || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="DeductType" label="扣减类型" >
            <template slot-scope="scope">
              <span>{{ scope.row.DeductType || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="DeductTypeName" label="扣减类型名称" >
            <template slot-scope="scope">
              <span>{{ getDeductTypeName(scope.row.DeductType) || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="BillingId" label="开单ID" width="150">
            <template slot-scope="scope">
              <span>{{ scope.row.BillingId || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="Amount" label="合计金额"  >
            <template slot-scope="scope">
              <span class="amount-value">¥{{ formatMoney(scope.row.Amount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ItemName" label="品项名称" >
            <template slot-scope="scope">
              <span>{{ scope.row.ItemName || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ItemCategory" label="品项分类" >
            <template slot-scope="scope">
              <el-tag 
                :type="getItemCategoryType(scope.row.ItemCategory)" 
                size="small">
                {{ scope.row.ItemCategory || '无' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="BillingDate" label="开单日期">
            <template slot-scope="scope">
              <span>{{ formatDate(scope.row.BillingDate) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="MemberName" label="客户名称" >
            <template slot-scope="scope">
              <span>{{ scope.row.MemberName || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="MemberPhone" label="客户手机号" min-width="130">
            <template slot-scope="scope">
              <span>{{ scope.row.MemberPhone || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="StoreName" label="门店名称" >
            <template slot-scope="scope">
              <span>{{ scope.row.StoreName || '无' }}</span>
            </template>
          </el-table-column>
        </NCC-table>
        <pagination 
          v-show="total > 0" 
          :total="total" 
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize" 
          @pagination="handlePagination" 
        />
      </div>
    </div>
  </div>
</template>

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

export default {
  name: 'DeductList',
  components: {
    Pagination
  },
  data() {
    return {
        query: {
          StoreId: undefined,
          StartTime: undefined,
          EndTime: undefined,
          ItemId: undefined,
          ItemCategory: undefined,
          MinAmount: undefined,
          MaxAmount: undefined
        },
        storeOptions: [],
        itemOptions: [],
        itemCategoryOptions: [],
        list: [],
        listLoading: false,
        total: 0,
        listQuery: {
          currentPage: 1,
          pageSize: 10
        }
    }
  },
  computed: {
    // 基于当前列表数据的统计信息
    pageStatistics() {
      if (!this.list || this.list.length === 0) {
        return {
          totalCount: 0,
          totalAmount: 0,
          totalProjectNumber: 0
        }
      }
      let totalAmount = 0
      let totalProjectNumber = 0
      this.list.forEach(item => {
        const amount = Number(item.Amount) || 0
        const projectNum = Number(item.ProjectNumber) || 0
        totalAmount += amount
        totalProjectNumber += projectNum
      })
      return {
        totalCount: this.list.length,
        totalAmount,
        totalProjectNumber
      }
    }
  },
  created() {
      this.setDefaultTimeRange()
      this.initStoreOptions()
    this.initItemOptions()
      this.initItemCategoryOptions()
    this.search()
  },
  methods: {
    // 设置默认时间范围（本月1号到现在）
    setDefaultTimeRange() {
      const now = new Date()
      const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
      this.query.StartTime = this.formatDate(firstDayOfMonth)
      this.query.EndTime = this.formatDate(now)
    },

    // 初始化门店选项
    initStoreOptions() {
      request({
        url: '/api/Extend/LqMdxx',
        method: 'GET',
        data: {
          currentPage: 1,
          pageSize: 1000
        }
      }).then(res => {
        if (res.data && res.data.list) {
          this.storeOptions = res.data.list
        }
      }).catch(() => {
        this.storeOptions = []
      })
    },

    // 初始化品项选项
    initItemOptions() {
      request({
        url: '/api/Extend/LqXmzl',
        method: 'GET',
        data: {
          currentPage: 1,
          pageSize: 1000
        }
      }).then(res => {
        if (res.data && res.data.list) {
          this.itemOptions = res.data.list
        }
      }).catch(() => {
        this.itemOptions = []
      })
    },

    // 初始化品项分类选项（使用项目资料表 qt2 字段）
    initItemCategoryOptions() {
      request({
        url: '/api/Extend/lqxmzl/GetDistinctFieldData?fieldName=qt2',
        method: 'GET'
      }).then(res => {
        if (res.code === 200 && res.data && res.data.values) {
          this.itemCategoryOptions = res.data.values.map(item => ({
            label: item,
            value: item
          }))
        } else {
          this.itemCategoryOptions = []
        }
      }).catch(() => {
        this.itemCategoryOptions = []
      })
    },

    // 查询数据
    search() {
      this.listLoading = true

      const params = {
        currentPage: this.listQuery.currentPage,
        pageSize: this.listQuery.pageSize
      }

      if (this.query.ItemId) {
        params.ItemId = this.query.ItemId
      }

      if (this.query.StoreId) {
        params.StoreId = this.query.StoreId
      }

      if (this.query.StartTime) {
        params.StartTime = this.query.StartTime
      }

      if (this.query.EndTime) {
        params.EndTime = this.query.EndTime
      }

      if (this.query.ItemCategory) {
        params.ItemCategory = this.query.ItemCategory
      }

      if (this.query.MinAmount !== null && this.query.MinAmount !== undefined && this.query.MinAmount !== '') {
        params.MinAmount = this.query.MinAmount
      }

      if (this.query.MaxAmount !== null && this.query.MaxAmount !== undefined && this.query.MaxAmount !== '') {
        params.MaxAmount = this.query.MaxAmount
      }

      request({
        url: '/api/Extend/lqkdkdjlb/deduct-list',
        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
        this.list = []
        this.total = 0
      })
    },

    // 处理分页变化
    handlePagination({ page, limit }) {
        this.listQuery.currentPage = page
        this.listQuery.pageSize = limit
        this.search()
    },

    // 重置查询条件
    reset() {
        this.query = {
          StoreId: undefined,
          StartTime: undefined,
          EndTime: undefined,
          ItemId: undefined,
          ItemCategory: undefined,
          MinAmount: undefined,
          MaxAmount: undefined
        }
        this.setDefaultTimeRange()
        this.listQuery.currentPage = 1
        this.listQuery.pageSize = 10
        this.list = []
        this.total = 0
        this.search()
    },

    // 格式化金额
    formatMoney(value) {
      if (value === null || value === undefined || value === '') {
        return '0.00'
      }
      const num = parseFloat(value)
      if (isNaN(num)) {
        return '0.00'
      }
      return num.toFixed(2)
    },

    // 格式化日期
    formatDate(value) {
      if (!value) {
        return ''
      }
      const date = new Date(value)
      if (isNaN(date.getTime())) {
        return ''
      }
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    // 获取品项分类的标签类型
    getItemCategoryType(category) {
      if (!category) {
        return 'info'
      }
      if (category === '医美') {
        return 'danger'
      } else if (category === '科美') {
        return 'warning'
      } else if (category === '生美') {
        return 'success'
      }
      return 'info'
    },

    // 获取扣减类型名称
    getDeductTypeName(deductType) {
      if (!deductType) {
        return '无'
      }
      // 根据扣减类型返回对应的名称
      const typeMap = {
        '储值': '储值扣减',
        '品项': '品项扣减',
        '体验': '体验扣减',
        '赠送': '赠送扣减'
      }
      return typeMap[deductType] || deductType
    }
  }
}
</script>

<style lang="scss" scoped>
.amount-value {
  color: #F56C6C;
  font-weight: 500;
}

.statistics-cards {
  margin: 16px 0;
}

.statistics-card {
  height: 100px;
  padding: 12px;
  border-radius: 12px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;

  .card-icon {
    width: 60px;
    height: 60px;
    border-radius: 8px;
    background: linear-gradient(135deg, #409EFF, #67C23A);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;

    i {
      font-size: 24px;
      color: #fff;
    }
  }

  .card-content {
    flex: 1;

    .card-title {
      font-size: 14px;
      color: #909399;
      margin-bottom: 8px;
    }

    .card-value {
      font-size: 22px;
      font-weight: bold;
      color: #303133;
    }
  }
}
</style>

