<!--  -->
<template>
  <div>
    <el-form :model="form" :rules="rules" ref="ruleForm">
      <p style="color: red; padding: 0 0 10px 100px">
        注意：活动所有奖品的中奖概率之和必须等于100%;
        <br />活动奖品必须选择一个默认奖品，该奖品建议设置为谢谢参与;
      </p>
      <el-form-item label="所属活动" prop="groupId" label-width="100PX">
        <el-select
          v-model.trim="form.groupId"
          style="width: 100% !important"
          placeholder="请选择所属活动"
          :disabled="true"
        >
          <el-option
            v-for="item in groupList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <div v-for="(reword, index) in form.rewordList" :key="index">
        <el-row :gutter="10">
          <el-col :span="9">
            <el-form-item
              :label="`奖品${index + 1}`"
              label-width="100PX"
              :prop="'rewordList.' + index + '.name'"
              :rules="[
                { required: true, message: '请输入活动名称', trigger: 'blur' },
              ]"
            >
              <el-input
                v-model.trim="reword.name"
                autocomplete="off"
                placeholder="请输入奖品名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item
              :prop="'rewordList.' + index + '.chances'"
              :rules="[
                { required: true, validator: validNumber, trigger: 'blur' },
              ]"
            >
              <el-input
                v-model.trim="reword.chances"
                type="number"
                autocomplete="off"
                placeholder="请输入中奖概率"
              >
                <i
                  slot="suffix"
                  class="el-input__icon"
                  style="padding-right: 5px"
                  >%</i
                >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item
              :prop="'rewordList.' + index + '.stock'"
              :rules="[
                { required: true, validator: validNumber1, trigger: 'blur' },
              ]"
            >
              <el-input
                v-model.trim="reword.stock"
                type="number"
                autocomplete="off"
                placeholder="请输入库存"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item
              :prop="'rewordList.' + index + '.isDefault'"
              :rules="[
                {
                  required: true,
                  message: '请输入选择是否默认',
                  trigger: 'blur',
                },
              ]"
            >
              <el-select
                v-model.trim="reword.isDefault"
                style="width: 100% !important"
                placeholder="请选择是否默认"
              >
                <el-option :value="true" label="是"></el-option>
                <el-option :value="false" label="否"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="1">
            <i
              class="el-icon-delete delete"
              v-if="!(form.rewordList.length <= 1)"
              @click="deteleRow(reword, index)"
            ></i>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item
            label="备注"
            label-width="100px"
            :prop="'rewordList.' + index + '.memo'"
          >
            <el-input
              type="textarea"
              :rows="2"
              v-model.trim="reword.memo"
              autocomplete="off"
              placeholder="请输入备注"
            ></el-input>
          </el-form-item>
        </el-row>
      </div>
      <div style="text-align: center">
        <el-button
          :disabled="form.rewordList.length <= 1"
          class="add-reword"
          round
          icon="el-icon-minus"
          @click="onRemoveReword"
          >删除奖品</el-button
        >
        <el-button
          class="add-reword"
          round
          icon="el-icon-plus"
          @click="onAddReword"
          >添加奖品</el-button
        >
      </div>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="onClose('ruleForm')">取 消</el-button>
      <el-button type="primary" @click="onSubmit('ruleForm')">确 定</el-button>
    </div>
  </div>
</template>

<script>
import Tooltip from "@/components/Tooltip/index";
import pagination from "@/components/Pagination/index";
import dayjs from "dayjs";
import numeral from "numeral";
import cleanDeep from "clean-deep";
import { luckDrawPrizeBatchAdd } from "./api";
const validNumber1 = (rule, value, callback) => {
  const re = /^[0-9]+$/;
  if ((value == "" && typeof value == "string") || value == null) {
    callback(new Error("请输入库存"));
  } else if (!re.test(value) && value < 0) {
    callback(new Error("输入库存为正整数"));
  } else {
    callback();
  }
};
const validNumber = (rule, value, callback) => {
  if ((value == "" && typeof value == "string") || value == null) {
    callback(new Error("请输入中奖概率"));
  } else if (value < 0) {
    callback(new Error("输入值不能小于0"));
  } else {
    callback();
  }
};
export default {
  components: { pagination, Tooltip },
  props: ["groupList", "close", "getList", "list"],
  data() {
    return {
      validNumber1: validNumber1,
      validNumber: validNumber,
      form: {
        groupId: Number(this.$route.query.groupId),
        rewordList: [
          {
            name: null,
            chances: null,
            stock: null,
            isDefault: null,
            memo: null,
          },
        ],
      },
      rules: {
        groupId: [
          { required: true, message: "请选择所属活动", trigger: "change" },
        ],
      },
      pageInfo: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 1, // 总条数
        page_size: [10, 20, 40, 50], // 选择限制显示条数
      },
    };
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    if (this.list && Array.isArray(this.list)) {
      let arr = this.list.map((item) => {
        return {
          name: item.name,
          stock: item.stock,
          isDefault: item.isDefault,
          memo: item.memo,
          chances: item.chances * 100,
          id: item.id,
        };
      });
      console.log(arr);
      this.$set(this.form, "rewordList", arr);
      this.$forceUpdate();
    }
  },
  methods: {
    onRemoveReword() {
      // 删除奖品
      let form = this.form;
      if (form.rewordList.length <= 1) {
        return;
      }
      this.form.rewordList.pop();
    },
    deteleRow(row, index) {
      let form = this.form;
      if (form.rewordList.length <= 1) {
        return;
      }
       this.form.rewordList.splice(index,1);
    },
    onAddReword() {
      // 添加奖品
      let form = this.form;
      form.rewordList.push({
        name: null,
        chances: null,
        stock: null,
        isDefault: null,
      });
    },
    onSubmit(formName) {
      this.$refs[formName].validate((item) => {
        if (item) {
          let form = Object.assign({}, this.form);
          const rewordList = form.rewordList ? form.rewordList : [];
          let params = [];
          let chanceCount = 0;
          rewordList.forEach((item) => {
            chanceCount += Number(item.chances);
            params.push({
              name: item.name,
              groupId: form.groupId,
              chances: numeral(item.chances ? item.chances / 100 : 0).format(
                "0.0000"
              ),
              stock: item.stock,
              isDefault: item.isDefault,
              memo: form.memo,
              enabled: 1,
              id: item.id || null,
            });
          });
          if (chanceCount != 100) {
            this.$message.error("所有奖品的概率之和必须等于100%");
            return;
          }
          luckDrawPrizeBatchAdd(params).then((res) => {
            this.messageTips("添加", res, formName);
          });
        }
      });
    },
    messageTips(title, res, formName) {
      if (res.code == 200) {
        this.$message.success(title + "成功");
        this.onClose(formName);
        this.getList();
      } else {
        this.$message.error(res.msg);
      }
    },
    onClose(formName) {
      this.$refs[formName].resetFields();
      this.close();
    },
  },
};
</script>
<style lang="less" scoped>
.dialog-footer {
  width: 100%;
  text-align: right;
}

.reword-list {
  // display: flex;
  // .el-form-item {
  //   flex: 1;
  // }
}

.add-reword {
  margin-bottom: 22px;
  width: 180px;
  border-style: dashed;
}
.delete {
  font-size: 16px;
  line-height: 40px;
  cursor: pointer;
}
</style>
