<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.status" 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 label="发布时间" prop="issueTime">
        <el-date-picker
          v-model="daterangeIssueTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :picker-options="pickerOptions"
        ></el-date-picker>
      </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="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="displayContent" >
        <template slot-scope="scope">
          <span   v-html="scope.row.displayContent">  </span>
        </template>
      </el-table-column>--><!-- <el-table-column label="内容" align="center" prop="displayContent" >
        <template slot-scope="scope">
          <span   v-html="scope.row.displayContent">  </span>
        </template>
      </el-table-column>-->
      <el-table-column label="部门列表" align="center" prop="deptName"  style="white-space: pre-wrap;">
        <template slot-scope="scope">
          <span v-html='scope.row.allDept==1 ?"全部": scope.row.deptListName.replace(/;/g ,"<br>")'>  </span>
        </template>
      </el-table-column>
      <el-table-column label="任务模板" align="center" prop="fileTempOriginalName" v-if ="taskShow" >
        <template slot-scope="scope">
          <span v-for="(item, index) in (scope.row.fileTempName==null?'':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.status].label}}</span>
        </template>
      </el-table-column>-->
      <el-table-column label="发布时间" align="center" prop="issueTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.issueTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="已阅读企业数" align="center" prop="readDeptId" >
      <template slot-scope="scope">
        <span> {{scope.row.readDeptId==""?"0":scope.row.readDeptId.split(",").length-1}}</span>
      </template>
      </el-table-column>
      <el-table-column label="已上传数量" align="center" prop="fileCount" />
      <!--<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 v-show="scope.row.status==0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ehsNoticeMessage:ehsNoticeMessage:edit']"
          >修改</el-button>
          <el-button v-show="scope.row.status==0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ehsNoticeMessage:ehsNoticeMessage:remove']"
          >删除</el-button>
          <el-button v-show="scope.row.status==0"
            size="mini"
            type="text"
            icon="el-icon-s-tools"
            @click="handleIssueNews(scope.row)"
            v-hasPermi="['ehsNoticeMessage:ehsNoticeMessage:issueNews']"
          >发布</el-button>
          <el-button v-show="scope.row.status==1"
             size="mini"
             type="text"
             icon="el-icon-s-data"
               @click="handleListFile(scope.row)"
             v-hasPermi="['ehsNoticeMessage:ehsNoticeMessage:total']"
          >统计</el-button>
          <el-button
                     size="mini"
                     type="text"
                     icon="el-icon-tickets"
                     @click="handleDetail(scope.row)"
                     v-hasPermi="['ehsNoticeMessage:ehsNoticeMessage:displayDetail']"
          >显示</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="部门" prop="deptList">
          <el-checkbox v-model="allDeptCheck" @change="allDeptChange">全部部门</el-checkbox>
          <el-select  v-model="form.deptList" multiple collapse-tags v-if = "deptShow"
            style="margin-left: 20px;" placeholder="请选择">
            <el-option
              v-for="de in allDeptList"
              :key="de.deptId"
              :label="de.deptName"
              :value="de.deptId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上报模板" v-if="taskShow">
          <file-upload v-model="form.fileTempName" :noFileType="true" />
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.displayContent" :min-height="192"/>
        </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="openFile" width="500px" append-to-body>
      <el-button type="primary" @click="downAllFile">下载全部附件</el-button>

      <el-table v-loading="loading" :data="ehsNoticeMessageFileList" @selection-change="handleSelectionChange">
          <el-table-column label="部门名称" align="center" prop="deptName" />
          <el-table-column label="上报情况" align="center" prop="originalName" >
            <template slot-scope="scope">
              <span v-if="scope.row.originalName==null">未上报</span>
              <span v-else>
                <el-tooltip class="item" effect="dark" content="点击下载文件" placement="right">
                <el-link type="primary" @click="dload(scope.row)">{{scope.row.originalName}}</el-link>
                </el-tooltip>
              </span>
            </template>
          </el-table-column>
      </el-table>

    <el-pagination
      small
      :page.sync="pageNum"
      :limit.sync="pageSize"
      @pagination="diloagListFile"
      :hide-on-single-page="true"
      :total="total1">
    </el-pagination>

    </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>
  </div>
</template>

<script>
import { listEhsNoticeMessageAdmin,listEhsNoticeMessage, getEhsNoticeMessage, delEhsNoticeMessage, addEhsNoticeMessage,
  updateEhsNoticeMessage,issueNews,displayDetailEhsNoticeMessage } from "@/api/ehs/ehsNoticeMessage";
import {listAllDept2 } from "@/api/system/dept";
import {listFileEhsNoticeMessageFile } from "@/api/ehs/ehsNoticeMessageFile";
export default {
  name: "EhsNoticeMessage",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      totalFileList: 0,//上报统计
      // 内部公告表格数据
      ehsNoticeMessageList: [],
      // 弹出层标题
      title: "",
      openFile:false,//上报统计
      ehsNoticeMessageFileList:[],//上报统计
      downaAllnoticeMessageId:null,//下载全部附件的id
      // 是否显示弹出层
      open: false,
      //是否发布
      isIssue:false,
      //部门列表是否显示
      deptShow:true,
      //全部部门是否选中
      allDeptCheck:false,
      taskShow:false,//临时任务模板上传
      openDetail:false,
      daterangeIssueTime:[],//发布时间
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        displayContent: null,
        fileName: null,
        status: null,
        readDeptId: null,
        deptList: null,
        allDept: null,
        createDeptId: null,
        deptId: null,
        createUserId: null,
        updateUserId: null,
        mesgType: this.$route.query.noticeType,
      },
      statusList: [{
        value: '0',
        label: '未发布',
      }, {
        value: '1',
        label: '已发布'
      }],
      //所有部门列表字典
      allDeptList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      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]);
          }
        }]
      },
      // 弹框分页
      total1:2,
      pageNum: 1,
      pageSize: 6,
    };
  },
  created() {
    this.getList();
    this.getListAllDept();
    this.taskShow = this.$route.query.noticeType==1 ?true :false; //=0 消息，=1临时任务
  },
  methods: {
    // 下载
    dload(row){
      if(!row.fileName)return
      this.$download.saveAs(`${process.env.VUE_APP_BASE_API}${row.fileName}`,`${row.originalName}`)
    },
    /** 查询内部公告列表 */
    getList() {
        this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeIssueTime && '' != this.daterangeIssueTime) {
        this.queryParams.params["beginIssueTime"] = this.daterangeIssueTime[0];
        this.queryParams.params["endIssueTime"] = this.daterangeIssueTime[1];
      }
        listEhsNoticeMessageAdmin(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;
    },
    /** 阅读 */
    handleDetail(row) {
      displayDetailEhsNoticeMessage(row.noticeMessageId).then(response => {
        this.form = response.data;
        this.openDetail = true;
        this.title = "阅读消息通知";
        this.getList();
      });
    },
    // 表单重置
    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,
        fileTempName:null,
        fileTempOriginalName:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.daterangeIssueTime = [];
      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;
        if(this.form.allDept == 1){
          this.allDeptCheck = true;
          this.deptShow = false;
          this.form.deptList = ""
        }else{
          this.form.deptList = this.form.deptList.split(",").map(Number);
          console.log(this.form.deptList);
        }
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {


        if (valid) {
          let ad = this.allDeptCheck ==true ? 1:0;
          this.form.allDept = ad;
          if(this.form.allDept==0)
            this.form.deptList = this.form.deptList.join();
          else
            this.form.deptList = "";
          //文件
          if(this.taskShow == 1){
            if(this.form.fileTempName==null ||this.form.fileTempName==''){
              this.$modal.alert("请选择模板文件");
              return;
            }
            let fileTemp = this.form.fileTempName.split(",");
            let oFile = [];
            for(let i=0;i<fileTemp.length ;i++){
              let f = fileTemp[i].split("/");
              let f1 = f[f.length-1].split("_");
              let fName = [];
              for(let j = 0 ;j< f1.length-1;j++){
                fName.push(f1[j]);
              }
              let fLast = f1[f1.length-1].split(".")
              let f2 =fName.join("_")+"."+ fLast[fLast.length-1];
              oFile.push(f2);
            }
            this.form.fileTempOriginalName =  oFile.join(",");
          }
          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/exportAdmin', {
        ...this.queryParams
      }, `ehsNoticeMessage_${new Date().getTime()}.xlsx`)
    },
    /** 发布 */
    handleIssueNews(row) {
      this.$modal.confirm('是否确认发布此通知？').then(function() {
        return issueNews({"noticeMessageId":row.noticeMessageId});
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("发布成功");
      }).catch(() => {});
    },
    allDeptChange(selection) {
      this.form.deptList = [];
      console.log(selection);
      this.deptShow =(!selection)
      this.allDeptCheck = selection;
    },
    handleListFile(row) {
      this.loading = true;
      this.openFile = true;
      this.downaAllnoticeMessageId = row.noticeMessageId;
      listFileEhsNoticeMessageFile({"noticeMessageId":row.noticeMessageId}).then(response => {
        this.ehsNoticeMessageFileList = response.rows;
        this.totalFileList = response.total;
        this.loading = false;
      })
    },

    // 查询弹框内部分页
    diloagListFile(row){
      this.loading = true;
      this.openFile = true;
      let data = { pageNum : this.pageNum, pageSize: this.pageSize, "noticeMessageId":row.noticeMessageId}
      listFileEhsNoticeMessageFile(data).then(response => {
        this.ehsNoticeMessageFileList = response.rows;
        this.totalFileList = response.total;
        this.total = response.total;
        this.loading = false;
      })
    },
    downloadFile(row,index){
      this.$download.saveAs(`${process.env.VUE_APP_BASE_API}${row.fileTempName.split(",")[index]}`,`${row.fileTempOriginalName.split(",")[index]}`);
    },
    downAllFile(){
      let p =  "/ehsNoticeMessageFile/ehsNoticeMessageFile/downloadlist/" + this.downaAllnoticeMessageId
      console.log(p)
      this.$download.zip(p);
/*      var elt = document.createElement('a');
      elt.setAttribute('href', process.env.VUE_APP_BASE_API + "/downloadlist/" + this.downaAllnoticeMessageId);
      elt.setAttribute('download', "");
      elt.style.display = 'none';
      document.body.appendChild(elt);
      elt.click();
      document.body.removeChild(elt);*/
    },
  }
};
</script>
