<template>
  <ht-save-button
    :is-submit="isSubmit"
    :request-method="requestMethod"
    :scope-name="scopeName"
    @before-save-data="beforeSaveData"
    @request-save-data="requestSaveData"
    :loading="loading"
    :disabled="disabled"
  ><slot></slot></ht-save-button>
</template>

<script>
import req from "@/request.js";
export default {
  name: "ht-submit-button",
  props: {
    url: {
      type: String,
      required: true
    },
    requestMethod: {
      type: String,
      default: "POST"
    },
    model: {
      type: [Object, Array],
      default(){
        return {};
      }
    },
    isSubmit: {
      type: Boolean,
      default: true
    },
    type: {
      type: String,
      default: "primary"
    },
    scopeName: {
      type: String,
      required: true
    },
    context: {
      type: String
    },
    loading: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    alertMsg: {
      type: Boolean,
      default: true,
    },
    restoreUrl: {
      type: String
    },
    aliasProp: {
      type: String
    },
  },
  computed:{
    calUrl: function(){
      if(this.context){
        return window.context[this.context] + this.url;
      }
      return this.url;
    },
    calRestoreUrl: function(){
      if(this.context){
        return window.context[this.context] + this.restoreUrl;
      }
      return this.restoreUrl;
    }
  },
  mounted() {},
  methods: {
    async beforeSaveData() {
      await this.$emit("before-save-data");
    },
    async requestSaveData() {
      let response = await req.request({
        data: this.model,
        url: this.calUrl,
        method: this.requestMethod
      }).finally(() => {
      });

      if (response.data && response.data.state) {
        if (response.data && response.data.errorCode && response.data.errorCode == '5035' && this.restoreUrl) {
          this.$confirm( response.data.message,'提示',{
                cancelButtonText: '取消',
                confirmButtonText: '确定',
                type: 'warning',
                closeOnClickModal: false,
              }
            ).then(async () => {
               let response1 = await req.request({
                  url: this.calRestoreUrl+this.model[this.aliasProp],
                  method: 'get'
                }).finally(() => {});

                if (response1.data && response1.data.state) {
                    this.emitSuccess(response1)
                }
            })
        }else{
          this.emitSuccess(response)
        }
      }
    },
    emitSuccess(response){
      this.$emit("after-save-data",response.data);
      this.$message.success(response.data.message || "操作成功");

      if(response.data.value){
        this.$emit("after-response-value",response.data.value);
      }
    }
  }
};
</script>
