<template>
  <div class="app-container">
    <div class="base-info">
      <div class="base-info-title">基础信息</div>
      <!-- 基础信息 -->
      <div class="base-info-form">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px">
          <el-form-item label="盲票类型" prop="type">
            <el-radio-group v-model="form.type" size="small">
              <el-radio label="online">线上盲票</el-radio>
              <el-radio label="offline">线下盲票</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="盲票组名称" prop="title">
            <el-input
              v-model="form.title"
              style="width: 587px"
              size="small"
              placeholder="请输入盲票组名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="图片" prop="picUrl">
            <image-upload
              v-model="ticketPicUrl"
              :limit="1"
              :file-size="0.2"
            />
          </el-form-item>
          <div class="tip">
            上传1张图片，支持jpg、png格式上传，大小不超过200k；
          </div>
          <el-form-item label="面值" prop="facePrice">
            <el-input
              v-model="form.facePrice"
              style="width: 240px"
              size="small"
              placeholder="请输入面值"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="售价" prop="salePrice">
            <el-input
              v-model="form.salePrice"
              style="width: 240px"
              size="small"
              placeholder="请输入售价"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="盲票总数" prop="quantity">
            <el-input
              v-model="form.quantity"
              style="width: 240px"
              size="small"
              placeholder="请输入盲票总数"
            >
              <template slot="append">张</template>
            </el-input>
          </el-form-item>
          <el-form-item label="每包张数" prop="pkgUnit">
            <el-input
              v-model="form.pkgUnit"
              style="width: 240px"
              size="small"
              placeholder="请输入每包张数"
            >
              <template slot="append">张</template>
            </el-input>
          </el-form-item>
          <el-form-item
            label="采购单价"
            prop="pkgSalePrice"
            v-if="form.type == 'offline'"
          >
            <el-input
              v-model="form.pkgSalePrice"
              style="width: 240px"
              size="small"
              placeholder="请输入采购单价"
            >
              <template slot="append">元/包</template>
            </el-input>
          </el-form-item>
          <el-form-item label="佣金系数" prop="saleCommRate">
            <el-input
              v-model="form.saleCommRate"
              style="width: 240px"
              size="small"
              placeholder="请输入佣金系数"
            >
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
          <div class="tip">
            例如：一张盲票用户支付10元，盲票佣金系数90%，经销商佣金比例20%，那么经销商佣金为10元*90%*20%=1.8元
          </div>
        </el-form>
      </div>
      <div class="base-info-title">奖级设置</div>
      <!-- 奖级设置 -->

      <!-- 奖级列表 -->
      <awards-list ref="awards" v-model="awardsList" @handleCommand="handleCommand" @close="close" />
      <!-- 保存 -->
      <div class="save-btn">
        <el-button size="small" @click="back"> 取 消 </el-button>
        <div class="ge"></div>
        <el-button type="primary" size="small" @click="submitForm">
          保 存
        </el-button>
      </div>
    </div>

    <!-- 添加商品 -->
    <goods-add :dialog-visible="goodsTableVisible" @close="close" @confirmGoods="confirmGoods" v-if="goodsTableVisible" />
    <!-- 添加券 -->
    <coupon-add :dialog-visible="couponTableVisible" @close="close" @confirmCoupon="confirmCoupon" v-if="couponTableVisible" />
    <!-- 添加盲豆 -->
    <coin-add :dialog-visible="coinTableVisible" @close="close" @confirmCoin="confirmCoin" v-if="coinTableVisible" /> 
  </div>
</template>
<script>
import CustomFieldsMixin from "@/mixins/CustomFields";
import { ticketBoxCreate } from "@/api/business/ticket";
import { accMul } from "@/utils/util";
import AwardsList from "./components/AwardsList"
import GoodsAdd from "./components/GoodsAdd"
import CouponAdd from "./components/CouponAdd"
import CoinAdd from "./components/CoinAdd"
export default {
  name: "TicketCreate",
  mixins: [CustomFieldsMixin],
  components: {
    AwardsList,
    GoodsAdd,
    CouponAdd,
    CoinAdd,
  },
  data() {
    return {
      loading: false,
      form: {
        type: "online", //盲票类型
        title: "", // 盲票名称
        picUrl: "", // 图片
        facePrice: "", // 面值
        salePrice: "", // 售价
        quantity: "", // 数量
        pkgUnit: 200, // 张数
        pkgSalePrice: 0, // 单价
        saleCommRate: "", // 基数
      },
      rules: {
        type: [
          { required: true, message: "请选择盲票类型", trigger: "change" },
        ],
        title: [
          { required: true, message: "请输入盲票组名称", trigger: "blur" },
        ],
        picUrl: [
          {
            required: true,
            message: "请上传盲票图片",
            trigger: "change",
          },
        ],
        facePrice: [
          { required: true, message: "请输入面值", trigger: "blur" },
          {
            pattern:
              /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/,
            message: "请输入合法的金额数字，最多两位小数",
            trigger: ["blur", "change"],
          },
        ],
        salePrice: [
          { required: true, message: "请输入售价", trigger: "blur" },
          {
            pattern:
              /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/,
            message: "请输入合法的金额数字，最多两位小数",
            trigger: ["blur", "change"],
          },
        ],
        quantity: [
          { required: true, message: "请输入数量", trigger: "blur" },
          {
            pattern: /^([1-9]\d*)$/,
            message: "请输入合法的数字",
            trigger: ["blur", "change"],
          },
        ],
        pkgUnit: [
          { required: true, message: "请输入每包张数", trigger: "blur" },
          {
            pattern: /^([1-9]\d*)$/,
            message: "请输入合法的数字",
            trigger: ["blur", "change"],
          },
        ],
        pkgSalePrice: [
          { required: true, message: "请输入采购单价", trigger: "blur" },
          {
            pattern:
              /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/,
            message: "请输入合法的金额数字，最多两位小数",
            trigger: ["blur", "change"],
          },
        ],
        saleCommRate: [
          { required: true, message: "请输入分佣基数", trigger: "blur" },
          {
            pattern:
              /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/,
            message: "请输入合法的数字，最多两位小数",
            trigger: ["blur", "change"],
          },
        ],
      },

      // 奖级列表
      awardsList: [],
      goodsTableVisible: false, // 添加商品弹框
      couponTitle: "", // 券名称
      couponTableVisible: false, // 添加卡券弹框
      coinTableVisible: false, // 添加盲豆弹框
      pageParams: {
        pageNum: 1,
        pageSize: 10,
      },
    };
  },
  computed: {
    ticketPicUrl: {
      get() {
        return this.form.picUrl ? this.form.picUrl.split(',').map(item => {
          return {
            fileName: item
          }
        }) : []
      },
      set(val) {
        console.log('val', val)
        this.$set(this.form, 'picUrl', val.map(item => { return item.fileName }).toString())
      }
    }
  },
  methods: {
    // 保存
    submitForm() {
      const subForm = this.$refs["form"];
      subForm.validate((valid) => {
        if (valid) {
          // let prizeIndex = this.awardsList.findIndex((item) => {
          //   return !item.prizeList.length;
          // });
          // // 判断没有设置奖品的奖级
          // if (prizeIndex != -1) {
          //   this.$message.error(
          //     `请设置${this.awardsList[prizeIndex].name}的奖品！`
          //   );
          //   return;
          // }

          let prizeIndex = this.awardsList.findIndex((item) => {
            return !item.prizeList.length && item.quantity > 0;
          });

          // 判断没有设置奖品的奖级
          if (prizeIndex != -1) {
            this.$message.error(
              `请设置${this.awardsList[prizeIndex].name}的奖品！`
            );
            return;
          }

          if (this.form.quantity % this.form.pkgUnit != 0) {
            this.$message.error("每包数量错误！");
            return;
          }

          let quantityTotal = 0;
          this.awardsList.forEach((item) => {
            quantityTotal += item.quantity;
          });
          if (this.form.quantity != quantityTotal) {
            this.$message.error("盲票数量和奖品数量不一致！");
            return;
          }

          // if (this.form.saleCommRate > 100) {
          //   this.$message.error("分佣基数不能大于100！");
          //   return;
          // }

          this.awardsList.forEach((item) => {
            item.prizeList = item.prizeList.map((ele) => {
              return {
                ...ele,
                refId: ele.goodsId || ele.couponId,
                prizeType: ele.prizeType,
                quantity: ele.quantity,
                value: Number(ele.coinValue),
              };
            });
          });

          let filterArr = this.awardsList.filter((item) => {
            return item.prizeList.length != 0;
          });

          let filterArr2 = filterArr.filter((item) => {
            return item.quantity != 0;
          });

          let data = {
            ...this.form,
            facePrice: accMul(this.form.facePrice, 100),
            salePrice: accMul(this.form.salePrice, 100),
            pkgSalePrice: accMul(this.form.pkgSalePrice, 100),
            awardsList: filterArr2,
          };

          const loading = this.$loading({
            lock: true,
            text: "保存中",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.4)",
          });

          ticketBoxCreate(data)
            .then((res) => {
              loading.close();
              if (res.code == 0) {
                this.msgSuccess("保存成功");
                this.$store.dispatch("tagsView/delView", this.$route);
                this.$router.go(-1);
              }
            })
            .catch(() => {
              loading.close();
            });
        } else {
          this.getFormErrorMessage(subForm);
          return false;
        }
      });
    },

    // 关闭弹框
    close() {
      this.goodsTableVisible = false;
      this.couponTableVisible = false;
      this.coinTableVisible = false;
    },

    // 添加奖品种类
    handleCommand(e) {
      if (e == "goods") {
        this.goodsTableVisible = true;
      } else if (e == "coupon") {
        this.couponTableVisible = true;
      } else if (e == "coin") {
        this.coinTableVisible = true;
      }
    },

    // 确认选中商品
    confirmGoods(arr) {
      this.$refs.awards.add(1, arr)
    },

    // 确认选中卡券
    confirmCoupon(arr) {;
      this.$refs.awards.add(1, arr)
    },

    // 确认输入盲豆
    confirmCoin(obj) {
      this.$refs.awards.add(2, obj)
    },

    // 取消
    back() {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.go(-1);
    },
  },
};
</script>
<style lang="scss" scoped>
.base-info-title {
  padding: 10px;
  border-bottom: 1px solid #eaeaea;
  margin-bottom: 20px;
}
.tip {
  padding-left: 100px;
  height: 32px;
  margin-bottom: 20px;
  color: #828282;
  font-size: 14px;
}
.save-btn {
  display: flex;
  align-content: center;
  justify-content: center;
  margin-bottom: 100px;
  .ge {
    width: 100px;
  }
}
.prize {
  width: 1000px;
  margin-bottom: 50px;
  background: #f9f9f9;
  border: 1px solid #bbbbbb;
  font-size: 14px;
  &-top {
    padding: 10px 20px;
    margin-bottom: 10px;
    display: flex;
    align-content: center;
    justify-content: space-around;
    border-bottom: 1px solid #bbbbbb;
    div {
      line-height: 36px;
    }
  }
  &-btn {
    border-top: 1px solid #bbbbbb;
    padding: 10px;
  }
}

.dialog-search {
  display: flex;
  line-height: 32px;
  margin-bottom: 20px;
  .ge {
    width: 40px;
  }
}

.dialog-btn {
  display: flex;
  align-content: center;
  justify-content: flex-end;
  padding: 40px 0 0;
  .ge {
    width: 40px;
  }
}
</style>
