<template>
  <div v-loading="loading">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="150px" class="order_form">
      <el-form-item label="活动名称" prop="activityName">
        <el-input v-model="ruleForm.activityName" placeholder="请输入活动名称"></el-input>
      </el-form-item>
      <el-form-item label="活动时间" prop="activityTime">
        <el-date-picker
          v-model="ruleForm.activityTime"
          :picker-options="pickerOptions"
          class="filter-item"
          type="daterange"
          format="yyyy年MM月dd日"
          value-format="yyyy-MM-dd"
          align="left"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="促销方式" prop="promotionMethod">
        <el-select v-model="ruleForm.promotionMethod" clearable placeholder="请选择促销方式">
          <el-option label="按总件数" value="按总件数"></el-option>
          <el-option label="按总金额" value="按总金额"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="满减活动" prop="amountRange">
        <el-button type="primary" @click="addActivity">添加活动</el-button>
        <span class="info">请点击添加活动</span>
      </el-form-item>
      <!-- <el-form-item>
        <span class="money">*</span>消费满
        <el-input
          style="width:90px;"
          onkeyup="value=value.replace(/[^\d.]/g,'')"
          v-model="ruleForm.amountRange"
        ></el-input>元，减
        <el-input
          v-model="ruleForm.reductionAmount"
          onkeyup="value=value.replace(/[^\d.]/g,'')"
          style="width:90px;"
        ></el-input>元
      </el-form-item> -->
      <el-form-item v-for="(item,index) in addActivityData" :key="index" >
        <span class="money">*</span>消费满
        <el-input
          style="width:90px;"
          onkeyup="value=value.replace(/[^\d.]/g,'')"
          v-model="item.amountRange"
        ></el-input>元，减
        <el-input
          style="width:90px;"
          onkeyup="value=value.replace(/[^\d.]/g,'')"
          v-model="item.reductionAmount"
        ></el-input>元
        <el-button type="text" @click="removeActivity(item.key)">删除</el-button>
      </el-form-item>
      <el-form-item label="活动方式" prop="activityMode">
        <el-input v-model="ruleForm.activityMode" placeholder="请输入活动方式"></el-input>
      </el-form-item>
      <el-form-item label="绑定商品标签" prop="boundGoods">
        <el-select v-model="ruleForm.boundGoods" clearable placeholder="请选择绑定商品标签">
          <el-option
            v-for="item in shopList"
            :key="item.F_TagName"
            :label="item.F_TagName"
            :value="item.F_TagName"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getProviceCity, getDictionary } from "@/api/commonAPI";
import {
  getFullMarketingDetail,
  addFullMarketing,
  editFullMarketing,
  getMerchandise,
  getshopping,
} from "@/api/marketingManagement/fullGiveMarketing";
import { validateTel } from "@/utils/validate";
import { filterContent, pickerOptions } from "@/utils";
export default {
  name: "AddOrEdit",
  props: {
    rowid: {
      type: String,
      default: "",
    },
    callid: {
      type: Number,
      default: 0,
    },
    layerid: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      props: {
        // 自定义省市下拉数据的key值
        value: "code",
        label: "name",
        children: "entityJson",
      },
      pickerOptions, //日期数据
      sourceOptions: [], // 工单来源下拉数据
      shopList: [], //绑定商品数据
      addActivityData: [{
        amountRange:'',
        reductionAmount:'',
      }], //添加活动的数据
      ruleForm: {
        unique_id: "", //		否	string	callid
        ordercode: "",
        activityName: "", //活动名称
        activityTime: "", //活动时间
        promotionMethod: "", //促销方式
        reductionAmount: "", //满减金额
        amountRange: "", //金额区间
        activityMode: "", //活动方式
        boundGoods: "", //绑定商品
      },
      reductionAmount: [], //满减金额
      amountRange: [], //金额区间
      rules: {
        activityName: [
          {
            required: true,
            trigger: "blur",
            message: "请输入活动名称",
          },
        ],
        activityTime: [
          {
            required: true,
            trigger: "blur",
            message: "请选择活动时间",
          },
        ],
        promotionMethod: [
          {
            required: true,
            trigger: "change",
            message: "请选择促销方式",
          },
        ],
        boundGoods: [
          {
            required: true,
            trigger: "change",
            message: "请选择商品标签",
          },
        ],
      },
      loading: false,
    };
  },
  created() {
    this.getShopList(); //获取绑定商品
    if (this.callid) {
      this.ruleForm.unique_id = this.callid;
    }
    Promise.all([]).then(() => {
      if (this.rowid) {
        this.ruleForm.ordercode = this.rowid;
        this.getDetail(this.rowid);
      }
    });
  },
  methods: {
    submitForm() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.addActivityData && this.addActivityData.length > 0) {
            this.addActivityData.map((item) => {
              this.reductionAmount.push(item.reductionAmount);
              this.amountRange.push(item.amountRange);
            });
            if(this.reductionAmount.filter(i=>i&&i.trim()).length==0||this.amountRange.filter(i=>i&&i.trim()).length==0){
              this.$message.error("请输入满减金额!");
              this.reductionAmount = [];
              this.amountRange = [];
              return
            }
          } else {
            this.$message.error("请输入满减金额!");
            this.reductionAmount = [];
            this.amountRange = [];
            return;
          }
          this.ruleForm.content = filterContent.delHtmlTag(
            this.ruleForm.content
          ); // 保存内容时去掉 html 标签
          this.loading = true;
          return new Promise((response) => {
            const params = {
              F_Type: 3,
              F_ID: this.rowid ? this.rowid : "",
              F_Name: this.ruleForm.activityName, //活动名称
              F_Describe: this.ruleForm.promotionMethod, //促销方式
              F_Money: this.reductionAmount.toString(), //满减金额
              F_AmountRange: this.amountRange.toString(), //金额区间
              F_StartTime:
                this.ruleForm.activityTime && this.ruleForm.activityTime[0], //开始时间
              F_EndTime:
                this.ruleForm.activityTime && this.ruleForm.activityTime[1], //结束时间
              F_Commodity: this.ruleForm.boundGoods, //商品ID
              F_ActivityMode: this.ruleForm.activityMode, //活动金额
            };
            // 添加
            if (!this.rowid) {
              addFullMarketing(params)
                .then((response) => {
                  this.loading = false;
                  if (response.state.toLowerCase() === "success") {
                    this.$parent.$layer.close(this.layerid);
                    if (this.callid) {
                      this.$parent.getOrderRecord(); // 重新加载来电弹屏工单记录
                    } else {
                      this.$parent.btn_search(); // 重新加载父级数据
                    }
                    this.$message.success("恭喜你，添加成功!");
                  }
                })
                .catch(() => {
                  this.loading = false;
                });
              return;
            }
            // 编辑
            editFullMarketing(params)
              .then((response) => {
                this.loading = false;
                if (response.state.toLowerCase() === "success") {
                  this.$parent.$layer.close(this.layerid);
                  this.$parent.getList(); // 重新加载父级数据
                  this.$message.success("恭喜你，编辑成功!");
                }
              })
              .catch(() => {
                this.loading = false;
              });
          });
        } else {
          this.$message.error("请输入有效的必填项信息!");
          this.reductionAmount = [];
          this.amountRange = [];
          return false;
        }
      });
    },
    resetForm() {
      this.$refs.ruleForm.resetFields();
      this.ruleForm.activityTime = "";
      this.addActivityData = [];
    },
    // 详情
    getDetail(rid) {
      getFullMarketingDetail(rid).then((response) => {
        if (response.state.toLowerCase() === "success") {
          const res = response.data;
          this.ruleForm.activityName = res.F_Name;
          this.ruleForm.promotionMethod = res.F_Describe;
          this.addActivityData = res.F_Money.split(
            ","
          ).map((reductionAmount, i) => ({
            reductionAmount,
            amountRange: res.F_AmountRange.split(",")[i],
          }));
          // this.ruleForm.reductionAmount = res.F_Money;
          // this.ruleForm.amountRange = res.F_AmountRange;
          this.ruleForm.activityMode = res.F_ActivityMode;
          this.ruleForm.boundGoods = res.F_Commodity;
          this.ruleForm.activityTime = [res.F_StartTime, res.F_EndTime];
        }
      });
    },
    //获取绑定商品
    getShopList() {
      getshopping({ CLass: 3 })
        .then((response) => {
          if (response.state.toLowerCase() == "success") {
            this.shopList = response.data;
          }
        })
        .catch((result) => {
          console.log(result);
        });
    },
    //添加活动方法
    addActivity() {
      // if (!this.ruleForm.amountRange || !this.ruleForm.reductionAmount) {
      //   this.$message.error("请填写金额数据");
      //   return;
      // }
      this.addActivityData.push({
        amountRange: '', //满减区间
        reductionAmount: '', //满减金额
        key: Date.now(),
      });
      // this.ruleForm.amountRange = "";
      // this.ruleForm.reductionAmount = "";
    },
    //删除活动方法
    removeActivity(itemId) {
      var index = this.addActivityData.findIndex((item) => {
        return item.key == itemId;
      });
      if (index !== -1) {
        this.addActivityData.splice(index, 1);
      }
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
.order_form {
  .form_select {
    width: 100%;
  }
  .form_date {
    width: 100%;
  }
}
.money {
  color: #f56c6c;
  margin-left: 4px;
}
.info {
  color: #c0c4cc;
  font-size: 12px;
  margin-left: 5px;
}
</style>