<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2>主任工资</h2>
        <p class="page-desc">管理主任工资数据，包括业绩、提成、补贴、扣款等信息</p>
      </div>
      <div class="header-right">
        <el-button 
          type="primary" 
          icon="el-icon-cpu"
          @click="showCalculateDialog"
          :loading="calculateLoading"
        >
          计算工资
        </el-button>
        <el-button 
          icon="el-icon-refresh" 
          @click="getList"
          :loading="loading"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="50px">
        <el-form-item label="月份" prop="month">
          <el-date-picker
            v-model="queryParams.month"
            type="month"
            placeholder="选择月份"
            format="yyyyMM"
            value-format="yyyyMM"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="门店" prop="storeId">
          <el-select 
            v-model="queryParams.storeId" 
            placeholder="请选择门店"
            clearable
            filterable
            style="width: 200px"
          >
            <el-option
              v-for="store in storeList"
              :key="store.id"
              :label="store.fullName"
              :value="store.id"
            />
          </el-select>
        </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="table-container">
      <NCC-table 
        v-loading="loading" 
        :data="list" 
        border 
        stripe
        height="calc(100vh - 420px)"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <!-- 基本信息 -->
        <el-table-column prop="StoreName" label="门店名称" width="140" align="center" fixed="left">
          <template slot-scope="scope">
            <div class="store-name">
              <i class="el-icon-shop store-icon"></i>
              <span>{{ scope.row.StoreName || '无' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="EmployeeName" label="员工姓名" width="100" align="center" fixed="left">
          <template slot-scope="scope">
            <div class="employee-name">
              <i class="el-icon-user employee-icon"></i>
              <span>{{ scope.row.EmployeeName || '无' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="Position" label="岗位" width="100" align="center" fixed="left">
          <template slot-scope="scope">
            <span>{{ scope.row.Position || '无' }}</span>
          </template>
        </el-table-column>

        <!-- 动态列：根据返回数据自动渲染 -->
        <el-table-column
          v-for="(value, key) in tableColumns"
          :key="key"
          :prop="key"
          :label="value.label"
          :width="value.width || 120"
          :align="value.align || 'center'"
        >
          <template slot-scope="scope">
            <span v-if="value.type === 'money'">{{ formatMoney(scope.row[key]) }}</span>
            <span v-else-if="value.type === 'percent'">{{ formatPercent(scope.row[key]) }}</span>
            <span v-else>{{ scope.row[key] || '无' }}</span>
          </template>
        </el-table-column>
      </NCC-table>
    </div>

    <!-- 计算工资弹窗 -->
    <el-dialog
      title="计算主任工资"
      :visible="calculateDialogVisible"
      width="500px"
      :close-on-click-modal="false"
      @close="handleCalculateDialogClose"
    >
      <el-form label-width="100px" label-position="right">
        <el-form-item label="选择年份" required>
          <el-date-picker
            v-model="calculateYear"
            type="year"
            placeholder="请选择年份"
            format="yyyy"
            value-format="yyyy"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="选择月份" required>
          <el-date-picker
            v-model="calculateMonth"
            type="month"
            placeholder="请选择月份"
            format="yyyyMM"
            value-format="yyyyMM"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCalculateDialogClose">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleCalculateConfirm"
          :loading="calculateLoading"
        >
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDirectorSalaryList, calculateDirectorSalary } from '@/api/extend/directorSalary'
import { getStoreSelector } from '@/api/extend/store'

export default {
  name: 'DirectorSalary',
  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,
      calculateLoading: false,
      list: [],
      total: 0,
      storeList: [],
      calculateDialogVisible: false,
      calculateYear: getCurrentYear(),
      calculateMonth: getCurrentMonth(),
      queryParams: {
        currentPage: 1,
        pageSize: 300, // 写死为300
        year: getCurrentYear(),
        month: getCurrentMonth(), // yyyyMM 格式
        storeId: ''
      },
      // 表格列配置（根据实际返回数据动态生成）
      tableColumns: {}
    }
  },
  created() {
    this.getStoreList()
    this.getList()
  },
  methods: {
    // 获取门店列表
    async getStoreList() {
      try {
        const response = await getStoreSelector()
        this.storeList = response.data.list || []
      } catch (error) {
        console.error('获取门店列表失败:', error)
        this.storeList = []
      }
    },

    // 获取列表数据
    async getList() {
      this.loading = true
      try {
        // 处理年月：从month选择器中提取年份和月份
        let year = ''
        let month = ''
        
        if (this.queryParams.month && this.queryParams.month.length === 6) {
          // yyyyMM 格式，如 202512
          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 {
          // 使用默认值（当前年月）
          const now = new Date()
          year = now.getFullYear().toString()
          month = String(now.getMonth() + 1).padStart(2, '0')
        }

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

        const response = await getDirectorSalaryList(params)

        if (response.code === 200) {
          this.list = response.data.list || []
          this.total = (response.data.pagination && response.data.pagination.total) || 0
          
          // 根据返回数据动态生成表格列
          if (this.list.length > 0) {
            this.generateTableColumns(this.list[0])
          }
        } else {
          this.$message.error(response.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取主任工资列表失败:', error)
        this.$message.error('获取数据失败'+error)
      } finally {
        this.loading = false
      }
    },

    // 根据数据动态生成表格列
    generateTableColumns(sampleData) {
      if (!sampleData || typeof sampleData !== 'object') {
        this.tableColumns = {}
        return
      }

      const columns = {}
      const excludeFields = ['StoreName', 'EmployeeName', 'Position', 'Id', 'CreateTime', 'UpdateTime', 'CreateUser', 'UpdateUser', 'StatisticsMonth']
      
      // 金额字段关键词
      const moneyFields = ['Performance', 'Commission', 'Salary', 'Subsidy', 'Deduction', 'Amount', 'Fee', 'Bonus', 'Deposit', 'Supplement', 'Payment', 'Consumption', 'Reward', 'Handwork', 'Gross', 'Guaranteed', 'Transportation', 'Allowance', 'Total']
      // 百分比字段关键词
      const percentFields = ['Point', 'Rate', 'Percentage', 'Percent']
      
      // 定义字段顺序（重要字段优先）
      const fieldOrder = [
        'GoldTriangleTeam', 'TotalPerformance', 'BasePerformance', 'CooperationPerformance',
        'TotalCommission', 'BasePerformanceCommission', 'CooperationPerformanceCommission',
        'FinalGrossSalary', 'ActualSalary', 'TotalSubsidy', 'TotalDeduction',
        'IsLocked', 'IsNewStore', 'NewStoreProtectionStage'
      ]
      
      // 先处理有序字段
      const processedFields = new Set()
      fieldOrder.forEach(key => {
        if (sampleData.hasOwnProperty(key) && !excludeFields.includes(key)) {
          processedFields.add(key)
          const type = this.getFieldType(key)
          columns[key] = {
            label: this.formatFieldLabel(key),
            width: this.getColumnWidth(key, type),
            align: 'center',
            type: type,
            order: fieldOrder.indexOf(key)
          }
        }
      })
      
      // 再处理其他字段
      Object.keys(sampleData).forEach(key => {
        if (!excludeFields.includes(key) && !processedFields.has(key)) {
          const type = this.getFieldType(key)
          columns[key] = {
            label: this.formatFieldLabel(key),
            width: this.getColumnWidth(key, type),
            align: 'center',
            type: type,
            order: 999 // 其他字段排在后面
          }
        }
      })
      
      // 按order排序
      const sortedColumns = {}
      Object.keys(columns)
        .sort((a, b) => columns[a].order - columns[b].order)
        .forEach(key => {
          sortedColumns[key] = columns[key]
        })
      
      this.tableColumns = sortedColumns
    },

    // 获取字段类型
    getFieldType(key) {
      const lowerKey = key.toLowerCase()
      
      // 状态类字段始终是文本类型（如 Status、Reached、IsNewStore 等）
      const statusFields = ['status', 'reached', 'isnewstore', 'islocked']
      if (statusFields.some(field => lowerKey.includes(field))) {
        return 'text'
      }
      
      const moneyFields = ['performance', 'commission', 'salary', 'subsidy', 'deduction', 'amount', 'fee', 'bonus', 'deposit', 'supplement', 'payment', 'consumption', 'reward', 'handwork', 'gross', 'guaranteed', 'transportation', 'allowance', 'total']
      const percentFields = ['point', 'rate', 'percentage', 'percent']
      
      // 注意：payment 需要排除 PaymentStatus 这种状态字段
      if (moneyFields.some(field => lowerKey.includes(field)) && !lowerKey.includes('status')) {
        return 'money'
      } else if (percentFields.some(field => lowerKey.includes(field))) {
        return 'percent'
      }
      return 'text'
    },

    // 格式化字段标签
    formatFieldLabel(key) {
      // 字段名中文映射
      const labelMap = {
        // 业绩相关
        'StoreTotalPerformance': '门店总业绩',
        'StoreBillingPerformance': '门店开单业绩',
        'StoreRefundPerformance': '门店退卡业绩',
        'StoreLifeline': '门店生命线',
        'PerformanceCompletionRate': '业绩完成率',
        'TotalPerformance': '总业绩',
        'BasePerformance': '基础业绩',
        'CooperationPerformance': '合作业绩',
        'GoldTriangleTeam': '金三角团队',
        
        // 考核相关
        'PerformanceReached': '业绩是否达标',
        'HeadCountReached': '人头是否达标',
        'ConsumeReached': '消耗是否达标',
        'AssessmentDeduction': '考核扣款金额',
        'UnreachedIndicatorCount': '未达标指标数量',
        
        // 人头相关
        'HeadCount': '进店消耗人数',
        'TargetHeadCount': '目标人头数',
        
        // 消耗相关
        'StoreConsume': '门店消耗金额',
        'TargetConsume': '目标消耗金额',
        
        // 提成相关
        'CommissionRateBelowLifeline': '≤生命线部分提成比例',
        'CommissionRateAboveLifeline': '>生命线部分提成比例',
        'CommissionAmountBelowLifeline': '≤生命线部分提成金额',
        'CommissionAmountAboveLifeline': '>生命线部分提成金额',
        'TotalCommissionAmount': '提成总金额',
        'TotalCommission': '提成合计',
        'BasePerformanceCommission': '基础业绩提成',
        'CooperationPerformanceCommission': '合作业绩提成',
        
        // 底薪相关
        'BaseSalary': '底薪金额',
        'ActualBaseSalary': '实际底薪',
        
        // 考勤相关
        'WorkingDays': '在店天数',
        'LeaveDays': '请假天数',
        
        // 工资相关
        'GrossSalary': '应发工资',
        'FinalGrossSalary': '最终应发工资',
        'ActualSalary': '实发工资',
        
        // 扣款相关
        'TotalDeduction': '扣款合计',
        'MissingCard': '缺卡扣款',
        'LateArrival': '迟到扣款',
        'LeaveDeduction': '请假扣款',
        'SocialInsuranceDeduction': '扣社保',
        'RewardDeduction': '扣除奖励',
        'AccommodationDeduction': '扣住宿费',
        'StudyPeriodDeduction': '扣学习期费用',
        'WorkClothesDeduction': '扣工作服费用',
        
        // 补贴相关
        'TotalSubsidy': '补贴合计',
        'MonthlyTrainingSubsidy': '当月培训补贴',
        'MonthlyTransportSubsidy': '当月交通补贴',
        'LastMonthTrainingSubsidy': '上月培训补贴',
        'LastMonthTransportSubsidy': '上月交通补贴',
        
        // 奖金相关
        'Bonus': '发奖金',
        'ReturnPhoneDeposit': '退手机押金',
        'ReturnAccommodationDeposit': '退住宿押金',
        
        // 支付相关
        'MonthlyPaymentStatus': '当月是否发放',
        'PaidAmount': '支付金额',
        'PendingAmount': '待支付金额',
        'LastMonthSupplement': '补发上月',
        'MonthlyTotalPayment': '当月支付总额',
        
        // 其他
        'IsLocked': '是否锁定',
        'StoreType': '门店类型',
        'StoreCategory': '门店类别',
        'IsNewStore': '是否新店',
        'NewStoreProtectionStage': '新店保护阶段'
      }
      
      return labelMap[key] || key
    },

    // 获取列宽
    getColumnWidth(key, type) {
      if (type === 'money' || type === 'percent') {
        return 120
      }
      if (key.length > 10) {
        return 150
      }
      return 120
    },

    // 搜索
    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: 300, // 写死为300
        year: getCurrentYear(),
        month: getCurrentMonth(),
        storeId: ''
      }
      this.getList()
    },

    // 显示计算工资弹窗
    showCalculateDialog() {
      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.calculateYear = getCurrentYear()
      this.calculateMonth = getCurrentMonth()
      this.calculateDialogVisible = true
    },

    // 关闭计算工资弹窗
    handleCalculateDialogClose() {
      this.calculateDialogVisible = false
    },

    // 确认计算工资
    async handleCalculateConfirm() {
      if (!this.calculateYear || !this.calculateMonth) {
        this.$message.warning('请选择年份和月份')
        return
      }

      // 从calculateMonth中提取月份（yyyyMM格式，如202512）
      const year = this.calculateYear
      const month = this.calculateMonth.length === 6 
        ? this.calculateMonth.substring(4, 6) 
        : this.calculateMonth

      this.calculateLoading = true
      try {
        const response = await calculateDirectorSalary(year, month)
        if (response.code === 200) {
          this.$message.success('计算工资成功')
          this.calculateDialogVisible = false
          this.getList()
        } else {
          this.$message.error(response.msg || '计算工资失败')
        }
      } catch (error) {
        console.error('计算工资失败:', error)
        this.$message.error(error.message || '计算工资失败')
      } finally {
        this.calculateLoading = false
      }
    },

    // 格式化金额
    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>
.app-container {
  padding: 20px;
  background: #f5f5f5;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

  .header-left {
    h2 {
      margin: 0 0 8px 0;
      color: #303133;
      font-size: 20px;
      font-weight: 600;
    }

    .page-desc {
      margin: 0;
      color: #909399;
      font-size: 14px;
    }
  }

  .header-right {
    display: flex;
    gap: 12px;
  }
}

.search-container {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-container {
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.store-name,
.employee-name {
  display: flex;
  align-items: center;
  gap: 6px;

  .store-icon,
  .employee-icon {
    color: #409EFF;
    font-size: 16px;
  }
}

// 表格样式优化
::v-deep .el-table {
  .el-table__header-wrapper {
    th {
      background-color: #f5f7fa;
      color: #606266;
      font-weight: 600;
    }
  }

  .el-table__body-wrapper {
    .el-table__row {
      &:hover {
        background-color: #f5f7fa;
      }
    }
  }
}
</style>

