<template>
  <div class="app-container goods-add add-groupLottery">
    <el-divider content-position="left">基础信息</el-divider>
    <el-form ref="addItem" :rules="rules" :model="addData" label-width="150px">
      <el-row :gutter="10">
        <el-col :xs="{span: 22, offset: 0}" :sm=" {span: 18, offset: 0}" :lg="{span: 10, offset: 0}">
          <el-form-item label="拼团活动名称:" prop="title">
            <el-input v-model="addData.title" placeholder="输入活动名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="23">
          <el-form-item label="活动封面:" prop="picUrl">
            <image-upload
              v-model="marketingPicUrl"
              :limit="1"
              :file-size="0.2"
              @change="$refs.addItem.validateField(['picUrl'])"
            />
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="活动日期:" prop="dateValue">
            <el-date-picker value-format="timestamp" v-model="addData.dateValue" :picker-options="setYearDisabled" type="datetimerange"
                            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"  :default-time="['20:00:00', '20:00:00']"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="成团人数:" prop="fakeNum">
            <el-input v-model="addData.fakeNum" type="number"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="发起拼团最大次数:" prop="fakeNum">
            <el-input v-model="addData.fakeNum" type="number"/>
          </el-form-item>
        </el-col>
        <el-col :span="24">
        <el-form-item label="加入拼团最大次数:" prop="fakeNum">
          <el-input v-model="addData.fakeNum" type="number"/>
        </el-form-item>
          </el-col>
        <el-col :span="24">
        <el-form-item label="参与拼团最大次数:" prop="fakeNum">
          <el-input v-model="addData.fakeNum" type="number"/>
        </el-form-item>
          </el-col>
        <el-col :span="24">
        <el-form-item label="佣金系数:" prop="fakeNum">
          <el-input v-model="addData.fakeNum" type="number"/>%
        </el-form-item>
          </el-col>
        <el-col :span="24">
        <el-form-item label="参与门店:" prop="fakeNum">
          <el-input v-model="addData.fakeNum" type="text"/>
        </el-form-item>
          </el-col>
        <el-col :span="24">
          <el-form-item label="是否允许退款:" prop="type" label-width="140px">
              <el-radio-group v-model="addData.codeType" >
                <el-radio :label="1">是</el-radio>
                <el-radio :label="2">否</el-radio>
              </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">奖品设置</el-divider>
      <el-row :gutter="10">
        <el-col :span="22">
          <el-form-item label="" prop="awardsList">
            <!-- 奖级列表 -->
            <awards-list ref="awards" v-model="awardsList"  @handleCommand="handleCommand" @close="close"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider content-position="left">活动详情</el-divider>
      <el-row>
        <el-col :span="22">
          <el-form-item label="" prop="description">
            <wang-editor ref="editor" v-model="addData.description"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row>
      <el-col :span="24" style="text-align: center">
        <el-button type="info" @click="$router.replace('/marketing/marketing')">取消</el-button>
        <el-button type="primary" @click="update()">保存</el-button>
      </el-col>
    </el-row>

    <!-- 添加商品 -->
    <goods-add :dialog-visible="goodsTableVisible" @close="close" @confirmGoods="confirmGoods"
               v-if="goodsTableVisible"/>
    <!-- 添加券 -->
    <coupon-add :dialog-visible="couponTableVisible" @close="close" @confirmCoupon="confirmCoupon"
                v-if="couponTableVisible"/>
    <!-- 添加券包 -->
    <coupon-pkg-add :dialog-visible="couponPkgTableVisible" @close="close" @confirmCouponPkg="confirmCouponPkg"
                    v-if="couponPkgTableVisible"/>
    <!-- 添加盲豆 -->
    <coin-add :dialog-visible="coinTableVisible" @close="close" @confirmCoin="confirmCoin" v-if="coinTableVisible"/>
  </div>
</template>

<script>
import { publicFileGetUrl } from "@/api/common";
import {getMarketingDetail, addMarketing} from '@/api/business/marketing'
import Upload from '@/components/DragImageUpload'
import WangEditor from '@/components/WangEditor'
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"

export default {
  name: 'MarketingAdd',
  components: {
    Upload,
    WangEditor,
    AwardsList,
    GoodsAdd,
    CouponAdd,
    CouponPkgAdd,
    CoinAdd,
  },
  data() {
    return {
      //禁止选择当前今天之前的日期
      setYearDisabled: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7
        }
      },
      id: this.$route.query.id,
      addData: {
        picUrl: '',//活动主图
        startTime: '',//开始时间
        endTime: '',//结束时间
        fakeNum: 0,//初始用户数
        description: '',//活动详情
        awardsList: [],//奖级列表
        codeType: 2,//获取类型
      },
      rules: {
        title: [{required: true, message: '请输入活动名称', trigger: 'blur'}],
        picUrl: [{required: true, message: '请上传活动封面', trigger: 'change'}],
        dateValue: [{required: true, message: '请设置活动日期', trigger: 'change'}],
        fakeNum:[{ pattern: /^([0-9]\d*)$/, message: "请输入正确的数字", trigger: ["blur", "change"]}]
      },
      // 奖级列表
      awardsList: [
        {
          name: "一等奖",
          sort: 1,
          quantity: 0,
          prizeList: [],
          insideNum: 0,
        },
        {
          name: "二等奖",
          sort: 2,
          quantity: 0,
          prizeList: [],
          insideNum: 0,
        },
        {
          name: "三等奖",
          sort: 3,
          quantity: 0,
          prizeList: [],
          insideNum: 0,
        },
        {
          name: "四等奖",
          sort: 4,
          quantity: 0,
          prizeList: [],
          insideNum: 0,
        },
        {
          name: "五等奖",
          sort: 5,
          quantity: 0,//名额数量
          prizeList: [],//列表
          insideNum: 0,//内定数量
        }
      ],
      goodsTableVisible: false, // 添加商品弹框
      couponTitle: "", // 券名称
      couponTableVisible: false, // 添加卡券弹框
      couponPkgTableVisible: false, // 添加券包弹框
      coinTableVisible: false, // 添加盲豆弹框
      pageParams: {
        pageNum: 1,
        pageSize: 10,
      },
      dateValue: [],//开始与结束日期
    }
  },
  computed: {
    marketingPicUrl: {
      get() {
        return this.addData.picUrl ? this.addData.picUrl.split(',').map(item => {
          return {
            fileName: item
          }
        }) : []
      },
      set(val) {
        this.$set(this.addData, 'picUrl', val.map(item => {
          return item.fileName
        }).toString())
      }
    },
  },
  created() {
    if (this.id) {
      getMarketingDetail(this.id).then(res => {
        const { startTime, endTime, description, fakeNum, codeType, picUrl, realNum, title, awardsList, id } = res.data
        this.addData = { title, dateValue:[startTime,endTime], picUrl, fakeNum, codeType, realNum, description, awardsList, id }
        if(description) {
          this.$refs.editor.setContent(description)
        }
        if(awardsList){
          awardsList.forEach((item) => {
              item.prizeList.forEach((ele) => {
                (ele.picUrl = publicFileGetUrl + ele.picUrl.split(',')[0]),
                  (ele.prizeType = JSON.parse(ele.prizeType).value);
                  ele.couponDetail = ele.couponDetail ? encodeURI(ele.couponDetail) : ''
              });
          });
          this.$nextTick(() => {
            this.$refs.awards.add(3, awardsList)
          })
          this.awardsList = awardsList
        }
      })
    }
  },

  methods: {
    // 保存
    update() {
      this.$refs.addItem.validate((valid, items) => {
        if (valid) {
          if(this.addData.dateValue[0] == this.addData.dateValue[1]){
            this.msgError('活动开始时间与结束时间不能相等！')
            return;
          }
          if(this.awardsList.length < 1) {
            this.msgError('请至少设置一个奖级的的奖品！')
            return;
          }
          // 判断没有设置奖品的奖级
          let prizeIndex = this.awardsList.findIndex((item) => {
            return !item.prizeList.length;
          });
          if (prizeIndex != -1) {
            this.$message.error(
              `请至少设置一个奖级的的奖品！`
            );
            return;
          }
          // 判断没有设置奖级数量
          let prizeIndexThree = this.awardsList.findIndex((item) => {
            return !item.quantity && item.quantity != 0;
          });
          if (prizeIndexThree != -1) {
            this.$message.error(
              `请设置${this.awardsList[prizeIndexThree].name}的奖级数量！`
            );
            return;
          }
          // 判断没有设置内定数量
          let prizeIndexTwo = this.awardsList.findIndex((item) => {
            return !item.insideNum && item.insideNum != 0;
          });
          if (prizeIndexTwo != -1) {
            this.$message.error(
              `请设置${this.awardsList[prizeIndexTwo].name}的内定数量！`
            );
            return;
          }

          // 判断内定名额大于奖品名额
          let quantityIndex = this.awardsList.findIndex((item) => {
            return item.insideNum > item.quantity;
          });
          if (quantityIndex != -1) {
            this.$message.error(
              `${this.awardsList[quantityIndex].name}的内定名额大于奖品名额，请重新设置！`
            );
            return;
          }
          let quantityIndexTwo = this.awardsList.findIndex((item) => {
            return item.prizeList.length != 0 && item.quantity == 0;
          });
          if (quantityIndexTwo != -1) {
            this.$message.error(
              `${this.awardsList[quantityIndexTwo].name}的名额不能为0，请重新设置！`
            );
            return;
          }

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

          const { fakeNum, description, title, picUrl, codeType } = this.addData
          addMarketing({
            title,
            description: encodeURI(description),
            fakeNum,
            startTime: this.addData.dateValue[0],
            endTime: this.addData.dateValue[1],
            awardsList: this.awardsList,
            codeType:Number(codeType),
            picUrl, id:this.addData.id?this.addData.id:"",
          }).then(res => {
            if (res.code === 0) {
              this.$message({
                message: this.addData.id ? '修改成功!' : '添加成功!',
                type: 'success'
              })
              this.$store.dispatch('tagsView/delView', this.$route)
              this.$router.go(-1)
            }
          })
        } else {
          if (items && Object.keys(items).length > 0) {
            this.$message({
              message: items[Object.keys(items)[0]][0].message,
              type: 'warning'
            })
          }
        }
      })
    },

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

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

    // 确认选中商品
    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)
    },

  }
}
</script>

<style scoped lang="scss">
.goods-add {
  .tip {
    font-size: 12px;
    color: #999;
  }

  .el-divider {
    .is-left {
      color: #409EFF;
      font-size: 20px;
      font-weight: bolder;
      left: 10px;
    }
  }
}
.add-groupLottery .el-input{
  width: 340px;
}
</style>
