<template>
  <el-dialog
    title="批量设置红包"
    :visible.sync="visible"
    width="800px"
    append-to-body
  >
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      style="width: 100%"
    >
      <el-table-column
        type="index"
        label="序号"
        width="80"
        align="center"
      />
      <el-table-column
        prop="periodName"
        label="营期"
        align="center"
      />
      <el-table-column
        label="金额"
        align="center"
        width="200"
      >
        <template slot-scope="scope">
          <el-input-number
            v-model="scope.row.amount"
            :min="0.01"
            :precision="2"
            :step="0.01"
            size="small"
            style="width: 150px"
          />
        </template>
      </el-table-column>
    </el-table>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSave">保 存</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { batchSaveRedPacketByPeriod } from "@/api/course/userCoursePeriod";

export default {
  name: 'BatchRedPacket',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    selectedData: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      loading: false,
      tableData: []
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.initTableData()
      }
    }
  },
  methods: {
    // 初始化表格数据
    initTableData() {
      this.tableData = this.selectedData.map(item => ({
        ...item,
        amount: 0.01
      }))
    },
    // 保存
    handleSave() {
      this.$confirm(`是否确定？确定后营期下的所有公司红包金额都将设置成对应值`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true;
        const saveData = this.tableData.map(item => ({
          periodId: item.periodId,
          redPacketMoney: item.amount
        }));

        batchSaveRedPacketByPeriod(saveData).then(response => {
          if (response.code === 200) {
            this.$message.success('设置成功');
            this.$emit('success');
            this.handleClose();
          } else {
            this.$message.error(response.msg || '批量设置失败');
          }
        }).catch(error => {
          this.$message.error('批量设置失败：' + error.message);
        }).finally(() => {
          this.loading = false;
        });
      })
    },
    // 关闭
    handleClose() {
      this.$emit('update:visible', false)
    }
  }
}
</script>

<style scoped>
.el-input-number {
  width: 100%;
}
</style>
