<template>
  <div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          size="mini"
          :disabled="this.selectCompanyIds.length === 0"
          @click="handleChangeRedPacket"
          v-hasPermi="['course:period:setCompanyRedPacket']"
        >批量设置红包</el-button>
      </el-col>
    </el-row>
    <!-- 公司列表弹窗 -->
    <!--    <el-dialog title="设置红包" :visible.sync="companyDialogVisible" width="800px" append-to-body>-->
    <el-table :data="companyList" border @selection-change="handleSelectionCompany">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="公司名称" prop="companyName" align="center" />
      <el-table-column label="操作" align="center" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleInputAmount(scope.row)"
            v-hasPermi="['course:period:setCourseRedPacket']"
          >设置红包</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--      <div slot="footer" class="dialog-footer">-->
    <!--      </div>-->
    <!--    </el-dialog>-->

    <!-- 课程红包设置弹窗 -->
    <el-dialog title="设置红包金额" :visible.sync="courseDialogVisible" width="1200px" append-to-body>
      <el-table :data="redPacketList" border>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="课程" prop="courseName" align="center" />
        <el-table-column label="小节" prop="videoName" align="center" />
        <el-table-column label="营期日期" prop="dayDate" align="center"/>
        <el-table-column label="红包金额" width="200px" align="center">
          <template slot-scope="scope">
            <el-input-number
              v-model="scope.row.amount"
              :min="0.0"
              :precision="2"
              :step="0.01"
              size="small"
              style="width: 150px"
            >
              <template slot="append">元</template>
            </el-input-number>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="courseDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">保 存</el-button>
      </div>
    </el-dialog>

    <!-- 课程红包设置弹窗 -->
    <el-dialog title="设置红包金额" :visible.sync="batchRedPacketDialog.visible" width="400px" append-to-body>
      <el-form ref="batchRedPacketForm" :model="batchRedPacketDialog.form" label-width="100px">
        <el-form-item label="红包金额" prop="amount" :rules="{required: true, message: '红包金额不能为空', trigger: 'blur'}">
          <div style="display: inline-flex; align-items: center">
            <el-input-number
              v-model="batchRedPacketDialog.form.amount"
              :min="0.1"
              :precision="2"
              :step="0.01"
              size="small"
            >
            </el-input-number>
            <span style="margin-left: 10px">元</span>
          </div>
          <div style="color: rgba(169,88,18,0.9)">金额低于0.1元将自动置为0.1元</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="batchRedPacketDialog.visible = false">取 消</el-button>
        <el-button type="primary"
                   :loading="batchRedPacketDialog.saveLoading"
                   :disabled="batchRedPacketDialog.saveLoading"
                   @click="handleChange">保 存</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getPeriodCompanyList,
  batchSaveRedPacket,
  getPeriodRedPacketList,
  batchSaveRedPacketByCompany
} from "@/api/course/userCoursePeriod";
import redPacket from "@/views/course/userCoursePeriod/redPacket.vue";

export default {
  name: "RedPacket",
  computed: {
    // redPacket() {
    //   return redPacket
    // }
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    activeTab: {
      type: String,
      default: ''
    },
    periodId: {
      type: [String, Number],
      default: ''
    },
    // videoId: {
    //   type: [String, Number],
    //   default: ''
    // }
  },
  data() {
    return {
      // companyDialogVisible: false,
      // activeTab: '',
      courseDialogVisible: false,
      companyList: [],
      redPacketList: [],
      currentCompany: null,
      selectCompanyIds: [],
      batchRedPacketDialog: {
        visible: false,
        form: {
          amount: 0.1
        },
        saveLoading: false,
      }
    };
  },
  created() {
    if(this.activeTab == "company"){
      this.getCompanyList();
    }
  },
  watch: {
    activeTab(val) {
      this.activeTab = val;
      if (val == "company") {
        this.getCompanyList();
      }
    },
    companyDialogVisible(val) {
      if (!val) {
        this.$emit('update:visible', false);
      }
    }
  },
  methods: {
    // 获取公司列表
    getCompanyList() {
      getPeriodCompanyList({
        periodId: this.periodId
      }).then(response => {
        this.companyList = response.data || [];
      });
    },
    // 点击录入金额
    handleInputAmount(row) {
      this.currentCompany = row;
      this.courseDialogVisible = true;
      this.getCourseList();
    },
    // 获取课程列表
    getCourseList() {
      getPeriodRedPacketList({
        periodId: this.periodId,
        companyId: this.currentCompany.companyId
      }).then(response => {
        this.redPacketList = (response.data || []).map(item => ({
          ...item,
          amount:item.amount ?? 0.1
        }));
      });
    },
    // 保存红包金额
    handleSave() {
      // 筛选出有金额的项目
      const validAmountItems = this.redPacketList.filter(item => item.amount >= 0);
      if (validAmountItems.length === 0) {
        this.$message.warning('请至少设置一个红包金额');
        return;
      }

      // 验证金额范围
      const invalidItems = validAmountItems.filter(item => item.amount < 0.0);
      if (invalidItems.length > 0) {
        this.$message.error('红包金额需要大于等于0元');
        return;
      }

      const saveData = validAmountItems.map(item => ({
        companyId: this.currentCompany.companyId,
        redPacketMoney: item.amount,
        videoId: item.videoId,
        periodId: this.periodId,
        dataType: 2
      }));

      batchSaveRedPacket(saveData).then(response => {
        if (response.code === 200) {
          this.$message.success('保存成功');
          this.courseDialogVisible = false;
          this.$emit('success');
        } else {
          this.$message.error(response.msg || "保存失败");
        }
      }).catch(error => {
        this.$message.error("保存失败：" + error.message);
      });
    },
    handleSelectionCompany(selection) {
      this.selectCompanyIds = selection.map(item => item.companyId);
    },
    handleChangeRedPacket() {
      this.batchRedPacketDialog.visible = true
      this.$refs.batchRedPacketForm.resetFields()
    },
    handleChange() {
      if (!this.selectCompanyIds.length) {
        this.$message.warning('请选择公司');
        return;
      }

      this.$refs.batchRedPacketForm.validate((valid) => {
        if (!valid) {
          this.$message.warning('请填写正确的红包金额')
          return;
        }
        this.batchRedPacketDialog.saveLoading = true

        const saveData = {
          periodId: this.periodId,
          companyIds: this.selectCompanyIds,
          redPacketMoney: this.batchRedPacketDialog.form.amount
        }
        batchSaveRedPacketByCompany(saveData).then(response => {
          const {code, msg} = response
          if (code === 200) {
            this.$message.success('保存成功');
            this.batchRedPacketDialog.visible = false;
            this.$emit('success');
          } else {
            this.$message.error(msg || "保存失败");
          }
          this.batchRedPacketDialog.saveLoading = false
        })
      });
    },
  }
};
</script>

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