<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
              :limit="1"
              :value="form.picUrl"
              :file-size="50"
              :is-public="true"
              @input="pictureSelect"
            />
          </el-form-item>
          <div class="tip">
            上传1张图片，支持jpg、png格式上传，建议使用尺寸800x800像素以上、大小不超过1M的正方形图片；
          </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>
      <!-- 奖级设置 -->
      <div class="prize" v-for="(item, index) in awardsList" :key="index">
        <div class="prize-top">
          <div>奖级名称：{{ item.name }}</div>
          <div>奖级：{{ item.sort }}</div>
          <div>
            奖级数量：
            <el-input-number
              v-model="item.quantity"
              controls-position="right"
              @change="handleChangeAll($event, item)"
              :min="0"
              size="small"
            ></el-input-number>
          </div>
        </div>
        <div class="prize-table">
          <el-table :data="item.prizeList" class="el-table">
            <el-table-column label="奖品图片">
              <template slot-scope="scope">
                <el-image
                  style="width: 70px; height: 70px"
                  :src="scope.row.picUrl"
                  :preview-src-list="[scope.row.picUrl]"
                >
                </el-image>
              </template>
            </el-table-column>
            <el-table-column label="奖品名称" prop="title" />
            <el-table-column label="奖品类型">
              <template slot-scope="scope">
                <div v-if="scope.row.prizeType == 'goods'">商品</div>
                <div v-if="scope.row.prizeType == 'coupon'">券</div>
                <div v-if="scope.row.prizeType == 'coin'">盲豆</div>
              </template>
            </el-table-column>
            <!-- <el-table-column label="奖品数量" prop="storeName">
              <template slot-scope="scope">
                <div>
                  <el-input-number
                    v-model="scope.row.quantity"
                    controls-position="right"
                    @change="handleChange($event, index)"
                    :min="1"
                    size="small"
                  ></el-input-number>
                </div>
              </template>
            </el-table-column> -->
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="handleDel(scope.$index, item)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="prize-btn">
          <el-dropdown @command="handleCommand($event, index)">
            <el-button type="primary" size="small">
              添加奖品<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="goods">商品</el-dropdown-item>
              <el-dropdown-item command="coupon">券</el-dropdown-item>
              <el-dropdown-item command="coin">盲豆</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <!-- 保存 -->
      <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>

    <!-- 添加商品 -->
    <el-dialog
      title="添加实物奖品"
      width="1000px"
      :visible.sync="goodsTableVisible"
      :before-close="close"
    >
      <div class="dialog-search">
        <div>商品名称：</div>
        <el-input
          v-model="goodsTitle"
          placeholder="请输入商品名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQueryGoods"
        />
        <div class="ge"></div>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQueryGoods"
          >查询</el-button
        >
      </div>
      <el-table
        v-loading="loading"
        :data="goodsList"
        @selection-change="handleSelectionGoods"
        class="el-table"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          fixed="left"
        />
        <el-table-column label="商品ID" prop="goodsId" />
        <el-table-column label="商品图片">
          <template slot-scope="{ row }">
            <div v-if="row.picUrl">
              <el-image
                style="width: 100px; height: 100px"
                :src="row.picUrl.split(',')[0]"
                :preview-src-list="row.picUrl.split(',')"
              >
              </el-image>
            </div>
            <p v-else>-</p>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="title" min-width="85" />

        <el-table-column label="商品价格" min-width="85">
          <template slot-scope="scope">
            <div>￥{{ $numberFormat(scope.row.value) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="商品库存" prop="quantity" width="80" />
      </el-table>
      <pagination
        v-show="goodsTotal > 0"
        :total="goodsTotal"
        :page.sync="pageParams.pageNum"
        :limit.sync="pageParams.pageSize"
        @pagination="getGoodsList"
      />
      <div class="dialog-btn">
        <el-button size="small" @click="close"> 取 消 </el-button>
        <div class="ge"></div>
        <el-button type="primary" size="small" @click="confirmGoods">
          确 认
        </el-button>
      </div>
    </el-dialog>
    <!-- 添加卡券 -->
    <el-dialog
      title="添加券奖品"
      width="1000px"
      :visible.sync="couponTableVisible"
      :before-close="close"
    >
      <div class="dialog-search">
        <div>券名称：</div>
        <el-input
          v-model="couponTitle"
          placeholder="请输入券名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQueryCoupon"
        />
        <div class="ge"></div>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQueryCoupon"
          >查询</el-button
        >
      </div>
      <el-table
        v-loading="loading"
        :data="couponList"
        @selection-change="handleSelectionCoupon"
        class="el-table"
      >
        <el-table-column
          type="selection"
          width="55"
          align="center"
          fixed="left"
        />
        <el-table-column label="券ID" prop="couponId" />
        <el-table-column label="券图片">
          <template slot-scope="scope">
            <div>
              <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.picUrl"
                :preview-src-list="[scope.row.picUrl]"
              >
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="券名称" prop="title" min-width="85" />
        <el-table-column label="使用场景" min-width="85">
          <template slot-scope="scope">
            <div>{{ scope.row.type.desc }}</div>
          </template>
        </el-table-column>
        <el-table-column label="券价格" min-width="85">
          <template slot-scope="scope">
            <div>￥{{ $numberFormat(scope.row.discount) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="有效期限" min-width="85">
          <template slot-scope="scope">
            <div>{{ scope.row.useArea.desc }}</div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="couponTotal > 0"
        :total="couponTotal"
        :page.sync="pageParams.pageNum"
        :limit.sync="pageParams.pageSize"
        @pagination="getCouponList"
      />
      <div class="dialog-btn">
        <el-button size="small" @click="close"> 取 消 </el-button>
        <div class="ge"></div>
        <el-button type="primary" size="small" @click="confirmCoupon">
          确 认
        </el-button>
      </div>
    </el-dialog>
    <!-- 添加盲豆 -->
    <el-dialog
      title="添加盲豆奖品"
      :visible.sync="coinTableVisible"
      :before-close="close"
      width="500px"
    >
      <el-form
        :model="coinForm"
        :rules="coinRules"
        ref="coinForm"
        label-width="100px"
      >
        <el-form-item label="盲豆数量" prop="quantity">
          <el-input
            v-model="coinForm.quantity"
            size="small"
            placeholder="请输入盲豆数量"
            style="width: 200px"
          />
        </el-form-item>
      </el-form>
      <div class="dialog-btn">
        <el-button size="small" @click="close"> 取 消 </el-button>
        <div class="ge"></div>
        <el-button type="primary" size="small" @click="confirmCoin">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import CustomFieldsMixin from "@/mixins/CustomFields";
import { getGoodsList } from "@/api/business/goods";
import { getCouponList } from "@/api/business/coupon";
import { ticketBoxCreate } from "@/api/business/ticket";
import { publicFileGetUrl } from "@/api/common";
import { accMul } from "@/utils/util";
export default {
  name: "TicketCreate",
  mixins: [CustomFieldsMixin],
  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: [
          {
            type: "array",
            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: [
        {
          name: "奖品一",
          sort: 1,
          quantity: 0,
          prizeList: [],
        },
        {
          name: "奖品二",
          sort: 2,
          quantity: 0,
          prizeList: [],
        },
        {
          name: "奖品三",
          sort: 3,
          quantity: 0,
          prizeList: [],
        },
        {
          name: "奖品四",
          sort: 4,
          quantity: 0,
          prizeList: [],
        },
        {
          name: "奖品五",
          sort: 5,
          quantity: 0,
          prizeList: [],
        },
        {
          name: "奖品六",
          sort: 6,
          quantity: 0,
          prizeList: [],
        },
        {
          name: "奖品七",
          sort: 7,
          quantity: 0,
          prizeList: [],
        },
        {
          name: "奖品八",
          sort: 8,
          quantity: 0,
          prizeList: [],
        },
        {
          name: "奖品九",
          sort: 9,
          quantity: 0,
          prizeList: [],
        },
        {
          name: "奖品十",
          sort: 10,
          quantity: 0,
          prizeList: [],
        },
      ],

      prizeIndex: null, // 奖级下标

      goodsTitle: "", // 商品名称
      goodsTableVisible: false, // 添加商品弹框
      goodsList: [], // 商品列表
      goodsTotal: 0, // 商品总数
      selectGoodsList: [], // 选中商品

      couponTitle: "", // 券名称
      couponTableVisible: false, // 添加卡券弹框
      couponList: [], // 卡券列表
      couponTotal: 0, // 卡券总数
      selectCouponList: [], // 选中卡券

      coinTableVisible: false, // 添加盲豆弹框
      coinForm: { quantity: "" },
      coinRules: {
        quantity: [
          { required: true, message: "请输入数量", trigger: "blur" },
          {
            pattern: /^([1-9]\d*)$/,
            message: "请输入合法的数字",
            trigger: ["blur", "change"],
          },
        ],
      },

      pageParams: {
        pageNum: 1,
        pageSize: 10,
      },
    };
  },
  created() {
    this.getGoodsList();
    this.getCouponList();
  },
  methods: {
    // 商品列表
    getGoodsList() {
      this.loading = true;
      getGoodsList(
        "pageNum=" +
          this.pageParams.pageNum +
          "&pageSize=" +
          this.pageParams.pageSize +
          "&",
        { title: this.goodsTitle, status: "on" }
      ).then((res) => {
        this.goodsList = res.rows.map((item) => {
          return {
            ...item,
            picUrl: publicFileGetUrl + item.picUrl.split(',')[0],
          };
        });
        this.goodsTotal = res.total;
        this.loading = false;
      });
    },

    // 卡券列表
    getCouponList() {
      this.loading = true;
      getCouponList(
        "pageNum=" +
          this.pageParams.pageNum +
          "&pageSize=" +
          this.pageParams.pageSize +
          "&",
        { title: this.couponTitle, status: "on" }
      ).then((res) => {
        this.couponList = res.rows.map((item) => {
          return {
            ...item,
            type: JSON.parse(item.type),
            useArea: JSON.parse(item.useArea),
            picUrl: publicFileGetUrl + item.picUrl,
          };
        });
        this.couponTotal = res.total;
        this.loading = false;
      });
    },

    // 保存
    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,
            picUrl: this.form.picUrl[0].fileName,
            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;
        }
      });
    },

    // 添加图片
    pictureSelect(data) {
      this.form.picUrl = data;
    },

    // 改变奖级数量
    handleChangeAll(e, item) {
      this.$set(item, "quantity", e);
      this.$forceUpdate();
      // this.getQuantity();
    },

    // 改变奖品数量
    handleChange(e, index) {
      this.prizeIndex = index;
      this.$forceUpdate();
      // this.getQuantity();
    },

    // 奖级商品删除
    handleDel(index, item) {
      this.prizeIndex = item.sort - 1;
      let list = item.prizeList;
      list.splice(index, 1);
      this.$set(item, "prizeList", list);
      // this.getQuantity();
    },

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

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

    // 查询商品
    handleQueryGoods() {
      this.getGoodsList();
    },

    // 查询券
    handleQueryCoupon() {
      this.getCouponList();
    },

    // 选中商品
    handleSelectionGoods(e) {
      this.selectGoodsList = e.map((item) => {
        return {
          prizeType: "goods",
          // quantity: 1,
          goodsId: item.goodsId,
          picUrl: item.picUrl,
          title: item.title,
        };
      });
    },

    // 选中卡券
    handleSelectionCoupon(e) {
      this.selectCouponList = e.map((item) => {
        return {
          prizeType: "coupon",
          // quantity: 1,
          couponId: item.couponId,
          picUrl: item.picUrl,
          title: item.title,
        };
      });
    },

    // 确认选中商品
    confirmGoods() {
      this.awardsList[this.prizeIndex].prizeList = this.awardsList[
        this.prizeIndex
      ].prizeList.concat(this.selectGoodsList);
      // this.getQuantity();
      this.getGoodsList();
      this.close();
    },

    // 确认选中卡券
    confirmCoupon() {
      this.awardsList[this.prizeIndex].prizeList = this.awardsList[
        this.prizeIndex
      ].prizeList.concat(this.selectCouponList);
      // this.getQuantity();
      this.getCouponList();
      this.close();
    },

    // 确认输入盲豆
    confirmCoin() {
      let coin = {
        prizeType: "coin",
        // quantity: 1,
        title: `盲豆 x${this.coinForm.quantity}`,
        picUrl: publicFileGetUrl + "md.jpeg",
        coinValue: this.coinForm.quantity,
      };
      this.$refs["coinForm"].validate((valid) => {
        if (valid) {
          this.awardsList[this.prizeIndex].prizeList.push(coin);
          // this.getQuantity();
          this.close();
        } else {
          return false;
        }
      });
    },

    // 计算奖级数量
    getQuantity() {
      let num = 0;
      this.awardsList[this.prizeIndex].prizeList.forEach((item) => {
        num += item.quantity;
      });
      this.awardsList[this.prizeIndex].quantity = num;
    },

    // 取消
    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>