<template>
  <basic-container>
    <!--搜索栏-->
    <el-form size="small" label-position="right" style="padding-left: 10px;padding-right: 10px;" :inline="true">
      <el-row :span="24">
        <el-form-item label="消息标题:">
          <el-input v-model="query.title" placeholder="消息标题" clearable></el-input>
        </el-form-item>

        <el-form-item label="消息类型:">
          <el-select v-model="query.category" placeholder="消息类型" style="width:100%" clearable>
            <el-option v-for="(item,key,index) in newsType" :key="index" :label="item.dictValue" :value="item.dictKey">
            </el-option>
          </el-select>
        </el-form-item>

        <div class="searchBtn">
          <el-button type="primary" size="small" icon="el-icon-search" @click="searchChange1">搜 索</el-button>
          <el-button size="small" icon="el-icon-delete" @click="searchReset1">清 空</el-button>
        </div>
        <!-- </el-col> -->
      </el-row>
    </el-form>
    <!--搜索-->
    <avue-crud :option="option" :table-loading="loading" :data="data" ref="crud" v-model="form"
      :permission="permissionList" @row-del="rowDel" :page.sync="page" :before-open="beforeOpen"
      @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
      @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-view" @click="handleRemarkRead">标记已读</el-button>
        <el-button type="primary" size="small" icon="el-icon-delete" @click="handleDelete">批量删除</el-button>
      </template>
      <template slot-scope="{row}" slot="category">
        <el-tag>{{row.categoryName}}</el-tag>
      </template>
      <template v-slot:contentLabel>
        <div></div>
      </template>
      <template v-slot:contentForm>
        <div v-html="form.content"></div>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
  import { getNotice, getNewsType } from "@/api/desk/notice";
  import { getList, remove, read } from "@/api/tenant/notice";
  import {mapState} from "vuex";

  export default {
    components: {},
    data() {
      return {
        loading: false,
        selectionList: [],
        page: {
          pageSize: 20,
          currentPage: 1,
          total: 0,
        },
        query: {},
        data: [],
        form: {},
        newsType: []
      }
    },
    created() {
      getNewsType().then(res => {
        this.newsType = res.data.data;
      })
    },
    computed: {
      ...mapState({
        loginType: (state) => state.user.userInfo.login_type,
      }),
      ids() {
        let ids = [];
        this.selectionList.forEach((ele) => {
          ids.push(ele.id);
        });
        return ids;
      },
      option() {
        const self = this;
        return {
          height: "auto",
          calcHeight: 30,
          align: "center",
          menuAlign: "center",
          tip: false,
          addBtn: false,
          viewBtn: true,
          delBtn: true,
          editBtn: false,
          excelBtn: false,
          columnBtn: false,
          searchBtn: true,
          searchShow: true,
          searchMenuSpan: 6,
          dialogType: "drawer",
          border: true,
          index: true,
          indexLabel: "序号",
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "消息标题",
              prop: "title",
              display: false,
              // search: true,
            },
            {
              label: "日期",
              prop: "releaseTime",
              type: "date",
              format: "yyyy年MM月dd日",
              display: false,
            },
            {
              label: "消息类型",
              type: "select",
              dicData: self.newsType,
              // dicUrl: "/api/jobslink-api/system/dict/dictionary?code=notice",
              // props: {
              //   label: "dictValue",
              //   value: "dictKey",
              // },
              // dataType: "number",
              display: false,
              slot: true,
              prop: "category",
              // search: true,
              rules: [
                {
                  required: true,
                  message: "请输入通知类型",
                  trigger: "blur",
                },
              ],
            },
            {
              label: "状态",
              prop: "isRead",
              type: "select",
              display: false,
              dicData: [
                {
                  value: 0,
                  label: "未读",
                },
                {
                  value: 1,
                  label: "已读",
                },
              ],
            },
            {
              label: "通知内容",
              prop: "content",
              formslot: true,
              labelslot: true,
              hide: true,
              minRows: 6,
              labelWidth: 0,
              span: 24,
            },
          ],
        }

      }
    },
    watch: {},
    methods: {
      /*删除消息*/
      rowDel(row) {
        const h = this.$createElement;
        this.$confirm(
          h("div", null, [
            h("p", { style: "font-size: 16px" }, "您确定要删除此消息吗? "),
            h("p", { style: "color: red" }, "一旦删除则无法找回"),
          ]),
          {
            type: "warning",
            showClose: false,
            showCancelButton: true,
            confirmButtonText: "确定",
            cancelButtonText: "取消",
          }
        )
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            this.refreshChange();
          })
          .catch(() => { });
      },
      /*批量删除消息*/
      handleDelete() {
        if (this.ids.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        const h = this.$createElement;
        this.$confirm(
          h("div", null, [
            h(
              "p",
              { style: "font-size: 16px" },
              "您确定要批量删除选中的消息吗? "
            ),
          ]),
          {
            type: "warning",
          }
        )
          .then(() => {
            return remove(this.ids.join(","));
          })
          .then(() => {
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            this.refreshChange();
          })
          .catch(() => { });
      },
      /*标记已读*/
      handleRemarkRead() {
        if (this.ids.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        let idList = []
        const h = this.$createElement;
        for (let i = 0; i < this.ids.length; i++) {
          this.data.forEach(ele => {
            if (ele.isRead == 0 && ele.id == this.ids[i])
              idList.push(ele.id)
          })
        }
        if (idList.length == 0) {
          this.$message.error('所选消息为已读状态，请勿重复操作')
        }
        else {
          this.$confirm(
            h("div", null, [
              h(
                "p",
                { style: "font-size: 16px" },
                "您确定要标记选中消息为已读吗? "
              ),
            ]),
            {
              type: "warning",
              showClose: false,
              showCancelButton: true,
            }
          )
            .then(() => {
              return read(idList.join(","));
            })
            .then(() => {
              this.$message({
                type: "success",
                message: "操作成功!",
              });
              this.refreshChange();
            })
            .catch(() => { });
        }
      },
      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page, this.query);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, this.query);
        done();
      },
      searchReset1() {
        this.query = {};
        this.onLoad(this.page, this.query);
      },
      searchChange1() {
        this.page.currentPage = 1;
        this.onLoad(this.page, this.query);
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getNotice(this.form.id).then((res) => {
            const data = res.data.data;
            if (this.form.isRead === 0) {
              read(data.id).then(() => {
                this.$store.commit("NOTICE_READ");
                this.refreshChange();
              });
            }
            this.form = data;
          });
        }
        done();
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      /*刷新本页 带搜索参数*/
      refreshChange() {
        if (this.loginType === 'Type-S') {
          this.$store.dispatch("workGetUnreadCount");
        } else {
          this.$store.dispatch("getUnreadCount");
        }
        this.onLoad(this.page, this.query);
      },
      /*加载数据*/
      onLoad(page, params = {}) {
        this.loading = true;
        var userType = 3
        if (this.loginType === 'Type-T') {
          userType = 1
        } else if (this.loginType === 'Type-S') {
          userType = 3
        }
        getList(
          page.currentPage,
          page.pageSize,
          Object.assign(params, this.query),
          userType
        ).then((res) => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
    },
  };
</script>
<style scoped>
  .el-form-item {
    margin-bottom: 18px;
    padding: 0 10px;
  }

  .searchBtn {
    display: inline-block;
    margin-bottom: 18px;
  }
</style>
