<template>
  <div class="m-container">
    <el-page-header @back="onCancel" :content="title"></el-page-header>
    <!-- <h3 class="infoTitle">优惠券信息</h3>
    <el-divider></el-divider> -->
    <el-form :model="form" ref="form" class="form">
      <el-row>
        <el-col style="width: 500px">
          <el-form-item
            label="优惠券名称"
            prop="name"
            :rules="[{ required: true, message: '请输入优惠卷名称' }]"
          >
            <el-input
              :disabled="isDisabled"
              v-model="form.name"
              placeholder="请输入优惠卷名称"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col style="width: 500px">
          <el-form-item
            label="描述"
            prop="description"
            :rules="[{ required: true, message: '请输入优惠卷描述' }]"
          >
            <el-input
              :disabled="isDisabled"
              v-model="form.description"
              maxlength="20"
              type="textarea"
              :rows="3"
              show-word-limit
              placeholder="请输入优惠券描述，该描述会在优惠券上展示"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <!-- <el-col style="width: 395px">
          <el-form-item
            label="优惠券类型"
            prop="type"
            :rules="[{ required: true, message: '请选择优惠卷类型' }]"
          >
            <el-select
              :disabled="isDisabled"
              placeholder="优惠券类型"
              v-model.trim="form.type"
              filterable
              clearable
              @change="changeType"
              style="width: 355px !important"
            >
              <el-option
                v-for="item in couponTypeList"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col style="width: 395px" v-if="form.type == 'FULL_REDUCTION'">
          <el-form-item
            label="面值"
            prop="faceValue"
            :rules="[{ required: true, message: '请输入面值' }]"
          >
            <el-input
              v-model="form.faceValue"
              placeholder="请输入面值"
              :disabled="isDisabled"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col style="width: 395px" v-if="form.type == 'FULL_REDUCTION'">
          <el-form-item
            label="达标金额"
            prop="fullAmount"
            :rules="[{ required: true, message: '请输入达标金额' }]"
          >
            <el-input
              v-model="form.fullAmount"
              placeholder="请输入达标金额"
              :disabled="isDisabled"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col style="width: 395px" v-if="form.type == 'DISCOUNT'">
          <el-form-item
            label="折扣"
            prop="faceValue"
            :rules="[{ required: true, message: '请输入折扣' }]"
          >
            <el-input
              v-model="form.faceValue"
              placeholder="请输入折扣"
              :disabled="isDisabled"
            >
              <template slot="append">%</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col style="width: 395px">
          <el-form-item
            label="有效期类型"
            prop="effectiveType"
            :rules="[{ required: true, message: '请选择有效期类型' }]"
          >
            <el-select
              style="width: 355px !important"
              placeholder="优惠券类型"
              v-model.trim="form.effectiveType"
              filterable
              clearable
              @change="changeEffectiveType"
              :disabled="isDisabled"
            >
              <el-option label="固定有效期天数" value="DAYS"></el-option>
              <el-option label="固定时间段" value="TIME_BUCKET"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col style="width: 395px" v-if="form.effectiveType == 'DAYS'">
          <el-form-item
            prop="deadline"
            :rules="[{ required: true, message: '请输入有效期天数' }]"
          >
            <span style="color: #606266"
              ><span style="color:#F56C6C">*</span>有效期天数
              <el-tooltip placement="top" popper-class="mTooltip">
                <div slot="content">自领取之日起多少天有效</div>
                <i
                  class="el-icon-question"
                  style="font-size: 18px; color: #f56c6c"
                ></i> </el-tooltip
            ></span>
            <el-input v-model="form.deadline" placeholder="请输入有效期天数" :disabled="isDisabled">
              <template slot="append">天</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col style="width: 395px" v-if="form.effectiveType == 'TIME_BUCKET'">
          <el-form-item
            prop="effectiveTime"
            :rules="[{ required: true, message: '请选择有效期' }]"
          >
            <span style="color: #606266"
              ><span style="color:#F56C6C">*</span>有效期
              <el-tooltip placement="top" popper-class="mTooltip">
                <div slot="content">优惠券可使用时间段</div>
                <i
                  class="el-icon-question"
                  style="font-size: 18px; color: #f56c6c"
                ></i> </el-tooltip
            ></span>
            <el-date-picker
              style="width: 100%"
              v-model="form.effectiveTime"
              :picker-options="{ firstDayOfWeek: 1 }"
              type="datetimerange"
              :default-time="['00:00:00', '23:59:59']"
              range-separator="-"
              start-placeholder="活动开始日期"
              end-placeholder="活动结束日期"
              :disabled="isDisabled"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col style="width: 395px">
          <el-form-item
            label="库存总量(-1为不限制)"
            prop="stockCount"
            :rules="[{ required: true, message: '请输入库存总量' }]"
          >
            <el-input v-model="form.stockCount" placeholder="请输入库存总量">
              <template slot="append">张</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col style="width: 395px">
          <el-form-item
            label="预警值(-1为不限制)"
            prop="warningStockNum"
            :rules="[{ required: true, message: '请输入预警值' }]"
          >
            <el-input v-model="form.warningStockNum" placeholder="请输入预警值">
              <template slot="append">张</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col style="width: 395px">
          <el-form-item
            prop="limitExchangeNum"
            :rules="[{ required: true, message: '请输入领取上限' }]"
          >
            <span style="color: #606266"
              >
              <span style="color:#F56C6C">*</span> 领取上限
              <el-tooltip placement="top" popper-class="mTooltip">
                <div slot="content">用户可领取最大张数</div>
                <i
                  class="el-icon-question"
                  style="font-size: 18px; color: #f56c6c"
                ></i> </el-tooltip
            ></span>
            <el-input
              :disabled="isDisabled"
              v-model="form.limitExchangeNum"
              placeholder="请输入领取上限"
            >
              <template slot="append">张</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col style="width: 395px">
          <el-form-item label="领取时间" prop="getTime"  :rules="[{ required: true, message: '请输入领取时间' }]">
            <el-date-picker
              style="width: 100%"
              v-model="form.getTime"
              :picker-options="{ firstDayOfWeek: 1 }"
              type="datetimerange"
              :default-time="['00:00:00', '23:59:59']"
              range-separator="-"
              start-placeholder="活动开始日期"
              end-placeholder="活动结束日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-button type="primary" v-if="activeRow" @click="resetCoupon"
          >保存</el-button
        >
        <el-button type="primary" v-else @click="addCoupon">提交</el-button>
        <el-button type="danger" @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { addSysCoupon, resetSysCoupon } from "./api.js";
import { couponTypeList } from "@/utils/searchArray";
import { getTimes } from "@/utils";
export default {
  data() {
    return {
      couponTypeList,
      form: {
        name: "",
        description: "",
        type: "FULL_REDUCTION",
        faceValue: "",
        fullAmount: "",
        effectiveType: "",
        effectiveTime: [],
        stockCount: "",
        warningStockNum: "",
        limitExchangeNum: "",
        getTime: [],
      },
      activeRow: null,
      isDisabled: false,
      title: "新增优惠券",
    };
  },
  mounted() {
    if (this.$route.query.row) {
      this.activeRow = JSON.parse(this.$route.query.row);
      this.form = { ...this.activeRow };
      // 优惠券只能时满减
      this.form.type = 'FULL_REDUCTION'

      let effectiveStartTime = this.activeRow.effectiveStartTime;
      let effectiveExpireTime = this.activeRow.effectiveExpireTime;
      let startDate = this.activeRow.startDate;
      let endDate = this.activeRow.endDate;
      this.$set(this.form, "effectiveTime", [
        effectiveStartTime,
        effectiveExpireTime,
      ]);
      this.$set(this.form, "getTime", [startDate, endDate]);
      this.title = this.activeRow.name;
      if (this.activeRow?.consumeNum > 0) {
        this.isDisabled = true;
      }
    }
  },
  methods: {
    changeType(val) {
      this.form.faceValue = "";
      this.form.fullAmount = "";
    },
    changeEffectiveType() {
      // this.form.effectiveTime = [];
      this.$set(this.form,'effectiveTime',[])
      this.$set(this.form,'deadline',null)
      // this.form.deadline = "";
    },
    onCancel() {
      this.$router.push("/couponManager");
    },
    resetForm() {
      this.$refs.form.resetFields();
      if (this.activeRow) {
        this.form = { ...this.activeRow };
        let effectiveStartTime = this.activeRow.effectiveStartTime;
        let effectiveExpireTime = this.activeRow.effectiveExpireTime;
        let startDate = this.activeRow.startDate;
        let endDate = this.activeRow.endDate;
        this.$set(this.form, "effectiveTime", [
          effectiveStartTime,
          effectiveExpireTime,
        ]);
        this.$set(this.form, "getTime", [startDate, endDate]);
      }
    },
    async addCoupon() {
      this.$refs.form.validate(async (some) => {
        if (some) {
          this.$confirm("您确定新增优惠券?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(async () => {
              try {
                let { effectiveTime, getTime, ...rest } = this.form;
                let params = {
                  ...rest,
                  ...getTimes(effectiveTime, [
                    "effectiveStartTime",
                    "effectiveExpireTime",
                  ],'YYYY-MM-DD HH:mm:ss'),
                  ...getTimes(getTime, ["startDate", "endDate"],'YYYY-MM-DD HH:mm:ss'),
                };
                const res = await addSysCoupon(params);
                this.$message.success("新增成功");
                this.onCancel();
              } catch (e) {
                console.log(e);
              }
            })
            .catch(() => {});
        }
      });
    },
    resetCoupon() {
      this.$refs.form.validate(async (some) => {
        if (some) {
          this.$confirm("您确定修改优惠券?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(async () => {
              try {
                let { effectiveTime, getTime, ...rest } = this.form;
                let params = {
                  ...rest,
                  ...getTimes(effectiveTime, [
                    "effectiveStartTime",
                    "effectiveExpireTime",
                  ],'YYYY-MM-DD HH:mm:ss'),
                  ...getTimes(getTime, ["startDate", "endDate"],'YYYY-MM-DD HH:mm:ss'),
                };
                const res = await resetSysCoupon(params);
                this.$message.success("新增成功");
                this.onCancel();
              } catch (e) {
                console.log(e);
              }
            })
            .catch(() => {});
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.form {
  margin-top: 30px;
}
.infoTitle {
  font-weight: 400;
  margin-top: 30px;
  font-size: 18px;
}
/deep/label {
  font-weight: 400;
}
</style>
