<!-- eslint-disable vue/no-use-v-if-with-v-for -->
<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" @close="reset">
    <div class="app-container">
      <div class="tab">
        <div
          v-for="(item, index) in tabList"
          :key="index"
          class="tab_item"
          :class="{ active: form.type == item.type }"
          @click="tabClick(item)"
        >
          {{ item.name }}
          <span class="bor" />
        </div>
      </div>
      <!-- 优惠券 -->
      <div class="content">
        <el-form
          ref="form"
          :inline="true"
          :model="form"
          :rules="rules"
          label-width="120px"
          label-position="left"
        >
          <el-form-item label="优惠券券名" prop="title" style="width: 100%">
            <el-input v-model="form.title" placeholder="" style="width: 289px" />
          </el-form-item>
          <el-form-item label="使用门槛" prop="fullAmount">
            <el-input
              v-model="form.fullAmount"
              oninput="value= value.replace(/[^\d|\.]/g, '')"
              placeholder=""
              style="width: 180px; margin-right: 66px"
            >
              <template #prepend>满</template>
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item v-if="form.type == 1" label="" prop="discountAmount">
            <el-input
              v-model="form.discountAmount"
              oninput="value= value.replace(/[^\d|\.]/g, '')"
              placeholder=""
              style="width: 180px"
            >
              <template #prepend>减</template>
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="有效期类型" style="width: 100%">
            <el-radio-group v-model="form.validityType">
              <el-radio
                v-for="item in couponEnum.validityType"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="form.validityType == 'fixed'"
            label="有效期（天）"
            prop="validDays"
            style="width: 100%"
          >
            <el-input v-model="form.validDays" placeholder="" style="width: 200px">
              <template #append>天</template>
            </el-input>
          </el-form-item>

          <el-form-item
            v-if="form.validityType == 'custom'"
            label="有效时间"
            prop="validEndTime"
            style="width: 100%"
          >
            <el-date-picker
              v-model="validityTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-dd HH:mm:ss"
              @change="validityChange"
            />
          </el-form-item>
          <!-- <el-form-item label="使用门槛" prop="daysToTakeEffect" style="width: 100%;">
          <el-input v-model="form.daysToTakeEffect" placeholder="" style="width: 200px;">
            <template #prepend>隔</template>
            <template #append>天生效</template>
          </el-input>
          <el-tooltip class="item" effect="dark" content="领取后0天后0点0分" placement="top-start">
            <i class="el-icon-question" />
          </el-tooltip>
        </el-form-item> -->
          <el-form-item label="可用周期" prop="userDays" style="width: 100%">
            <el-checkbox-group v-model="form.userDays">
              <el-checkbox
                v-for="(city, index) in couponEnum.cycle"
                :key="index"
                :value="city.label"
                @change="userDayChagne"
              >
                {{ city.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="指定时间段" style="width: 100%">
            <el-radio-group v-model="form.useTimeType">
              <el-radio
                v-for="item in couponEnum.useTimeType"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="form.useTimeType == 'custom'"
            label="指定时间段"
            prop="useEndTime"
            style="width: 100%"
          >
            <el-time-picker
              v-model="useTime"
              is-range
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
              value-format="HH:mm"
              @change="useTimeChange"
            />
          </el-form-item>
          <el-form-item label="发放数量" prop="number" style="width: 100%">
            <el-input
              v-model="form.number"
              oninput="value=value.replace(/^(0+)|[^\d]+/g,'')"
              placeholder=""
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="赠送商品" prop="products" v-if="form.type == 2">
            <div>
              <el-button type="primary" icon="plus" @click="$refs.refGoodsSelect.show()">
                添加
              </el-button>
              <div class="shop_list">
                <div class="item_wrap" v-if="form.proName">
                  <div class="name">{{ form.proName }}</div>
                  <div class="del" @click="delProduct">删除</div>
                </div>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <GoodsSelect ref="refGoodsSelect" radio @success="slectShop" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="onSubmitHandle">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import couponEnum from "../couponEnum";
import couponApi from "@/api/account/coupon";
import productApi from "@/api/product/index";
import { ElNotification } from "element-plus";
export default {
  data() {
    const validateProduct = (rule, value, callback) => {
      if (!this.form.proId) {
        callback(new Error("请选择商品"));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      dialogTitle: "",
      tabList: [
        { name: "优惠券", type: 1 },
        { name: "商品券", type: 2 },
      ],
      tabActive: 1,
      couponEnum,
      dialogVisible: false,
      loading: false,
      validityTime: "",
      useTime: ["06:00:00", "23:59:59"],
      form: {
        id: "",
        shopId: "",
        type: "1",
        title: "",
        fullAmount: null,
        discountAmount: null,
        validityType: "fixed",
        validStartTime: "",
        validEndTime: "",
        userDays: [],
        validDays: "",
        useTimeType: "all",
        useStartTime: "",
        useEndTime: "",
        proId: "",
        proName: "",
        number: "",
      },
      rules: {
        title: [
          {
            required: true,
            message: "填写券名",
            trigger: "blur",
          },
        ],
        fullAmount: [
          {
            required: true,
            message: "填写满减金额",
            trigger: "blur",
          },
        ],
        discountAmount: [
          {
            required: true,
            message: "填写满减金额",
            trigger: "blur",
          },
        ],
        number: [
          {
            required: true,
            message: "填写发放数量",
            trigger: "blur",
          },
        ],
        validDays: [
          {
            required: true,
            message: "填写有效天数",
            trigger: "blur",
          },
        ],
        daysToTakeEffect: [
          {
            required: true,
            message: "填写生效天数",
            trigger: "blur",
          },
        ],
        userDays: [
          {
            required: true,
            message: "选择可用周期",
            trigger: "change",
          },
        ],
        validEndTime: [
          {
            required: true,
            message: "选择有效时间段",
            trigger: "change",
          },
        ],
        useEndTime: [
          {
            required: true,
            message: "选择指定时间段",
            trigger: "change",
          },
        ],
        products: [
          {
            required: true,
            validator: validateProduct,
            trigger: "change",
          },
        ],
      },
      resetForm: "",
    };
  },
  methods: {
    reset() {
      this.$refs.form.resetFields();
      this.form = {
        id: "",
        shopId: "",
        type: "1",
        title: "",
        fullAmount: 0,
        discountAmount: null,
        validityType: "fixed",
        validStartTime: "",
        validEndTime: "",
        userDays: [],
        validDays: "",
        useTimeType: "all",
        useStartTime: "",
        useEndTime: "",
        proId: "",
        proName: "",
        number: "",
      };
      this.form.type = 1;
    },
    async open(data) {
      if (data && data.id) {
        this.dialogTitle = "修改优惠券";
      } else {
        this.dialogTitle = "新增优惠券";
      }
      this.dialogVisible = true;
      this.resetForm = { ...this.form };
      if (data) {
        this.form = { ...data, userDays: data.userDays.split(",") };
        if (data.proId) {
          productApi.getDetail(data.proId).then((res) => {});
        }
      }
    },
    close() {
      this.dialogVisible = false;
    },
    /**
     * 切换类型
     * @param item
     */
    tabClick(item) {
      this.form = this.resetForm;
      this.form.number = "";
      this.form.type = item.type;
      this.$refs.form.resetFields();
    },

    /**
     * 选择可用周期
     */
    userDayChagne(e) {
      console.log(this.form.userDays);
    },

    /**
     * 有效期选择
     * @param e
     */
    validityChange(e) {
      console.log(e);
      this.form.validStartTime = e[0];
      this.form.validEndTime = e[1];
    },

    /**
     * 指定时间段选择
     * @param e
     */
    useTimeChange(e) {
      this.form.useStartTime = e[0];
      this.form.useEndTime = e[1];
    },

    /**
     * 选择商品
     * @param res
     */
    slectShop(res) {
      if (!res || res.length <= 0) {
        return;
      }
      console.log(res);
      this.form.proId = res[res.length - 1].id;
      this.form.proName = res[res.length - 1].name;
    },
    delProduct() {
      this.form.proId = "";
      this.form.proName = "";
    },
    /**
     * 判断是否存在重复商品
     * @param id
     */
    checkShop(id) {
      let falg = false;
      this.form.products.map((item) => {
        // eslint-disable-next-line eqeqeq
        if (item.id == id) {
          falg = true;
        }
      });
      return falg;
    },

    /**
     * 提交
     */
    onSubmitHandle() {
      console.log(this.form);
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true;
            const submitdata = {
              ...this.form,
              userDays: this.form.userDays.toString(),
            };
            const res = this.form.id
              ? await couponApi.edit(submitdata)
              : await couponApi.add(submitdata);
            ElNotification({
              title: "成功",
              message: `${this.form.id ? "编辑" : "添加"}成功`,
              type: "success",
            });
            this.loading = false;
            this.close();
            this.$emit("success");
          } catch (error) {
            this.loading = false;
            console.log(error);
          }
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.tab {
  display: flex;
  margin-bottom: 30px;
  padding-left: 10px;
  .tab_item {
    margin-right: 64px;
    font-weight: 400;
    font-size: 16px;
    color: #666666;
    cursor: pointer;
    .bor {
      display: block;
      width: 56px;
      height: 6px;
      background-color: transparent;
      border-radius: 3px 3px 3px 3px;
      margin: 5px auto 0;
    }
  }
  .active {
    color: #3f9eff;
    .bor {
      background-color: #3f9eff;
    }
  }
}
.content {
  font-weight: 400;
  font-size: 16px;
  color: #666666;
}
.shop_list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 15px;
  .item_wrap {
    $size: 80px;
    display: flex;
    align-items: center;
    .name {
      width: $size;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .del {
      font-weight: 400;
      font-size: 14px;
      color: #3f9eff;
      margin-left: 11px;
    }
  }
}
</style>
