<template>
  <div>
    <!-- 标题 -->
    <el-row>
      <el-col
        :span="24"
        class="first-row"
      >
        <div class="tag">新闻聚焦</div>
      </el-col>
    </el-row>

    <!-- 分割线 -->
    <hr style="background-color: #CCCCCC;height: 1px;border: 0;">
    <div style="margin: 32px 0;"></div>

    <!-- 时间选择器和增加按钮 -->
    <el-row>
      <el-col :span="8">
        <el-date-picker
          v-model="select_datetime"
          type="daterange"
          align="center"
          unlink-panels
          range-separator="至"
          :start-placeholder="startTime"
          :end-placeholder="endTime"
          @change="dateChange"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
          class="shijian_plus"
        >
        </el-date-picker>
      </el-col>
      <el-col :span="6">
        <el-button
          type="primary"
          @click="hangdleAddNewsFocus"
        >添加</el-button>
      </el-col>
    </el-row>

    <div style="margin: 20px 0;"></div>
    <hr style="background-color: #CCCCCC;height: 1px;border: 0;">

    <!-- 表格区域 -->
    <el-row>
      <el-col
        :span="24"
        class="third-row"
      >
        <!-- 表单 -->
        <el-table
          :data="tableData"
          style="width: 100%;font-size: 14px;"
          highlight-current-row
          height="450"
        >
          <el-table-column
            prop="title"
            label="标题"
            align="center"
            width="200"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="publishTime"
            label="时间"
            align="center"
            width="180"
          >
          </el-table-column>
          <el-table-column
            prop="source"
            label="来源"
            align="center"
            width="200"
          >
          </el-table-column>

          <el-table-column
            prop="content"
            label="内容"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>

          <el-table-column
            label="图片"
            align="center"
            width="180"
          >
            <template slot-scope="{row}">
              <img
                style="width: 82px; height: 60px"
                :src="row.image"
              >
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            width="180"
          >
            <template slot-scope="{ row }">
              <el-button
                type="warning"
                size="mini"
                @click="amendNewsFocus(row)"
              >编辑</el-button>
              <el-button
                type="danger"
                size="mini"
                @click="deleteNewsFocus(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <div style="margin: 20px 0;"></div>

    <!-- 分页器 -->
    <el-row>
      <div class="pagination_smoke">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="totalCount"
          :page-size="pageSize"
          :current-page.sync="curPage"
          @current-change="changeCurPage"
        >
        </el-pagination>
      </div>

    </el-row>

    <!-- 新增 新闻聚焦 弹窗 -->
    <el-dialog
      title="添加新闻聚焦"
      :visible.sync="dialogFormVisible"
      center
      style="width:90%"
      top="8vh"
      :before-close="handleClose"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        style="width:80%"
        label-width="80px"
      >
        <el-form-item
          label="新闻图片"
          prop="image"
          ref="headimgUpload"
        >
          <el-upload
            ref="my_upload"
            action="#"
            :auto-upload="false"
            list-type="picture-card"
            :limit="1"
            :on-change="getLocalImg"
            :on-preview="handlePictureCardPreview"
            :on-exceed="handleExceed"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus avatar-uploader-icon"></i>
            <div
              slot="tip"
              class="el-upload__tip"
            >只能上传jpg/jpeg/bmp/png格式，且提示上传图片成功后才能提交添加</div>
          </el-upload>

          <el-dialog
            :visible.sync="dialogVisible"
            append-to-body
          >
            <img
              width="100%"
              :src="dialogImageUrl"
            >
          </el-dialog>

        </el-form-item>

        <el-form-item
          label="时间"
          prop="publishTime"
        >
          <el-date-picker
            v-model="form.publishTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item
          label="标题"
          prop="title"
        >
          <el-input v-model="form.title"></el-input>
        </el-form-item>

        <el-form-item
          label="来源"
          prop="source"
        >
          <el-input v-model="form.source"></el-input>
        </el-form-item>

        <el-form-item
          label="内容"
          prop="content"
        >
          <el-input
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6}"
            v-model="form.content"
          ></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer">
        <el-button
          type="primary"
          @click="addNewsFocus('form')"
        >确 定</el-button>
        <el-button @click="dialogFormVisible = false;clearFiles()">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改 新闻聚焦 弹窗 -->
    <el-dialog
      title="修改新闻聚焦"
      :visible.sync="dialogFormVisible2"
      center
      style="width:90%"
      top="8vh"
    >
      <el-form
        :model="form"
        style="width:80%"
        label-width="80px"
      >
        <el-form-item label="新闻图片">

          <el-upload
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="getLocalImg2"
          >
            <img
              v-if="form.image"
              :src="form.image"
              class="avatar"
            >
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
            ></i>

            <div
              slot="tip"
              class="el-upload__tip"
            >只能上传jpg/jpeg/bmp/png格式</div>
          </el-upload>

        </el-form-item>

        <el-form-item label="时间">
          <el-date-picker
            v-model="form.publishTime"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="标题">
          <el-input v-model="form.title"></el-input>
        </el-form-item>

        <el-form-item label="来源">
          <el-input v-model="form.source"></el-input>
        </el-form-item>

        <el-form-item label="内容">
          <el-input
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 6}"
            v-model="form.content"
          ></el-input>
        </el-form-item>

      </el-form>

      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="hangdleAmendNewsFocus"
        >确 定</el-button>
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "",
  data() {
    return {
      select_datetime: [], // 选择的时间范围
      startTime: "", // 开始时间
      endTime: "", // 结束时间
      // 默认时间选择
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      tableData: [], // 表格数据
      curPage: 1, // 当前页
      pageSize: 4, // 每页记录数
      totalCount: null, // 总条数
      dialogVisible: false, // 放大图片弹窗
      dialogImageUrl: "", // 放大图片数据
      dialogFormVisible: false, // 增加弹窗
      dialogFormVisible2: false, // 修改弹窗
      // 表格数据
      form: {
        title: "", // 标题
        publishTime: "", // 时间
        source: "", // 来源
        content: "", // 内容
        image: "", // 图片
        imageName: "", // 图片
      },
      // 表格验证规则
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        publishTime: [
          { required: true, message: "请选择时间", trigger: "blur" },
        ],
        source: [{ required: true, message: "请输入来源", trigger: "blur" }],
        content: [{ required: true, message: "请输入内容", trigger: "blur" }],
        image: [{ required: true, message: "请选择图片" }],
      },
    };
  },
  mounted() {
    this.getData();
  },
  methods: {
    // 整理参数函数
    handleCurrentChange(val) {
      this.curPage = val;
      this.getData();
    },
    // 获取新闻聚焦列表数据
    async getData() {
      let params = {
        curPage: this.curPage,
        pageSize: this.pageSize,
        startTime: this.startTime,
        endTime: this.endTime,
        // orderField: "startTime",
        // order: "asc",
      };
      let res = await this.$axios({
        url: "/diseaseRight/newsFocus/list",
        method: "get",
        params,
      });
      // console.log(res);
      if (res.data.success) {
        this.tableData = res.data.data.list;
        this.totalCount = res.data.data.totalCount;
      } else {
        console.log("获取 新闻聚焦列表数据 失败");
      }
    },
    // 上传图片
    async getLocalImg(file) {
      let formData = new FormData();
      formData.append("file", file.raw);
      let res = await this.$axios({
        url: "/diseaseRight/file/imageUpload",
        method: "post",
        data: formData,
        headers: {
          "Admin-Token": sessionStorage.getItem("token"),
        },
      });
      // console.log(res);
      if (res.data.success) {
        // 响应式添加image的值
        this.$set(this.form, "image", res.data.data.imageName);
        this.$message.success("图片上传成功!");
        //等待照片上传完成清除验证提示
        this.$nextTick(() => {
          this.$refs["headimgUpload"].clearValidate();
        });
        // console.log(this.form.image);
      } else {
        this.$message.error("图片上传失败!");
      }
    },
    async getLocalImg2(file) {
      let formData = new FormData();
      formData.append("file", file.raw);
      let res = await this.$axios({
        url: "/diseaseRight/file/imageUpload",
        method: "post",
        data: formData,
        headers: {
          "Admin-Token": sessionStorage.getItem("token"),
        },
      });
      // console.log(res);
      if (res.data.success) {
        this.form.image = res.data.data.showUrl;
      } else {
        console.log("上传图片失败");
      }
    },
    hangdleAddNewsFocus() {
      this.dialogFormVisible = true;
      this.form = {};
      this.$nextTick(() => {
        this.clearFiles();
      });
    },
    // 添加新闻聚焦
    addNewsFocus(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          let res = await this.$axios({
            method: "post",
            url: "/diseaseRight/newsFocus/save",
            headers: {
              "Admin-Token": sessionStorage.getItem("token"),
            },
            data: this.form,
          });
          // console.log(res);
          if (res.data.success) {
            this.handleCurrentChange(1);
            this.$message.success("添加成功!");
            this.clearFiles();
          } else {
            this.$message.error("添加失败!");
          }
        } else {
          console.log("提交失败!!");
          return false;
        }
      });
    },
    // 修改新闻聚焦
    amendNewsFocus(row) {
      // console.log(row);
      this.form = { ...row };
      this.dialogFormVisible2 = true;
    },
    // 修改新闻聚焦请求
    async hangdleAmendNewsFocus() {
      this.dialogFormVisible2 = false;
      this.form.image = this.form.imageName;
      let res = await this.$axios({
        method: "put",
        url: "/diseaseRight/newsFocus/update",
        headers: {
          "Admin-Token": sessionStorage.getItem("token"),
        },
        data: this.form,
      });
      // console.log(res);
      if (res.data.success) {
        this.handleCurrentChange(this.curPage);
        this.$message.success("修改成功!");
      } else {
        this.$message.error("修改失败!");
      }
    },
    // 删除新闻聚焦
    deleteNewsFocus(id) {
      this.$confirm("确定删除吗?", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(async () => {
          let res = await this.$axios({
            method: "delete",
            url: "/diseaseRight/newsFocus/delete",
            headers: {
              "Admin-Token": sessionStorage.getItem("token"),
            },
            data: [id],
          });
          // console.log(res);
          if (res.data.success) {
            this.$message.success("删除成功");
            let totalPage = Math.ceil((this.totalCount - 1) / this.pageSize);
            let currentPage =
              this.curPage > totalPage ? totalPage : this.curPage;
            this.curPage = currentPage < 1 ? 1 : currentPage;
            this.handleCurrentChange(this.curPage);
          } else {
            this.$message.error("删除失败!");
          }
        })
        .catch(() => {
          this.$message.info("已取消");
        });
    },
    // 改变时间函数
    dateChange(val) {
      if (val) {
        this.startTime = val[0];
        this.endTime = val[1];
        this.handleCurrentChange(1);
      } else {
        this.startTime = "";
        this.endTime = "";
        this.handleCurrentChange(1);
      }
    },
    // 换页逻辑
    changeCurPage(val) {
      // console.log(`当前页: ${val}`);
      this.handleCurrentChange(val);
    },
    // 点击文件列表中已上传的文件时的钩子 放大图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 文件超出个数限制时的钩子
    handleExceed() {
      this.$message.warning(`只能同时上传一张照片`);
    },
    // 文件列表移除文件时的钩子
    handleRemove() {
      this.form.image = "";
    },
    // 清空已上传的文件列表
    clearFiles() {
      this.$refs.my_upload.clearFiles();
    },
    // Dialog关闭前的回调
    handleClose(done) {
      this.clearFiles();
      done();
    },
  },
};
</script>

<style scoped>
.first-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
}
.tag {
  width: 108px;
  height: 40px;
  font-size: 24px;
  font-family: Microsoft YaHei-3970(82674968);
  font-weight: bold;
  color: #000000;
  line-height: 54px;
}
.shijian_plus.el-date-editor--daterange {
  width: 250px;
}
.third-row {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 0;
}
.pagination_smoke {
  text-align: center;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  border-radius: 6px;
  border: 1px dashed #ccc;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>