<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="开始日期" prop="startDate">
        <el-date-picker
          v-model="queryParams.startDate"
          type="date"
          placeholder="选择开始日期"
          value-format="yyyy-MM-dd"
          clearable
        />
      </el-form-item>
      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker
          v-model="queryParams.endDate"
          type="date"
          placeholder="选择结束日期"
          value-format="yyyy-MM-dd"
          clearable
        />
      </el-form-item>
      <el-form-item label="指标名称" prop="indicatorName">
        <el-input
          v-model="queryParams.indicatorName"
          placeholder="请输入指标名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['wecom:customerStatistics:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日期" align="center" prop="curDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.curDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="重要指标" align="center" prop="indicatorName" width="180" :show-overflow-tooltip="true" />
      <el-table-column label="N组(投放)" align="center" prop="ntfGroup" width="100">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.indicatorName === '总成本（当日）'"
            v-model="scope.row.ntfGroup"
            size="mini"
            :controls="false"
            style="width: 100%"
            @blur="handleUpdateCost(scope.row.curDate,scope.row.ntfGroup,'ntfGroup')"
            @keyup.enter.native="handleUpdateCost(scope.row.curDate,scope.row.ntfGroup,'ntfGroup')"
          />
          <span v-else>{{ scope.row.ntfGroup }}</span>
        </template>
      </el-table-column>
      <el-table-column label="O组(公司孵化)" align="center" prop="ofhGroup" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.indicatorName === '总成本（当日）'"
            v-model="scope.row.ofhGroup"
            size="mini"
            :controls="false"
            style="width: 100%"
            @blur="handleUpdateCost(scope.row.curDate,scope.row.ofhGroup,'ofhGroup')"
            @keyup.enter.native="handleUpdateCost(scope.row.curDate,scope.row.ofhGroup,'ofhGroup')"
          />
          <span v-else>{{ scope.row.ofhGroup }}</span>
        </template>
      </el-table-column>
      <el-table-column label="P组(商务)" align="center" prop="pswGroup" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.indicatorName === '总成本（当日）'"
            v-model="scope.row.pswGroup"
            size="mini"
            :controls="false"
            style="width: 100%"
            @blur="handleUpdateCost(scope.row.curDate,scope.row.pswGroup,'pswGroup')"
            @keyup.enter.native="handleUpdateCost(scope.row.curDate,scope.row.pswGroup,'pswGroup')"
          />
          <span v-else>{{ scope.row.pswGroup }}</span>
        </template>
      </el-table-column>
      <el-table-column label="W组(A1组)" align="center" prop="wa1Group" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.indicatorName === '总成本（当日）'"
            v-model="scope.row.wa1Group"
            size="mini"
            :controls="false"
            style="width: 100%"
            @blur="handleUpdateCost(scope.row.curDate,scope.row.wa1Group,'wa1Group')"
            @keyup.enter.native="handleUpdateCost(scope.row.curDate,scope.row.wa1Group,'wa1Group')"
          />
          <span v-else>{{ scope.row.wa1Group }}</span>
        </template>
      </el-table-column>
      <el-table-column label="X组(B1组)" align="center" prop="xb1Group" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.indicatorName === '总成本（当日）'"
            v-model="scope.row.xb1Group"
            size="mini"
            :controls="false"
            style="width: 100%"
            @blur="handleUpdateCost(scope.row.curDate,scope.row.xb1Group,'xb1Group')"
            @keyup.enter.native="handleUpdateCost(scope.row.curDate,scope.row.xb1Group,'xb1Group')"
          />
          <span v-else>{{ scope.row.xb1Group }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Y组(C1组)" align="center" prop="yc1Group" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.indicatorName === '总成本（当日）'"
            v-model="scope.row.yc1Group"
            size="mini"
            :controls="false"
            style="width: 100%"
            @blur="handleUpdateCost(scope.row.curDate,scope.row.yc1Group,'yc1Group')"
            @keyup.enter.native="handleUpdateCost(scope.row.curDate,scope.row.yc1Group,'yc1Group')"
          />
          <span v-else>{{ scope.row.yc1Group }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Z组(D1组)" align="center" prop="zd1Group" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.indicatorName === '总成本（当日）'"
            v-model="scope.row.zd1Group"
            size="mini"
            :controls="false"
            style="width: 100%"
            @blur="handleUpdateCost(scope.row.curDate,scope.row.zd1Group,'zd1Group')"
            @keyup.enter.native="handleUpdateCost(scope.row.curDate,scope.row.zd1Group,'zd1Group')"
          />
          <span v-else>{{ scope.row.zd1Group }}</span>
        </template>
      </el-table-column>
      <el-table-column label="AA组(E1组)" align="center" prop="aaGroup" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.indicatorName === '总成本（当日）'"
            v-model="scope.row.aaGroup"
            size="mini"
            :controls="false"
            style="width: 100%"
            @blur="handleUpdateCost(scope.row.curDate,scope.row.aaGroup,'aaGroup')"
            @keyup.enter.native="handleUpdateCost(scope.row.curDate,scope.row.aaGroup,'aaGroup')"
          />
          <span v-else>{{ scope.row.aaGroup }}</span>
        </template>
      </el-table-column>
      <el-table-column label="AC组(自然流)" align="center" prop="acGroup" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.indicatorName === '总成本（当日）'"
            v-model="scope.row.acGroup"
            size="mini"
            :controls="false"
            style="width: 100%"
            @blur="handleUpdateCost(scope.row.curDate,scope.row.acGroup,'acGroup')"
            @keyup.enter.native="handleUpdateCost(scope.row.curDate,scope.row.acGroup,'acGroup')"
          />
          <span v-else>{{ scope.row.acGroup }}</span>
        </template>
      </el-table-column>
      <el-table-column label="AD组(F1组)" align="center" prop="adGroup" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.indicatorName === '总成本（当日）'"
            v-model="scope.row.adGroup"
            size="mini"
            :controls="false"
            style="width: 100%"
            @blur="handleUpdateCost(scope.row.curDate,scope.row.adGroup,'adGroup')"
            @keyup.enter.native="handleUpdateCost(scope.row.curDate,scope.row.adGroup,'adGroup')"
          />
          <span v-else>{{ scope.row.adGroup }}</span>
        </template>
      </el-table-column>
      <el-table-column label="AE组(G1组)" align="center" prop="aeGroup" width="120">
        <template slot-scope="scope">
          <el-input-number
            v-if="scope.row.indicatorName === '总成本（当日）'"
            v-model="scope.row.aeGroup"
            size="mini"
            :controls="false"
            style="width: 100%"
            @blur="handleUpdateCost(scope.row.curDate,scope.row.aeGroup,'aeGroup')"
            @keyup.enter.native="handleUpdateCost(scope.row.curDate,scope.row.aeGroup,'aeGroup')"
          />
          <span v-else>{{ scope.row.aeGroup }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { listCustomerStatistics, updateCustomerStatistics,exportCustomerStatistics } from "@/api/wecom/customerStatistics"

export default {
  name: "CustomerStatistics",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户统计数据表格数据
      dataList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        startDate: undefined,
        endDate: undefined,
        indicatorName: undefined
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询客户统计数据列表 */
    getList() {
      this.loading = true
      console.log('=== 开始请求数据 ===')
      console.log('查询参数:', this.queryParams)

      listCustomerStatistics(this.queryParams).then(response => {
        console.log('=== API 返回数据 ===')
        console.log('完整响应:', response)
        console.log('rows 数据:', response.rows)
        console.log('total:', response.total)
        console.log('rows 长度:', response.rows ? response.rows.length : 0)

        if (response.rows && response.rows.length > 0) {
          console.log('第一条数据:', response.rows[0])
          console.log('第一条数据的 aaGroup:', response.rows[0].aaGroup)
          console.log('第一条数据的 nGroup:', response.rows[0].nGroup)
        } else {
          console.warn('⚠️ rows 为空或不存在')
        }

        this.dataList = response.rows
        this.total = response.total
        this.loading = false

        console.log('=== 数据绑定完成 ===')
        console.log('dataList:', this.dataList)
        console.log('total:', this.total)
      }).catch(error => {
        console.error('=== API 请求失败 ===')
        console.error('错误信息:', error)
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('/wecom/customerStatistics/export', {
        ...this.queryParams
      }, `客户统计数据_${new Date().getTime()}.xlsx`)
    },
    /** 处理成本更新 */
    handleUpdateCost(date, cost, attr) {
      // 校验 cost 是否为有效数字
      if (cost === '' || cost === null || cost === undefined) {
        this.$modal.msgWarning("请输入成本金额");
        return;
      }

      const numCost = Number(cost);
      if (isNaN(numCost)) {
        this.$modal.msgWarning("成本金额必须为数字");
        return;
      }

      // 可选: 校验是否为负数
      if (numCost < 0) {
        this.$modal.msgWarning("成本金额不能为负数");
        return;
      }

      const formattedDate = this.parseTime(date, '{y}-{m}-{d}');
      updateCustomerStatistics(formattedDate, numCost, attr).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      }).catch(() => {
        this.getList(); // 失败时刷新数据以还原修改
      });
    }
  }
}
</script>
