<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否发布" prop="status" >
        <el-select v-model="queryParams.deptId" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in statusList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ehsNoticeMessage:ehsNoticeMessage:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['ehsNoticeMessage:ehsNoticeMessage:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['ehsNoticeMessage:ehsNoticeMessage:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['ehsNoticeMessage:ehsNoticeMessage:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ehsNoticeMessageList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
   <!--   <el-table-column label="主键" align="center" prop="noticeMessageId" />-->
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="任务模板" align="center" prop="fileTempOriginalName" v-if ="taskShow" >
        <template slot-scope="scope">
          <span v-for="(item, index) in scope.row.fileTempName.split(',')" :key="index" >
            <el-link type="primary" @click="downloadFile(scope.row,index)" > {{(scope.row.fileTempOriginalName=='' ||scope.row.fileTempOriginalName==null)?"": scope.row.fileTempOriginalName.split(",")[index] }} </el-link>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="提交状态" align="center" prop="status" >
        <template slot-scope="scope">
          <span> {{ statusList[scope.row.fileState].label }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否阅读" align="center" prop="isRead" >
      <template slot-scope="scope">
        <span> {{ scope.row.isRead==0?"未阅读":"已阅读"}}</span>
      </template>
      </el-table-column>
      <el-table-column label="通知时间" align="center" prop="createTime"  />
      <el-table-column label="上报文件" align="center" prop="originalName" >
        <template slot-scope="scope">
          <el-link type="primary" @click="downloadDeptFile(scope.row)" > {{(scope.row.originalName=='' ||scope.row.originalName==null)?"": scope.row.originalName }} </el-link>
        </template>
      </el-table-column>
      <!--<el-table-column label="0不是全部，1全部企业" align="center" prop="allDept" />-->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetail(scope.row)"
            v-hasPermi="['ehsNoticeMessage:ehsNoticeMessage:detail']"
          >阅读</el-button>
          <el-button v-show="scope.row.fileState==0 && scope.row.messageFileId==null"
                     size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handlefileUpload(scope.row)"
                     v-hasPermi="['ehsNoticeMessage:ehsNoticeMessage:uploadFile']"
          >上传附件</el-button>
          <el-button v-show="scope.row.fileState==0 && scope.row.messageFileId!=null"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDeleteFile(scope.row)"
            v-hasPermi="['ehsNoticeMessage:ehsNoticeMessage:deleteFile']"
          >删除附件</el-button>
          <el-button v-show="scope.row.fileState!=1 && scope.row.messageFileId!=null"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleSubmitFile(scope.row)"
            v-hasPermi="['ehsNoticeMessage:ehsNoticeMessage:submitFile']"
          >提交监管平台</el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改内部公告对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
<!--        <el-form-item label="内容">
          <editor v-model="form.displayContent" :min-height="192"/>
        </el-form-item>-->

        <el-form-item label="部门" prop="deptList">
          <el-checkbox v-model="form.allDept">全部企业</el-checkbox>
          <el-select  v-model="form.deptList" multiple collapse-tags
            style="margin-left: 20px;" placeholder="请选择">
            <el-option
              v-for="dict in allDeptList"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="文件下载列表" prop="fileName">
          <file-upload v-model="form.fileName"  fileType=""/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="openDetail" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
            {{form.title}}
        </el-form-item>
        <el-form-item label="内容">
          <template slot-scope="scope">
            <span   v-html="form.displayContent">  </span>
          </template>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          {{form.remark}}
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelDetail">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 文件上传 -->
    <el-dialog title="文件上传" :visible.sync="openFile" width="500px" append-to-body>
      <file-upload v-model="form.fileName"  fileType=""/>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="fileSave">确 定</el-button>
        <el-button @click="cancelFile">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEhsNoticeMessageAdmin,listEhsNoticeMessage, getEhsNoticeMessage, delEhsNoticeMessage, addEhsNoticeMessage,
    updateEhsNoticeMessage,issueNews,detailEhsNoticeMessage } from "@/api/ehs/ehsNoticeMessage";
import {listAllDept2 } from "@/api/system/dept";
import {delEhsNoticeMessageFile,addEhsNoticeMessageFile,updateEhsNoticeMessageFile } from "@/api/ehs/ehsNoticeMessageFile";
export default {
  name: "EhsNoticeMessage",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 内部公告表格数据
      ehsNoticeMessageList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //是否发布
      isIssue:false,
      //阅读
      openDetail:false,
      //文件上传
      openFile:false,
      //当前通知id
      curNoticeMessageId:"",
      taskShow:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        displayContent: null,
        fileName: null,
        status: null,
        readDeptId: null,
        mesgType: this.$route.query.noticeType,
        deptList: null,
        allDept: null,
        createDeptId: null,
        deptId: null,
        createUserId: null,
        updateUserId: null
      },
      statusList: [{
        value: '0',
        label: '未提交',
      }, {
        value: '1',
        label: '已提交'
      }],
      //所有部门列表字典
      allDeptList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getListAllDept();
    this.taskShow = this.$route.query.noticeType==1 ?true :false; //=0 消息，=1临时任务
  },
  methods: {
    /** 查询内部公告列表 */
    getList() {
        this.loading = true;
        listEhsNoticeMessage(this.queryParams).then(response => {
        this.ehsNoticeMessageList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 单位信息列表 */
    getListAllDept() {
      console.log(this.$store.state.user.deptId);
      this.loading = true;
      listAllDept2().then(response => {
        this.allDeptList = response.data;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cancelDetail() {
      this.openDetail = false;
    },
    cancelFile() {
      this.openFile = false;
    },
    // 表单重置
    reset() {
      this.form = {
        noticeMessageId: null,
        title: null,
        displayContent: null,
        fileName: null,
        status: null,
        readDeptId: null,
        mesgType: this.$route.query.noticeType,
        deptList: null,
        allDept: null,
        createDeptId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        deptId: null,
        createUserId: null,
        updateUserId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.noticeMessageId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const noticeMessageId = row.noticeMessageId || this.ids
      getEhsNoticeMessage(noticeMessageId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.noticeMessageId != null) {
            updateEhsNoticeMessage(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEhsNoticeMessage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const noticeMessageIds = row.noticeMessageId || this.ids;
      this.$modal.confirm('是否确认删除内部公告编号为"' + noticeMessageIds + '"的数据项？').then(function() {
        return delEhsNoticeMessage(noticeMessageIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ehsNoticeMessage/ehsNoticeMessage/export', {
        ...this.queryParams
      }, `ehsNoticeMessage_${new Date().getTime()}.xlsx`)
    },
    /** 发布 */
    handleDelete(row) {
      this.$modal.confirm('是否确认发布此通知？').then(function() {
        return issueNews({"noticeMessageId":row.noticeMessageId});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("发布成功");
      }).catch(() => {});
    },
    /** 阅读 */
    handleDetail(row) {
      detailEhsNoticeMessage(row.noticeMessageId).then(response => {
        this.form = response.data;
        this.openDetail = true;
        this.title = "阅读消息通知";
        this.getList();
      });
  },
    /** 提交 */
    handleSubmitFile(row) {
      this.$modal.confirm('是否确认提交？').then(function() {
        console.log()
        return updateEhsNoticeMessageFile({"id":row.messageFileId,"state":1});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("提交成功");
      }).catch(() => {});
    },
    handlefileUpload(row) {
      this.openFile = true;
      this.curNoticeMessageId = row.noticeMessageId
    },
    /** 删除文件按钮操作 */
    handleDeleteFile(row) {
      this.$modal.confirm('是否确认删除文件？').then(function() {
        return delEhsNoticeMessageFile(row.messageFileId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    fileSave(row){
      console.log(this.form.fileName)
      //    /profile/upload/2023/12/07/DCS控制系统_20231207142444A003.png,/profile/upload/2023/12/07/d138c31525828b6641a65f518fd9756_20231207142444A004.jpg
      let fileTemp = this.form.fileName.split(",");
      let oFile = [];
      for(let i=0;i<fileTemp.length ;i++){
        let f = fileTemp[i].split("/");
        let f1 = f[f.length-1].split("_")[0];
        let f2 = f[f.length-1].split(".")[1];
        oFile.push(f1+"."+f2);
      }
      let fileInfo = {};
      fileInfo.noticeMessageId = this.curNoticeMessageId ;
      fileInfo.originalName =  oFile.join(",");
      fileInfo.fileName =  this.form.fileName;
      addEhsNoticeMessageFile(fileInfo).then(response => {
        this.$modal.msgSuccess("上传文件成功");
        this.openFile = false;
        this.getList();
      });
    },
    downloadFile(row,index){
      this.$download.saveAs(`${process.env.VUE_APP_BASE_API}${row.fileTempName.split(",")[index]}`,`${row.fileTempOriginalName.split(",")[index]}`);
    },
    downloadDeptFile(row){
      this.$download.saveAs(`${process.env.VUE_APP_BASE_API}${row.fileName}`,`${row.originalName}`);
    },
  }
};
</script>
