<!-- eslint-disable vue/no-use-v-if-with-v-for -->
<template>
  <div class="app-container">
    <div class="tab">
      <div v-for="(item,index) in tabList" v-if="(form.id&&form.type == item.type)||!form.id" :key="index" class="tab_item" :class="{active: form.type == item.type}" @click="tabClick(item)"> {{ item.name }} <span class="bor" /></div>
    </div>
    <!-- 优惠券 -->
    <div v-if="form.type == 1" 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 v-if="form.type == 1" label="使用门槛" prop="fullAmount">
          <el-input v-model="form.fullAmount" oninput="value= value.replace(/[^\d|\.]/g, '')" placeholder="" style="width: 180px;margin-right: 66px;">
            <template slot="prepend">满</template>
            <template slot="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 slot="prepend">减</template>
            <template slot="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" :label="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 slot="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="结束日期"
            :default-time="['06:00:00', '23:59:59']"
            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 slot="prepend">隔</template>
            <template slot="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" :label="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" :label="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-tooltip class="item" effect="dark" content="限用户自行领取，（当库存为 0时，集草等活动仍会赠送）" placement="top-start">
            <i class="el-icon-question" />
          </el-tooltip> -->
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="dialogVisible = false">取 消</el-button> -->
        <el-button type="primary" :loading="loading" @click="onSubmitHandle">确 定</el-button>
      </span>
    </div>
    <div v-if="form.type == 2">
      <el-form ref="form" :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: 100px;margin: 0 23px;"><template slot="suffix">元</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" :label="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 slot="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="结束日期"
            :default-time="['06:00:00', '23:59:59']"
            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 slot="prepend">隔</template>
            <template slot="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" :label="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" :label="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-tooltip class="item" effect="dark" content="限用户自行领取，（当库存为 0时，集草等活动仍会赠送）" placement="top-start">
            <i class="el-icon-question" />
          </el-tooltip> -->
        </el-form-item>
        <el-form-item label="赠送商品" prop="products">
          <div>
            <el-button type="primary" icon="el-icon-plus" @click="$refs.shopListRef.show([...form.products])">
              添加 </el-button>
          </div>
          <div class="shop_list">
            <div
              v-for="(item, index) in form.products"
              :key="item.id"
              class="item_wrap"
            >
              <div class="name">{{ item.name }}</div>
              <el-input v-model="item.num" placeholder="请填写数量" style="width: 100px;" />
              <div class="del" @click="form.products.splice(index, 1)">删除</div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button @click="dialogVisible = false">取 消</el-button> -->
        <el-button type="primary" :loading="loading" @click="onSubmitHandle">确 定</el-button>
      </span>
    </div>
    <shopList ref="shopListRef" @success="slectShop" />
  </div>
</template>

<script>
import couponEnum from './couponEnum'
import shopList from '@/components/shopList'
import { addTbShopCoupon, getTbShopCouponInfo } from '@/api/coupon'
export default {
  components: { shopList },
  data() {
    const validateProduct = (rule, value, callback) => {
      if (!this.form.products.length) {
        callback(new Error('请选择商品'))
      } else {
        callback()
      }
    }
    return {
      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: '',
        products: [],
        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: ''
    }
  },
  mounted() {
    this.resetForm = { ...this.form }
    this.form.type = this.$route.query.type
    this.form.useStartTime = this.useTime[0]
    this.form.useEndTime = this.useTime[1]
    if (this.$route.query.id) { this.form.id = this.$route.query.id; this.getCouponInfo(this.$route.query.id) }
  },
  methods: {
    /**
     * 切换类型
     * @param item
     */
    tabClick(item) {
      this.form = this.resetForm
      this.form.number = ''
      this.form.type = item.type
      this.$refs.form.resetFields()
    },

    /**
     * 获取优惠券详情
     */
    async getCouponInfo(id) {
      const resInfo = await getTbShopCouponInfo(id)
      this.form = resInfo
      if (resInfo.validityType === 'custom') {
        this.validityTime = [resInfo.validStartTime, resInfo.validEndTime]
      }
      if (resInfo.useTimeType === 'custom') {
        this.useTime = [resInfo.useStartTime, resInfo.useEndTime]
      }
      this.form.userDays = this.form.userDays.split(',')
    },

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

    /**
     * 有效期选择
     * @param e
     */
    validityChange(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.length <= 0) {
        return
      }
      this.form.products = []
      if (this.form.products.length) {
        res.map(async item => {
          if (!await this.checkShop(item.id)) {
            this.form.products.push({
              productId: item.id,
              name: item.name,
              num: null
            })
          }
        })
      } else {
        this.form.products.push({
          productId: res[0].id,
          name: res[0].name,
          num: null
        })
      }
    },

    /**
     * 判断是否存在重复商品
     * @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
            if (!this.form.shopId) { this.form.shopId = localStorage.getItem('shopId') }
            this.form.userDays = this.form.userDays.toString()
            // eslint-disable-next-line no-unused-vars
            const res = await addTbShopCoupon(this.form)
            this.$store.dispatch('tagsView/delView', this.$route) // 关闭当前页
            this.$router.replace({ name: 'coupon_list' }) // 要打开的页面
            this.$notify({
              title: '成功',
              message: `${this.form.id ? '编辑' : '添加'}成功`,
              type: 'success'
            })
            this.loading = false
          } catch (error) {
            this.loading = false
            console.log(error)
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.tab{
  display: flex;
  margin-bottom: 30px;
  padding-top: 40px;
  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>
