<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-date-picker 
                v-model="query.startTime" 
                type="datetime" 
                value-format="yyyy-MM-dd HH:mm:ss" 
                format="yyyy-MM-dd HH:mm:ss" 
                placeholder="开始时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束时间">
              <el-date-picker 
                v-model="query.endTime" 
                type="datetime" 
                value-format="yyyy-MM-dd HH:mm:ss" 
                format="yyyy-MM-dd HH:mm:ss" 
                placeholder="结束时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开单活动">
              <el-select
                v-model="query.activityId"
                placeholder="请选择开单活动"
                filterable
                clearable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="item in activityOptions"
                  :key="item.id"
                  :label="item.activityName"
                  :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.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.memberId"
                placeholder="请选择会员"
                filterable
                remote
                :remote-method="remoteMemberMethod"
                :loading="memberLoading"
                clearable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="item in memberOptions"
                  :key="item.id"
                  :label="`${item.khmc}(${item.sjh || ''} ${item.gsmdName || ''})`"
                  :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.itemType"
                placeholder="请选择品项类型"
                filterable
                clearable
                :style='{"width":"100%"}'>
                <el-option
                  v-for="item in itemTypeOptions"
                  :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-select
                v-model="query.SourceType"
                placeholder="请选择购买类型"
                clearable
                :style='{"width":"100%"}'>
                <el-option label="购买" value="购买" />
                <el-option label="赠送" value="赠送" />
                <el-option label="体验" value="体验" />
              </el-select>
            </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 prop="billingTime" label="开单时间" min-width="160">
            <template slot-scope="scope">
              <i class="el-icon-time" style="margin-right: 4px; color: #409EFF;"></i>
              <span>{{ formatDateTime(scope.row.billingTime) || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="memberName" label="会员名称" min-width="120">
            <template slot-scope="scope">
              <i class="el-icon-user" style="margin-right: 4px; color: #409EFF;"></i>
              <span>{{ scope.row.memberName || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="memberPhone" label="会员手机号" min-width="120">
            <template slot-scope="scope">
              <i class="el-icon-phone" style="margin-right: 4px; color: #67C23A;"></i>
              <span>{{ scope.row.memberPhone || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="itemName" label="品项名称" min-width="150">
            <template slot-scope="scope">
              <i class="el-icon-goods" style="margin-right: 4px; color: #409EFF;"></i>
              <span>{{ scope.row.itemName || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="itemType" label="品项类型" min-width="100">
            <template slot-scope="scope">
              <el-tag 
                :type="getItemTypeTagType(scope.row.itemType)" 
                size="small">
                {{ scope.row.itemType || '无' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="activityName" label="营销活动名称" min-width="150">
            <template slot-scope="scope">
              <i class="el-icon-tickets" style="margin-right: 4px; color: #67C23A;"></i>
              <span>{{ scope.row.activityName || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="actualPrice" label="实付金额" min-width="120" align="right">
            <template slot-scope="scope">
              <i class="el-icon-money" style="margin-right: 4px; color: #67C23A;"></i>
              <span class="amount-paid">¥{{ formatMoney(scope.row.actualPrice) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="projectNumber" label="项目数" min-width="100" align="right">
            <template slot-scope="scope">
              <i class="el-icon-menu" style="margin-right: 4px; color: #67C23A;"></i>
              <span>{{ scope.row.projectNumber || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="sourceType" label="来源类型" min-width="100">
            <template slot-scope="scope">
              <i class="el-icon-link" style="margin-right: 4px; color: #909399;"></i>
              <span>{{ scope.row.sourceType || '无' }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              <i class="el-icon-edit-outline" style="margin-right: 4px; color: #909399;"></i>
              <span>{{ scope.row.remark || '无' }}</span>
            </template>
          </el-table-column>
        </NCC-table>
        <pagination 
          v-show="total > 0" 
          :total="total" 
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize" 
          @pagination="search" 
        />
      </div>
    </div>
  </div>
</template>

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

export default {
  name: 'BillingItemDetailList',
  components: {
    Pagination
  },
  data() {
    return {
      query: {
        startTime: undefined,
        endTime: undefined,
        activityId: undefined,
        itemId: undefined,
        memberId: undefined,
        itemType: undefined,
        SourceType: undefined
      },
      activityOptions: [],
      itemOptions: [],
      itemTypeOptions: [],
      memberOptions: [],
      memberLoading: false,
      list: [],
      listLoading: false,
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20
      }
    }
  },
  created() {
    this.setDefaultTimeRange()
    this.initActivityOptions()
    this.initItemOptions()
    this.initItemTypeOptions()
    this.initMemberOptions()
    this.search()
  },
  methods: {
    // 设置默认时间范围（本月1号到现在）
    setDefaultTimeRange() {
      const now = new Date()
      const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
      
      this.query.startTime = this.formatDateTime(firstDayOfMonth.getTime())
      this.query.endTime = this.formatDateTime(now.getTime())
    },

    // 初始化开单活动选项
    initActivityOptions() {
      request({
        url: '/api/Extend/lqpackageinfo/GetPackageInfoListAsync',
        method: 'GET',
        data: {
          currentPage: 1,
          pageSize: 1000
        }
      }).then(res => {
        if (res.data && res.data.list) {
          this.activityOptions = res.data.list
        }
      }).catch(() => {
        this.activityOptions = []
      })
    },

    // 初始化品项选项
    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字段数据）
    initItemTypeOptions() {
      request({
        url: '/api/Extend/lqxmzl/GetDistinctFieldData?fieldName=qt2',
        method: 'GET'
      }).then(res => {
        if (res.code == 200 && res.data && res.data.values) {
          this.itemTypeOptions = res.data.values.map(item => ({
            label: item,
            value: item
          }))
        } else {
          this.itemTypeOptions = []
        }
      }).catch(() => {
        this.itemTypeOptions = []
      })
    },

    // 初始化会员选项
    initMemberOptions() {
      request({
        url: '/api/Extend/LqKhxx',
        method: 'GET',
        data: {
          currentPage: 1,
          pageSize: 10
        }
      }).then(res => {
        if (res.code == 200 && res.data.list && res.data.list.length > 0) {
          this.memberOptions = res.data.list
        }
      }).catch(() => {
        this.memberOptions = []
      })
    },

    // 会员远程搜索
    remoteMemberMethod(query) {
      if (query !== '') {
        this.memberLoading = true
        request({
          url: '/api/Extend/LqKhxx',
          method: 'GET',
          data: {
            currentPage: 1,
            pageSize: 20,
            keyword: query
          }
        }).then(res => {
          this.memberLoading = false
          if (res.code == 200 && res.data.list && res.data.list.length > 0) {
            this.memberOptions = res.data.list
          } else {
            this.memberOptions = []
          }
        }).catch(() => {
          this.memberLoading = false
          this.memberOptions = []
        })
      } else {
        this.memberOptions = []
      }
    },

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

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

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

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

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

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

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

      if (this.query.itemType) {
        params.itemType = this.query.itemType
      }
      if (this.query.SourceType) {
        params.SourceType = this.query.SourceType
      }

      request({
        url: '/api/Extend/lqkdkdjlb/billing-item-detail-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
      })
    },

    // 重置查询条件
    reset() {
      this.query = {
        startTime: undefined,
        endTime: undefined,
        activityId: undefined,
        itemId: undefined,
        memberId: undefined,
        itemType: undefined,
        SourceType: undefined
      }
      this.setDefaultTimeRange()
      this.listQuery.currentPage = 1
      this.listQuery.pageSize = 20
      this.list = []
      this.total = 0
    },

    // 获取品项类型的标签类型
    getItemTypeTagType(itemType) {
      const typeMap = {
        '购买': 'success',
        '赠送': 'info',
        '体验': 'warning'
      }
      return typeMap[itemType] || ''
    },

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

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '无'
      try {
        const date = new Date(dateTime)
        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}`
      } catch (e) {
        return dateTime
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.amount-paid {
  color: #67C23A;
  font-weight: 500;
}
</style>

