
<style scoped>
.user-panel {
  margin: 10px auto;
}
</style>
<template>
  <el-dialog
    :visible.sync="showDialog"
    :title="title"
    :modal-append-to-body="false"
    style="text-align: left"
    :width="'800px'"
    @close="closeDialog"
    :close-on-click-modal="false"
  >
    <div class="user-panel" v-loading="loading">
      <el-form
        ref="form"
        :model="formModel"
        :rules="ruleValidate"
        :label-width="'100px'"
        :inline="true"
      >
        <el-row>
          <el-form-item label="企业" prop="companyId">
            <el-select
              v-model="formModel.companyId"
              filterable
              placeholder="请选择"
              style="width: 90%"
              :filter-method="filterMethod"
            >
              <el-option
                v-for="company in companyInfoList"
                :key="company.id"
                :label="company.companyName"
                :value="company.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="新闻类型" prop="newsTypeId">
            <el-select-tree
              :props="props"
              :options="newsTypeList"
              v-model="formModel.newsTypeId"
              size=""
              height="200"
            ></el-select-tree>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="formModel.title"
              placeholder="请输入标题"
              style="width: 300px"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="图片" prop="picUrl">
            <el-upload
              class="avatar-uploader"
              name="photoFile"
              :action="uploadImgUrl"
              :show-file-list="false"
              :headers="headers"
              :data="uploadData"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              accept="image/png,image/jpeg"
            >
              <img v-if="fileUrl" :src="fileUrl" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="内容" prop="content">
            <mce-editor
              ref="editor"
              uploadName="upfile"
              v-model="formModel.content"
              :url="uploadUrl"
              :config="editorConfig"
            ></mce-editor>
          </el-form-item>
        </el-row>
        <el-form-item label="排序号" prop="sortNo">
          <el-input-number
            v-model="formModel.sortNo"
            :min="1"
            style="width: 300px"
          ></el-input-number>
        </el-form-item>
        <el-row>
          <el-form-item label="是否首页展示(轮播)" prop="topFlag">
            <el-radio-group v-model="formModel.topFlag">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting"
        >确 定</el-button
      >
    </span>
  </el-dialog>
</template>
<script>
import Constant from "@/constant";
import newsInfoApi from "@/api/base/newsInfo";
import newsTypeApi from "@/api/base/newsType";
import companyInfoApi from "@/api/base/companyInfo";
import SelectTree from "@/components/SelectTree";
import MceEditor from "@/components/Tinymce";
import { getToken } from "@/utils/auth";

export default {
  props: ["businessKey", "title"],
  components: {
    "mce-editor": MceEditor,
    "el-select-tree": SelectTree,
  },
  data() {
    return {
      formModel: {},
      ruleValidate: {
        companyId: [{ required: true, message: "请选择", trigger: "blur" }],
        newsTypeId: [{ required: true, message: "请选择", trigger: "blur" }],
        title: [{ required: true, message: "不能为空", trigger: "blur" }],
        sortNo:[
          { required: true, message: "不能为空", trigger: "blur" },
        ]
      },
      showDialog: true,
      loading: false,
      submitting: false,
      editorConfig: {
        height: 500,
        width: 600,
      },
      uploadUrl: Constant.serverUrl + "/tinymce/upload?token=" + getToken(),
      newsInfoList: [],
      newsTypeList: [],
      props: {
        // 配置项（必选）
        value: "id",
        label: "name",
      },
      companyInfoList: [],
      //上传图片start
      uploadImgUrl: Constant.serverUrl + "/uploadPicture",
      uploadData: {
        subFolder: "newsInfo",
      },
      fileUrl: "",
      headers: {
        Authorization: getToken(),
      },
      //上传图片end
    };
  },
  created() {
    var self = this;
    newsTypeApi.list().then(function (response) {
      var jsonData = response.data;
      if (jsonData.result) {
        if (jsonData.data != null && jsonData.data != "") {
          self.newsTypeList = jsonData.data;
        }
      }
    });
  },
  methods: {
    closeDialog() {
      this.$emit("close", false);
    },
    handleSubmit() {
      var self = this;

      this.$refs["form"].validate((valid) => {
        if (valid) {
          (function () {
            var id = self.formModel.id;

            self.formModel.content = self.$refs.editor.getContent();
            if (id == null || id.length == 0) {
              return newsInfoApi.add(self.formModel);
            } else {
              return newsInfoApi.update(self.formModel);
            }
          })().then(function (response) {
            var jsonData = response.data;

            if (jsonData.result) {
              self.$message({
                message: "保存成功!",
                type: "success",
              });

              self.$emit("close", true);
            } else {
              self.$message({
                message: jsonData.message + "",
                type: "warning",
              });

              self.$emit("close", false);
            }
          });
        }
      });
    },
    filterMethod(query, item) {
      var self = this;
      var formData = new FormData();
      formData.append("pageSize", 5);
      formData.append("companyName", query);

      companyInfoApi.list(formData).then(function (response) {
        var jsonData = response.data;
        if (jsonData.result) {
          self.companyInfoList = jsonData.data;
        }
      });
    },
    handleAvatarSuccess(res, file) {
      this.loading = false;
      var self = this;
      self.formModel.picUrl = res.data;
      self.fileUrl = res.data + "?x-oss-process=image/resize,m_lfit,w_200";
    },
    beforeAvatarUpload(file) {
      this.loading = true;
      // const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error("上传图片只能是 JPG 格式!");
      // }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
  },
  mounted: function () {
    var self = this;

    (function () {
      if (self.businessKey.length == 0) {
        return newsInfoApi.create();
      } else {
        return newsInfoApi.edit(self.businessKey);
      }
    })()
      .then((response) => {
        var jsonData = response.data;
        self.loading = false;

        if (jsonData.result) {
          self.formModel = jsonData.data;
          if (self.formModel.content != null) {
            self.$refs.editor.setContent(self.formModel.content);
          }

          if (self.formModel.topFlag != null) {
            self.formModel.topFlag = false;
          }

          if (self.formModel.companyName != null) {
            var formData = new FormData();
            formData.append("pageSize", 5);
            formData.append("companyName", self.formModel.companyName);

            companyInfoApi.list(formData).then(function (response) {
              var jsonData = response.data;
              if (jsonData.result) {
                self.companyInfoList = jsonData.data;
              }
            });
          }

          let picUrl = self.formModel.picUrl;
          if (picUrl != null) {
            self.fileUrl =
              picUrl +
              "?x-oss-process=image/resize,m_lfit,w_200";
          }
        } else {
          self.$message.error(jsonData.message + "");
        }
      })
      .catch((error) => {
        self.$message.error(error + "");
      });
  },
};
</script>