<!--系统模板设置-->
<template>
  <div class="index-home">
    <div v-loading.fullscreen.lock="loadingFull" />
    <div class="search">
      <el-form
        ref="searchParams"
        :model="searchParams"
        label-width="80px"
      >
        <el-input
          v-model="searchParams.title"
          placeholder="模板标题"
          clearable
        ></el-input>
        <el-input
          v-model="searchParams.key"
          placeholder="索引标识"
          clearable
        ></el-input>
        <el-select
          v-model="searchParams.type"
          placeholder="请选择模板类型"
          clearable
        >
          <el-option
            label="富文本"
            value="0"
          ></el-option>
          <el-option
            label="图片"
            value="1"
          ></el-option>
          <el-option
            label="文件"
            value="2"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          @click="search"
          icon="el-icon-search"
        >搜索</el-button>
        <el-button
          type="success"
          icon="el-icon-edit"
          @click="newlyAdded(dialogVisible = true)"
        >新增模板</el-button>
      </el-form>
    </div>
    <el-table
      :data="tableData"
      border
      style="width: 100%"
    >
      <el-table-column
        type="index"
        label="序号"
        width="80"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="title"
        label="标题"
      > </el-table-column>
      <el-table-column
        prop="key"
        label="索引"
        width="350"
      > </el-table-column>
      <el-table-column
        prop="type"
        label="类型"
        width="180"
        align="center"
      >
        <template slot-scope="{ row }">
          <el-tag
            type="success"
            v-if="row.type == 0"
            size="mini"
          >富文本</el-tag>
          <el-tag
            type="warning"
            size="mini"
            v-else-if="row.type == 1"
          >图片</el-tag>
          <el-tag
            size="mini"
            v-else
          >文件</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="status"
        label="状态"
        align="center"
        width="180"
      >
        <template slot-scope="{ row }">
          <el-tag
            size="mini"
            type="success"
            v-if="row.status == 1"
          >正常</el-tag>
          <el-tag
            size="mini"
            type="danger"
            v-else
          >暂停</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="updated_at"
        label="修改时间"
      > </el-table-column>
      <el-table-column
        label="操作"
        align="center"
      >
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            plain
            size="mini"
            @click="queryTemplete(row)"
          >查看</el-button>
          <el-button
            type="success"
            plain
            size="mini"
            @click="editTemplete(row)"
          >编辑</el-button>
          <el-button
            type="warning"
            plain
            size="mini"
            @click="cutOutTemplete(row.id)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页-->
    <div class="paging">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="changePage.page"
        background
        :page-sizes="[15, 20, 30, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalPage"
      >
      </el-pagination>
    </div>
    <!--新增模板-->
    <el-dialog
      :title="type == 1 ? '新增模板' : '编辑模板'"
      :visible.sync="dialogVisible"
      width="60%"
      center
    >
      <el-form
        ref="form"
        :model="form"
        label-width="100px"
        :rules="formRule"
        class="demo-ruleForm"
        width="80%"
      >
        <el-form-item
          label="标题"
          prop="title"
        >
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item
          label="索引标识"
          prop="key"
        >
          <el-input
            v-model="form.key"
            :disabled="keyInput"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="状态"
          prop="status"
        >
          <el-select
            v-model="form.status"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in status"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="注意事项："
          prop="remark"
        >
          <el-input
            type="textarea"
            v-model="form.remark"
            rows="5"
          ></el-input>
          <div style="font-size:12px;color:#409EFF;">
            注：学生上传文件时注意事项（选填）
          </div>
        </el-form-item>
        <div class="position">
        <span class="xing">*</span>
        <el-form-item label="上传模板">
          <el-tabs
            v-model="activeName"
            @tab-click="handleClick"
          >
            <el-tab-pane
              label="图片"
              name="first"
            >
              <el-upload
                class="upload-demo"
                ref="upload"
                :action=" base_url + '/upload'"
                :file-list="fileList"
                :auto-upload="true"
                :on-success="uploadSuccess"
                accept=".jpg,.jpeg,.png"
                :data="fileData"
                limit="1"
                :multiple="true"
                list-type="picture-card"
              >
                <i
                  slot="default"
                  class="el-icon-plus"
                ></i>
                <div
                  slot="tip"
                  class="el-upload__tip"
                >
                  只能上传一张jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-tab-pane>
            <el-tab-pane
              label="文件"
              name="second"
            >
              <el-upload
                class="upload-demo"
                ref="uploadFile"
                :action="base_url+'/upload'"
                :file-list="fileList"
                :auto-upload="true"
                :on-success="uploadSuccess"
                accept=".docx,.doc,.pdf"
                :data="fileData"
              >
                <el-button
                  slot="trigger"
                  size="mini"
                  type="primary"
                >选择文件</el-button>

                <div
                  slot="tip"
                  class="el-upload__tip"
                >
                  上传word,pdf文件，且不超过500kb
                </div>
              </el-upload>
            </el-tab-pane>
            <el-tab-pane
              label="富文本"
              name="third"
            >
              <tinymce
                v-model="form.body"
                :height="300"
                width="95%"
              />
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
        </div>
      </el-form>
      <div class="form-bt">
        <el-button @click="cancel">取 消</el-button>
        <el-button
          v-if="type == 1"
          type="primary"
          @click="sure()"
        >确定</el-button>
        <el-button
          v-else
          type="primary"
          @click="modifyTemplates()"
        >保存编辑</el-button>
      </div>
    </el-dialog>
    <!--查看模板-->
    <el-dialog
      :visible.sync="lookTemplates"
      width="50%"
      center
    >
      <div class="title">
        {{ lookList.title }}
      </div>
      <div class="title-time">更新时间： {{ lookList.updated_at }}</div>
      <!--富文本-->
      <div
        class="content"
        v-if="lookList.type == 0"
      >
        <p v-html="lookList.body"></p>
      </div>
      <!--图片-->

      <div
        v-if="lookList.type == 1"
        class="edit-image"
      >
        <div
          class="img-list"
          @click="imageDetail(item)"
          v-for="(item, index) in lookList.resource"
        >
          <img
            :src="item"
            alt=""
          />
        </div>

        <div
          class="big-img"
          v-show="imgDetaildialogVisible"
          @click="closeBigImg"
        >
          <img
            :src="bigImage"
            alt=""
          />
        </div>
      </div>
      <!--word链接-->
      <div
        v-if="lookList.type == 2"
        class="text"
      >
        <a
          :href="lookList.resource"
          target="_blank"
        >点击下载模板：{{ lookList.title }}</a>
      </div>
      <span slot="footer">
        <el-button
          type="primary"
          @click="lookTemplates = false"
        >关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  templates,
  templatesList,
  lookTemplates,
  modifyTemplates,
  deleteTemplates
} from "@/api/TemplateSet/index";
import Tinymce from "@/components/Tinymce";
export default {
  data() {
    return {
      bigImage: "",
      imgDetaildialogVisible: false,
      keyInput: false,
      dialogVisible: false, //弹出层变量
      lookTemplates: false,
      lookList: "",
      tableData: [],
      loadingFull: false,
      type: "", //表单提交类型1为新增模板，2为编辑模板
      fileList: [], //上传文件列表
      form: {
        title: "",
        key: "",
        type: 1,
        body: "",
        status: "",
        remark: "",
        resource_ids: []
      }, //新增修改列表
      searchParams: {
        title: "",
        key: "",
        type: ""
      }, //搜索框数据
      file: "",
      formRule: {
        title: [
          { required: true, message: "模板标题不能为空", trigger: "blur" }
        ],
        key: [{ required: true, message: "索引不能为空", trigger: "blur" }],
        status:[{ required: true, message: "请选择状态", trigger: "change" }],
      },
      activeName: "first",
      fileData: {
        file_type: "img"
      },
      totalPage: 0,
      changePage: {
        limit: 15, //每页显示条数
        page: 1 //当前页码
      },
      status: [
        {
          value: 0,
          name: "暂停"
        },
        {
          value: 1,
          name: "正常"
        }
      ]
    };
  },
  components: { Tinymce },
  created() {
    this.templatesList();
  },
  methods: {
    //取消添加
    cancel(){
      this.dialogVisible=false
      this.$refs.form.resetFields()
    },
    //关闭大图
    closeBigImg() {
      this.imgDetaildialogVisible = false;
    },
    //查看大图
    imageDetail(item) {
      this.imgDetaildialogVisible = true;
      this.bigImage = item;
    },

    async templatesList(params) {
      //模板列表
      console.log("909090");
      this.loadingFull = true;

      await templatesList(params).then(res => {
        console.log(res, "log");
        this.totalPage = res.data.meta.pagination.total;
        this.loadingFull = false;
        this.tableData = res.data.data;
        console.log(this.totalPage);
      });
    },
    async search() {
      this.loadingFull = true;
      //搜索templates
      await templatesList(this.searchParams).then(res => {
        this.totalPage = res.data.meta.pagination.total;
        this.loadingFull = false;
        this.tableData = res.data.data;
        this.loadingFull = false;
      });
    },

    newlyAdded: function() {
      //新增模板
      this.form = {
        title: "",
        key: "",
        type: 1,
        resource_type: 1,
        body: "",
        status: "",
        resource_ids: []
      }; //新增修改列表
      this.type=1
      this.keyInput = false;
      this.activeName = "first";
      this.fileData.file_type = "img";
      this.fileList = [];
    },
    //创建、修改模板操作
    async sure() {
      console.log(this.form, "type");
      console.log(this.type, "type");
      console.log(this.file);
      this.form.body = this.file;
      if(!this.form.body){
         this.$message({
              message: "请上传模板文件",
              type: "error"
            });
            return;
      }
      //创建模板
      await templates(this.form)
        .then(res => {
          if (res.code == 200) {
            this.dialogVisible = false;
            this.templatesList();
            this.$message({
              message: "模板创建成功",
              type: "success"
            });
          } else {
            console.log(res, "error");
            this.$message.error("模板上传失败");
          }
        })
        .catch(err => {
          console.log(err, "");
          this.loadingFull = false;
        });
    },
    async modifyTemplates(row) {
      const date = {
        title: this.form.title,
        body: this.file,
        remark: this.form.remark,
        id: this.form.id,
        type: this.form.type
      };
      await modifyTemplates(date)
        .then(res => {
          ///this.templatesList();
          this.dialogVisible = false;
          this.$message({
            message: "模板修改成功",
            type: "success"
          });
        })
        .catch(err => {
          console.log(err, "");
          this.loadingFull = false;
        });
    },
    //查看模板
    async queryTemplete(row) {
      this.loadingFull = true;
      const params = {
        id: row.id
      };
      await lookTemplates(params).then(res => {
        this.lookTemplates = true;
        console.log(res, "templatesList");
        this.lookList = res.data;
        this.loadingFull = false;
      });
      console.log(row, "row");
    },
    //编辑模板配置文件类型
    async editTemplete(row) {
      this.keyInput = true;
      console.log(row, "id");
      this.type = 2;
      let date = row;
      if (row.type == 1) {
        this.activeName = "first";
        this.fileData.file_type = "img";
      } else if (row.type == 2) {
        this.activeName = "second";
        this.fileData.file_type = "file";
      } else {
        this.activeName = "third";
      }
      this.form = date;
      this.dialogVisible = true;
    },
    //删除模板
    cutOutTemplete: function(id) {
      const data = id;
      this.$confirm("此操作将删除此项模板, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.deleteModel(id);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    async deleteModel(id) {
      await deleteTemplates(id).then(res => {
        console.log(res, "delete");
        if (!res.code) {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.templatesList();
        } else {
          this.$message({
            type: "error",
            message: "删除失败!"
          });
        }
      });
    },
    //切换上传内容图片、文件、富文本
    handleClick(tab) {
      console.log(tab.name);
      if (tab.name == "first") {
        this.form.type = 1;
        this.form.resource_type = 1;
        this.fileData.file_type = "img";
      } else if (tab.name == "second") {
        this.form.type = 2;
        this.form.resource_type = 2;
        this.fileData.file_type = "file";
      } else {
        this.form.type = 0;
        this.form.resource_type = 0;
      }
    },
    //上传图片

    uploadSuccess(response, file, fileList) {
      if (response.code == 200) {
        this.file = response.data.path;
        let path = response.data.path;
        console.log(path, "_----------------------");
        this.form.body = path;
        console.log(this.form, "mobashezhi");
        let arr = [];
        arr.push(response.data.id);
        this.form.resource_ids = arr;
        console.log(this.form.resource_ids);
      }
    },
    //点击切换页码
    handleCurrentChange(e) {
      this.page=e
      this.changePage = {
        title: this.searchParams.title,
        key: this.searchParams.key,
        type: this.searchParams.type,
        page: e,
        limit:this.limit
      };
      console.log(this.searchParams, "xuying-----------------");
      this.templatesList(this.changePage);
    },
    //选择每页显示条数
    handleSizeChange(e) {
      this.limit=e
      this.changePage.limit = this.searchParams;
      this.changePage.limit = e;
      this.changePage.page=this.page
      this.templatesList(this.changePage);
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/assets/styles/content.scss";
.position{
  position: relative;
  .xing{
position: absolute;
color: red;
top: 15px;
    left: 20px;
  }
}
.el-dialog {
  margin-top: 20px !important;
}
.form-bt {
  margin: 0 auto;
  text-align: center;
}
.title {
  height: 50px;
  line-height: 50px;
  text-align: center;
  font-size: 30px;
}
.content {
  margin-top: 20px;
  font-size: 16px;
  line-height: 22px;
}
.image {
  margin-top: 30px;
  text-align: center;
  width: 100%;
  height: auto;
}
.text {
  height: 50px;
  font-size: 16px;
  color: #409eff;
  margin-top: 20px;
}
.title-time {
  text-align: center;
  margin-top: 10px;
  font-size: 14px;
  color: rgb(143, 142, 142);
}
.edit-image {
  text-align: center;
  display: flex;
  flex-flow: row wrap;
}

.img-list {
  flex: 0 0 200px;
  height: 200px;
  width: 200px;
  margin: 20px 5px 5px;
  overflow: hidden;
  img {
    border: 1px solid #ccc;
    border-radius: 5px;
    height: 200px;
    width: 200px;
  }
}
.big-img {
  position: fixed;
  z-index: 99999;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.6);
  overflow: hidden;
  img {
    margin-top: 3%;
    width: 33%;
    height: auto;
  }
}
</style>
