<template>
  <div class="switch-warp" v-if="policyValid" v-loading="loading">
    <el-switch
      v-model="useFlagTemp"
      active-text="默认启用（免征增值税）"
      @change="handleChange"
    >
    </el-switch>
    <slot></slot>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";

export default {
  name: "Policy2022040101EnableSwitch",
  data() {
    return {
      loading: false,
      useFlagTemp: false,
    };
  },
  mounted() {
    this.getPolicyAsync();
  },
  computed: {
    ...mapGetters("policy2022040101", ["policyValid", "useFlag"]),
  },
  watch: {
    useFlag: {
      immediate: true,
      handler(newVal, oldVal) {
        this.useFlagTemp = newVal;
      },
    },
  },
  methods: {
    handleChange(value) {
      this.loading = true;
      this.savePolicyAsync({ useFlag: value })
        .then((res) => {})
        .catch((err) => {
          // 保存失败，恢复原状；
          this.useFlagTemp = !value;
          this.$message.error(err.msg || err);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    ...mapActions("policy2022040101", ["getPolicyAsync", "savePolicyAsync"]),
  },
};
</script>

<style scoped>
.switch-warp {
  display: inline-block;
}
</style>
