<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="pxmc" label="项目名称" align="left" width="150" />
                  <el-table-column prop="px" label="项目编号" align="left" width="120" />
                  <el-table-column prop="pxjg" label="项目价格" align="right" width="120">
                    <template slot-scope="scope">
                      <span class="amount-value">¥{{ formatMoney(scope.row.pxjg) }}</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="120">
                    <template slot-scope="scope">
                      <span class="amount-value">¥{{ formatMoney(scope.row.totalPrice) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column prop="actualPrice" label="实付金额" align="right" width="120">
                    <template slot-scope="scope">
                      <span class="amount-paid">¥{{ formatMoney(scope.row.actualPrice) }}</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="remark" label="备注" align="left" show-overflow-tooltip>
                    <template slot-scope="scope">
                      {{ scope.row.remark || '无' }}
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column prop="kdhy" label="会员号" align="left" width="140" />
          <el-table-column prop="kdhyc" label="会员姓名" align="left" width="100" />
          <el-table-column prop="kdhysjh" label="手机号" align="left" width="120" />
          <el-table-column prop="jsj" label="金三角" align="left" width="120">
            <template slot-scope="scope">
              {{ scope.row.jsj || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="gjlx" label="顾客类型" align="left" width="100">
            <template slot-scope="scope">
              <el-tag :type="scope.row.gjlx === '3' ? 'success' : 'info'" size="small">
                {{ getCustomerType(scope.row.gjlx) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="kdrq" label="开单日期" align="left" width="160">
            <template slot-scope="scope">
              {{ formatTime(scope.row.kdrq) }}
            </template>
          </el-table-column>
          <el-table-column prop="zdyj" label="指定业绩" align="right" width="120">
            <template slot-scope="scope">
              <span class="amount-value">¥{{ formatMoney(scope.row.zdyj) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="sfyj" label="实付业绩" align="right" width="120">
            <template slot-scope="scope">
              <span class="amount-paid">¥{{ formatMoney(scope.row.sfyj) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="qk" label="欠款" align="right" width="120">
            <template slot-scope="scope">
              <span class="amount-debt">¥{{ formatMoney(scope.row.qk) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="paidDebt" label="已付欠款" align="right" width="120">
            <template slot-scope="scope">
              <span class="amount-paid">¥{{ formatMoney(scope.row.paidDebt) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="deductAmount" label="扣款金额" align="right" width="120">
            <template slot-scope="scope">
              <span class="amount-value">¥{{ formatMoney(scope.row.deductAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="fkfs" label="付款方式" align="left" width="100">
            <template slot-scope="scope">
              {{ scope.row.fkfs || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="ckfs" label="充值方式" align="left" width="100">
            <template slot-scope="scope">
              {{ scope.row.ckfs || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="fkyy" label="付款原因" align="left" width="120">
            <template slot-scope="scope">
              {{ scope.row.fkyy || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="tjr" label="推荐人" align="left" width="100">
            <template slot-scope="scope">
              {{ scope.row.tjr || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="khly" label="客户来源" align="left" width="100">
            <template slot-scope="scope">
              {{ scope.row.khly || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="sfskdd" label="是否收款单" align="left" width="110">
            <template slot-scope="scope">
              <el-tag 
                :type="scope.row.sfskdd === '是' ? 'warning' : 'info'" 
                size="small"
              >
                {{ scope.row.sfskdd || '无' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createUserName" label="创建人" align="left" width="100">
            <template slot-scope="scope">
              {{ scope.row.createUserName || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="jj" label="简介" align="left" min-width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.jj || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="bz" label="备注" align="left" min-width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.bz || '无' }}
            </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: 'BillingRecord',
  components: {
    Pagination
  },
  data() {
    return {
      kdhyLoading: false,
      kdhyOptions: [],
      query: {
        memberId: '',
        startTime: '',
        endTime: '',
        currentPage: 1,
        pageSize: 20
      },
      list: [],
      total: 0,
      listLoading: false
    }
  },
  created() {
    // 如果有路由参数，自动设置会员ID并查询
    if (this.$route.query.memberId) {
      this.query.memberId = this.$route.query.memberId
      if (this.$route.query.startTime) {
        this.query.startTime = this.$route.query.startTime
      }
      if (this.$route.query.endTime) {
        this.query.endTime = this.$route.query.endTime
      }
      this.search()
    }
    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/lqkdkdjlb/GetBillingRecordByMemberId',
        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()
    },

    // 获取顾客类型
    getCustomerType(type) {
      const typeMap = {
        '1': '散客',
        '2': '体验客',
        '3': '会员'
      }
      return typeMap[type] || '无'
    },

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

    // 格式化金额
    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>

