<template>
  <div class="videoManage manage-page">
    <div class="flex-view flex-title">
      <div class="table-title">官网新闻管理</div>
      <div class="table-title-btn blue" @click="openModel({}, 0)">
        <img src="../../assets/manageImg/add-btn.png" alt="" />{{$t('text.add')}}
      </div>
    </div>

    <div class="table-view">
      <el-table
        :data="tableData"
        :row-class-name="tableRowClassName"
        height="620"
        style="width: 100%"
      >
        <el-table-column prop="detailedIntroductionSort" :label="$t('text.sortOrder')">
        </el-table-column>
        <el-table-column prop="detailedIntroductionName" label="新闻标题">
        </el-table-column>
        <el-table-column prop="detailedIntroductionEnName" label="新闻英文标题">
        </el-table-column>
        <el-table-column prop="newsTime" label="日期">
          <template slot-scope="scope">
            <div class="table-flex">
              <div>{{ scope.row.newsTime | formatDate }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column :label="$t('text.operations')">
          <template slot-scope="scope">
            <div class="table-flex">
              <div class="table-operate blue" @click="openModel(scope.row, 1)">
                <img src="../../assets/manageImg/table-edit.png" alt="" />{{$t('text.edit')}}
              </div>
              <el-popconfirm
                @confirm="confirmDel(scope.row)"
                :title="$t('text.deleteContent')"
                icon-color="red"
              >
                <div class="table-operate red" slot="reference">
                  <img
                    src="../../assets/manageImg/table-delete.png"
                    alt=""
                  />{{$t('text.delete')}}
                </div>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      title="提示"
      top="10vh"
      :visible.sync="addModel"
      width="900px"
      class="vrcode-model manage-model"
      :append-to-body="true"
    >
      <div class="vrcode-model-title">
        {{ modelName }}
      </div>

      <div class="vrcode-content" v-if="nowData">
        <div class="manage-left">
          <div class="manage-input w-350">
            <div class="input-title">新闻标题</div>
            <input
              type="text"
              v-model="nowData.detailedIntroductionName"
              placeholder="请输入新闻标题"
            />
          </div>
          <div class="manage-input w-350">
            <div class="input-title">新闻英文标题</div>
            <input
              type="text"
              v-model="nowData.detailedIntroductionEnName"
              placeholder="请输入新闻英文标题"
            />
          </div>
          <div class="manage-input w-350">
            <div class="input-title">{{$t('text.sortOrder')}}</div>
            <input
              type="number"
              v-model="nowData.detailedIntroductionSort"
              :placeholder="$t('placeholder.sortOrderPlaceholder')"
            />
          </div>

          <div class="manage-input w-350">
            <div class="input-title">新闻日期选择</div>
            <el-date-picker
              v-model="nowData.newsTime"
              type="date"
              placeholder="选择日期"
            >
            </el-date-picker>
          </div>
          <div class="manage-input w-350">
            <div class="input-title">新闻内容编写</div>
            <div></div>
            <input
              @click="openNewsModel(0)"
              type="text"
              v-model="nowData.detailedIntroductionText"
              placeholder="点击进行编写内容"
            />
          </div>
          <div class="manage-input w-350">
            <div class="input-title">新闻英文内容编写</div>
            <input
              @click="openNewsModel(1)"
              type="text"
              v-model="nowData.detailedIntroductionEnText"
              placeholder="点击进行编写内容"
            />
          </div>
        </div>

        <div class="manage-right">
          <div class="manage-input w-350">
            <div class="input-title">新闻展示图片(图片大小不能超过2MB)</div>
          </div>
          <div class="manage-img" v-loading="loading">
            <label for="sel-img">
              <img
                v-show="nowData.detailedIntroductionImage"
                class=""
                :src="nowData.detailedIntroductionImage"
                alt="案例图片"
              />
              <img
                class="upload-img"
                v-show="!nowData.detailedIntroductionImage"
                src="../../assets/img/upload-img.png"
                alt=""
              />
            </label>
            <input
              ref="fileInput"
              type="file"
              :multiple="false"
              id="sel-img"
              accept="image/*"
              @change="handleImageChange($event, 0)"
            />
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <div class="vrcode-btn blue-btn w-100" @click="changeAddModel">
          {{$t('index.confirm')}}
        </div>
        <div class="vrcode-btn cancle-btn w-100" @click="addModel = false">
          {{$t('index.cancel')}}
        </div>
      </span>
    </el-dialog>

    <el-dialog
      :close-on-click-modal="false"
      title="新闻内容编写"
      top="10vh"
      :visible.sync="newsModel"
      width="1300px"
      class="vrcode-model manage-model"
      :append-to-body="true"
    >
      <div class="vrcode-model-title">
        新闻{{ newsEdit == 1 ? "英文" : "中文" }}内容编写
      </div>

      <div class="vrcode-content flex-no">
        <div style="border: 1px solid #ccc; width: 100%" v-loading="upLoading">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editor"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height:600px; overflow-y: hidden"
            v-model="html"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
            @onChange="handleChange"
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <div class="vrcode-btn blue-btn w-100" @click="changeNewModel">
          {{$t('index.confirm')}}
        </div>
        <div class="vrcode-btn cancle-btn w-100" @click="closeNewsModel">
          {{$t('index.cancel')}}
        </div>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { DomEditor } from "@wangeditor/editor";
export default {
  components: {
    Editor,
    Toolbar,
  },

  data() {
    return {
      newsModel: false,
      newsEdit: 0, //编辑/添加的是中文还是英文 0是中文1是英文
      tableData: [],
      addModel: false,
      nowData: {
        detailedIntroductionImage: "",
        detailedIntroductionEnName: "",
        detailedIntroductionEnText: "",
        detailedIntroductionText: "",
        detailedIntroductionName: "",
        detailedIntroductionSort: "",
        newsTime: "",
        type: 3,
      },
      modelName: this.$t('text.add'),
      typeSelList: [],
      TypeSel: "",
      selId: "",
      loading: false,

      //
      upLoading: false,
      editor: null,
      html: "",
      mode: "default",
      editorConfig: {
        placeholder: "请编写新闻内容...",
        backColor: "red", // 背景颜色
        MENU_CONF: {
          uploadImage: {
            customUpload: this.uploaadImg,
          },
          uploadVideo: {
            customUpload: this.uploaadVideo,
          },
        },
      },
      toolbarConfig: {},
    };
  },
  filters: {
    formatDate: function (value) {
      if (!value) return "";
      const date = new Date(value);

      // 处理时区问题，转换为本地时间
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");

      return `${year}-${month}-${day}`;
    },
  },
  mounted() {
    this.dataInit();
  },
  beforeDestroy() {
    const editor = this.editor;
    if (editor == null) return;
    editor.destroy(); // 销毁编辑器
  },
  methods: {
    dataInit() {
      this.api.website_getowpabyowpidMan().then((res) => {
        if (res.data.code == 200) {
          this.tableData = res.data.data.filter(
            (item) => item && item.type === 3
          );
        }
      });
    },
    handleCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal() ，否则会报错
      //   设置工具栏详情
      this.toolbarConfig = {
        excludeKeys: [
          "insertVideo",
          "uploadVideo",
          "group-video",
          "fullScreen",
        ],
      };
    },
    closeNewsModel() {
      if (this.upLoading) {
        this.$message("请等待图片上传完成");
        return;
      }
      this.html = "";
      this.newsModel = false;
    },
    // 新闻弹窗点击确定
    changeNewModel() {
      if (this.newsEdit == 0) {
        this.nowData.detailedIntroductionText = this.html;
      } else {
        this.nowData.detailedIntroductionEnText = this.html;
      }
      this.newsModel = false;
      this.newsEdit = 0;
    },
    // 打开新闻页面 0是中文编辑 1是英文
    openNewsModel(type) {
      if (type == 0) {
        this.html = this.nowData.detailedIntroductionText
          ? this.nowData.detailedIntroductionText
          : "";
      } else {
        this.html = this.nowData.detailedIntroductionEnText
          ? this.nowData.detailedIntroductionEnText
          : "";
      }
      this.newsEdit = type;
      this.newsModel = true;
    },
    handleChange(content) {
      const toolbar = DomEditor.getToolbar(content);
      //   查看工具栏列表toolbar.getConfig().toolbarKeys
    },
    // 上传图片到线上 并且插入到富文本编辑器中
    async uploaadImg(file, insertFn) {
      // 处理入参
      this.upLoading = true;
      var data = { file: file };
      await this.api
        .websiteUploadImage(data)
        .then((res) => {
          this.upLoading = false;
          if (res.data.code == 200) {
            this.$message.success("插入图片成功");
            insertFn(res.data.msg); // 页面插入图片
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          this.upLoading = false;
          this.$message.error("插入图片失败");
        });
    },
    uploaadVideo(file, insertFn) {
      this.$emit("uploadVideo", file, insertFn);
    },

    openModel(item, type) {
      if (type == 0) {
        this.modelName = this.$t('text.add');
        this.addModel = true;
        this.nowData = {
          detailedIntroductionImage: "",
          detailedIntroductionEnName: "",
          detailedIntroductionEnText: "",
          detailedIntroductionText: "",
          detailedIntroductionName: "",
          detailedIntroductionSort: "",
          type: 3,
        };
      } else {
        this.modelName = this.$t('text.edit');
        this.nowData = JSON.parse(JSON.stringify(item));
        this.addModel = true;
      }
    },

    changeAddModel() {
    if(this.loading){
           this.$message.error("图片还未上传成功，请耐心等待。");
           return
        }
   if(!this.nowData.detailedIntroductionImage){
           this.$message.error("图片还未上传。");
           return
         }
              this.Addloading = this.$loading({
        lock: true,
        text: this.$t('message.loading'),
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      if (this.modelName == this.$t('text.edit')) {
        var data = { ...this.nowData, id: this.nowData.id.toString() };
        this.api.website_updateops(data).then((res) => {
          this.Addloading.close();
          if (res.data.code == 200) {
            this.$message.success(res.data.msg);
            this.dataInit();
            this.addModel = false;
          } else {
            this.$message.error(res.data.msg);
            this.addModel = false;
          }
        });
      } else {
        var data = { ...this.nowData };
        this.api.website_addops(data).then((res) => {
          this.Addloading.close();
          if (res.data.code == 200) {
            this.$message.success(res.data.msg);
            this.dataInit();
            this.addModel = false;
          } else {
            this.$message.error(res.data.msg);
            this.addModel = false;
          }
        });
      }
    },
    handleImageChange(event, type) {
      this.loading = true;
      if (event.target.files.length === 0) {
        // 用户点击了取消
        this.loading = false;
        return;
      }
      const file = event.target.files[0];

      const reader = new FileReader();
      const maxSize = 2 * 1024 * 1024; // 2MB in bytes
      // if (file.size > maxSize) {
      //   this.$message.error("图片大小不能超过2MB");
      //   this.$refs.fileInput.value = "";
      //    this.loading = false;
      //   return;
      // }

      reader.onload = (e) => {
        const imageData = e.target.result;
        const convertedFile = new File([imageData], file.name, {
          type: file.type,
        });
        // 处理转换后的文件...

        var data = { file: convertedFile };
        this.api.websiteUploadImage(data).then((res) => {
          this.loading = false;
          if (res.data.code == 200) {
            this.nowData.detailedIntroductionImage = res.data.msg;
            this.$refs.fileInput.value = "";
          } else {
            this.$message.error(res.data.msg);
            this.$refs.fileInput.value = "";
          }
        }).catch((err) => {
          this.loading = false;
            this.$refs.fileInput.value = "";
          this.$message.error("插入图片失败");
        });
      };
      reader.readAsArrayBuffer(file);
    },

    confirmDel(item) {
      var data = { id: item.id.toString() };
      this.api.website_delops(data).then((res) => {
        if (res.data.code == 200) {
          this.dataInit();
          this.$message.success(res.data.msg);
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 == 1) {
        return "warning-row";
      } else if (rowIndex % 2 == 0) {
        return "success-row";
      }
      return "";
    },
  },
};
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
<style lang="scss"></style>