<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '编辑文章' : '新增文章' }}</span>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文章标题" style="width: 500px;" />
        </el-form-item>
        <el-form-item label="子标题" prop="subTitle">
          <el-input v-model="form.subTitle" placeholder="请输入子标题" style="width: 500px;" />
        </el-form-item>
        <el-form-item label="封面图片" prop="bannerImg">
          <el-upload
            class="avatar-uploader"
            :action="upload.url"
            :headers="upload.headers"
            :show-file-list="false"
            :on-success="handleBannerSuccess"
            :before-upload="beforeUpload">
            <img v-if="form.bannerImg" :src="getBannerImageUrl(form.bannerImg)" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <div class="el-upload__tip">建议上传尺寸: 750px × 400px，大小不超过2MB</div>
        </el-form-item>
        <el-form-item label="轮播图片" prop="rotaImg">
          <el-upload
            class="upload-demo"
            :action="upload.url"
            :headers="upload.headers"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleRotaSuccess"
            :file-list="rotaFileList"
            multiple
            list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
          <div class="el-upload__tip">可上传多张轮播图片，建议尺寸统一，每张图片不超过2MB</div>
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入作者" style="width: 300px;" />
        </el-form-item>
        <el-form-item label="正文内容" prop="content">
          <editor 
            v-model="form.content" 
            :min-height="400"
            :init="{
              plugins: 'preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern help emoticons autosave',
              toolbar: 'code undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link anchor | alignleft aligncenter alignright alignjustify outdent indent | styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | table image media charmap emoticons hr pagebreak insertdatetime print preview | fullscreen | bdmap indent2em lineheight formatpainter axupimgs',
              height: 650
            }"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="cancel">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { getInfo, addInfo, updateInfo } from "@/api/consult/info";
import { getToken } from "@/utils/auth";

export default {
  name: "ConsultAdd",
  data() {
    return {
      // 是否编辑模式
      isEdit: false,
      // 表单参数
      form: {
        id: null,
        title: null,
        subTitle: null,
        bannerImg: null,
        rotaImg: null,
        content: null,
        author: null,
        isDel: 0
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: "文章标题不能为空", trigger: "blur" }
        ],
        author: [
          { required: true, message: "作者不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "文章内容不能为空", trigger: "blur" }
        ]
      },
      // 上传参数
      upload: {
        // 上传地址
        url: process.env.VUE_APP_BASE_API + "/back/upload/config/file",
        // 请求头部
        headers: { Authorization: "Bearer " + getToken() }
      },
      // 轮播图片文件列表
      rotaFileList: [],
      // 预览图片URL
      dialogImageUrl: '',
      // 是否显示预览图片对话框
      dialogVisible: false
    };
  },
  created() {
    const id = this.$route.params && this.$route.params.id;
    if (id) {
      this.isEdit = true;
      this.getInfo(id);
    } else {
      // 设置默认值
      this.form.isDel = 0;
      this.form.author = this.$store.getters.name || '管理员';
    }
  },
  methods: {
    /** 获取文章详情 */
    getInfo(id) {
      getInfo(id).then(response => {
        this.form = response.data;
        // 处理轮播图片
        if (this.form.rotaImg) {
          const rotaImages = this.form.rotaImg.split(',');
          this.rotaFileList = rotaImages.map((url, index) => {
            return {
              name: `轮播图${index + 1}`,
              url: this.getImageUrl(url)
            };
          });
        }
      });
    },
    // 取消按钮
    cancel() {
      this.$router.push("/consult/index");
    },
    // 表单提交
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理轮播图片数据 - 已在handleRotaSuccess中处理，这里只需确保没有blob URL
          if (this.rotaFileList.length > 0) {
            // 再次检查确保没有blob URL
            this.form.rotaImg = this.form.rotaImg.split(',')
              .filter(url => url && !url.startsWith('blob:'))
              .join(',');
          }

          if (this.form.id != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.$router.push("/consult/index");
            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.$router.push("/consult/index");
            });
          }
        }
      });
    },
    // 封面图片上传成功处理
    handleBannerSuccess(res, file) {
      if (res.code === 200) {
        // 只保存接口返回的原始数据，不添加访问路径
        this.form.bannerImg = res.data;
        console.log('封面图片原始路径:', this.form.bannerImg);
      } else {
        this.$message.error('上传失败');
      }
    },
    // 轮播图片上传成功处理
    handleRotaSuccess(res, file, fileList) {
      if (res.code === 200) {
        // 打印上传响应，帮助调试
        console.log('上传响应:', res);
        
        // 只在展示时添加访问路径，这里为了预览需要添加完整URL
        const fileUrl = process.env.VUE_APP_BASE_API + res.data;
        
        // 更新当前上传的文件URL（用于预览）
        file.url = fileUrl;
        
        this.rotaFileList = fileList;
        
        // 更新表单中的轮播图片数据 - 只保存原始路径
        this.form.rotaImg = fileList.map(item => {
          // 如果是新上传的文件，只保存原始路径
          if (item.response && item.response.data) {
            return item.response.data;
          }
          // 如果已经有URL，需要去掉前缀保存原始路径
          else if (item.url && !item.url.startsWith('blob:')) {
            // 如果URL包含API前缀，去掉前缀
            if (item.url.startsWith(process.env.VUE_APP_BASE_API)) {
              return item.url.replace(process.env.VUE_APP_BASE_API, '');
            }
            return item.url;
          }
          return '';
        }).filter(url => url).join(',');
        
        console.log('最终保存的轮播图片原始路径:', this.form.rotaImg);
      } else {
        this.$message.error('上传失败');
      }
    },
    // 上传前检查
    beforeUpload(file) {
      const isImage = file.type.indexOf('image') !== -1;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传图片只能是图片格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    // 删除图片
    handleRemove(file, fileList) {
      this.rotaFileList = fileList;
    },
    // 预览图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url || file.response.url;
      this.dialogVisible = true;
    },
    // 获取封面图片完整URL
    getBannerImageUrl(imagePath) {
      if (!imagePath) return '';
      // 如果已经是完整URL，直接返回
      if (imagePath.startsWith('http')) {
        return imagePath;
      }
      // 否则添加API前缀
      return process.env.VUE_APP_BASE_API + imagePath;
    },
    // 获取图片完整URL
    getImageUrl(imagePath) {
      if (!imagePath) return '';
      // 如果已经是完整URL，直接返回
      if (imagePath.startsWith('http')) {
        return imagePath;
      }
      // 否则添加API前缀
      return process.env.VUE_APP_BASE_API + imagePath;
    }
  }
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-upload__tip {
  margin-top: 5px;
  color: #909399;
  font-size: 12px;
}
</style>