<template>
  <div>
    <!-- 标题 -->
    <el-row class="first-row">
      <div class="tag">活动策划</div>
    </el-row>

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

    <el-tabs>
      <!-- 策划内容区域 -->
      <el-tab-pane label="策划内容">
        <!-- 时间选择器和增加按钮 -->
        <el-row style="marginTop:10px">
          <el-col :span="6">
            <el-date-picker
              v-model="select_datetime"
              type="daterange"
              align="center"
              unlink-panels
              range-separator="至"
              @change="dateChange"
              value-format="yyyy-MM-dd HH:mm:ss"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              class="shijian_plus"
            >
            </el-date-picker>
          </el-col>
          <el-col :span="6">
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="dialogFormVisible = true;form = {};"
            >添加活动策划</el-button>
          </el-col>
        </el-row>

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

        <!-- 表格区域 -->
        <el-row>
          <el-table
            :data="tableData"
            highlight-current-row
            height="450"
            v-loading="loading"
            element-loading-text="加载中"
            element-loading-spinner="el-icon-loading"
          >
            <el-table-column
              prop="title"
              label="标题"
              align="center"
              width="300"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              prop="startTime"
              label="时间"
              align="center"
              width="220"
            >
            </el-table-column>
            <el-table-column
              prop="content"
              label="内容"
              align="center"
              show-overflow-tooltip
            >
            </el-table-column>

            <el-table-column
              label="操作"
              align="center"
              width="200"
            >
              <template slot-scope="{ row }">
                <el-button
                  type="warning"
                  size="mini"
                  @click="amendEventPlanning(row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  @click="deleteEventPlanning(row.id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </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-tab-pane>

      <!-- 月度小结区域 -->
      <el-tab-pane label="月度小结">
        <!-- 时间日期选择器和增加按钮 -->
        <el-row style="marginTop:10px">
          <el-col :span="6">
            <el-date-picker
              v-model="select_datetime2"
              type="month"
              value-format="yyyy-MM"
              placeholder="选择月份筛选"
              @change="getData2"
            >
            </el-date-picker>
          </el-col>
          <el-col :span="6">
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="handleAdd"
            >添加月度小结</el-button>
          </el-col>
        </el-row>

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

        <!-- 表格区域 -->
        <el-row>
          <el-table
            :data="tableData2"
            highlight-current-row
            height="450"
            v-loading="loading"
            element-loading-text="加载中"
            element-loading-spinner="el-icon-loading"
          >
            <el-table-column
              prop="month"
              label="时间"
              align="center"
              width="120"
            >
            </el-table-column>
            <el-table-column
              prop="title"
              label="标题"
              align="center"
              width="220"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              label="内容"
              align="center"
              show-overflow-tooltip
            >
              <template slot-scope="{row}">
                <div
                  style="height:25px"
                  v-html="row.content"
                ></div>
              </template>
            </el-table-column>

            <el-table-column
              label="操作"
              align="center"
              width="200"
            >
              <template slot-scope="{ row }">
                <el-button
                  type="warning"
                  size="mini"
                  @click="editNodulus(row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  @click="deleteNodulus(row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-row>

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

        <!-- 分页器 -->
        <el-row>
          <div class="pagination_smoke">
            <el-pagination
              background
              layout="prev, pager, next"
              :total="totalCount2"
              :page-size="pageSize2"
              :current-page.sync="curPage2"
              @current-change="changeCurPage2"
            >
            </el-pagination>
          </div>

        </el-row>

      </el-tab-pane>
    </el-tabs>

    <!-- 新增 活动策划 弹窗 -->
    <el-dialog
      title="添加活动策划"
      :visible.sync="dialogFormVisible"
      :close-on-click-modal="false"
      center
      style="width:90%"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        style="width:80%"
        label-width="80px"
      >
        <el-form-item
          label="时间"
          prop="startTime"
        >
          <el-date-picker
            v-model="form.startTime"
            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="content"
        >
          <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="addEventPlanning('form')"
        >确 定</el-button>
        <el-button @click="dialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改 活动策划 弹窗 -->
    <el-dialog
      title="修改活动策划"
      :visible.sync="dialogFormVisible2"
      :close-on-click-modal="false"
      center
      style="width:90%"
    >
      <el-form
        :model="form"
        style="width:80%"
        label-width="80px"
      >

        <el-form-item label="时间">
          <el-date-picker
            v-model="form.startTime"
            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
            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="hangdleAmendEventPlanning"
        >确 定</el-button>
        <el-button @click="dialogFormVisible2 = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增或编辑 月度小结 弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible3"
      :close-on-click-modal="false"
      center
      style="width:90%"
    >
      <el-form
        :model="form2"
        :rules="rules2"
        ref="form2"
        style="width:80%"
        label-width="80px"
      >
        <el-form-item
          label="时间"
          prop="month"
        >
          <el-date-picker
            v-model="form2.month"
            value-format="yyyy-MM"
            type="month"
            placeholder="选择时间"
          >
          </el-date-picker>
        </el-form-item>

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

        <el-form-item
          label="内容"
          prop="content"
        >
          <quill-editor
            ref="QuillEditor"
            v-model="form2.content"
            style="height: 200px;marginBottom:20px"
            :options="editorOption"
          >
          </quill-editor>

          <el-upload
            v-show="false"
            class="avatar-uploader"
            name="img"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="getLocalImg"
          >
          </el-upload>

        </el-form-item>

      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="handleAddOrUpdata('form2')"
        >确 定</el-button>
        <el-button @click="dialogFormVisible3 = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
// 引入富文本编辑框和样式
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
export default {
  name: "EventPlanning",
  components: { quillEditor },
  data() {
    return {
      select_datetime: [], // 策划内容选择的时间范围
      select_datetime2: "", // 月度小结选择的时间范围
      startTime: "", // 开始时间
      endTime: "", // 结束时间

      tableData: [], // 策划内容表格数据
      curPage: 1, // 当前页
      pageSize: 7, // 每页记录数
      totalCount: null, // 总条数

      tableData2: [], // 月度小结表格数据
      curPage2: 1, // 当前页
      pageSize2: 6, // 每页记录数
      totalCount2: null, // 总条数

      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogFormVisible3: false,
      form: {
        title: "", // 标题
        startTime: "", // 时间
        content: "", // 内容
      },
      rules: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        startTime: [{ required: true, message: "请选择时间", trigger: "blur" }],
        content: [{ required: true, message: "请输入内容", trigger: "blur" }],
      },
      form2: {
        title: "", // 标题
        month: "", // 时间
        content: "", // 内容
      },
      rules2: {
        title: [{ required: true, message: "请输入标题", trigger: "blur" }],
        month: [{ required: true, message: "请选择时间", trigger: "blur" }],
        content: [{ required: true, message: "请输入内容", trigger: "blur" }],
      },
      // 富文本自定义
      editorOption: {
        placeholder: "请输入内容",
        modules: {
          toolbar: {
            container: [
              ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
              [{ indent: "-1" }, { indent: "+1" }], // 缩进
              ["image"],
              ["clean"], //清除字体样式
            ],
            handlers: {
              image: function (value) {
                if (value) {
                  // 调用element的图片上传组件
                  document.querySelector(".avatar-uploader input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
      },
      title: "",
      loading: false,
    };
  },
  mounted() {
    this.getData();
    this.getData2();
  },
  methods: {
    // 获取活动策划列表数据
    async getData() {
      this.loading = true;
      let params = {
        curPage: this.curPage,
        pageSize: this.pageSize,
        startTime: this.startTime,
        endTime: this.endTime,
      };
      let res = await this.$axios({
        url: "/diseaseRight/eventPlanning/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("获取 活动策划列表数据 失败");
      }
      this.loading = false;
    },
    // 添加活动策划
    addEventPlanning(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          let res = await this.$axios({
            method: "post",
            url: "/diseaseRight/eventPlanning/save",
            headers: {
              "Admin-Token": sessionStorage.getItem("token"),
            },
            data: this.form,
          });
          // console.log(res);
          if (res.data.success) {
            this.handleCurrentChange(1);
            this.$message.success("添加成功!");
          } else {
            this.$message.error("添加失败!");
          }
        } else {
          console.log("提交失败!!");
          return false;
        }
      });
    },
    // 修改活动策划
    amendEventPlanning(row) {
      this.form = { ...row };
      this.dialogFormVisible2 = true;
    },
    // 修改活动策划请求
    async hangdleAmendEventPlanning() {
      this.dialogFormVisible2 = false;
      let res = await this.$axios({
        method: "put",
        url: "/diseaseRight/eventPlanning/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("修改失败!");
      }
    },
    // 删除活动策划
    deleteEventPlanning(id) {
      this.$confirm("确定删除吗?", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(async () => {
          let res = await this.$axios({
            method: "delete",
            url: "/diseaseRight/eventPlanning/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);
    },
    // 策划内容整理参数
    handleCurrentChange(val) {
      this.curPage = val;
      this.getData();
    },

    // 获取月度小结列表数据
    async getData2() {
      this.loading = true;
      let params = {
        curPage: this.curPage2,
        pageSize: this.pageSize2,
        month: this.select_datetime2,
      };
      let res = await this.$axios({
        url: "/diseaseRight/eventPlanningMonthSummary/list",
        method: "get",
        params,
      });
      // console.log(res);
      if (res.data.success) {
        this.tableData2 = res.data.data.list;
        this.totalCount2 = res.data.data.totalCount;
      } else {
        console.log("获取 月度小结列表数据 失败");
      }
      this.loading = false;
    },
    // 添加月度小结按钮回调
    handleAdd() {
      this.dialogFormVisible3 = true;
      this.title = "添加";
      this.$nextTick(() => {
        this.$refs.form2.resetFields();
        this.form2 = {
          title: "",
          month: "",
          content: "",
        };
      });
    },
    // 编辑按钮回调
    editNodulus(row) {
      this.form2 = { ...row };
      this.dialogFormVisible3 = true;
      this.title = "编辑";
    },
    // 删除按钮回调
    deleteNodulus(row) {
      this.$confirm("确定删除吗?", "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(async () => {
          let res = await this.$axios({
            method: "delete",
            url: "/diseaseRight/eventPlanningMonthSummary/delete",
            headers: {
              "Admin-Token": sessionStorage.getItem("token"),
            },
            data: [row.id],
          });
          // console.log(res);
          if (res.data.success) {
            this.$message.success("删除成功");
            let totalPage = Math.ceil((this.totalCount2 - 1) / this.pageSize2);
            let currentPage =
              this.curPage2 > totalPage ? totalPage : this.curPage2;
            this.curPage2 = currentPage < 1 ? 1 : currentPage;
            this.getData2();
          } else {
            this.$message.error("删除失败!");
          }
        })
        .catch(() => {
          this.$message.info("已取消");
        });
    },
    // 添加或编辑 月度小结 请求
    handleAddOrUpdata(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.dialogFormVisible3 = false;
          if (this.form2.id) {
            // 编辑请求
            let res = await this.$axios({
              method: "put",
              url: "/diseaseRight/eventPlanningMonthSummary/update",
              headers: {
                "Admin-Token": sessionStorage.getItem("token"),
              },
              data: this.form2,
            });
            // console.log(res);
            if (res.data.success) {
              this.getData2();
              this.$message.success("编辑成功!");
            } else {
              this.$message.error(res.data.message);
            }
          } else {
            // 添加请求
            let res = await this.$axios({
              method: "post",
              url: "/diseaseRight/eventPlanningMonthSummary/save",
              headers: {
                "Admin-Token": sessionStorage.getItem("token"),
              },
              data: this.form2,
            });
            // console.log(res);
            if (res.data.success) {
              this.handleCurrentChange2(1);
              this.$message.success("添加成功!");
            } else {
              this.$message.error(res.data.message);
            }
          }
        } else {
          console.log("提交失败!!");
          return false;
        }
      });
    },
    // 月度小结换页逻辑
    changeCurPage2(val) {
      this.handleCurrentChange2(val);
    },
    // 月度小结整理参数
    handleCurrentChange2(val) {
      this.curPage2 = val;
      this.getData2();
    },
    // 富文本插入图片请求
    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) {
        // 获取富文本组件实例
        let quill = this.$refs.QuillEditor.quill;
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, "image", res.data.data.showUrl);
        // 调整光标到最后
        quill.setSelection(length + 1);
        this.$message.success("图片插入成功!");
      } else {
        this.$message.error("图片插入失败!");
      }
    },
  },
};
</script>

<style scoped>
.first-row {
  display: flex;
  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;
}
.pagination_smoke {
  text-align: center;
}
</style>