<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 v-model="query.storeId" placeholder="请选择门店" clearable filterable>
                <el-option v-for="store in storeOptions" :key="store.id" :label="store.dm" :value="store.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="会员号">
              <el-input v-model="query.memberNo" placeholder="请输入会员号" clearable @keyup.enter.native="search()" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="会员姓名">
              <el-input v-model="query.memberName" placeholder="请输入会员姓名" clearable @keyup.enter.native="search()" />
            </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="kdhy" label="会员号"  width="140" /> -->
          <el-table-column prop="kdhyc" label="会员姓名"   />
          <el-table-column prop="kdhysjh" label="手机号"  width="140"/>
          <el-table-column prop="jsj" label="金三角"   width="140"/>
          <el-table-column prop="gjlx" label="顾客类型"  >
            <template slot-scope="scope">
              <el-tag :type="scope.row.gjlx === '会员' ? 'success' : 'info'" size="small">
                {{ scope.row.gjlx || '无' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="kdrq" label="开单日期"  width="160">
            <template slot-scope="scope">
              {{ formatTime(scope.row.kdrq) }}
            </template>
          </el-table-column>
          <el-table-column prop="zdyj" label="指定业绩"  >
            <template slot-scope="scope">
              <span class="amount-value">¥{{ formatMoney(scope.row.zdyj) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="sfyj" label="实付业绩"  >
            <template slot-scope="scope">
              <span class="amount-paid">¥{{ formatMoney(scope.row.sfyj) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="qk" label="欠款"  >
            <template slot-scope="scope">
              <span class="amount-debt">¥{{ formatMoney(scope.row.qk) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="paidDebt" label="已付欠款"  >
            <template slot-scope="scope">
              <span class="amount-paid">¥{{ formatMoney(scope.row.paidDebt) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="deductAmount" label="扣款金额"  >
            <template slot-scope="scope">
              <span class="amount-value">¥{{ formatMoney(scope.row.deductAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="fkfs" label="付款方式"  >
            <template slot-scope="scope">
              {{ scope.row.fkfs || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="ckfs" label="充值方式"  >
            <template slot-scope="scope">
              {{ scope.row.ckfs || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="tjr" label="推荐人"  >
            <template slot-scope="scope">
              {{ scope.row.tjr || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="khly" label="客户来源"  >
            <template slot-scope="scope">
              {{ scope.row.khly || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="sfskdd" label="是否收款单"  >
            <template slot-scope="scope">
              {{ scope.row.sfskdd || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="activityName" label="活动名称"  >
            <template slot-scope="scope">
              {{ scope.row.activityName || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="jj" label="简介"  show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.jj || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="bz" label="备注"  show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.bz || '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="createUserName" label="创建人"  >
            <template slot-scope="scope">
              {{ scope.row.createUserName || '无' }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="操作" width="120" fixed="right">
            <template slot-scope="scope">
              <el-button
                type="danger"
                size="small"
                icon="el-icon-delete"
                :disabled="!scope.row.qk || scope.row.qk <= 0"
                @click="handleClearDebt(scope.row)"
              >
                清空欠款
              </el-button>
            </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: 'DebtRecord',
  components: {
    Pagination
  },
  data() {
    return {
      query: {
        storeId: undefined,
        memberNo: '',
        memberName: '',
        currentPage: 1,
        pageSize: 20
      },
      storeOptions: [],
      list: [],
      total: 0,
      listLoading: false
    }
  },
  created() {
    this.initStoreOptions()
  },
  methods: {
    // 初始化门店选项
    initStoreOptions() {
      request({
        url: '/api/Extend/LqMdxx',
        method: 'GET',
        data: {
          currentPage: 1,
          pageSize: 1000
        }
      }).then(res => {
        this.storeOptions = res.data.list || []
      }).catch(err => {
        console.error('获取门店列表失败:', err)
      })
    },

    // 获取欠款记录列表
    getList() {
      if (!this.query.storeId) {
        this.$message({
          type: 'warning',
          message: '请选择门店',
          duration: 1500
        })
        return
      }

      this.listLoading = true

      const params = {
        StoreId: this.query.storeId,
        currentPage: this.query.currentPage,
        pageSize: this.query.pageSize
      }

      request({
        url: '/api/Extend/lqkdkdjlb/GetDebtRecordByStoreId',
        method: 'GET',
        data: params
      }).then(res => {
        if (res.data && res.data.list) {
          let data = res.data.list

          this.list = data
          this.total = (res.data.pagination && res.data.pagination.total) || 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 = {
        storeId: undefined,
        memberNo: '',
        memberName: '',
        currentPage: 1,
        pageSize: 20
      }
      this.list = []
      this.total = 0
    },

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

    // 清空欠款
    handleClearDebt(row) {
      if (!row.id) {
        this.$message({
          type: 'error',
          message: '数据异常，无法清空欠款',
          duration: 1500
        })
        return
      }

      this.$confirm(`确定要清空会员"${row.kdhyc || '无'}"的欠款吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        request({
          url: `/api/Extend/lqkdkdjlb/clear-debt/${row.id}`,
          method: 'POST'
        }).then(res => {
          this.$message({
            type: 'success',
            message: '清空欠款成功',
            duration: 1500
          })
          // 刷新列表
          this.getList()
        }).catch(err => {
          console.error('清空欠款失败:', err)
          this.$message({
            type: 'error',
            message: err.msg || '清空欠款失败，请重试',
            duration: 1500
          })
        })
      }).catch(() => {
        // 用户取消操作
      })
    }
  }
}
</script>

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

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

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

