<template>
  <el-dialog
    title="额外数据"
    :visible="visible"
    width="1200px"
    :close-on-click-modal="false"
    @close="handleClose"
    class="extra-data-dialog"
  >
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :model="queryParams" :inline="true" label-width="50px">
        <el-form-item label="年份">
          <el-date-picker
            v-model="queryParams.year"
            type="year"
            placeholder="选择年份"
            format="yyyy"
            value-format="yyyy"
            @change="handleQuery"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="月份">
          <el-date-picker
            v-model="queryParams.month"
            type="month"
            placeholder="选择月份"
            format="yyyyMM"
            value-format="yyyyMM"
            @change="handleQuery"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-section">
      <el-button 
        type="success" 
        icon="el-icon-download"
        @click="handleExportTemplate"
        :loading="exportTemplateLoading"
      >
        导出模板
      </el-button>
      <el-button 
        type="primary" 
        icon="el-icon-upload2"
        @click="handleImport"
        :loading="importLoading"
      >
        导入
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <NCC-table 
        v-loading="loading" 
        :data="list" 
        border 
        stripe
        height="400px"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="EmployeeName" label="健康师姓名" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.EmployeeName || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="EmployeePhone" label="健康师电话" width="130" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.EmployeePhone || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="Year" label="年份" width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.Year || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="Month" label="月份" width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.Month || '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="BaseRewardPerformance" label="基础奖励业绩" width="140" align="center">
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.BaseRewardPerformance) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="CooperationRewardPerformance" label="合作奖励业绩" width="140" align="center">
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.CooperationRewardPerformance) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="NewCustomerPerformance" label="新客业绩" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.NewCustomerPerformance) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="NewCustomerConversionRate" label="新客成交率" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ formatPercent(scope.row.NewCustomerConversionRate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="UpgradePerformance" label="升单业绩" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.UpgradePerformance) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="UpgradeConversionRate" label="升单成交率" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ formatPercent(scope.row.UpgradeConversionRate) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="UpgradeCustomerCount" label="升单人头数" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.UpgradeCustomerCount || '0' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="OtherPerformanceAdd" label="其他业绩加" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.OtherPerformanceAdd) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="OtherPerformanceSubtract" label="其他业绩减" width="120" align="center">
          <template slot-scope="scope">
            <span>{{ formatMoney(scope.row.OtherPerformanceSubtract) }}</span>
          </template>
        </el-table-column>
      </NCC-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-section">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="queryParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 导入文件上传（隐藏） -->
    <input
      ref="fileInput"
      type="file"
      accept=".xlsx,.xls"
      style="display: none"
      @change="handleFileInputChange"
    />
  </el-dialog>
</template>

<script>
import { getExtraCalculationList, importExtraCalculationFromExcel } from '@/api/extend/healthCoachSalary'
import request from '@/utils/request'

export default {
  name: 'ExtraDataDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    // 获取当前年月
    const getCurrentYear = () => {
      return new Date().getFullYear().toString()
    }
    const getCurrentMonth = () => {
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      return `${year}${month}`
    }

    return {
      loading: false,
      exportTemplateLoading: false,
      importLoading: false,
      list: [],
      total: 0,
      queryParams: {
        currentPage: 1,
        pageSize: 20,
        Year: getCurrentYear(),
        Month: getCurrentMonth().substring(4, 6), // 只取月份部分
        year: getCurrentYear(), // 用于表单绑定
        month: getCurrentMonth() // 用于表单绑定，yyyyMM格式
      }
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.getList()
      }
    }
  },
  methods: {
    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        // 处理年月：优先使用表单绑定的 year 和 month
        let year = this.queryParams.year || this.queryParams.Year
        let month = ''
        
        // 如果queryParams.month是完整的yyyyMM格式，需要拆分
        if (this.queryParams.month && this.queryParams.month.length === 6) {
          year = this.queryParams.month.substring(0, 4)
          month = this.queryParams.month.substring(4, 6)
        } else if (this.queryParams.year && this.queryParams.month) {
          // 分别选择年份和月份
          year = this.queryParams.year
          month = this.queryParams.month.length === 6 
            ? this.queryParams.month.substring(4, 6) 
            : this.queryParams.month
        } else {
          // 使用默认值
          month = this.queryParams.Month || ''
        }

        // 同步更新 Year 和 Month（用于接口调用）
        this.queryParams.Year = year
        this.queryParams.Month = month

        const params = {
          currentPage: this.queryParams.currentPage,
          pageSize: this.queryParams.pageSize,
          Year: year || '',
          Month: month || ''
        }

        const response = await getExtraCalculationList(params)

        if (response.code === 200) {
          this.list = response.data.list || []
          this.total = (response.data.pagination && response.data.pagination.total) || 0
        } else {
          this.$message.error(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取额外数据列表失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleQuery() {
      this.queryParams.currentPage = 1
      this.getList()
    },

    // 重置搜索
    resetQuery() {
      const getCurrentYear = () => {
        return new Date().getFullYear().toString()
      }
      const getCurrentMonth = () => {
        const now = new Date()
        const year = now.getFullYear()
        const month = String(now.getMonth() + 1).padStart(2, '0')
        return `${year}${month}`
      }

      this.queryParams = {
        currentPage: 1,
        pageSize: 20,
        Year: getCurrentYear(),
        Month: getCurrentMonth().substring(4, 6),
        year: getCurrentYear(),
        month: getCurrentMonth()
      }
      this.getList()
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.queryParams.currentPage = 1
      this.getList()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.queryParams.currentPage = val
      this.getList()
    },

    // 导出模板
    async handleExportTemplate() {
      this.exportTemplateLoading = true
      try {
        // 获取当前筛选的年月
        let year = this.queryParams.Year
        let month = this.queryParams.Month
        
        if (this.queryParams.month && this.queryParams.month.length === 6) {
          year = this.queryParams.month.substring(0, 4)
          month = this.queryParams.month.substring(4, 6)
        } else if (this.queryParams.year && this.queryParams.month) {
          year = this.queryParams.year
          month = this.queryParams.month.length === 6 
            ? this.queryParams.month.substring(4, 6) 
            : this.queryParams.month
        }

        // 获取健康师列表
        const healthCoachResponse = await request({
          url: '/api/Extend/user?page=1&pageSize=1000&gw=健康师',
          method: 'GET'
        })

        if (healthCoachResponse.code !== 200 || !healthCoachResponse.data || !healthCoachResponse.data.list) {
          this.$message.error('获取健康师数据失败')
          return
        }

        const healthCoachList = healthCoachResponse.data.list

        // 动态导入 xlsx 库
        const XLSX = await import('xlsx')

        // 构建表头
        const headers = [
          'id',
          '健康师姓名',
          '健康师电话',
          '年份',
          '月份',
          '基础奖励业绩',
          '合作奖励业绩',
          '新客业绩',
          '新客成交率',
          '升单业绩',
          '升单成交率',
          '升单人头数',
          '其他业绩加',
          '其他业绩减'
        ]

        // 构建数据行
        const dataRows = healthCoachList.map(item => [
          item.id || '',
          item.realName || item.name || item.userName || '无',
          item.mobilePhone || item.telephone || '无',
          year || '',
          month || '',
          '', // 基础奖励业绩
          '', // 合作奖励业绩
          '', // 新客业绩
          '', // 新客成交率
          '', // 升单业绩
          '', // 升单成交率
          '', // 升单人头数
          '', // 其他业绩加
          ''  // 其他业绩减
        ])

        // 合并表头和数据
        const excelData = [headers, ...dataRows]

        // 创建工作表
        const ws = XLSX.utils.aoa_to_sheet(excelData)

        // 设置列宽
        const colWidths = headers.map(() => ({ wch: 15 }))
        ws['!cols'] = colWidths

        // 创建工作簿
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, '健康师额外数据模板')

        // 生成文件名
        const now = new Date()
        const timestamp = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + 
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0') + 
          String(now.getSeconds()).padStart(2, '0')
        const fileName = `健康师额外数据模板_${year}年${month}月_${timestamp}.xlsx`

        // 导出文件
        XLSX.writeFile(wb, fileName)

        this.$message.success('导出模板成功')
      } catch (error) {
        console.error('导出模板失败:', error)
        this.$message.error('导出模板失败，请重试')
      } finally {
        this.exportTemplateLoading = false
      }
    },

    // 导入
    handleImport() {
      this.$refs.fileInput.click()
    },

    // 文件上传前验证
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                     file.type === 'application/vnd.ms-excel'
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isExcel) {
        this.$message.error('只能上传Excel文件!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!')
        return false
      }
      return true
    },

    // 文件输入变化
    handleFileInputChange(event) {
      const file = event.target.files[0]
      if (file) {
        if (this.beforeUpload(file)) {
          this.submitUpload(file)
        }
        // 清空input，以便可以重复选择同一文件
        event.target.value = ''
      }
    },

    // 提交上传
    async submitUpload(file) {
      if (!file) {
        this.$message.warning('请选择要上传的文件')
        return
      }

      this.importLoading = true
      try {
        const response = await importExtraCalculationFromExcel(file)

        if (response.code === 200) {
          this.$message.success('导入成功')
          this.fileList = []
          this.getList()
          this.$emit('refresh')
        } else {
          this.$message.error(response.msg || '导入失败')
        }
      } catch (error) {
        console.error('导入失败:', error)
        this.$message.error(error.message || '导入失败，请重试')
      } finally {
        this.importLoading = false
      }
    },

    // 关闭弹窗
    handleClose() {
      this.$emit('update:visible', false)
      this.$emit('close')
    },

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

    // 格式化百分比
    formatPercent(value) {
      if (value === null || value === undefined || value === '') {
        return '0.00%'
      }
      return (Number(value) * 100).toFixed(2) + '%'
    }
  }
}
</script>

<style lang="scss" scoped>
.extra-data-dialog {
  .search-section {
    margin-bottom: 20px;
    padding: 15px;
    background: #f5f7fa;
    border-radius: 4px;
  }

  .action-section {
    margin-bottom: 20px;
    display: flex;
    gap: 12px;
  }

  .table-section {
    margin-bottom: 20px;
  }

  .pagination-section {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
  }
}
</style>

