<template>
  <Modal
    class="bind-secret-key-dialog"
    v-model="modalIsShow"
    title="绑定key和secret"
    :mask-closable="false"
    @on-cancel="cancel"
  >
    <Form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      :key="modalForm.id"
      :label-width="100"
    >
      <FormItem prop="accessKey" label="accessKey">
        <Input
          v-model.trim="modalForm.accessKey"
          placeholder="请输入accessKey"
          clearable
        ></Input>
      </FormItem>

      <FormItem prop="accessSecret" label="accessSecret">
        <Input
          v-model.trim="modalForm.accessSecret"
          placeholder="请输入accessSecret"
          clearable
        ></Input>
      </FormItem>
    </Form>
    <div slot="footer">
      <Button type="text" @click="cancel">取消</Button>
      <Button type="primary" :disabled="isSubmit" @click="submit">确认</Button>
    </div>
  </Modal>
</template>

<script>
import { axios } from "../../libs/http";

const initModalForm = {
  examCode: "",
  accessKey: "",
  accessSecret: "",
};

export default {
  name: "bind-secret-key-dialog",
  props: {
    instance: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  computed: {
    isEdit() {
      return !!this.instance.id;
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: { ...initModalForm },
      rules: {
        accessKey: [
          {
            required: true,
            message: "请输入accessKey",
            trigger: "change",
          },
        ],
        accessSecret: [
          {
            required: true,
            message: "请输入accessSecret",
            trigger: "change",
          },
        ],
      },
    };
  },
  watch: {
    instance(val) {
      this.initData(val);
    },
  },
  methods: {
    initData(val) {
      this.modalForm = Object.assign(initModalForm, val);
    },
    cancel() {
      this.initData(this.instance);
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate();
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      let result = true;
      await axios.post("/system/exam/task/bind", this.modalForm).catch(() => {
        result = false;
      });

      if (!result) return;

      this.isSubmit = false;
      this.$Message.success("绑定成功！");
      this.$emit("modified");
      this.cancel();
    },
  },
};
</script>
