<template>
  <el-dialog
    ref="dialog"
    :title="(isEdit ? '编辑' : '新增') + '语音'"
    width="580px"
    :visible.sync="visible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @open="visibleChange"
  >
    <el-form
      ref="modalFormComp"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="语音文件" prop="attachmentId">
        <upload-file-view
          :upload-data="uploadData"
          :upload-url="uploadUrl"
          :format="format"
          input-width="300px"
          @valid-error="validError"
          @upload-success="uploadSuccess"
          ref="UploadFileView"
        ></upload-file-view>
      </el-form-item>
      <el-form-item label="内容描述" prop="content">
        <el-input
          type="textarea"
          v-model.trim="form.content"
          placeholder="请输入"
          :maxlength="1000"
          :rows="5"
          show-word-limit
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="播报时间" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio
            v-for="(val, key) in ACTIVITY_AUDIO_TYPE"
            :key="key"
            :label="key"
          >
            <span>{{ val }}</span>
            <el-input-number
              v-model.trim="form.playTime"
              :min="1"
              :step="1"
              step-strictly
              style="width: 50px; margin: 0 5px;"
              :controls="false"
            >
            </el-input-number>
            <span>分钟</span>
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="d-flex justify-content-center">
      <el-button type="primary" @click="submitForm" :loading="loading"
        >保 存</el-button
      >
      <el-button @click="closeDialog">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { saveActivityAudio } from "@/api/examwork-activity";
import { ACTIVITY_AUDIO_TYPE } from "@/constant/constants";
import { objAssign } from "@/utils/utils";

const initForm = {
  id: null,
  audioDefault: "CUSTOM",
  attachmentId: null,
  type: "BEFORE",
  playTime: 60,
  activityId: null,
  content: "",
};

export default {
  name: "ActivityAudioDialog",
  components: {},
  props: {
    instance: Object,
  },
  computed: {
    isEdit() {
      return this.instance.id;
    },
  },
  data() {
    return {
      visible: false,
      ACTIVITY_AUDIO_TYPE,
      form: {
        ...initForm,
      },
      rules: {
        attachmentId: [{ required: true, message: "请上传语音文件" }],
        content: [
          { required: true, message: "请输入内容描述", trigger: "blur" },
        ],
        type: [
          {
            validator: (value, rule, callback) => {
              if (!this.form.type) {
                return callback(new Error("请选择播报时间类型"));
              }
              if (!this.form.playTime) {
                return callback(new Error("请输入播报时间"));
              }

              callback();
            },
            trigger: "change",
          },
        ],
      },
      loading: false,
      // upload
      uploadUrl: "/api/admin/sys/file/upload",
      uploadData: {
        type: "upload",
      },
      format: ["mp3"],
    };
  },
  methods: {
    visibleChange() {
      if (this.instance.id) {
        objAssign;
        this.form = objAssign(initForm, this.instance);
      } else {
        this.form = { ...initForm };
        this.form.activityId = this.instance.activityId;
      }
      this.form.playTime = this.form.playTime / 60;

      this.$nextTick(() => {
        this.$refs.modalFormComp.clearValidate();
        this.$refs.UploadFileView.setAttachmentName(
          this.instance.attachmentName || ""
        );
      });
    },
    openDialog() {
      this.visible = true;
    },
    closeDialog() {
      this.visible = false;
    },
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uploadSuccess(data) {
      this.$message.success("上传成功！");
      this.form.attachmentId = data.id;
      this.$refs.modalFormComp.validateField("attachmentId");
    },
    async submitForm() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (this.loading) return;
      this.loading = true;
      const datas = {
        ...this.form,
      };
      datas.playTime = datas.playTime * 60;
      const res = await saveActivityAudio(datas).catch(() => {});
      this.loading = false;
      if (!res) return;
      this.$emit("reload");
      this.$notify({ title: "保存成功", type: "success" });
      this.closeDialog();
    },
  },
};
</script>
