<!-- 消费返现 -->
<template>
  <div class="gyq_container">
    <div class="gyq_content">
      <div v-if="shopInfo.isHeadShop == 1 || isUse">
        <HeaderCard name="消费返现" intro="允许客户充值并使用余额支付" icon="xffx"
          :showSwitch="shopInfo.isHeadShop == 1 || shopInfo.shopType == 'only'" v-model:isOpen="form.isEnable">
        </HeaderCard>
        <div style="padding-top: 14px;">
          <el-tabs v-model="tabsValue">
            <el-tab-pane label="基础明细" :name="1">
              <el-form ref="formRef" :model="form" :rules="rules" label-position="left" label-width="100px">
                <el-form-item label="可用门店">
                  <el-radio-group v-model="form.useType">
                    <el-radio label="全部门店" value="all"></el-radio>
                    <el-radio label="指定门店可用" value="part"></el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="选择门店" prop="shopIdList" v-if="form.useType == 'part'">
                  <selectBranchs all v-model="form.shopIdList" />
                </el-form-item>
                <el-form-item label="适用用户">
                  <el-radio-group v-model="form.applicableUser">
                    <el-radio label="全部用户" value="all"></el-radio>
                    <el-radio label="仅限新用户" value="new"></el-radio>
                    <el-radio label="仅会员（分店需开启超级会员可用）" value="vip"></el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="返现类型">
                  <el-radio-group v-model="form.cashbackType">
                    <el-radio label="按比例返现" value="percentage"></el-radio>
                    <el-radio label="固定金额" value="fix"></el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="阶梯设置" prop="stepValidate">
                  <div class="row">
                    <div class="item border" v-for="(item, index) in form.cashbackStepList" :key="index">
                      <div class="row_title">
                        <span>{{ `第${index + 1}组` }}</span>
                        <el-icon @click="form.cashbackStepList.splice(index, 1)">
                          <Delete />
                        </el-icon>
                      </div>
                      <div class="ipt">
                        <div class="ipt_row">
                          <span>返现门槛</span>
                          <el-input placeholder="请输入返现门槛" :maxlength="8" v-model="item.amount"
                            @input="e => item.amount = filterNumberInput(e)">
                            <template #append>元</template>
                          </el-input>
                        </div>
                        <div class="ipt_row">
                          <span>{{ form.cashbackType == 'percentage' ? '返现比例' : '返现金额' }}</span>
                          <el-input :maxlength="8"
                            :placeholder="form.cashbackType == 'percentage' ? '请输入返现比例' : '请输入返现金额'"
                            v-model="item.cashbackAmount" @input="e => item.cashbackAmount = filterNumberInput(e)">
                            <template #append>
                              {{ form.cashbackType == 'percentage' ? '%' : '元' }}
                            </template>
                          </el-input>
                        </div>
                      </div>
                    </div>
                    <div class="item" v-if="shopInfo.isHeadShop == 1 || shopInfo.shopType == 'only'">
                      <el-button type="primary" @click="addCashBackItem">添加阶梯</el-button>
                    </div>
                  </div>
                </el-form-item>
                <div v-if="shopInfo.isHeadShop == 1 || shopInfo.shopType == 'only'">
                  <el-form-item style="margin-top: 50px;">
                    <el-button type="primary" @click="submitHandle">保存</el-button>
                    <el-button @click="router.back()">取消</el-button>
                  </el-form-item>
                </div>
              </el-form>
            </el-tab-pane>
            <el-tab-pane label="返现明细" :name="2">
              <record />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <div v-else>门店未参与消费返现或主店已关闭活动，如需开启参与请联系主店</div>
    </div>
  </div>
</template>

<script setup>
import HeaderCard from "../components/headerCard.vue";
import record from "./record.vue";
import selectBranchs from "../components/selectBranchs.vue";
import { ref, onMounted } from 'vue'
import { useRouter } from "vue-router";
import { consumeCashback, consumeCashbackPost } from '@/api/coupon/index.js'
import { filterNumberInput } from '@/utils'

const router = useRouter();
const tabsValue = ref(1)
const formRef = ref(null)
const shopInfo = ref(JSON.parse(localStorage.getItem('userInfo')))
const form = ref({
  useType: 'all', // all 全部可用 part部分门店可用
  shopIdList: [], // 门店列表
  applicableUser: 'all', // 适用用户 all全部用户 new新用户 vip会员
  cashbackType: 'percentage', // 返现类型 percentage比例 fix固定
  cashbackStepList: [], // 返现配置
  isEnable: false //是否启用
})

const rules = ref({
  shopIdList: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (form.value.shopIdList.length <= 0) {
          callback(new Error('请选择门店'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  stepValidate: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (form.value.cashbackStepList.length <= 0) {
          callback(new Error('请添加阶梯'))
          return
        }

        let flag = true;
        let errStr = ''
        form.value.cashbackStepList.map(item => {
          if (form.value.cashbackType == 'percentage') {
            if (+item.cashbackAmount > 100) {
              flag = false
              errStr = '输入有误，请检查返现比例是不是大于100'
            }
          }
          if (form.value.cashbackType == 'fix') {
            if (!+item.amount || !+item.cashbackAmount || +item.cashbackAmount > +item.amount) {
              flag = false
              errStr = '输入有误，请检查返现金额是不是大于返现门槛'
            }
          }
        })

        if (!flag) {
          callback(new Error(errStr))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 添加返现阶梯
function addCashBackItem() {
  form.value.cashbackStepList.push({
    amount: '',
    cashbackAmount: ''
  })
}

// 提交保存
function submitHandle() {
  formRef.value.validate(async (valid) => {
    try {
      if (valid) {
        await consumeCashbackPost(form.value);
        ElNotification({
          title: "注意",
          message: "保存成功",
          type: "success",
        });
      }
    } catch (err) {
      console.log(err);
    }
  });
}

// 配置信息获取
const isUse = ref(false)
async function consumeCashbackAjax() {
  try {
    const res = await consumeCashback()
    if (res.cashbackStepList == null) {
      res.cashbackStepList = []
    }
    form.value = res

    if (res.isEnable == 1) {
      if (res.useType == 'all' || shopInfo.value.shopType == 'only') {
        isUse.value = true
      } else {
        let currentShopId = shopInfo.value.shopId;
        res.shopIdList.some((item) => {
          if (item == currentShopId) {
            isUse.value = true;
            return true;
          }
        });
      }
    } else {
      isUse.value = false
    }
  } catch (error) {
    console.log(error);
  }
}

onMounted(() => {
  consumeCashbackAjax()
})
</script>

<style scoped lang="scss">
.gyq_container {
  padding: 14px;

  .gyq_content {
    padding: 14px;
    background-color: #fff;
    border-radius: 8px;
  }
}

.row {
  .item {
    position: relative;

    &:not(:first-child) {
      margin-top: 16px;
    }

    .row_title {
      position: absolute;
      top: 0;
      left: 4px;
      transform: translateY(-50%);
      background-color: #fff;
      padding: 0 10px;
      display: flex;
      align-items: center;
      gap: 10px;
    }

    &.border {
      padding: 10px;
      border: 1px solid #ddd;
      border-radius: 4px;
    }

    .ipt_row {
      span {
        color: #555;
      }
    }
  }
}
</style>