<template>
  <div class="app-container">
    <div class="cot-box">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="90px" style="margin: 0 auto;width: 70%">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="活动时间" prop="activeTimeType">
          <div class="d-s">
            <div class="icon-type" v-for="(item,index) in activityTimeTypeList" :key="index"
                 :class="{ 'acvtive' : index === tindex1 }" @click="Typeindex1(index)">
              <img src="@/assets/images/wx.png" style="width: 20px;height: 20px" v-if="index != tindex1">
              <img src="@/assets/images/xz.png" style="width: 20px;height: 20px" v-if="index == tindex1">
              {{ item }}
            </div>
            <el-date-picker
              v-model="ruleForm.activeStartTime"
              style="width: 160px"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="开始日期">
            </el-date-picker>
            <span style="margin: 0 5px">至</span>
            <el-date-picker
              v-model="ruleForm.activeEndTime"
              style="width: 160px"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="结束日期">
            </el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="通知内容" prop="noticeContent">
          <div>
            <el-button type="text" @click="ifWrite = !ifWrite">编辑</el-button>
          </div>
          <el-input type="textarea" :disabled="ifWrite" v-model="ruleForm.noticeContent"
                    placeholder="请输入通知内容"></el-input>
        </el-form-item>
        <el-form-item label="活动详情" prop="activityDetails">
          <el-input type="textarea" v-model="ruleForm.activityDetails" placeholder="请输入活动详情"></el-input>
        </el-form-item>
        <el-form-item label="活动奖品" prop="courtesyReward">
          <div style="display: flex">
            <div style="width: 17%">
              <el-checkbox-group v-model="ruleForm.courtesyReward">
                <div>
                  <el-checkbox label="3" name="type">赠送积分</el-checkbox>
                </div>
                <div>
                  <el-checkbox label="2" name="type">赠送成长值</el-checkbox>
                </div>
                <div style="display: flex;font-size: 14px;margin: 15px 0">
                  <el-checkbox label="0" name="type">赠送优惠券</el-checkbox>
                  <img src="@/assets/images/tjb.png"
                       style="width: 20px;height: 20px;cursor: pointer;margin-top: 7px;margin-left: 10px"
                       @click="addCoupons()">
                </div>
              </el-checkbox-group>
            </div>
            <div style="width: 100%">
              <div style="display: flex;font-size: 14px;">
                <div style="width: 10%">赠送</div>
                <el-input placeholder="请输入赠送的积分数量" style="width: 100%;"
                          v-model="ruleForm.points">
                  <template slot="append">积分</template>
                </el-input>
              </div>

              <div style="display: flex;font-size: 14px;margin: 15px 0">
                <div style="width: 10%">赠送</div>
                <el-input placeholder="请输入赠送的成长值数量" style="width: 100%;"
                          v-model="ruleForm.growthValue">
                  <template slot="append">成长值</template>
                </el-input>
              </div>

              <div v-for="(item,index) in couponList" :key="index" style="display: flex;font-size: 14px;margin: 15px 0">
                <div style="width: 9.5%">赠送</div>
                <el-select v-model="item.vouchersId" style="width: 45%" placeholder="请选择">
                  <el-option
                    v-for="(item1,index1) in cardCouponList"
                    :key="index1"
                    :label="item1.name"
                    :value="item1.id"></el-option>
                </el-select>
                <el-input style="width: 45%;margin-left: 10px" v-model="item.giftCardTotal">
                  <template slot="append">张</template>
                </el-input>
                <img src="@/assets/images/ljt.png" style="width: 25px;height: 25px;margin-left: 10px"
                     @click="deleteCoupons(index)">
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item style="text-align: center">
          <el-button @click="resetForm('ruleForm')">取消</el-button>
          <el-button type="primary" @click="submitRuleForm('ruleForm')">保存</el-button>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>

<script>
import {
  listActiveNewlyweds,
  getActiveNewlyweds,
  delActiveNewlyweds,
  addActiveNewlyweds,
  updateActiveNewlyweds,
  huiActiveNewlyweds,
  editActiveNewlyweds, getInfoActiveNewlyweds, insertActiveNewlyweds, editActiveNewlyweds1
} from "@/api/EventMarketing/activeNewlyweds";
import {getoilName, listExchange, listFavorable, looklook, looklooklook} from "@/api/EventMarketing/activeConsumption";
import QRCode from "qrcodejs2";
import {
  delActiveFullminus,
  editActiveFullminus,
  getActiveFullminus,
  updateActiveFullminus
} from "@/api/EventMarketing/activeFullminus";
import {listCardCoupon} from "@/api/EventMarketing/cardCoupon";

export default {
  name: "ActiveNewlyweds",
  props: ['activeId'],
  data() {
    return {
      opendetails: false,
      looklist: [],
      statisticsyou: {},
      labelPosition: 'left',
      loadingdialog: false,
      centerDialogVisible: false,
      pdidlist: [],//判断优惠券id
      pddhidlist: [],//判断兑换券id
      tableData: [],//优惠券
      tableDatadh: [],//兑换券
      dialogTableVisible: false,//优惠券
      dialogTableVisibledh: false,//兑换券
      tableDatas: [],
      //请求优惠券列表时的参数
      youhuiquan: {
        name: '',
        pageNum: 1,
        pageSize: 10,
      },
      ytotal: 0,
      //请求兑换券列表时的参数
      duihuanquan: {
        name: '',
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      dtotal: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      ztotal: 0,
      // 新人有礼活动表格数据
      activeNewlywedsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        chainStoreId: null,
        storeId: null,
        name: null,
        activeStartTime: null,
        activeEndTime: null,
        courtesyReward: null,
        activeCode: null,
        isonline: null,
        status: null,
        remainderTotal: null,
        points: null,
        growthValue: null,
      },
      activeFullminusList: [],
      // 表单参数
      form: {
        id: "",
        tableDatas: [],
        courtesyReward: [],
        activeNewlywedsChildList: [],
      },

      ruleForm: {
        activeTimeType: 0,
        courtesyReward: []
      },
      ifWrite: true,
      tindex1: 0,
      activityTimeTypeList: [
        "永久有效", "自定义"
      ],
      couponList: [],
      // 优惠券列表信息
      cardCouponList: [],
      // 表单校验
      rules: {
        name: [
          {required: true, message: '活动名称不能为空', trigger: 'blur'},
        ],
        activeTimeType: [
          {required: true, message: '活动时间不能为空', trigger: 'blur'},
        ],
        noticeContent: [
          {required: true, message: '通知内容不能为空', trigger: 'blur'},
        ],
        activityDetails: [
          {required: true, message: '活动详情不能为空', trigger: 'blur'},
        ],
        courtesyReward: [
          {required: true, message: '活动奖品不能为空', trigger: 'blur'},
        ],
      }
    };
  },
  created() {
    if (this.activeId) {
      this.getInfo()
    }
    this.getCardCoupon()
  },
  methods: {
    getCardCoupon() {
      listCardCoupon({status: 1, putType: 1}).then(res => {
        this.cardCouponList = res.data.records
      })
    },
    getInfo() {
      getInfoActiveNewlyweds(this.activeId).then(res => {
        if (res.data) {
          this.ruleForm = res.data
          if (res.data.courtesyReward) this.ruleForm.courtesyReward = res.data.courtesyReward.split(",")
          if (res.data.activeTimeType) this.tindex1 = res.data.activeTimeType
          if (res.data.couponList) this.couponList = res.data.couponList
        } else {
          this.ruleForm = {
            activeTimeType: 0,
            courtesyReward: []
          }
          this.tindex1 = 0
        }
      })
    },
    addCoupons() {
      let data = {
        activeGift: 0,
        vouchersId: "",
        giftCardTotal: "",
      }
      this.couponList.push(data)
    },
    deleteCoupons(index) {
      this.couponList.splice(index, 1);
    },
    Typeindex1(index) {
      this.tindex1 = index
      this.ruleForm.activeTimeType = index
    },
    submitRuleForm(formName) {
      if (this.tindex1 == 1) {
        if (!this.ruleForm.activeStartTime || !this.ruleForm.activeEndTime) {
          this.$message.error("请选择活动开始时间")
          return
        }
      }
      if (this.ruleForm.courtesyReward && this.ruleForm.courtesyReward.includes("0")) {
        if (!this.couponList || this.couponList.length == 0) {
          this.$message.error("请先选择赠送优惠券信息!")
          return;
        }
      }
      if (this.ruleForm.courtesyReward && this.ruleForm.courtesyReward.includes("3")) {
        if (!this.ruleForm.points) {
          this.$message.error("请输入赠送积分!")
          return;
        }
      }
      if (this.ruleForm.courtesyReward && this.ruleForm.courtesyReward.includes("2")) {
        if (!this.ruleForm.growthValue) {
          this.$message.error("请输入赠送成长值!")
          return;
        }
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.ruleForm.courtesyReward) this.ruleForm.courtesyReward = this.ruleForm.courtesyReward.toString()
          if (this.couponList) this.ruleForm.couponList = this.couponList
          if (this.ruleForm.id) {
            editActiveNewlyweds1(this.ruleForm).then(response => {
              this.$modal.msgSuccess("修改成功");
              // this.getInfo()
              this.$router.push({path: "/EventMarketing/center/index", query: {id: '6'}})
            });
          } else {
            insertActiveNewlyweds(this.ruleForm).then(response => {
              if (response.data == 1) {
                this.$modal.msgSuccess("新增成功");
                // this.getInfo()
                this.$router.push({path: "/EventMarketing/center/index", query: {id: '6'}})
              } else {
                this.$modal.msgError("新增失败");
              }
            });
          }
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.ifWrite = true
      // this.getInfo()
      this.$router.push({path: "/EventMarketing/center/index",query: {activeId:this.activeId}})
    },
    /** 查询新人有礼活动列表 */
    getList() {
      this.loading = true;
      listActiveNewlyweds(this.queryParams).then(res => {
        this.activeFullminusList = res.data.records
        this.ztotal = res.data.total;
        console.log('wwwwwc', res)
        this.loading = false;
      })
      // this.loading = true;
      // listActiveNewlyweds(this.queryParams).then(response => {
      //   this.activeNewlywedsList = response.data.records;
      //   this.total = response.data.total;
      //   this.loading = false;
      // });
    },
    getoilName() {
      getoilName().then(res => {
        console.log(res)
        this.oillist = res.data

      })

    },
    addDatas() {
      this.open = true
      this.form = {
        id: "",
        tableDatas: [],
        courtesyReward: [],
        activeNewlywedsChildList: [],
      }
      this.form.tableDatas = []
      this.tableDatas = []
      this.pdidlist = []
      this.pddhidlist = []
    },
    qrcodelook(url) {
      this.loadingdialog = true
      this.centerDialogVisible = true
      setTimeout(() => {
        this.creatQrCode(url)
        this.loadingdialog = false
      }, 1000);
    },
    creatQrCode(url) {
      document.getElementById("qrCode").innerHTML = ""
      new QRCode(this.$refs.qrCodeUrl, {
        text: url, // 二维码的内容
        width: 300,
        height: 300,
        colorDark: '#000',
        colorLight: '#fff',
        correctLevel: QRCode.CorrectLevel.H
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: 1,
        chainStoreId: null,
        storeId: null,
        name: null,
        activeStartTime: null,
        activeEndTime: null,
        courtesyReward: [],
        tableDatas: [],
        activeNewlywedsChildList: [],
        activeCode: null,
        isonline: null,
        status: null,
        remainderTotal: null,
        points: null,
        growthValue: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.pdidlist = []
      this.form.tableDatas = []
      this.pddhidlist = []
      this.tableDatas = []
      this.resetForm("form");
    },

    // 请求兑换券
    getlistExchange() {
      this.tableDatadh = []
      listExchange(this.duihuanquan).then(res => {
        if (res.code == 200) {
          this.dialogTableVisibledh = true
          this.tableDatadh = res.data.records
          this.dtotal = res.data.total
        }
      })

    },
    // 请求优惠券
    getlistFavorable() {
      this.tableData = []
      listFavorable(this.youhuiquan).then(res => {
        if (res.code == 200) {
          this.dialogTableVisible = true
          this.tableData = res.data.records
          this.ytotal = res.data.total
        }

      })
    },

    // 兑换券券列表选择
    Favorabledata(row) {
      this.dialogTableVisibledh = false
      if (this.pddhidlist.indexOf(row.id) > -1) {
        this.$message.error("该兑换卡券已存在")
        return
      }

      this.pddhidlist.push(row.id)
      console.log(row)
      let data = {
        activeGift: 2, //活动奖品 0:赠送积分1:赠送优惠券 2. 赠送兑换券 3:赠送成长值 4. 赠送实物
        goodsIds: "", //商品id
        goodsName: "", //商品名称
        goodsTotal: "", //商品数量
        vouchersId: row.id, //券id
        giftCardName: row.name, //赠送卡券名称
        giftCardType: row.type, //券类型
        validityZero: null,
        validityOne: null,
        validityTwo: null,
        validity: row.validity,
        giftCardDetail: row.cardDetail, //券详情
        giftCardTime: row.validity, //券有效期
        giftCardTotal: 1, //券数量
        instruction: row.useInstructions, //使用说明
      }

      this.tableDatas.push(data)
      this.$message.success("新增成功")
    },
    // 优惠券列表选择
    chosedata(row) {
      this.dialogTableVisible = false
      if (this.pdidlist.indexOf(row.id) > -1) {
        this.$message.error("该优惠卡券已存在")
        return
      }

      this.pdidlist.push(row.id)

      let data = {
        activeGift: 1, //活动奖品 0:赠送积分1:赠送优惠券 2. 赠送兑换券 3:赠送成长值 4. 赠送实物
        goodsIds: "", //商品id
        goodsName: "", //商品名称
        goodsTotal: "", //商品数量
        vouchersId: row.id, //券id
        giftCardName: row.name, //赠送卡券名称
        giftCardType: row.discountType, //券类型
        timeType: row.timeType,
        validityZero: row.validityZero,
        validityOne: row.validityOne,
        validityTwo: row.validityTwo,
        giftCardDetail: row.cardDetail, //券详情
        giftCardTime: "", //券有效期
        giftCardTotal: 1,//券数量
        instruction: row.instruction,//使用说明
      }

      this.form.tableDatas.push(data)

      this.$message.success("新增成功")

    },
    // 优惠券删除
    deletedata(row) {
      if (this.form.tableDatas && this.form.tableDatas.length > 0) {
        let delIdx = -1;
        for (let item of this.form.tableDatas) {
          delIdx++;
          if (item.id === row.id) {
            break
          }
        }
        this.pdidlist.splice(delIdx, 1);
        this.form.tableDatas.splice(delIdx, 1);


      }
    },
    // 兑换券删除
    deletedhdata(row) {
      if (this.tableDatas && this.tableDatas.length > 0) {
        let delIdx = -1;
        for (let item of this.tableDatas) {
          delIdx++;
          if (item.id === row.id) {
            break
          }
        }
        this.pddhidlist.splice(delIdx, 1);
        this.tableDatas.splice(delIdx, 1);


      }
    },
    lookDetail(row) {
      this.opendetails = true
      let data = {
        id: row.id,
        exchangeFrom: "新人有礼"
      }
      looklook(data).then(res => {
        this.looklist = res.data

        console.log('详情', res)
      })
      looklooklook(row.id).then(resp => {
        this.statisticsyou = resp.data
        console.log('优惠券详情统计', resp)
      })
    },
    Deleteshan(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除此条新人有礼活动的信息?').then(function () {
        return delActiveNewlyweds(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加新人有礼活动";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      getActiveNewlyweds(row.id).then(response => {
        this.form = response.data;
        if (response.data.activeNewlywedsChildList) {
          this.form.tableDatas = response.data.activeNewlywedsChildList.filter(item => item.activeGift == '1')
          this.tableDatas = response.data.activeNewlywedsChildList.filter(item => item.activeGift == '2')
        }
        this.open = true;
        this.title = "编辑";
      });
    },
    handleDeletexia(row, isonline) {
      // getActiveNewlyweds(row.id).then(response => {
      //
      //   let data = response.data
      //   data.isonline = 1
      //   updateActiveNewlyweds(data).then(response => {
      //     this.$modal.msgSuccess("下线成功");
      //     this.open = false;
      //     this.getList();
      //   });
      //
      // });
      this.$modal.confirm('确定上线此条新人有礼活动信息?').then(function () {
        return editActiveNewlyweds({id: row.id, isonline: isonline});
      }).then(() => {
        this.$modal.msgSuccess("上线成功");
        this.open = false;
        this.getList();
      }).catch(() => {
      });
    },
    submitForm() {
      // this.form.activeNewlywedsChildList
      this.form.activeNewlywedsChildList = this.form.tableDatas.concat(this.tableDatas);
      this.$refs["form"].validate(valid => {
        if (valid) {
          console.log(this.form)
          if (this.form.id) {

            updateActiveNewlyweds(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addActiveNewlyweds(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }

        }

      });
    },
    /** 提交按钮 */
    // submitForm() {
    //   // this.form.activeNewlywedsChildList
    //   this.form.activeNewlywedsChildList = this.form.tableDatas.concat(this.tableDatas);
    //   this.$refs["form"].validate(valid => {
    //     if (valid) {
    //       if (this.form.id != null) {
    //         updateActiveNewlyweds(this.form).then(response => {
    //           this.$modal.msgSuccess("修改成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       } else {
    //         addActiveNewlyweds(this.form).then(response => {
    //           this.$modal.msgSuccess("新增成功");
    //           this.open = false;
    //           this.getList();
    //         });
    //       }
    //     }
    //   });
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除此条新人有礼活动信息?').then(function () {
        return delActiveNewlyweds(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/marketingActivity/activeNewlyweds/export', {
        ...this.queryParams
      }, `activeNewlyweds_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style scoped lang="scss">
.box-bt {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 18px;
}

.x-box {
  background: #f9f9f9;
  border-radius: 6px;
  box-sizing: border-box;
  padding: 15px;
  width: 45%;
}

.cot-box {
  width: 100%;
  height: 89vh;
  border-radius: 8px;
  background: #fff;
  box-sizing: border-box;
  padding: 20px;
  margin: 0 auto;
}

.d-s {
  display: flex;
  align-items: center;
}

.icon-type {
  display: flex;
  align-items: center;
  font-weight: 400;
  font-size: 14px;
  color: #999999;
  margin-right: 20px;
  cursor: pointer;
}

.acvtive {
  color: #FF770F !important;
}

</style>