<template>
  <el-dialog title="适用门店" width="400px" v-model="visible" @closed="resetForm">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" label-position="right">
      <el-form-item label="适用门店">
        <el-radio-group v-model="form.useType">
          <el-radio value="all" label="全部门店"></el-radio>
          <el-radio value="part" label="指定门店"></el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="选择门店" v-if="form.useType == 'part'" prop="shopIds">
        <selectBranchs all v-model="form.shopIdList" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="handleOk" :loading="confirmLoading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from "vue";
import { ElNotification } from "element-plus";
import selectBranchs from "../../components/selectBranchs.vue";
import { rechargeRedemptionPut, rechargeRedemptionEnableStatus } from "@/api/coupon/index.js";

const visible = ref(false);
const confirmLoading = ref(false);
const formRef = ref(null);
const form = ref({
  useType: 1,
  shopIdList: [],
});

const resetForm = () => {
  form.value = {
    useType: 1,
    shopIdList: [],
  };
};

const rules = {
  shopIdList: [
    {
      required: true,
      message: "请选择门店",
      trigger: "change",
    },
  ],
};

// 提交保存
const handleOk = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        confirmLoading.value = true;
        await rechargeRedemptionPut({
          useType: form.value.useType,
          shopIdList: form.value.shopIdList,
        });
        visible.value = false;
        ElNotification({
          type: "success",
          title: '注意',
          message: "保存成功",
        });
      } catch (error) {
        console.log(error);
      }
      setTimeout(() => {
        confirmLoading.value = false;
      }, 500);
    }
  });
};

// 获取状态
async function rechargeRedemptionEnableStatusAjax() {
  try {
    const res = await rechargeRedemptionEnableStatus();
    form.value.useType = res.useType || 'all';
    form.value.shopIdList = res.shopIdList || [];
  } catch (error) {
    console.log(error);
  }
}

function show() {
  visible.value = true;
  rechargeRedemptionEnableStatusAjax();
}

defineExpose({
  show,
});
</script>

<style scoped lang="scss"></style>