<!--
 * @Description: 新增/编辑弹框
 * @Author: 空白格
 * @Date: 2023-07-04 13:55:00
 * @LastEditors: 空白格
 * @LastEditTime: 2023-07-06 09:08:39
 * @FilePath: \cattle_webui\src\views\system\noticeMgr\Dialog\AddOrEditDialog.vue
 * @Copyright: Copyright (c) 2016~2023 by 空白格, All Rights Reserved.
-->
<template>
  <el-dialog :title="title" :visible.sync="open" width="700px" :close-on-click-modal="false" @close="cancel">
    <div class="dialog">
      <el-form v-loading="loading" :model="form" ref="form" :rules="rules" label-width="120px">
        <el-form-item label="标题名称" prop="name">
          <el-input v-if="model != 3" v-model="form.name" placeholder="标题名称" clearable style="width: 100%;" />
          <span v-else>{{ form.name }}</span>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio v-model="form.type" label="1">图文</el-radio>
        </el-form-item>
        <el-form-item label="banner图" prop="sliderImg">
          <el-upload :disabled="model==3" ref="upload" class="avatar-uploader" :action="uploadObj.url" :headers="uploadObj.headers"
            :show-file-list="false" accept=".jpg,.png" :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <div class="avatar" v-if="form.sliderImg">
              <el-image style="width: 100px; height: 100px" :src="form.sliderImg" fit="cover" />
            </div>
            <div class="upload-btn" v-else>
              <i class="el-icon-plus"></i>
              <div class="upload-btn-text">上传图片</div>
            </div>
            <div class="el-upload__tip" slot="tip">只能上传.jpg或.png格式</div>
          </el-upload>
        </el-form-item>
        <el-form-item :label="form.type == 1 ? '内容详情：' : '链接地址：'" prop="detail">
          <editor v-if="form.type == 1" v-model="form.detail" :fileSize="20" :min-height="200" />
          <el-input v-else v-model="form.detail" placeholder="请输入链接地址" clearable style="width: 100%;" />
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">关闭</el-button>
      <el-button v-if="model!=3" type="primary" @click="submitForm" :loading="loading" element-loading-text="提交中...">
        保存
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  saveAndAdd,
  saveAndEdit,
  getDetails
} from "@/api/system/selfServeAdvertis";
import Editor from "@/components/Editor";
import { getToken } from "@/utils/auth";
export default {
  name: "DataBox",
  components: {
    Editor,
  },
  data() {
    return {
      title: "编辑",
      model: "1", // 1 新增  2 编辑  3 详情
      open: false,
      loading: false,
      form: {
        name: null,
        type: null,
        sliderImg: null,
        detail: null,
      },
      rules: {
        name: [{ required: true, message: "请输入标题", trigger: ["change","blur"] }],
        type: [{ required: true, message: "请选择类型", trigger: ["change","blur"] }],
        sliderImg: [{ required: true, message: "请上传banner图", trigger: ["change","blur"] }],
        detail: [
          { required: true, message: "请输入内容", trigger: ["change","blur"] },
        ],
      },
      uploadObj: {
        url: process.env.VUE_APP_UPLOAD_FILE_API + "/upload/single/minio",
        Headers: { Authorization: "Bearer " + getToken() },
      },
    };
  },
  methods: {
    /**
     * 打开弹框
     * @date 2022-09-20
     * @param {any} obj
     * @returns {any}
     */
    openDialog(title, obj,type) {
      this.title = title;
      this.model = type
      this.open = true;
      if (obj) {
        this.$nextTick(() => {
          this.$set(this.form, 'id', obj.id);
          this.$set(this.form, 'name', obj.name);
          this.$set(this.form, 'sliderImg', obj.sliderImg);
          this.$set(this.form, 'detail', obj.detail);
          this.$set(this.form, 'type', (obj.type == 2 ? '1' : obj.type.toString()));
        });
      }
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
    },
    /** 
     * 获取详情
     */
    async getDetailsFun(param) {
      try {
        this.loading = true;
        const { data, code } = await getDetails({ id: param.id });
        if (code == 200) {
          this.$set(this, 'form', data)
        } else {
          this.cancel()
        }
      } catch (error) {
        console.error("error===", error)
      } finally {
        this.loading = false;
      }
    },
    /**
     * 保存
     * @date 2022-09-20
     * @returns {any}
     */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true;
            if (this.form.id) {
              const { code } = await saveAndEdit({ ...this.form });
              if (code === 200) {
                this.$message.success("操作成功!");
                this.$emit("getList");
                this.cancel();
              }
            } else {
              const { code } = await saveAndAdd({ ...this.form });
              if (code === 200) {
                this.$message.success("操作成功!");
                this.$emit("getList");
                this.cancel();
              }
            }

          } catch (error) {
          } finally {
            this.loading = false;
          }
        }
      });
    },
    /**
     * 重置
     * @date 2022-09-20
     * @returns {any}
     */
    reset() {
      this.$refs["form"].resetFields();
      this.form.id = undefined;
    },
    /**
     * 关闭弹框
     * @date 2022-09-20
     * @returns {any}
     */
    cancel() {
      this.reset();
      this.open = false;
    },
    /**
     * 上传成功
     * @date 2023-11-22
     * @param {any} res
     * @returns {any}
     */
     handleAvatarSuccess(res) {
      if (res.code === 200) {
        // this.form.mainImg = res?.data?.url;
        this.$set(this.form, 'sliderImg', res?.data?.url)
      }
    },
    /**
     * 上传文件之前之前
     * @date 2023-11-22
     * @param {any} file
     * @returns {any}
     */
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || "image/png";
      if (!isJPG) {
        this.$message.error("上传头像图片只能是jpg或png格式!");
      }
      return isJPG;
    },
  },
};
</script>

<style lang="scss" scoped>
.dialog {
  padding: 0 30px;
  max-height: 65vh;
  overflow-y: auto;
}
</style>
