<template>
  <div class="annual-summary-data-manage">
    <div class="page-header">
      <div class="header-content">
        <div class="header-title">
          <i class="el-icon-document"></i>
          <span>年度经营数据管理</span>
        </div>
        <div class="header-actions">
          <el-upload
            :action="importUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleImportSuccess"
            :before-upload="beforeUpload"
            :on-error="handleImportError"
            accept=".xlsx, .xls"
          >
            <el-button type="primary" icon="el-icon-upload2" size="medium">
              <i class="el-icon-upload2"></i>
              导入年度经营数据
            </el-button>
          </el-upload>
          <el-tooltip effect="dark" content="刷新" placement="top">
            <el-button icon="el-icon-refresh" circle @click="initData()"></el-button>
          </el-tooltip>
        </div>
      </div>
    </div>

    <div class="page-content">
      <div class="search-section">
        <el-form :inline="true" :model="listQuery" class="search-form">
          <el-form-item label="年度">
            <el-date-picker
              v-model="listQuery.year"
              type="year"
              value-format="yyyy"
              placeholder="选择年度"
              clearable
              @change="search()"
            />
          </el-form-item>
          <el-form-item label="月份">
            <el-select
              v-model="listQuery.month"
              placeholder="选择月份"
              clearable
              @change="search()"
              style="width: 150px"
            >
              <el-option v-for="i in 12" :key="i" :label="i + '月'" :value="i" />
            </el-select>
          </el-form-item>
          <el-form-item label="门店名称">
            <el-input
              v-model="listQuery.storeName"
              placeholder="请输入门店名称"
              clearable
              @keyup.enter.native="search()"
              style="width: 200px"
            />
          </el-form-item>
          <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-form>
      </div>

      <div class="table-section">
        <NCC-table
          v-loading="listLoading"
          :data="list"
          border
          stripe
          :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: '600' }"
        >
          <el-table-column
            v-for="col in columnOptions"
            :key="col.prop"
            :prop="col.prop"
            :label="col.label"
            :width="col.width"
            :align="col.align || 'center'"
          >
            <template slot-scope="scope">
              <span v-if="col.formatter" v-html="col.formatter(scope.row)"></span>
              <span v-else>{{ scope.row[col.prop] || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="handleEdit(scope.row)">
                <i class="el-icon-edit"></i>
                编辑
              </el-button>
              <el-button
                size="mini"
                type="text"
                class="NCC-table-delBtn"
                @click="handleDel(scope.row.id)"
              >
                <i class="el-icon-delete"></i>
                删除
              </el-button>
            </template>
          </el-table-column>
        </NCC-table>
        <pagination
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
          @pagination="initData"
        />
      </div>
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="form.id ? '编辑数据' : '新增数据'"
      :visible.sync="dialogVisible"
      width="700px"
      :close-on-click-modal="false"
    >
      <el-form ref="dataForm" :model="form" label-width="120px" label-position="right">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="门店名称">
              <el-input v-model="form.storeName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年度" required>
              <el-input-number v-model="form.year" disabled style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="月份" required>
              <el-input-number v-model="form.month" disabled style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="事业部">
              <el-input v-model="form.businessUnitName" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="本月总业绩">
              <el-input-number
                v-model="form.totalPerformance"
                :precision="2"
                :step="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="本月总消耗">
              <el-input-number
                v-model="form.totalConsume"
                :precision="2"
                :step="100"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="本月客头数">
              <el-input-number v-model="form.headCount" :step="1" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="本月客次数">
              <el-input-number v-model="form.personTime" :step="1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="本月总项目数">
              <el-input-number v-model="form.projectCount" :step="1" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getList, save, del } from '@/api/extend/annualSummary'
import { getToken } from '@/utils/auth'

export default {
  name: 'annualSummaryData',
  data() {
    return {
      listLoading: false,
      list: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        year: null,
        month: null,
        storeName: ''
      },
      columnOptions: [
        { label: '年度', prop: 'year', width: 80, align: 'center' },
        { label: '月份', prop: 'month', width: 80, align: 'center' },
        { label: '门店名称', prop: 'storeName', width: 180, align: 'left' },
        { label: '事业部', prop: 'businessUnitName', width: 150, align: 'left' },
        {
          label: '总业绩',
          prop: 'totalPerformance',
          width: 120,
          align: 'right',
          formatter: (row) => {
            return row.totalPerformance ? `¥${Number(row.totalPerformance).toLocaleString()}` : '¥0'
          }
        },
        {
          label: '总消耗',
          prop: 'totalConsume',
          width: 120,
          align: 'right',
          formatter: (row) => {
            return row.totalConsume ? `¥${Number(row.totalConsume).toLocaleString()}` : '¥0'
          }
        },
        {
          label: '客头数',
          prop: 'headCount',
          width: 100,
          align: 'right',
          formatter: (row) => {
            return row.headCount ? Number(row.headCount).toLocaleString() : '0'
          }
        },
        {
          label: '客次数',
          prop: 'personTime',
          width: 100,
          align: 'right',
          formatter: (row) => {
            return row.personTime ? Number(row.personTime).toLocaleString() : '0'
          }
        },
        {
          label: '总项目数',
          prop: 'projectCount',
          width: 100,
          align: 'right',
          formatter: (row) => {
            return row.projectCount ? Number(row.projectCount).toLocaleString() : '0'
          }
        }
      ],
      dialogVisible: false,
      form: {},
      importUrl: process.env.VUE_APP_BASE_API + '/api/Extend/LqAnnualSummary/import',
      uploadHeaders: { Authorization: getToken() }
    }
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      this.listLoading = true
      getList(this.listQuery)
        .then((res) => {
          this.list = res.data.list
          this.total = res.data.pagination.total
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    search() {
      this.listQuery.currentPage = 1
      this.initData()
    },
    reset() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        year: null,
        month: null,
        storeName: ''
      }
      this.initData()
    },
    handleDel(id) {
      this.$confirm('确定要删除选中的数据吗?', '提示', {
        type: 'warning'
      })
        .then(() => {
          del([id]).then((res) => {
            this.$message.success('删除成功')
            this.initData()
          })
        })
        .catch(() => {})
    },
    handleEdit(row) {
      this.form = { ...row }
      this.dialogVisible = true
    },
    handleSave() {
      save(this.form).then((res) => {
        this.$message.success('保存成功')
        this.dialogVisible = false
        this.initData()
      })
    },
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
                      file.type === 'application/vnd.ms-excel'
      if (!isExcel) {
        this.$message.error('只能上传 Excel 文件!')
        return false
      }
      this.listLoading = true
      return true
    },
    handleImportSuccess(res) {
      this.listLoading = false
      if (res.code === 200) {
        const data = res.data || {}
        const successCount = data.successCount || 0
        const failCount = data.failCount || 0
        if (failCount > 0) {
          const errorMsg = data.errorMessages ? '。' + data.errorMessages : ''
          this.$message.warning(`导入完成：成功 ${successCount} 条，失败 ${failCount} 条${errorMsg}`)
        } else {
          this.$message.success(`导入成功，共导入 ${successCount} 条数据`)
        }
        this.initData()
      } else {
        this.$message.error(res.msg || '导入失败')
      }
    },
    handleImportError(err) {
      this.listLoading = false
      this.$message.error('导入失败，请检查文件格式')
    }
  }
}
</script>

<style lang="scss" scoped>
.annual-summary-data-manage {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 84px);

  .page-header {
    background: #fff;
    border-radius: 8px;
    padding: 20px 24px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-title {
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: 600;
        color: #303133;

        i {
          font-size: 24px;
          color: #409EFF;
          margin-right: 12px;
        }
      }

      .header-actions {
        display: flex;
        align-items: center;
        gap: 12px;
      }
    }
  }

  .page-content {
    background: #fff;
    border-radius: 8px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

    .search-section {
      margin-bottom: 20px;
      padding-bottom: 20px;
      border-bottom: 1px solid #ebeef5;

      .search-form {
        ::v-deep .el-form-item {
          margin-bottom: 0;
        }
      }
    }

    .table-section {
      ::v-deep .el-table {
        .el-table__header th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }

        .el-table__body tr:hover > td {
          background-color: #f5f7fa;
        }
      }
    }
  }
}
</style>
