<template>
  <el-card class="home">
    <el-row :gutter="20">
      <el-col :span="4">
        <el-input
          v-model="queryData.keyworld"
          placeholder="请输入关键词进行筛选"
          clearable
        />
      </el-col>
      <el-button type="primary" class="button-new" @click="flashTableData"
        >查询</el-button
      >
      <el-button @click="restTableData">重置</el-button>
      <div style="float: right">
        <el-button
          size="mini"
          type="text"
          icon="el-icon-delete"
          class="button-text-new"
          @click="deleteData"
          >批量删除</el-button
        >
        <el-button
          type="primary"
          class="button-new"
          @click="addDataDialogVisabled = true"
          >动态发布</el-button
        >
      </div>
    </el-row>

    <el-row style="margin-top: 20px">
      <el-table :data="tableData" border @selection-change="tableChange">
        <el-table-column
          width="60"
          type="selection"
          align="center"
        ></el-table-column>
        <!--  全选 -->
        <el-table-column
          label="序号"
          width="60"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column label="动态标题" prop="title">
          <template slot-scope="scope">
            <div class="boxtitle">
              {{ scope.row.title }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="内容" prop="content">
          <template slot-scope="scope">
            <div class="boxcontent">
              {{ scope.row.content }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="图片地址" prop="imageUrl"></el-table-column>
        <el-table-column
          label="创建时间"
          prop="createDate"
          sortable
        ></el-table-column>
        <el-table-column width="200" label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="openEditDialog(scope.row)"
              type="text"
              icon="el-icon-setting"
              class="button-text-new"
              >编辑</el-button
            >
            <!-- <el-button size="mini" type="success" icon="el-icon-plus"
              >新增图片</el-button
            > -->
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              class="button-text-new"
              @click="deleteData(scope.row)"
              >删除</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              class="button-text-new"
              @click="openPreviewData(scope.row)"
              >预览</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 --> </el-row
    ><el-pagination
      style="margin-top: 20px; text-align: center"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryData.pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="queryData.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="queryData.total"
    >
    </el-pagination>

    <!-- 新增项目 -->
    <el-dialog
      :close-on-click-modal="false"
      title="新增项目"
      :visible.sync="addDataDialogVisabled"
      @close="addDataDialogClose"
    >
      <el-form
        ref="addDataFormRef"
        :model="addDataFrom"
        :rules="addDataFromRules"
        label-width="100"
      >
        <el-form-item prop="title" label="标题">
          <el-input
            v-model="addDataFrom.title"
            autocomplete="off"
            placeholder="标题"
            maxlength="200"
            @input="titleExceed"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item prop="note1" label="摘要">
          <el-input
            v-model="addDataFrom.note1"
            autocomplete="off"
            placeholder="摘要"
            maxlength="1000"
            show-word-limit
            type="textarea"
            @input="noteExceed"
            :rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item prop="content" label="内容">
          <el-input
            v-model="addDataFrom.content"
            autocomplete="off"
            placeholder="内容"
            maxlength="2000"
            @input="contentExceed"
            show-word-limit
            type="textarea"
            :rows="5"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <!-- <el-upload
          class="avatar-uploader"
          :action="fileUploadUrl"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="this.addDataFrom.imageUrl" :src="this.addDataFrom.imageUrl" class="avatar">

          <i v-else class="el-icon-plus avatar-uploader-icon"></i>

        </el-upload> -->

          <el-upload
            ref="addUpload"
            class="upload-demo"
            :action="fileUploadUrl"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-remove="addUploadRemoveFile"
            :on-exceed="handleExceed"
            :on-preview="showView"
            :limit="1"
            list-type="picture"
          >
            <el-button size="small" type="primary" class="button-new"
              >点击上传</el-button
            >
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDataDialogVisabled = false">取 消</el-button>
        <el-button
          type="primary"
          @click="addDataDialogConfirm"
          class="button-new"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <!-- 编辑项目 -->
    <el-dialog
      :close-on-click-modal="false"
      title="编辑项目"
      :visible.sync="editDataDialogVisabled"
      @close="editDataDialogClose"
    >
      <el-form
        ref="editDataFormRef"
        :model="eidtDataForm"
        :rules="eidtDataFromRules"
        label-width="100"
      >
        <el-form-item prop="title" label="标题">
          <el-input
            v-model="eidtDataForm.title"
            autocomplete="off"
            placeholder="标题"
            maxlength="200"
            @input="titleExceed"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item prop="note1" label="摘要">
          <el-input
            v-model="eidtDataForm.note1"
            autocomplete="off"
            placeholder="摘要"
            maxlength="1000"
            show-word-limit
            type="textarea"
            @input="noteExceed"
            :rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item prop="content" label="内容">
          <el-input
            v-model="eidtDataForm.content"
            autocomplete="off"
            placeholder="内容"
            maxlength="2000"
            show-word-limit
            type="textarea"
            @input="contentExceed"
            :rows="5"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <!-- <el-upload
          class="avatar-uploader"
          :action="fileUploadUrl"
          :show-file-list="false"
          :on-success="eidtHandleAvatarSuccess"
          :before-upload="editBeforeAvatarUpload">
          <img v-if="eidtDataForm.imageUrl" :src="eidtDataForm.imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload> -->
          <el-upload
            ref="editUpload"
            class="upload-demo"
            :action="fileUploadUrl"
            :on-success="eidtHandleAvatarSuccess"
            :before-upload="editBeforeAvatarUpload"
            :limit="1"
            :file-list="editDialogShowFileList"
            :on-remove="editUploadRemoveFile"
            :on-exceed="handleExceed"
            :on-preview="showView"
            list-type="picture"
          >
            <el-button size="small" type="primary" class="button-new"
              >点击上传</el-button
            >
            <div slot="tip" class="el-upload__tip">只能上传图片文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDataDialogVisabled = false">取 消</el-button>
        <el-button
          type="primary"
          @click="eidtDataDialogConfirm"
          class="button-new"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!-- 预览项目 -->
    <el-dialog
      :close-on-click-modal="false"
      title="预览项目"
      :visible.sync="perviewDataDialogVisabled"
      @close="perviewDataDialogClose"
      width="1300px"
      top="10vh"
    >
      <div class="preview-dialog">
        <div class="preview-title">
          <div class="title-text">
            <span>{{ previewData.title }}</span>
          </div>
          <div class="title-time">
            <span>发布时间：</span>
            <span>{{ previewData.updateDate }}</span>
          </div>
        </div>
        <div class="preview-note">
          <span>摘要：</span>
          <span>{{ previewData.note1 }}</span>
        </div>
        <div class="preview-image">
          <img
            width="100%"
            v-if="previewData.imageUrl != ''"
            :src="previewData.imageUrl"
            alt=""
          />
          <img
            width="100%"
            v-else
            src="~@/assets/img/activitiMyWorkDynamics/no-img.png"
            alt=""
          />
        </div>
        <div class="preview-content">
          <span>{{ previewData.content }}</span>
        </div>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisibleImg">
      <img width="100%" :src="previewImg" alt="" />
    </el-dialog>
  </el-card>
</template>

<script>
// @ is an alias to /src
export default {
  data () {
    return {
      fileUploadUrl: window.SITE_CONFIG.apiURL + '/upload',
      // 表格筛选条件对象
      queryData: {
        keyworld: '',
        pageIndex: 1,
        pageSize: 10,
        total: 0
      },
      // 表格数据数组对象
      tableData: [],
      // 新增数据对话框显示隐藏
      addDataDialogVisabled: false,
      // 最大可上传图片数
      maxImageCount: 3,
      // imageUrl: '',
      // 新增数据表单对象
      addDataFrom: {
        title: '',
        note1: '',
        content: '',
        imageUrl: '',
        delFlag: 0
      },
      // 新增数据表单验证对象
      addDataFromRules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        note1: [{ required: true, message: '请输入摘要', trigger: 'blur' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        imageUrl: [
          { required: true, message: '请输入图片地址', trigger: 'blur' }
        ]
      },
      editDataDialogVisabled: false,
      eidtDataForm: {
        title: '',
        note1: '',
        content: '',
        imageUrl: ''
      },
      eidtDataFromRules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        note1: [{ required: true, message: '请输入摘要', trigger: 'blur' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
        imageUrl: [
          { required: true, message: '请输入图片地址', trigger: 'blur' }
        ]
      },
      perviewDataDialogVisabled: false,
      previewData: {
        title: '',
        note1: '',
        content: '',
        imageUrl: '',
        delFlag: 0
      },
      previewImg: '', // 预览图片
      deleteDataArr: [],
      dialogVisibleImg: false
    }
  },
  created () {
    this.getTableData()
  },
  methods: {
    tableChange (val) {
      this.deleteDataArr = val.map((item) => item.id)
      console.log(this.deleteDataArr)
    },
    restTableData () {
      this.queryData.keyworld = ''
      this.getTableData()
    },
    showView (file) {
      this.previewImg = file.url
      this.dialogVisibleImg = true
    },
    getTableData () {
      this.$http
        .get('/workdynamics/page', {
          params: {
            limit: this.queryData.pageSize,
            page: this.queryData.pageIndex,
            name: this.queryData.keyworld
          }
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.tableData = res.data.list
          this.queryData.total = res.data.total
        })
        .catch(() => {})
    },
    flashTableData () {
      this.queryData.pageIndex = 1
      this.getTableData()
    },
    // 分页大小更改
    handleSizeChange (value) {
      this.queryData.pageSize = value
      this.getTableData()
    },
    // 当前索引更改
    handleCurrentChange (val) {
      this.queryData.pageIndex = val
      this.getTableData()
    },
    // 新增数据窗口关闭事件
    addDataDialogClose () {
      this.$refs.addDataFormRef.resetFields()
      this.addDataFrom.imageUrl = ''
      this.$refs.addUpload.clearFiles()
      // this.addDataFrom.imagesFiles = []
      // this.$refs.addDataFromUploadRef.clearFiles()
    },
    editDataDialogClose () {
      this.$refs.editDataFormRef.resetFields()
      this.eidtDataForm.imageUrl = ''
      this.$refs.editUpload.clearFiles()
    },
    // 追加数据
    addDataDialogConfirm () {
      this.$refs.addDataFormRef.validate(async (valid) => {
        if (valid) {
          // console.log("新增新增", this.addDataFrom);
          this.$http
            .post('/workdynamics/insert', this.addDataFrom)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              }
              this.$message.success('新增成功')
              this.addDataDialogVisabled = false
              this.getTableData()
            })
            .catch(() => {})
        } else {
          this.$message.success('表单数据填写不完整')
        }
      })
    },
    // 限定图片
    handleExceed () {
      this.$message({ type: 'error', message: '最多支持一张图片上传' })
    },
    // 限制标题
    titleExceed (str) {
      if (str.length >= 200) {
        this.$message.error('标题文字不能超过200字')
      }
    },
    // 限制内容
    contentExceed (str) {
      if (str.length >= 2000) {
        this.$message.error('内容文字不能超过2000字')
      }
    },
    // 限制摘要
    noteExceed (str) {
      if (str.length >= 1000) {
        this.$message.error('摘要文字不能超过1000字')
      }
    },
    // 删除数据
    deleteData (row) {
      if (this.deleteDataArr.length < 1) {
        this.$message({
            type: 'info',
            message: '请选择要删除的数据'
          })
      }else{
      this.$confirm('此操作将删除当前数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let ids = []
          if(row.id && this.deleteDataArr.length==0){
             ids = [row.id]
          }else{
            ids = this.deleteDataArr
          }
          this.$http
            .delete('/workdynamics/delete', {
              data: ids
            })
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              }
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.getTableData()
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })}
    },
    // 预览工作动态信息
    async openPreviewData (row) {
      console.log('预览预览', row)
      const { data: res } = await this.$http.get(
        `workdynamics/select/${row.id}`
      )

      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }

      this.previewData = res.data

      this.perviewDataDialogVisabled = true
    },
    perviewDataDialogClose () {
      this.perviewDataDialogVisabled = false
    },
    handleAvatarSuccess (res, file) {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }

      this.addDataFrom.imageUrl = res.data
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload (file) {
      const isImage =
        file.type === 'image/jpeg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传头像图片只能是 jpg/png 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    eidtHandleAvatarSuccess (res, file) {
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }

      this.eidtDataForm.imageUrl = res.data
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    editBeforeAvatarUpload (file) {
      const isImage =
        file.type === 'image/jpeg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('上传头像图片只能是 jpg/png 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    async openEditDialog (row) {
      const { data: res } = await this.$http.get(
        `workdynamics/select/${row.id}`
      )

      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }

      this.eidtDataForm = res.data

      this.editDataDialogVisabled = true
    },
    eidtDataDialogConfirm () {
      this.$refs.editDataFormRef.validate(async (valid) => {
        if (valid) {
          console.log(this.eidtDataForm)
          this.$http
            .put('/workdynamics/update', this.eidtDataForm)
            .then(({ data: res }) => {
              if (res.code !== 0) {
                return this.$message.error(res.msg)
              }
              this.$message.success('编辑成功')
              this.editDataDialogVisabled = false
              this.getTableData()
            })
            .catch(() => {})
        } else {
          this.$message.success('表单数据填写不完整')
        }
      })
    },
    addUploadRemoveFile (file, fileList) {
      this.$refs.addUpload.clearFiles()
      this.addDataFrom.imageUrl = ''
    },
    editUploadRemoveFile (file, fileList) {
      this.$refs.editUpload.clearFiles()
      this.eidtDataForm.imageUrl = ''
    }
  },
  computed: {
    editDialogShowFileList () {
      if (this.eidtDataForm.imageUrl) {
        return [
          { name: this.eidtDataForm.imageUrl, url: this.eidtDataForm.imageUrl }
        ]
      }
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .el-checkbox__input.is-checked .el-checkbox__inner,
.el-checkbox__input.is-indeterminate .el-checkbox__inner {
  background-color: #0058e1; //#3E8EF7
  border-color: #0058e1;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.boxtitle {
  width: 100%;
  max-height: 200px;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  word-break: break-all;
}
.boxcontent {
  width: 100%;
  max-height: 200px;
  -webkit-line-clamp: 4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  word-break: break-all;
}
.preview-dialog {
  width: 100%;
  height: 700px;
  overflow: auto;
  padding: 10px 10px;
  /*滚动条样式*/
  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-thumb {
    border-radius: 5;
    background: rgba(0, 0, 0, 0.25);
  }
  &::-webkit-scrollbar-track {
    border-radius: 0;
    background: #f2f2f2;
  }

  .preview-title {
    width: 100%;
    min-height: 90px;
    //margin-top: -40px;
    border-bottom: solid #c6c6c6 1px;
    .title-text {
      text-align: center;
      span {
        font-size: 24px;
        color: #0558e1;
      }
    }
    .title-time {
      width: 100%;
      height: 30px;
      margin-top: 14px;
      text-align: center;
      line-height: 30px;
      span {
        font-size: 16px;
        color: #606266;
      }
    }
  }
  .preview-note {
    width: 100%;
    min-height: 100px;
    text-align: left;
    margin-top: 24px;
    text-indent: 2em;
    span:first-child {
      font-size: 16px;
      color: #606266;
    }
    span:last-child {
      font-size: 16px;
      color: #212121;
      line-height: 30px;
    }
  }
  .preview-image {
    width: 900px;
    //height: 100%;
    //margin-top: 16px;
    padding-top: 5px;
    text-align: center;
    padding-left: 300px;
  }
  .preview-content {
    line-height: 30px;
    text-indent: 2em;
    margin-top: 16px;
    span {
      font-size: 16px;
      color: #212121;
    }
  }
}
.button-new {
  background-color: #0558e1;
  border: none;
}
.button-text-new {
  color: #0558e1;
}
.el-icon-delete {
  color: #0558e1;
}
</style>
