<template>
  <div :class="$style.wrapHeight">
    <div :class="$style.rowHeight">
      <km-tree-async
        ref="tree"
        :load-tree-data="loadTreeData"
        option-count="count"
        @treeSelectd="treeSelectd"
      />
      <div :class="$style.rightcard">
        <sd-detail-modal
          ref="kMapDetail"
          :record-id="kMapid"
          page-id="kmap/kmKmap/kmKmapData"
          :modal-props="{ width: 1000 }"
          @saved="fnKMapSaved"
          @actionBtnClick="actionBtnClick"
        >
          <template v-slot="{ model, fields }">
            <km-kmap-table
              ref="kmapTable"
              :model="model"
              :fields="fields"
              :default-category="defaultCategory"
            />
          </template>
        </sd-detail-modal>

        <a-card>
          <a-tabs v-model="activeKey">
            <a-tab-pane key="picturecard" tab="图文">
              <div :class="$style.wrapper">
                <div :class="$style.header">
                  <div :class="$style.order">
                    排序:<span
                      :class="[orderType === 'creationTime' ? $style.active : '']"
                      @click="fnSetOrderType('creationTime')"
                    >
                      发布时间<a-icon v-if="creationTimeDesc" type="caret-down" /><a-icon
                        v-else
                        type="caret-up"
                      />
                    </span>
                    |<span
                      :class="[orderType === 'readTimes' ? $style.active : '']"
                      @click="fnSetOrderType('readTimes')"
                    >
                      浏览次数
                    </span>
                  </div>

                  <a-input-search
                    placeholder="请输入搜索条件"
                    allow-clear
                    @search="onSearchChange"
                  />
                  <a-button
                    v-if="showDeleteBtn"
                    :disabled="pictureRowSelection.length <= 0"
                    @click="deleteRows"
                  >
                    删除
                  </a-button>
                  <a-button v-if="showCreateBtn" type="primary" @click="fnCreatDoc">
                    新建
                  </a-button>
                </div>

                <a-list
                  :grid="{ gutter: 16, column: 4 }"
                  :data-source="pictureData"
                  :pagination="pagination"
                  :loading="loading"
                  type="flex"
                >
                  <a-list-item slot="renderItem" slot-scope="item">
                    <a-card :class="$style.picturecard">
                      <div slot="cover" :class="$style.picturecover">
                        <img
                          v-if="item.cover"
                          :class="$style.img"
                          :src="
                            (`api/flow-mobile/v1/task-form-process/download-attachments/` +
                              item.cover)
                              | sdResource
                          "
                          class="ant-upload-list-item-image"
                          @click="fnReadDoc(item)"
                        />
                      </div>

                      <a-card-meta>
                        <template slot="title">
                          <a-checkbox
                            v-if="showDeleteBtn"
                            :value="item.id"
                            :checked="pictureRowSelection.includes(item.id)"
                            @change="fnPictureSelect"
                          >
                          </a-checkbox>
                          <span :class="{ [$style.title]: showDeleteBtn }">
                            <a @click="fnReadDoc(item)">{{ item.kmapName }}</a>
                          </span>
                        </template>
                        <template slot="description">
                          <div>
                            <span :class="$style.user">{{ item.creatorName }}</span>
                            <span :class="$style.datatime">{{
                              item.creationTime | sdDateFormat('YYYY-MM-DD')
                            }}</span>
                            <span><a-icon type="sd-eye" />{{ item.readTimes }}</span>
                            <span v-if="showEditBtn" :class="$style.edit">
                              <a @click="fnEditDoc(item)">编辑</a>
                            </span>
                          </div>
                        </template>
                      </a-card-meta>
                    </a-card>
                  </a-list-item>
                </a-list>
              </div>
            </a-tab-pane>
            <a-tab-pane key="textlist" tab="列表">
              <sd-oa-table
                v-if="expressions.length > 0"
                ref="kMapTable"
                :form-id="formId"
                page-id="kmap/kmKmap/kmKmapData"
                :columns="columns"
                :actions="showEditBtn === true ? actions : actions.slice(0, 2)"
                :filter-expressions="expressions"
                :show-selection="showDeleteBtn"
                :modal-props="{ width: 1000 }"
                :search-fields="['kmapName']"
                @recordsDeleted="onRecordsDeleted"
              >
                <a slot="fldSubject" slot-scope="text, record" @click="fnReadDoc(record)">
                  {{ text }}
                </a>
              </sd-oa-table>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </div>
    </div>
  </div>
</template>

<script>
import { Message, Modal } from 'ant-design-vue'
import { getUserPerms } from '@/common/store-mixin'
import crossWindowWatcher from '@/common/services/cross-window-watcher'
import PageService from '@/common/services/page-service'
import TableActionTypes from '@/common/services/table-action-types'
import TableColumnTypes from '@/common/services/table-column-types'
import KmKnowledageService from '../km-knowledage-service'

import components from './_import-components/km-knowledge-map-import'

export default {
  name: 'KmKnowledgeMap',
  metaInfo: {
    title: '知识地图',
  },
  components,
  provide() {
    return {
      oaKmapContext: this,
    }
  },
  data() {
    return {
      activeKey: 'textlist',
      expressions: [],
      columns: [
        {
          title: '序号',
          customRender: (text, record, index) => `${index + 1}`,
          width: '100px',
        },
        {
          title: '标题',
          dataIndex: 'kmapName',
          scopedSlots: { customRender: 'fldSubject' },
        },
        {
          title: '分类',
          dataIndex: 'kmapCategoryName',
        },
        {
          title: '作者',
          dataIndex: 'creatorName',
        },
        {
          title: '阅读次数',
          dataIndex: 'readTimes',
        },
        {
          title: '发布时间',
          dataIndex: 'creationTime',
          sdRender: TableColumnTypes.date,
          defaultSortOrder: 'desc',
          sorter: true,
        },
      ],

      actions: [
        {
          label: '新建',
          id: 'create',
          type: TableActionTypes.primary,
          permission: 'create',
          callback: () => {
            this.fnCreatDoc()
          },
        },
        {
          label: '删除',
          id: 'delete',
          type: TableActionTypes.oa.delete, // 删除按钮，不需要回调，会自动处理
        },
        {
          label: '编辑',
          id: 'edit',
          type: TableActionTypes.inline,
          callback: (record) => {
            this.fnEditDoc(record)
          },
        },
      ],
      formId: 'kmKmapData',

      showEditBtn: false,
      // 图文列表参数
      showCreateBtn: false,
      showDeleteBtn: false,
      pictureData: [],
      pagination: {
        onChange: (page) => {
          this.paginationChange(page)
        },
        current: 1,
        pageSize: 8,
        showTotal(total) {
          return `共${total}条`
        },
      },
      loading: false, // 图文列表数据的loading
      kMapid: null,
      pictureExpressions: [],
      orderType: 'creationTime',
      creationTimeDesc: true,
      pictureRowSelection: [],
      searchText: '',
      defaultCategory: '',
    }
  },

  watch: {
    pictureExpressions() {
      this.pictureListRefresh(true)
    },
    orderType() {
      this.pictureListRefresh()
    },
    creationTimeDesc() {
      this.pictureListRefresh()
    },
  },
  created() {
    this.loadData()

    // 判断权限
    const userPerms = getUserPerms()
    if ('kmKmapData-create' in userPerms) {
      this.showCreateBtn = true
    }
    if ('kmKmapData-delete' in userPerms) {
      this.showDeleteBtn = true
    }
    if ('kmKmapData-update' in userPerms) {
      this.showEditBtn = true
    }
  },
  methods: {
    // 获取分类树
    loadTreeData(parentCatId) {
      const params = {
        pageId: 'KmKmapData',
        categoryId: parentCatId || 0,
      }
      return KmKnowledageService.getKmapTree(params).then((res) => {
        return res.data
      })
    },

    // 查看知识地图
    fnReadDoc(record) {
      const url = `/km-kmap-pages/` + record.id
      crossWindowWatcher.waitForChanged(url).then((refreshFlag) => {
        if (refreshFlag) {
          this.$refs.kMapTable.refresh()
          this.pictureListRefresh()
        }
      })
    },

    // 创建知识地图
    fnCreatDoc() {
      this.kMapid = null
      this.$refs.kMapDetail.show()
    },

    fnEditDoc(record) {
      this.kMapid = record.id
      this.$refs.kMapDetail.show()
    },

    actionBtnClick(evt, btn) {
      if (btn.buttonId === 'save') {
        evt.waitUntil(
          new Promise((resolve, reject) => {
            if (this.$refs.kMapDetail.getFieldValue('type') === '0') {
              if (this.$refs.kMapDetail.getFieldValue('kmKmapKnowledgeList')) {
                resolve()
              } else {
                Message.warn('不使用模板时请至少录入一条关联知识')
                evt.preventDefault()
                resolve()
              }
            } else {
              resolve()
            }
          })
        )
      }
    },

    // 知识地图保存
    fnKMapSaved() {
      this.$refs.kMapTable.refresh()
      this.pictureListRefresh()
    },

    // 树选择节点后获取列表数据
    treeSelectd(item) {
      let parentId = ''
      let parentName = ''
      if (item.id !== undefined) {
        parentId = item.id
        parentName = item.text

        // 走这里表示是根节点，根节点要是没有的话就不用向上找了
      } else {
        parentId = item.selectedNodes[0].data.props.id
        parentName = item.selectedNodes[0].data.props.text
      }
      const obj = {
        id: parentId,
        name: parentName,
      }
      this.defaultCategory = [obj]
      this.selectdParentId = parseInt(parentId)
      this.selectdParentName = parentName

      const filter = [
        {
          dataType: 'str',
          name: 'kmapCategoryId',
          op: 'eq',
          stringValue: this.selectdParentId,
        },
      ]

      this.pictureExpressions = filter

      this.expressions = filter
    },

    // 图片列表页面翻页
    paginationChange(page) {
      this.pagination.current = page
      this.loadData()
    },

    pictureListRefresh(toFirstPage) {
      if (toFirstPage) this.pagination.current = 1
      return this.loadData()
    },

    loadData() {
      const pagination = this.pagination
      this.loading = true
      const param = {
        columns: 'kmapName,creationTime,cover,kmapCategoryName,creatorName,readTimes',
        maxResults: pagination.pageSize,
        startPosition: pagination.pageSize * (pagination.current - 1),
        formId: this.formId,
      }

      let orderBy = ''

      if (this.orderType === 'creationTime') {
        if (this.creationTimeDesc) {
          orderBy = 'creationTime desc'
        } else {
          orderBy = 'creationTime asc'
        }
      } else {
        orderBy = 'readTimes desc'
      }
      param.orderBy = orderBy

      if (this.searchText) {
        const searchExpressions = [
          {
            dataType: 'exps',
            op: 'or',
            expressionsValue: [
              {
                dataType: 'str',
                name: 'kmapName',
                op: 'like',
                stringValue: `%${this.searchText}%`,
              },
            ],
          },
        ]
        param.expressions = [...searchExpressions, ...this.pictureExpressions]
      } else {
        param.expressions = this.pictureExpressions
      }

      PageService.getList(param).then((res) => {
        this.pagination.total = res.data.totalSize
        this.pictureData = res.data.data
        this.loading = false
        const newInfo = { ...this.pagination }
        newInfo.total = res.data.totalSize
        this.pagination = newInfo
      })
    },

    // 处理排序
    fnSetOrderType(type) {
      if (type === 'creationTime') {
        if (this.orderType === 'creationTime') {
          this.creationTimeDesc = !this.creationTimeDesc
        }
      }
      this.orderType = type
    },

    // 图文列表选中
    fnPictureSelect(e) {
      if (e.target.checked) {
        if (this.pictureRowSelection.indexOf(e.target.value) === -1) {
          this.pictureRowSelection.push(e.target.value)
        }
      } else {
        this.pictureRowSelection.splice(
          this.pictureRowSelection.findIndex((it) => it.value === e.target.value),
          1
        )
      }
    },

    // 列表删除数据时图文也刷新一下
    onRecordsDeleted() {
      this.pictureListRefresh()
      this.$refs.tree.refresh() // 刷新树
    },

    // 图文列表删除数据
    deleteRows() {
      Modal.confirm({
        title: '你确定删除这项内容吗？',
        content: '删除这条数据后，就无法恢复初始的状态。',
        okText: '删除',
        okType: 'danger',
        onOk: () => {
          this.loading = true
          const params = {
            ids: this.pictureRowSelection.join(','),
          }

          PageService.delete(params, this.formId).then((res) => {
            if (res.status === 200) {
              this.pictureRowSelection = []
              this.loading = false
              this.pictureListRefresh()
              this.$refs.kMapTable.refresh()
            }
          })
        },
      })
    },

    onSearchChange(text) {
      if (this.searchText === text) return
      this.searchText = text.trim()
      const pagination = this.pagination
      pagination.current = 1
      this.localPagination = { ...pagination }
      this.loadData()
    },
  },
}
</script>

<style module lang="scss">
@use '@/common/design' as *;
.wrap-height {
  height: 100%;
  .row-height {
    display: flex;
    flex: auto;
    height: 100%;
    .rightcard {
      flex: 1;
      width: calc(100% - 20%);
      height: 100%;
    }
  }
}
// 图文搜索框
.wrapper {
  :global(.ant-input-search) {
    width: 200px;
  }
  :global(.ant-btn) {
    margin: 5px;
  }
  :global(.ant-list) {
    margin-top: 20px;
  }

  margin-top: -64px;
  .header {
    position: relative;
    z-index: 1;
    width: 80%;
    height: 42px;
    margin: 3px 0 3px 20%;
    text-align: right;
    .order {
      display: inline-block;
      margin-right: 30px;
      span {
        margin: 0 10px;
        cursor: pointer;
      }
      .active {
        color: $primary-color;
      }
    }
  }
}
// 图文样式
.picturecard {
  border: 1px solid $border-color-split;
  .picturecover {
    height: 18vh;
    background-image: url('../images/noimage.png');
    background-repeat: no-repeat;
    background-position-x: center;
    background-position-y: center;

    img[src=''],
    img:not([src]) {
      opacity: 0;
    }
    .img {
      width: 100%;
      height: 100%;
      border: none;
    }
  }
  .title {
    padding-left: 12px;
  }
  .datatime {
    padding: 0 10px;
  }
  .edit {
    float: right;
  }
}
</style>
