<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" :disabled="form.disabled" @change="$refs['form'].clearValidate();changeType($event)">
              <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-col :xs="{span: 22, offset: 0}" :sm=" {span: 18, offset: 0}" :lg="{span: 10, offset: 0}">
              <el-input
                v-model="form.title"
                size="small"
                placeholder="请输入盲票组名称"
              ></el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="图片" prop="picUrl">
            <Upload v-model="ticketPicUrl" :limit="3" :fileSize="0.5" @change="$refs.form.validateField(['picUrl'])"/>
          </el-form-item>
          <div class="tip" v-if="form.type != 'offline'">
            请上传图片，jpg、png格式；线上盲票第1张为封面图，第2张为奖品图，第3张为主题图;大小不超过500k
          </div>
          <div class="tip" v-else>
            上传1张图片，支持jpg、png格式上传，大小不超过500k；
          </div>
          <el-form-item label="面值" prop="facePrice">
            <el-input
              v-model="form.facePrice "
              style="width: 240px"
              size="small"
              placeholder="请输入面值" :disabled="form.disabled"
            >
              <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="prePrice">
            <el-input
              v-model="form.prePrice"
              style="width: 240px"
              size="small"
              placeholder="请输入预付售票价"
            >
              <template slot="append">元 / 张</template>
            </el-input>
          </el-form-item>
          <div class="tip" v-if="form.type != 'offline'">
            如果为0则不作为预售票购买
          </div>
          <el-form-item
            label="划线价"
            prop="originPrice"
            v-if="form.type != 'offline'"
          >
            <el-input
              v-model="form.originPrice"
              style="width: 240px"
              size="small"
              placeholder="请输入划线价"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <div class="tip" v-if="form.type != 'offline'">
            划线价为0或不填，则不显示划线价
          </div>
          <el-form-item label="盲票总数" prop="quantity">
            <el-input
              v-model="form.quantity"
              style="width: 240px"
              size="small"
              placeholder="请输入盲票总数" :disabled="form.disabled"
            >
              <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="请输入每包张数" :disabled="form.disabled"
            >
              <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-item label="销售范围" prop="saleChannelType" v-if="form.type == 'offline'">
            <el-radio-group v-model="form.saleChannelType" size="small" @change="$refs['form'].clearValidate()">
              <el-radio :label="1">所有渠道</el-radio>
              <el-radio :label="2">指定渠道</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="渠道" prop="channelIdList" v-if="form.saleChannelType == 2">
            <el-select
              v-model="form.channelIdList"
              placeholder="请选择渠道"
              style="width: 240px;"
              filterable
              clearable
              multiple
            >
              <el-option
                v-for="(item, index) in channelList"
                :key="index"
                :label="item.name"
                :value="item.channelId">
                <div>
                  <span style="float: left;">{{item.name}} </span>
                  <span style="float: right;">{{item.mobile}}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
          <div class="tip" v-if="form.type == 'offline'">注：盲票只对所选渠道下的门店可见</div>
        </el-form>
      </div>
      <!--  关联商品设置 -->
      <div class="base-info-title">商品设置（购买即可提货）</div>

      <award-form ref="awardFrom" @close="close" v-model="goodsList" :id="ids"  @goodsCommand="goodsCommand"></award-form>

      <!-- 奖级设置 -->
      <div class="base-info-title" >奖级设置</div>
      <!-- 奖级列表 -->
      <awards-list ref="awards" :id="ids" 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" :iconic="iconic" @confirmGoodsForm="confirmGoodsForm" @confirmGoods="confirmGoods" v-if="goodsTableVisible" />
    <!-- 添加券 -->
    <coupon-add :dialog-visible="couponTableVisible" :iconic="iconic" @close="close" @confirmCouponForm="confirmCouponForm" @confirmCoupon="confirmCoupon" v-if="couponTableVisible" />
    <!-- 添加券包 -->
    <coupon-pkg-add :dialog-visible="couponPkgTableVisible" :iconic="iconic" @close="close" @confirmCouponPkgForm="confirmCouponPkgForm" @confirmCouponPkg="confirmCouponPkg" v-if="couponPkgTableVisible" />
    <!-- 添加盲豆 -->
    <coin-add :dialog-visible="coinTableVisible" @close="close" @confirmCoin="confirmCoin" v-if="coinTableVisible" />
   </div>
</template>
<script>
import Upload from '@/components/DragImageUpload'
import { publicFileGetUrl } from "@/api/common";
import CustomFieldsMixin from "@/mixins/CustomFields";
import { ticketBoxCreate, setListDetail, ticketBoxDetail} from "@/api/business/ticket";
import { listAllChannel} from "@/api/admin/channel";
import { accMul, accDiv } from "@/utils/util";
import AwardsList from "./components/AwardsList"
import GoodsAdd from "./components/GoodsAdd"
import CouponAdd from "./components/CouponAdd"
import CouponPkgAdd from "./components/CouponPkgAdd"
import CoinAdd from "./components/CoinAdd"
import AwardForm from "./components/AwardForm"
export default {
  name: "TicketCreate",
  mixins: [CustomFieldsMixin],
  components: {
    AwardsList,
    GoodsAdd,
    CouponAdd,
    CouponPkgAdd,
    CoinAdd,
    Upload,
    AwardForm,
  },
  data() {
    return {
      loading: false,
      id: this.$route.query.id,
      ids: this.$route.query.id?this.$route.query.id:0,
      form: {
        type: "online", //盲票类型
        title: "", // 盲票名称
        picUrl: "", // 图片
        facePrice: "", // 面值
        salePrice: "", // 售价
        prePrice: 0, //预购价
        quantity: "", // 数量
        pkgUnit: 200, // 张数
        pkgSalePrice: 0, // 单价
        saleCommRate: "", // 基数
        originPrice: 0, //划线价
        disabled: false,
        saleChannelType: 1
      },
      // 上级渠道列表
      channelList:[],
      rules: {
        type: [
          { required: true, message: "请选择盲票类型", trigger: "change" },
        ],
        title: [
          { required: true, message: "请输入盲票组名称", trigger: "blur" },
        ],
        picUrl: [
          {
            required: true,
            message: "请上传盲票图片",
            trigger: ["blur", "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"],
          },
        ],
        prePrice: [
          { required: true, message: "请输入预付售票价", trigger: "blur" },
          {
            pattern:
              /^([0-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"],
          },
        ],
        originPrice: [{
          pattern:
            /^([0-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/,
          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"],
          },
        ],
        saleChannelType: [
          { required: true, message: "请选择销售范围", trigger: "change" },
        ],
        channelIdList: [
          { required: true, message: "请选择渠道", trigger: "change" },
        ],
      },

      // 奖级列表
      awardsList: [],
      //关联商品列表
      goodsList: [],
      goodsTableVisible: false, // 添加商品弹框
      couponTitle: "", // 券名称
      couponTableVisible: false, // 添加卡券弹框
      couponPkgTableVisible: false, // 添加券包弹框
      coinTableVisible: false, // 添加盲豆弹框
      pageParams: {
        pageNum: 1,
        pageSize: 10,
      },
      iconic: '',//区分添加的是关联商品还是奖品
    };
  },
  computed: {
    ticketPicUrl: {
      get() {
        return this.form.picUrl ? this.form.picUrl.split(',').map(item => {
          return {
            fileName: item
          }
        }) : []
      },
      set(val) {
        this.$set(this.form, 'picUrl', val.map(item => { return item.fileName }).toString())
      }
    }
  },
  created() {
    this.getChannelList()
    if (this.id) {
      let data = {
        boxId: this.id
      }
      ticketBoxDetail(data).then(res => {
        const { awardsList, goodsList, type, title, picUrl, facePrice, salePrice, prePrice, quantity, originPrice, pkgUnit, pkgSalePrice, saleCommRate, saleChannelType, channelList } = res.data
        this.form = {
          disabled:true,
          title, picUrl, quantity, pkgUnit, saleCommRate, saleChannelType,
          channelIdList: channelList.map(item => item.channelId),
          type: JSON.parse(type).value,
          facePrice:accDiv(facePrice, 100),
          salePrice:accDiv(salePrice, 100),
          prePrice:accDiv(prePrice,100),
          pkgSalePrice:accDiv(pkgSalePrice, 100),
          originPrice:accDiv(originPrice, 100)
        }
        if(awardsList){
          awardsList.forEach((item) => {
              item.isEdit = true
              item.prizeList.forEach((ele) => {
                (ele.picUrl = publicFileGetUrl + ele.picUrl.split(',')[0]),
                (ele.prizeType = JSON.parse(ele.prizeType).value);
              });
          });
          this.$nextTick(() => {
            this.$refs.awards.add(3, awardsList)
            this.$refs.awards.changetype(JSON.parse(type).value)
          })
          this.awardsList = awardsList
        }
        if(goodsList){
          goodsList.forEach((item) => {
              (item.picUrl = publicFileGetUrl + item.picUrl.split(',')[0]),
              // (item.prizeType = JSON.parse(item.prizeType).value);
              (item.type = JSON.parse(item.type).value);
          });
          if(this.$refs.awardFrom) {
            this.$nextTick(() => {
              this.$refs.awardFrom.add(3,goodsList)
            })
          }
          // this.goodsList = goodsList
        }
      })
    }
  },
  methods: {
    // 获取上级渠道下拉列表
    getChannelList(){
      listAllChannel().then(response => {
         this.channelList = response.data || [];
      });
    },

    // 保存
    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;
          // }
          if (this.form.quantity > 100000) {
            this.$message.error("盲票数量超出限制，请重新填写！");
            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 || ele.id,
                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;
          });

          // for (let i = 0; i < filterArr2.length; i++) {
          //   if(filterArr2[i].awardsLabel == "" || filterArr2[i].awardsLabel == undefined){
          //     this.$message.error("关联奖级不能为空");
          //     return
          //   }
          // }
          if (this.form.type == "offline") {
            this.form.originPrice = null
            for (let i = 0; i < filterArr2.length; i++) {
              for (let j = 0; j < filterArr2[i].prizeList; j++) {
                filterArr2[i].prizeList[j].quantity = null
              }
            }
          }
          if (this.form.type != "offline" && this.goodsList.length < 1) {
            this.$message.error("关联商品不能为空");
            return
          }

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

          if (this.id){
            data.boxId = this.id
          }

          let request = this.id ? setListDetail : ticketBoxCreate;

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

          request(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.couponPkgTableVisible = false;
      this.coinTableVisible = false;
    },

    changeType(e) {
      this.$refs.awards.changetype(e)
    },

    // 添加奖品种类
    handleCommand(e) {
      if (e == "goods") {
        this.iconic = 'goods'
        this.goodsTableVisible = true;
      } else if (e == "coupon") {
        this.iconic = 'coupon'
        this.couponTableVisible = true;
      } else if (e == "coupon_pkg") {
        this.iconic = 'couponPkg'
        this.couponPkgTableVisible = true;
      } else if (e == "coin") {
        this.coinTableVisible = true;
      }
    },
    goodsCommand(e) {
      if (e == "goods") {
        this.iconic = 'goodsForm'
        this.goodsTableVisible = true;
      } else if (e == "coupon") {
        this.iconic = 'couponForm'
        this.couponTableVisible = true;
      } else if (e == "coupon_pkg") {
        this.iconic = 'couponPkgForm'
        this.couponPkgTableVisible = true;
      }
    },
    // 确认选中商品
    confirmGoods(arr) {
      this.$refs.awards.add(1, arr)
    },

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

    // 确认选中券包
    confirmCouponPkg(arr) {
      this.$refs.awards.add(1, arr)
    },

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

    //选中的关联商品
    confirmGoodsForm(arr) {
      this.$refs.awardFrom.add(1,arr)
    },
    // 确认选中关联卡券
    confirmCouponForm(arr) {
      this.$refs.awardFrom.add(1, arr)
    },
    // 确认选中关联券包
    confirmCouponPkgForm(arr) {
      this.$refs.awardFrom.add(1, arr)
    },

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