<template>
  <el-dialog
    class="modify-device"
    :visible.sync="modalIsShow"
    title="上传设备信息"
    top="10vh"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @opened="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="modalForm"
      :rules="rules"
      label-width="70px"
    >
      <el-form-item prop="deviceInfo" label="文件：">
        <UploadFetchFile
          ref="UploadFetchFile"
          input-width="365px"
          :format="[]"
          :disabled="isSubmit"
          @file-change="deviceFileChange"
          @valid-change="validChange"
        />
      </el-form-item>
      <el-form-item label="备注：">
        <el-input
          v-model.trim="modalForm.remark"
          type="textarea"
          placeholder="请输入备注"
          clearable
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button type="danger" @click="cancel" plain>取消</el-button>
      <el-button type="primary" :disabled="isSubmit" @click="submit"
        >确认</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { appDeployDeviceSave } from "../api";
import UploadFetchFile from "../../../components/UploadFetchFile.vue";

const initModalForm = {
  id: "",
  remark: "",
  deviceInfo: null,
  md5: "",
};

export default {
  name: "modify-device",
  components: { UploadFetchFile },
  props: {
    deployId: {
      type: [String, Number],
    },
  },
  data() {
    return {
      modalIsShow: false,
      isSubmit: false,
      modalForm: {
        ...initModalForm,
      },
      rules: {
        deviceInfo: [
          {
            required: true,
            message: "请选择要上传的文件",
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    visibleChange() {
      this.modalForm = { ...initModalForm };
      this.modalForm.id = this.deployId;
      this.$nextTick(() => {
        this.$refs.UploadFetchFile.setAttachmentName("");
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    deviceFileChange({ file, md5 }) {
      this.modalForm.md5 = md5;
      this.modalForm.deviceInfo = file;

      this.$refs.modalFormComp.validateField("deviceInfo", () => {});
    },
    validChange(res) {
      if (!res.success)
        this.$notify.error({ title: "错误提示", message: res.message });
    },
    async submit() {
      const valid = await this.$refs.modalFormComp.validate();
      if (!valid) return;

      if (this.isSubmit) return;
      this.isSubmit = true;
      const result = await appDeployDeviceSave(this.modalForm).catch(() => {});
      this.isSubmit = false;
      if (!result) return;
      this.$message.success("上传成功！");
      this.$emit("modified");
      this.cancel();
    },
  },
};
</script>
