<template>
  <div class="fullHeight whiteBlock">
    <div class="pt_15 px_15">
      <!-- 党员活动 -->
      <el-form :inline="true" ref="searchForm" :model="searchForm" size="medium">
        <el-form-item label="标题">
          <el-input v-model="searchForm.title" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="下发部门" prop="issueDepartment">
          <el-select-v2
            :options="departmentNoticeList"
            value-key="data"
            label-key="name"
            v-model="searchForm.issueDepartment"
            :placeholder="$t('message.personnelPosition.please_select')"
            filterable
          ></el-select-v2>
        </el-form-item>
        <el-form-item label="时间" prop="time">
          <el-date-picker
            @blur="isStartOrEndMonth"
            v-model="searchForm.time"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" plain @click="getList">{{
            $t("message.energyManage.waybill.query")
          }}</el-button>
          <el-button type="warning" plain @click="refresh">{{
            $t("message.deviceManage.refresh")
          }}</el-button>
          <el-button
            v-permission="{
              key: 'add',
              menuPath: '/project/safeSame/noticeAnnouncement',
            }"
            type="primary"
            size="medium"
            @click="add"
            >新增</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="table_wrap whiteBlock">
      <el-table class="tables" :data="List">
        <el-table-column type="index" label="序号" align="center"></el-table-column>
        <!-- <el-table-column prop="image" align="center" label="图片">
              <template slot-scope="scope">
                <img
                  :preview="scope.row.file[0] ? scope.row.file[0].url : []"
                  :src="scope.row.file[0] ? scope.row.file[0].url : []"
                  alt=""
                  :width="$fontSize(50)"
                />
              </template>
            </el-table-column> -->
        <el-table-column prop="title" align="center" label="标题"></el-table-column>
        <el-table-column
          prop="issueDepartmentName"
          align="center"
          label="下发部门"
        ></el-table-column>
        <el-table-column
          prop="uploaderName"
          align="center"
          label="上传人"
        ></el-table-column>
        <el-table-column prop="uploadTime" align="center" label="时间"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <div class="tableBtns">
              <div
                v-permission="{
                  key: 'detail',
                  menuPath: '/project/safeSame/noticeAnnouncement',
                }"
                class="operationText"
                @click.stop="showDetailFn(scope.row)"
              >
                <i class="el-icon-tickets el-icon-tickets_up"></i>
                <span>详情</span>
              </div>
              <div
                v-permission="{
                  key: 'edit',
                  menuPath: '/project/safeSame/noticeAnnouncement',
                }"
                @click.stop="edit(scope.row)"
                class="operationText"
              >
                <img src="@/assets/images/icon-edit.png" class="w_15 h_15" />
                <span>编辑</span>
              </div>
              <div
                v-permission="{
                  key: 'delete',
                  menuPath: '/project/safeSame/noticeAnnouncement',
                }"
                @click.stop="deleteDev(scope.row)"
                class="operationText"
              >
                <img src="@/assets/images/icon-delete.png" class="w_15 h_15" />
                <span>删除</span>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="pagerBox"
        @size-change="SizeChange"
        @current-change="CurrentChange"
        :current-page="pagInfo.pageNo"
        :page-sizes="$store.state.PAGESIZRS"
        :page-size="pagInfo.pageSize"
        layout="total, sizes, prev, pager, next"
        :total="Number(pagInfo.total)"
        background
      ></el-pagination>
    </div>
    <!-- 新增 -->
    <el-dialog
      :modal-append-to-body="false"
      :title="title"
      :visible.sync="dialogShow"
      @close="close"
      class="dialog_w1200"
    >
      <div class="dialog_content">
        <el-form
          class="flex_direction"
          size="medium"
          :model="addEditForm"
          ref="addEditForm"
          :rules="addEditRules"
          :label-width="$px2rem(80)"
          :inline="true"
        >
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="addEditForm.title"
              class="w_1000"
              placeholder="请输入标题"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="合作单位" prop="enterpriseIds">
                  <el-select multiple v-model="addEditForm.enterpriseIds"
                    :placeholder="$t('message.personnelPosition.please_select')" filterable>
                    <el-option :label="item.enterpriseName" :value="item.id" v-for="(item, index) in cooperatorList"
                      :key="index">
                    </el-option>
                  </el-select>
                </el-form-item> -->
          <el-form-item label="内容" prop="content" class="line_h_140">
            <quill-editor
              class="ql-editor w_1000 ml_12f mt_20f"
              v-model="addEditForm.content"
              ref="myQuillEditor"
              :options="editorOption"
              @blur="onEditorBlur($event)"
              @focus="onEditorFocus($event)"
              @change="onEditorChange($event)"
            >
            </quill-editor>
          </el-form-item>
          <el-form-item label="配置" prop="showHome">
            <el-switch
              v-model="addEditForm.showHome"
              active-color="#13ce66"
              inactive-color="#ff4949"
            ></el-switch>
            {{ addEditForm.showHome ? "首页显示" : "专题页显示" }}
          </el-form-item>
          <el-form-item label="下发部门" prop="issueDepartment">
            <el-select-v2
              :options="departmentNoticeList"
              value-key="data"
              label-key="name"
              v-model="addEditForm.issueDepartment"
              :placeholder="$t('message.personnelPosition.please_select')"
              filterable
            ></el-select-v2>
          </el-form-item>
          <el-form-item label="上传附件" class="line_h_140">
            <el-upload
              :file-list="fileUplodList"
              :on-success="(res, file) => handleSuccess(res, file)"
              :on-remove="(file, fileList) => handleRemove(file, fileList)"
              :on-exceed="handleExceed"
              class="upload-demo"
              name="files"
              drag
              :action="$store.state.UPLOADURL"
              multiple
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </el-form-item>
          <el-form-item label="时间" prop="uploadTime">
            <el-date-picker
              v-model="addEditForm.uploadTime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="选择日期时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button
            class="cancleBtn"
            @click="dialogShow = false"
            icon="el-icon-circle-close"
            size="medium"
            >取消
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-circle-check"
            @click="submit"
            size="medium"
            >确认
          </el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 详情 -->
    <el-dialog
      :modal-append-to-body="false"
      title="详情"
      :visible.sync="dialogContent"
      class="dialog_w1200"
    >
      <div class="p_10_80">
        <h1 style="text-align: center">{{ detailData.title }}</h1>
        <div class="detailHeader">
          <span>{{ detailData.uploadTime }}</span>
        </div>
        <div class="detailContent">
          <div
            class="ql-editor"
            style="white-space: pre-wrap"
            v-html="detailData.content"
          ></div>
          <div class="preview_box" v-for="item in detailData.fileUrl" :key="item.uid">
            <el-image :src="setFileImg(item)" />
            <span class="download" @click="handlePreview(item)">{{ item.name }}</span>
          </div>
        </div>
        <div class="dialog-footer">
          <el-button
            type="primary"
            icon="el-icon-circle-check"
            @click="dialogContent = false"
            size="medium"
            >确认
          </el-button>
        </div>
      </div>
    </el-dialog>
    <RoutingPopup
      v-if="routingInfo.routFlag"
      @fatherMethodRout="fatherMethodRout"
      :routingInfo="routingInfo"
    />
  </div>
</template>
<script>
import VueQuillEditor from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import {
  getHomeNoticePageApi,
  addHomeNoticeConfigApi,
  editHomeNoticeConfigApi,
  deleteHomeNoticeConfigApi,
} from "@/assets/js/api/configManage";
import { getDictionaryItemApi } from "@/assets/js/api/companyDiagram.js";
import { getCooperatorListApi } from "@/assets/js/api/cooperationUnit";
import { isJSON } from "@/util/nowDate";
import dayjs from "dayjs";
import { encode } from "js-base64";
export default {
  components: {
    VueQuillEditor,
  },
  mounted() {
    this.getDepartmentNoticeList();
    this.getList();
    this.getCooperatorList();
  },
  data() {
    return {
      routingInfo: {
        routFlag: false,
        routName: "",
      },
      pagInfo: {
        pageNo: 1, //页数
        pageSize: 10, //条数
        total: 0, //总条数
      },
      detailData: {},
      dialogContent: false,
      current: -1,
      title: "",
      dialogShow: false,
      List: [],
      addEditForm: {
        title: "",
        content: "",
        file: "",
        uploader: "",
        showHome: false,
        issueDepartment: "1",
        uploadTime: "",
        enterpriseIds: [],
      },
      addEditRules: {
        title: [
          {
            required: true,
            message: "必填",
            trigger: "blur",
          },
        ],
        content: [
          {
            required: true,
            message: "必填",
            trigger: "blur",
          },
        ],
        enterpriseIds: [
          {
            required: true,
            message: "必选",
            trigger: "change",
          },
        ],
      },
      searchForm: {
        title: "",
        time: "",
        issueDepartment: "",
        currentMonthStart: "",
        currentMonthEnd: "",
      },
      fileUplodList: [],
      editorOption: {
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
            ["blockquote", "code-block"], //引用，代码块

            [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小
            [{ list: "ordered" }, { list: "bullet" }], //列表
            [{ script: "sub" }, { script: "super" }], // 上下标
            [{ indent: "-1" }, { indent: "+1" }], // 缩进
            [{ direction: "rtl" }], // 文本方向

            [{ size: ["small", false, "large", "huge"] }], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6, false] }], //几级标题

            [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            [{ font: [] }], //字体
            [{ align: [] }], //对齐方式

            ["clean"], //清除字体样式
            ["image"], //上传图片、上传视频
          ],
        },
        theme: "snow",
      },
      cooperatorList: [],
      whichModule: 2,
      departmentNoticeList: [],
    };
  },
  methods: {
    //获取列表数据
    getCooperatorList() {
      let data = {
        projectSn: this.$store.state.projectSn,
        pageNo: 1,
        pageSize: -1,
        // enterpriseTypeId: this.enterpriseTypeSelectId,
      };
      getCooperatorListApi(data).then((res) => {
        if (res.code == 200) {
          this.cooperatorList = res.result.records;
        }
      });
    },
    onEditorBlur() {
      // 失去焦点事件
    },
    onEditorFocus() {
      // 获得焦点事件
    },
    onEditorChange() {
      this.$refs.addEditForm.clearValidate();

      // 内容改变事件
    },
    //显示检查详细弹框
    showDetailFn(row) {
      this.detailData = row;
      this.dialogContent = true;
    },
    handleExceed() {
      this.$message.warning("文件超出最大限制,请删除上份文件!");
    },
    // 删除文件
    handleRemove(file, fileList) {
      this.fileUplodList = fileList;
    },
    handleSuccess(res, file, type) {
      if (res.status == "SUCCESS") {
        this.fileUplodList.push({
          name: file.name,
          url: this.$store.state.FILEURL + file.response.data[0].imageUrl,
        });
      }
    },
    // 预览
    handlePreview(row) {
      console.log(row);
      const url = row.url.includes("http://")
        ? row.url
        : this.$store.state.FILEURL + row.url;
      let src = encode(url);
      window.open(`${this.$store.state.PREVIEWURL}?url=${encodeURIComponent(src)}`);
    },
    setFileImg(row) {
      const extendName = row.name.substring(row.name.lastIndexOf(".") + 1).toLowerCase();
      if (!this.$store.state.fileImgTypeList.includes(extendName)) {
        //  无法识别文件类型的文件
        return this.$store.state.fileImgMap.unknown;
      } else if (["jpg", "png", "jpeg", "gif"].includes(extendName)) {
        // 图片类型，直接显示缩略图
        return row.url;
      } else {
        //  可以识别文件类型的文件
        return this.$store.state.fileImgMap[extendName];
      }
    },
    isStartOrEndMonth(event) {
      this.searchForm.currentMonthStart = dayjs(this.searchForm.time[0]).format(
        "YYYY-MM-DD"
      );
      this.searchForm.currentMonthEnd = dayjs(this.searchForm.time[1]).format(
        "YYYY-MM-DD"
      );
    },
    //查询数据
    getList() {
      getHomeNoticePageApi({
        projectSn: this.$store.state.projectSn,
        title: this.searchForm.title,
        issueDepartment: this.searchForm.issueDepartment,

        uploadTime_begin: this.searchForm.currentMonthStart,
        uploadTime_end: this.searchForm.currentMonthEnd,
        pageNo: this.pagInfo.pageNo,
        pageSize: this.pagInfo.pageSize,
        whichModule: this.whichModule,
      }).then((result) => {
        if (result.success) {
          //   result.result.records.map(item => {
          //     if (item.file.includes('[')) {
          //       item.file = JSON.parse(item.file);
          //       if (item.file.length !== 0 && !item.file[0].url.includes(this.$store.state.FILEURL)) {
          //         item.file[0].url = this.$store.state.FILEURL + item.file[0].url;
          //       }
          //     } else {
          //       let url = item.file;

          //       if (url.length !== 0 && !url.includes(this.$store.state.FILEURL)) {
          //         item.file = [{}];
          //         item.file[0].url = this.$store.state.FILEURL + url;
          //       }
          //     }
          //   });
          this.List = result.result.records.map((item) => {
            return {
              ...item,
              fileUrl:
                isJSON(item.fileUrl) && JSON.parse(item.fileUrl) instanceof Array
                  ? JSON.parse(item.fileUrl)
                  : [],
            };
          });
          this.pagInfo.total = result.result.total;
          console.log(" this.List", this.List);
        }
      });
    },
    //通知公告的下发部门
    getDepartmentNoticeList() {
      getDictionaryItemApi({
        dictionaryEncoding: "project_home_notice_department",
      }).then((res) => {
        if (res.result.length > 0) {
          this.departmentNoticeList = res.result;
        }
      });
    },
    linkRouteWorkSpace() {
      this.routingInfo.routFlag = true;
      this.routingInfo.routName = "安全待办通知公告";
    },
    fatherMethodRout() {
      this.routingInfo.routFlag = false;
    },
    add() {
      if (this.$store.state.userInfo.accountType == 6) {
        this.linkRouteWorkSpace();
        return;
      }
      this.title = "新增";
      this.dialogShow = true;
      this.fileUplodList = [];
      this.close();
    },

    edit(obj) {
      this.title = "编辑";
      this.dialogShow = true;
      this.addEditForm = JSON.parse(JSON.stringify(obj));
      // this.addEditForm.enterpriseIds = obj.enterpriseIds.split(",");
      this.fileUplodList = obj.fileUrl;
      this.addEditForm.showHome = params.showHome == 1 ? true : false;
    },
    submit() {
      //   if (this.fileUplodList.length == 0) {
      //     this.$message.error('请上传图片');
      //     return false;
      //   }
      let params = JSON.parse(JSON.stringify(this.addEditForm));
      params.projectSn = this.$store.state.projectSn;
      params.whichModule = this.whichModule;
      params.fileUrl = JSON.stringify(this.fileUplodList);
      params.showHome = params.showHome ? 1 : 2;
      // params.enterpriseIds = params.enterpriseIds.join(",");
      this.$refs.addEditForm.validate((valid) => {
        if (valid) {
          if (this.title == "新增") {
            addHomeNoticeConfigApi(params).then((result) => {
              if (result.success) {
                this.$message.success(result.message);
                this.getList();
              }
            });
          } else if (this.title == "编辑") {
            editHomeNoticeConfigApi(params).then((result) => {
              if (result.success) {
                this.$message.success(result.message);
                this.getList();
              }
            });
          }
          this.dialogShow = false;
        } else {
          return false;
        }
      });
    },
    deleteDev(obj) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteHomeNoticeConfigApi({ id: obj.id }).then((res) => {
            if (res.success) {
              this.getList();
              this.$message({
                type: "success",
                message: "删除成功!",
              });
            } else {
              this.$message({
                type: "error",
                message: res.message,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    close() {
      this.fileUplodList = [];
      this.addEditForm = {
        title: "",
        content: "",
        fileUrl: "",
        uploader: this.$store.state.userInfo.userId,
        showHome: false,
        issueDepartment: "1",
        uploadTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
        enterpriseIds: [],
      };
      this.$nextTick(() => {
        this.$refs.addEditForm.clearValidate();
      });
    },
    SizeChange(val) {
      this.pagInfo.pageSize = val;
      this.getList();
    },
    CurrentChange(val) {
      this.pagInfo.pageNo = val;
      this.getList();
    },
    refresh() {
      this.searchForm = {};
      this.searchForm.currentMonthStart = "";
      this.searchForm.currentMonthEnd = "";
      this.pagInfo.pageNo = 1; //页数
      this.pagInfo.pageSize = 10; //条数
      this.getList();
    },
  },
};
</script>
<style lang="less" scoped>
.download {
  color: #409eff;
  cursor: pointer;
}
.detailContent {
  .preview_box {
    display: flex;
    align-items: center;
  }
  .preview_box:not(:first-child) {
    margin-top: 10px;
  }
  /deep/ img {
    width: 100%;
  }
  .el-image {
    width: 30px;
    height: 30px;
  }
}
.detailHeader {
  text-align: center;
  padding: 20px;

  span {
    color: #ccc;
    font-size: 12px;
    margin-right: 20px;
  }
}
</style>
