<template>
  <div id="containt">
    <el-tabs v-model="activeName" class="tab-box">
      <el-tab-pane :label="$t1('列表')" name="second">
        <div class="tree-box fl">
          <div class="tit"><b>{{ $t1('通知类型') }}</b></div>
          <el-tree
            :props="defaultProps"
            :load="loadNode"
            node-key="notifyType"
            ref="tree"
            highlight-current
            lazy
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            class="tree-list"
            icon-class="el-icon-arrow-down"
          >
            <template #default="{ node, data }">
              <span class="el-tree-node__label">{{ data.notifyTypeName }}(<span
                v-if="data.notifyType"
                :class="{'f-red':notifyTypeNumMap[data.notifyType]>0}">{{
                  countNumStr(notifyTypeNumMap[data.notifyType])
                }}</span>
                <span v-if="!data.notifyType" :class="{'f-red':totalNum>0}">{{ countNumStr(totalNum) }}</span>)</span>
            </template>
          </el-tree>
        </div>
        <label id="labBtn">
          <div class="icon">
            <i class="el-icon-more"></i>
            <i class="el-icon-more"></i>
          </div>
        </label>
        <div class="main-right fr" style="padding-left:6px;">
          <div class="grid-height">
            <vxe-grid ref="table-m1" v-bind="vxeOption" @resizable-change="$vxeTableUtil.onColumnWitchChange"
                      @custom="$vxeTableUtil.customHandle">
              <template #form>
                <div class="clearfix screen-btns">
                  <div class="fl">
                    <base-table-export :option="{ title: $t1('消息通知导出'), targetRef: 'table-m1'}"
                                       :parent-target="_self"/>
                    <vxe-button icon="el-icon-brush" class="button-sty" @click="multiHandleRead" type="text"
                                status="primary"
                                plain>{{ $t1('标记已读') }}
                    </vxe-button>
                  </div>
                  <div class="fr">
                    <vxe-button icon="el-icon-brush" class="button-sty" @click="resetEvent" type="text" status="primary"
                                plain>{{ $t1('重置') }}
                    </vxe-button>
                    <vxe-button status="warning" icon="el-icon-search" class="button-sty" @click="searchEvent">
                      {{ $t1('搜索') }}
                    </vxe-button>
                  </div>
                </div>
                <vxe-form ref="form" class="screen-box" title-width="92px" title-align="right" :data="formData"
                          @submit="searchEvent" @reset="searchEvent">
                  <vxe-form-item :title="$t1('通知类型')+':'">
                    <template v-slot>
                      <el-input v-model="checkNodeData.notifyTypeName" size="small" disabled/>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item :title="$t1('通知内容')+':'" field="content">
                    <template v-slot>
                      <el-input v-model="formData.content" size="small" clearable/>
                    </template>
                  </vxe-form-item>
                  <vxe-form-item :title="$t1('状态')+':'">
                    <template v-slot>
                      <el-select v-model="formData.readed" clearable>
                        <el-option :value="0" :label="$t1('未读')"></el-option>
                        <el-option :value="1" :label="$t1('已读')"></el-option>
                      </el-select>
                    </template>
                  </vxe-form-item>
                </vxe-form>
              </template>
            </vxe-grid>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <notifyMessageInfoDialog v-if="showNoticeDialog" :visiable.sync="showNoticeDialog"
                             :dataId.sync="notifyMessageInfoId"
                             @readHanlde="notifyMessageReadHanlde"></notifyMessageInfoDialog>

    <wfContentDialog v-if="showWfDialog" :visible.sync="showWfDialog"
                     :option.sync="wfContentOption"></wfContentDialog>

  </div>
</template>

<script>
import notifyMessageInfoDialog from './infoDialog';
import {treeScollx} from '@base/utils/global.js';
import wfContentDialog from "../../../views/user/wf/wf_manage/wfContentDialog";

export default {
  name: 'notify_message:list',
  components: {wfContentDialog, notifyMessageInfoDialog,},
  data() {
    return {
      activeName: 'second',
      dataId: 0,
      showEdit: false,
      vxeOption: {},
      formData: {
        notifyType: [],
        readed: null
      },
      notifyTypes: [],
      showNoticeDialog: false,
      notifyMessageInfoIndex: null,
      notifyMessageInfoId: null,
      checkNode: {},
      defaultProps: {
        label: 'label', //这里是树结构中需显示的数据（即接口返回的需展示在页面上的参数）
        children: [],
        isLeaf: 'leaf'
      },
      notifyTypeNumMap: {},

      showWfDialog: false,
      wfContentOption: {},
    };
  },
  computed: {
    totalNum() {
      let num = 0;
      let notifyTypeNumMap = this.notifyTypeNumMap;
      for (let key in notifyTypeNumMap) {
        num = this.$baseAdd(num, notifyTypeNumMap[key])
      }
      return num;
    },
    checkNodeData() {
      return this.checkNode && this.checkNode.data ? this.checkNode.data : {};
    }
  },
  async mounted() {
    treeScollx({target: this, type: 'default'});
    if (this.$route.query.notifyType) {
      this.formData.notifyType = [this.$route.query.notifyType];
    }
    this.initTableList();
  },
  methods: {
    countNumStr(num) {
      num = num || 0;
      if (num > 99) {
        return '99+'
      } else {
        return num;
      }
    },
    initNotifyTypeNumMap() {
      let notifyTypes = this.notifyTypes.map(row => row.notifyType);
      notifyTypes.forEach(notifyType => {
        this.getUnreadMessageNum(notifyType);
      });
    },
    getUnreadMessageNum(notifyType) {
      this.$http({
        url: USER_PREFIX + '/notify_message/countMessage',
        method: `post`,
        data: {stringOne: notifyType},
        // isLoading: true,
        success: res => {
          this.$set(this.notifyTypeNumMap, notifyType, res.objx || 0)
        }
      });
    },
    searchEvent() {
      this.$refs['table-m1'].commitProxy('reload');
    },
    resetEvent() {
      this.formData = {};
      this.checkFirstNode();
      this.$refs['table-m1'].commitProxy('reload');
    },
    openEditDialog(row) {
      if (row.jumpContent) {
        this.notifyMessageRead(row, () => {
          let turl = row.jumpContent;
          let wfUrl = turl.split("?")[0];
          let param = this.getUrlParam(turl);
          let param2 = this.$baseLodash.cloneDeep(param);
          delete param2.dataId;
          delete param2.objTypeCode;
          this.wfContentOption = {
            objId: param.dataId,
            url: wfUrl,
            objTypeCode: param.objTypeCode || null,
            param: {
              _isNotifyMessage: true,
              ...param2
            }
          };
          this.showWfDialog = true;

          row.readed = 1;
          this.getUnreadMessageNum(row.notifyType);

        });
      }
    },
    getUrlParam(url) {
      var reg = /([^?&=]+)=([^?&=]+)/g, obj = {}, str = url;
      url.replace(reg, function () {
        obj[arguments[1]] = arguments[2];
      });
      return obj;
    },
    notifyMessageRead(row, callback) {
      if (row.readed == 0) {
        this.$http({
          url: USER_PREFIX + `/notify_message/read`,
          method: `post`,
          data: [row.id],
          isLoading: true,
          loadingTarget: document.body,
          success: res => {
            callback && callback();
          }
        });
      } else {
        callback && callback();
      }
    },
    initTableList() {
      let that = this;
      let tableOption = {
        vue: this,
        tableRef: 'table-m1',
        tableName: 'user_notify_message_list-m1',
        path: USER_PREFIX + '/notify_message/listPage',
        param: () => {
          return this.formData;
        },
        columns: [
          {type: 'checkbox', width: 48, resizable: false, fixed: 'left'},
          {
            title: this.$t1('通知内容'),
            field: 'content',
            width: 300,
            slots: {
              default: ({row}) => {
                if (row.content) {
                  let dom = document.createElement('div');
                  dom.innerHTML = row.content;
                  dom.querySelectorAll('p').forEach(item => {
                    item.remove();
                  });
                  return dom.innerText.trim();
                }
              }
            }
          },
          {
            title: this.$t1('通知类型'),
            field: 'notifyTypeName',
            width: 150
          },
          {
            width: 150,
            title: this.$t1('状态'),
            field: 'readed',
            slots: {
              default: ({row}) => {
                if (row.readed == 1) {
                  return [
                    <el-tag type="success">{this.$t1('已读')}</el-tag>
                  ]
                } else {
                  return [
                    <el-tag type="warning" onclick={() => {
                      this.handleRead(row);
                    }}>{this.$t1('未读')}</el-tag>
                  ]
                }
              }
            }
          },
          {
            title: this.$t1('阅读时间'),
            field: 'readTime',
            width: 150
          },
          {
            title: this.$t1('创建时间'),
            field: 'createDate',
            width: 150
          },
          {
            width: 100,
            fixed: 'right',
            title: '',
            sortable: false,
            slots: {
              default: ({row, rowIndex}) => {
                return [
                  <div>
                    <a
                      href="javascript:void(0);"
                      class="a-link"
                      onclick={() => {
                        this.checkNotifyMessage(row, rowIndex);
                      }}
                    >
                      <el-tooltip enterable={false} effect="dark" content={this.$t1('查看消息')} placement="top"
                                  popper-class="tooltip-skin">
                        <i class="el-icon-edit"/>
                      </el-tooltip>
                    </a>
                    <a
                      href="javascript:void(0);"
                      class="a-link"
                      onClick={() => {
                        this.openEditDialog(row);
                      }}
                    >
                      <el-tooltip enterable={false} effect="dark" content={this.$t1('查看单据')} placement="top"
                                  popper-class="tooltip-skin">
                        <i class="el-icon-files"/>
                      </el-tooltip>
                    </a>
                  </div>
                ];
              }
            }
          }
        ]
      };
      this.$vxeTableUtil.initVxeTable(tableOption).then(opts => {
        this.vxeOption = opts;
      });
    },
    handleRead(row) {
      if (row.readed == 0) {
        this.$baseConfirm(this.$t1('您确定要标记当前消息为已读吗？')).then(() => {
          this.$http({
            url: USER_PREFIX + `/notify_message/read`,
            method: `post`,
            data: [row.id],
            isLoading: true,
            success: res => {
              row.readed = 1;
              this.getUnreadMessageNum(row.notifyType);
            }
          });
        });
      } else {
        row.readed = 1;
        this.getUnreadMessageNum(row.notifyType);
      }
    },
    multiHandleRead(row) {
      let checkRows = this.$refs['table-m1'].getCheckboxRecords(true);
      let rows = checkRows.filter(item => item.readed == 0);
      if (!rows.length) {
        this.$baseAlert(this.$t1('请选择未读的消息'));
        return;
      }
      let data = rows.map(item => item.id);
      this.$baseConfirm(this.$t1('您确定要标记选中消息为已读吗？')).then(() => {
        this.$http({
          url: USER_PREFIX + `/notify_message/read`,
          method: `post`,
          data: data,
          isLoading: true,
          success: res => {
            rows.forEach(item => {
              item.readed = 1;
            });
            this.initNotifyTypeNumMap();
          }
        });
      });
    },
    checkNotifyMessage(row, index) {
      this.showNoticeDialog = true;
      this.notifyMessageInfoIndex = index;
      this.notifyMessageInfoId = row.id;
    },
    notifyMessageReadHanlde() {
      let rows = this.$refs['table-m1'].getTableData().fullData;
      rows[this.notifyMessageInfoIndex].readed = 1;
      this.getUnreadMessageNum(rows[this.notifyMessageInfoIndex].notifyType);
    },
    openNotifyMessageDialog(row) {
      this.$refs.notifyMessageDialog.open(row.jumpContent)
    },
    clearNodeClick() {
      this.checkNode = null;
      this.formData.notifyTypeName = null;
      this.formData.notifyType = null;
      this.$refs.tree.setCurrentKey();
      this.searchEvent();
    },
    handleNodeClick(data, node, v) {
      this.checkNode = node;
      this.formData.notifyTypeName = data.notifyTypeName;
      this.formData.notifyType = data.notifyType ? [data.notifyType] : [];
      this.$forceUpdate();
      this.searchEvent();
    },
    // 异步树叶子节点懒加载逻辑
    loadNode(node, resolve) {
      this.getNotifyTypes(() => {
        this.initNotifyTypeNumMap();
        this.initNodeData(node, resolve);
      })
    },
    initNodeData(node, resolve) {
      let data = this.notifyTypes.map(row => {
        return {
          label: row.notifyTypeName,
          id: row.id,
          notifyTypeName: row.notifyTypeName,
          notifyType: row.notifyType,
          leaf: true,

        }
      })
      data.unshift({
        label: this.$t1('全部消息'),
        id: -1,
        notifyTypeName: this.$t1('全部消息'),
        notifyType: 0,
        leaf: true,
      })
      resolve(data);
      this.$nextTick(() => {
        if (node.childNodes.length) {
          this.checkFirstNode();
          this.$forceUpdate();
        }
      });
    },
    checkFirstNode() {
      let notifyType = '0';
      let node = this.$refs.tree.getNode(notifyType);
      this.$refs.tree.setCurrentKey(node);
      this.checkNode = node;
    },
    getNotifyTypes(callback) {
      this.$http({
        url: USER_PREFIX + `/notify_type/list`,
        method: `post`,
        data: {},
        success: res => {
          let rows = res.objx || [];
          this.notifyTypes = rows;
          callback && callback(rows)
        }
      });
    },
  }
};
</script>
