<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="优惠券名称" prop="couponTitle">
        <el-input
          v-model="queryParams.couponTitle"
          placeholder="请输入优惠券名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="优惠券编码" prop="couponCode">
        <el-input
          v-model="queryParams.couponCode"
          placeholder="请输入优惠券编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:coupon:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:coupon:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:coupon:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:coupon:export']"
          >导出</el-button
        >
      </el-col>-->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="couponList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键id" align="center" prop="id" /> -->
      <el-table-column
        label="优惠券名称"
        align="center"
        prop="couponTitle"
        show-overflow-tooltip
      />
      <el-table-column label="优惠券编码" align="center" prop="couponCode" />
      <el-table-column label="优惠券类型" align="center" prop="couponType">
        <template slot-scope="scope">
          {{ scope.row.couponType == "FULL_REDUCTION_COUPON" ? "满减券" : "" }}
          {{ scope.row.couponType == "CASH_COUPON" ? "代金券" : "" }}
          {{ scope.row.couponType == "EXCHANGE_COUPON" ? "兑换券" : "" }}
          {{ scope.row.couponType == "DISCOUNT_COUPON" ? "抵扣券" : "" }}
        </template>
      </el-table-column>

      <el-table-column
        label="优惠券有效期(天)"
        align="center"
        prop="couponReductionDays"
      />
      <el-table-column label="优惠券面额" align="center" prop="couponPrice" />
      <el-table-column
        label="优惠券适用门槛"
        align="center"
        prop="couponConsumePrice"
      />
      <el-table-column label="领取方式" align="center" prop="receiveType">
        <template slot-scope="scope">
          {{ scope.row.receiveType == "NEW_PEOPLE_WELFARE" ? "新人福利" : "" }}
          {{ scope.row.receiveType == "EVENT_GIFT" ? "活动赠送" : "" }}
          {{ scope.row.receiveType == "CONSUME_REBATE" ? "消费返券" : "" }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="发放数量" align="center" prop="receiveCount" />
      <el-table-column label="发放数量上限" align="center" prop="receiveLimitCount" />-->
      <!-- <el-table-column label="全部商品" align="center" prop="useScope">
        <template slot-scope="scope">
          {{
            scope.row.useScope == "ALL_PRODUCT" ? "全部商品" : ""
          }}
          {{ scope.row.useScope == "SPECIFIED_COMMODITY" ? "指定商品" : "" }}
        
        </template>
      </el-table-column>-->
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:coupon:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:coupon:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券信息对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="800px"
      append-to-body
      :before-close="cancel"
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="130px"
        :inline="true"
      >
        <el-form-item label="优惠券名称" prop="couponTitle">
          <el-input
            v-model="form.couponTitle"
            maxlength="100"
            placeholder="请输入优惠券名称"
            style="width: 220px"
          />
        </el-form-item>

        <el-form-item label="优惠券有效期(天)" prop="couponReductionDays">
          <el-input
            maxlength="5"
            oninput="value=value.replace(/[^\d]/g,'')"
            v-model.number="form.couponReductionDays"
            placeholder="请输入优惠券有效期，单位：天"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="优惠券面额" prop="couponPrice">
          <el-input
            @keyup.native="form.couponPrice = oninput(form.couponPrice)"
            v-model="form.couponPrice"
        
            maxlength="8"
            placeholder="请输入优惠券面额，单位：元"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="优惠券适用门槛" prop="couponConsumePrice">
          <el-input
            :change="checkPrice()"
       
            maxlength="8"
            v-model="form.couponConsumePrice"
            placeholder="请输入优惠券适用门槛"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="领取方式" prop="receiveType">
          <el-select
            style="width: 220px"
            clearable
            v-model="form.receiveType"
            placeholder="请选择领取方式"
          >
            <el-option
              v-for="item in option"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券类型" prop="couponType">
          <el-select
            style="width: 220px"
            clearable
            v-model="form.couponType"
            placeholder="请选择优惠券类型"
          >
            <el-option
              v-for="item in couponTypeoption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="显示顺序" prop="showSort">
          <el-input
            v-model.number="form.showSort"
            placeholder="请输入显示顺序"
            oninput="value=value.replace(/[^\d]/g,'')"
            maxlength="5"
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item label="优惠券概述" prop="couponDescription">
          <el-input
            type="textarea"
            :rows="5"
            maxlength="300"
            style="width: 540px"
            v-model="form.couponDescription"
            placeholder="请输入优惠券概述，包括使用范围，使用注意事项等信息"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCoupon,
  getCoupon,
  delCoupon,
  addCoupon,
  updateCoupon,
} from "@/api/system/coupon";

export default {
  name: "Coupon",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠券信息表格数据
      couponList: [],
      // 弹出层标题
      title: "",
      couponTypeoption: [
        {
          value: "FULL_REDUCTION_COUPON",
          label: "满减券",
        },
        // {
        //   value: "CASH_COUPON",
        //   label: "代金券",
        // },
        // {
        //   value: "EXCHANGE_COUPON",
        //   label: "兑换券",
        // },
        // {
        //   value: "DISCOUNT_COUPON",
        //   label: "抵扣券",
        // },
      ],
      // options: [
      //   {
      //     value: "ALL_PRODUCT",
      //     label: "全部商品",
      //   },
      //   {
      //     value: "SPECIFIED_COMMODITY",
      //     label: "指定商品",
      //   },
      // ],
      option: [
        {
          value: "NEW_PEOPLE_WELFARE",
          label: "新人福利",
        },
        // {
        //   value: "EVENT_GIFT",
        //   label: "活动赠送",
        // },
        // {
        //   value: "CONSUME_REBATE",
        //   label: "消费返券",
        // },
      ],
      value: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        couponTitle: null,
        couponCode: null,
        couponType: null,
        couponReductionDays: null,
        couponPrice: null,
        couponConsumePrice: null,
        couponDescription: null,
        receiveType: null,
        receiveCount: null,
        receiveLimitCount: null,
        useScope: null,
        showSort: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        couponTitle: [
          {
            required: true,
            message: "请输入优惠券名称",
            trigger: "blur",
          },
        ],
        couponType: [
          {
            required: true,
            message: "请选择优惠券类型",
            trigger: "blur",
          },
        ],
        couponReductionDays: [
          {
            required: true,
            message: "请输入优惠券有效期",
            trigger: "blur",
         
          },
        ],
        couponPrice: [
          {
            required: true,
            message: "请输入优惠券面额",
            trigger: "blur",
          },
        ],
        couponConsumePrice: [
          {
            required: true,
            message: "请输入优惠券适用门槛",
            trigger: "blur",
          },
        ],
        couponDescription: [
          {
            required: true,
            message: "请输入优惠券概述",
            trigger: "blur",
          },
        ],
        receiveType: [
          {
            required: true,
            message: "请选择领取方式",
            trigger: "blur",
          },
        ],
        // useScope: [
        // {
        //       required: true,
        //       message: "请输入优惠券适用门槛",
        //       trigger: "blur"
        //     }
        // ],
        showSort: [
          {
            required: true,
            message: "请输入显示顺序",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /**只能输入数字且有小数点最多保留两位*/
    checkPrice() {
      let checkPlan = "" + this.form.couponConsumePrice;
      checkPlan = checkPlan
        .replace(/[^\d.]/g, "") // 清除“数字”和“.”以外的字符
        .replace(/\.{2,}/g, ".") // 只保留第一个. 清除多余的
        .replace(/^\./g, "") // 保证第一个为数字而不是.
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      if (checkPlan.indexOf(".") < 0 && checkPlan !== "") {
        // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        checkPlan = parseFloat(checkPlan) + "";
      } else if (checkPlan.indexOf(".") >= 0) {
        checkPlan = checkPlan.replace(/^()*(\d+)\.(\d\d).*$/, "$1$2.$3"); // 只能输入两个小数
      }
      this.form.couponConsumePrice = checkPlan;
    },

    oninput(num) {
      let str = num;
      const len1 = str.substr(0, 1);
      const len2 = str.substr(1, 1);
      //如果第一位是0，第二位不是点，就用数字把点替换掉
      if (str.length > 1 && len1 == 0 && len2 != ".") {
        str = str.substr(1, 1);
      }
      //第一位不能是.
      if (len1 == ".") {
        str = "";
      }
      //限制只能输入一个小数点
      if (str.indexOf(".") != -1) {
        const str_ = str.substr(str.indexOf(".") + 1);
        if (str_.indexOf(".") != -1) {
          str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1);
        }
      }
      //正则替换
      str = str.replace(/[^\d^.\\ .]+/g, ""); // 保留数字和小数点
      str = str.replace(".", "$#$").replace(/\./g, "").replace("$#$", "."); // 小数点后只能输两位
      str = str.replace(/^(-)*(\d+)\.(\d\d).*$/, "$1$2.$3");
      return str;
    },

    /** 查询优惠券信息列表 */
    getList() {
      this.loading = true;
      listCoupon(this.queryParams).then((response) => {
        this.couponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    changeInput(e) {
      if (e.target.value.indexOf(".") >= 0) {
        e.target.value = e.target.value.substring(
          0,
          e.target.value.indexOf(".") + 3
        );
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        couponTitle: null,
        couponCode: null,
        couponType: null,
        couponReductionDays: null,
        couponPrice: null,
        couponConsumePrice: null,
        couponDescription: null,
        receiveType: null,
        receiveCount: null,
        receiveLimitCount: null,
        useScope: null,
        showSort: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    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();
      const id = row.id || this.ids;
      getCoupon(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改优惠券信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.couponPrice) {
        this.form.couponPrice = Number(this.form.couponPrice);
      }
      if (this.form.couponConsumePrice) {
        this.form.couponConsumePrice = Number(this.form.couponConsumePrice);
      }

      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCoupon(this.form).then((response) => {
              if (response.code == 200) {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              }
            });
          } else {
            addCoupon(this.form).then((response) => {
              if (response.code == 200) {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const couponTitles = row.couponTitle || this.couponTitles;
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除优惠券名称为"' + couponTitles + '"的数据项？')
        .then(function () {
          return delCoupon(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/coupon/export",
        {
          ...this.queryParams,
        },
        `coupon_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
