<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
                :style='{"width":"100%"}'
                v-model="query.jksId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入健康师姓名"
                :remote-method="remoteMethod"
                :loading="jksLoading">
                <el-option
                  v-for="item in jksOptions"
                  :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 prop="jksxm" label="健康师姓名" align="left" width="120" />
          <el-table-column prop="jkszh" label="健康师账号" align="left" width="120" />
          <el-table-column prop="storeName" label="门店名称" align="left" width="120" />
          <el-table-column prop="memberId" label="会员号" align="left" width="140" />
          <el-table-column prop="memberName" label="会员姓名" align="left" width="100" />
          <el-table-column prop="jksyj" label="消耗业绩" align="right" width="120">
            <template slot-scope="scope">
              <span class="amount-value">¥{{ formatMoney(scope.row.jksyj) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="laborCost" label="手工费用" align="right" width="120">
            <template slot-scope="scope">
              <span class="amount-paid">¥{{ formatMoney(scope.row.laborCost) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="kdpxNumber" label="开单品项次数" align="right" width="140">
            <template slot-scope="scope">
              {{ scope.row.kdpxNumber || 0 }}
            </template>
          </el-table-column>
          <el-table-column prop="yjsj" label="业绩时间" align="left" width="160">
            <template slot-scope="scope">
              {{ formatTime(scope.row.yjsj) }}
            </template>
          </el-table-column>
          <el-table-column prop="glkdbh" label="关联开单编号" align="left" width="160" />
          <el-table-column prop="kdpxid" label="开单品项ID" align="left" width="160" />
          <el-table-column prop="jsjId" label="金三角ID" align="left" width="160" />
        </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: 'HealthTeacherPerformance',
  components: {
    Pagination
  },
  data() {
    return {
      jksLoading: false,
      jksOptions: [],
      query: {
        jksId: '',
        startTime: '',
        endTime: '',
        currentPage: 1,
        pageSize: 20
      },
      list: [],
      total: 0,
      listLoading: false
    }
  },
  created() {
    this.setDefaultTimeRange()
    this.getjksOptions()
    this.search()
  },
  methods: {
    // 设置默认时间范围（本月1号到现在）
    setDefaultTimeRange() {
      const now = new Date()
      const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
      
      this.query.startTime = this.formatDateTime(firstDayOfMonth)
      this.query.endTime = this.formatDateTime(now)
    },

    // 格式化日期为 yyyy-MM-dd
    formatDateTime(date) {
      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}`
    },

    // 获取健康师选项（初始）
    getjksOptions() {
      request({
        url: '/api/Extend/user?page=1&pageSize=10&gw=健康师',
        method: 'GET',
      }).then((res) => {
        if (res.code == 200 && res.data.list.length > 0) {
          this.jksOptions = res.data.list.map(item => ({
            value: item.id,
            label: (item.realName || item.name || item.userName) + '(' + (item.mobilePhone || item.account || item.userName) + ')',
          }));
        } else {
          this.jksOptions = [];
        }
      })
    },
    // 远程搜索健康师
    async remoteMethod(query) {
      if (query !== '') {
        this.jksLoading = true;
        await request({
          url: '/api/Extend/user?page=1&pageSize=20&gw=健康师&realName=' + query,
          method: 'GET',
        }).then((res) => {
          this.jksLoading = false;
          if (res.code == 200 && res.data.list.length > 0) {
            this.jksOptions = res.data.list.map(item => ({
              value: item.id,
              label: (item.realName || item.name || item.userName) + '(' + (item.mobilePhone || item.account || item.userName) + ')',
            }));
          } else {
            this.jksOptions = [];
          }
        })
      }
    },
    // 获取健康师消耗业绩列表
    getList() {
      this.listLoading = true

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

      if (this.query.jksId) {
        params.JksId = this.query.jksId
      }

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

      request({
        url: '/api/Extend/lqxhhyhk/GetJksyjList',
        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 = {
        jksId: '',
        startTime: '',
        endTime: '',
        currentPage: 1,
        pageSize: 20
      }
      this.setDefaultTimeRange()
      this.list = []
      this.total = 0
      this.getjksOptions()
      this.search()
    },

    // 格式化金额
    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>
.amount-value {
  color: #409EFF;
  font-weight: 500;
}

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

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

