<template>
  <div class="result-main">
    <div class="result-left">
      <el-collapse v-model="activeNames" @change="handleChange">
        <el-collapse-item title="全宗" name="1">
          <el-input
            v-model="filterFondsText"
            class="quick-search"
            placeholder="快速检索"
            suffix-icon="el-icon-search"
          />
          <el-tree
            ref="tree"
            :data="fondsOptions"
            show-checkbox
            default-expand-all
            node-key="id"
            :props="{children: 'children', label: 'fondsName'}"
            :filter-node-method="filterFondsNode"
            @check-change="getFondsCheckedKeys"
          />
        </el-collapse-item>
        <el-collapse-item title="档案门类" name="2">
          <el-input
            v-model="filterCategoryText"
            class="quick-search"
            placeholder="快速检索"
            suffix-icon="el-icon-search"
          />
          <el-tree
            ref="treeCategory"
            :data="categoryOptions"
            show-checkbox
            default-expand-all
            node-key="id"
            :props="{children: 'children', label: 'cnName'}"
            :filter-node-method="filterCategoryNode"
            @check-change="getCategoryCheckedKeys"
          />
        </el-collapse-item>
        <el-collapse-item title="档案分类" name="3">
          <el-input
            v-model="filterClassifyText"
            class="quick-search"
            placeholder="快速检索"
            suffix-icon="el-icon-search"
          />
          <!-- <div class="propListHeader">
            <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate" @change="checkAllChange">全部选择</el-checkbox>
          </div> -->
          <el-tree
            ref="treeClassify"
            v-loading="classifyLoading"
            :data="classifyOptions"
            show-checkbox
            default-expand-all
            node-key="id"
            :props="{children: 'children', label: 'name'}"
            :filter-node-method="filterClassifyNode"
            @check-change="getClassifyCheckedKeys"
          />
        </el-collapse-item>
        <el-collapse-item title="档案层级" name="4">
          <el-input
            v-model="filterLevelText"
            class="quick-search"
            placeholder="快速检索"
            suffix-icon="el-icon-search"
          />
          <el-tree
            ref="treeLevel"
            :data="levelOptions"
            show-checkbox
            default-expand-all
            node-key="value"
            :props="{children: 'children', label: 'label'}"
            :filter-node-method="filterLevelNode"
            @check-change="getLevelCheckedKeys"
          />
        </el-collapse-item>
      </el-collapse>
    </div>
    <div class="result-right">
      <div class="right-header">
        <div class="head-search">
          <!-- <el-select
            v-model="status"
            multiple
            collapse-tags
            placeholder="状态(支持多选)"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select> -->
          <div class="search-input">
            <el-input v-model="searchkeywords" placeholder="请输入检索关键字" class="input-with-select" @keyup.enter.native="handledResultSearch('search')">
              <el-button slot="append" icon="el-icon-search" @click="handledResultSearch('search')">搜索</el-button>
            </el-input>
          </div>
          <span class="change-search" @click="returnAdvanced">高级检索</span>
        </div>
        <div class="search-tip">
          <div v-if="isCommon">检索 “<span>{{ keywords }}</span>” 成功获得<i>{{ page.total }}</i>条结果</div>
          <div v-else>检索成功获得<i>{{ page.total }}</i>条结果<p>高级检索 点击查看检索条件</p></div>
        </div>
      </div>
      <div v-loading="resultLoading">
        <div v-if="resultData.length !== 0" class="result-list">
          <el-row v-for="(item,index) in resultData" :key="index" class="result-item" @dblclick.native="handleDetail(item)">
            <div class="result-item-title"><span>{{ getFileType(item.categoryLevel) }}</span><p>{{ item.maintitle }}</p></div>
            <p class="result-item-content" v-html="highlightKeywords(item.matekey)" />
            <div class="result-item-info">
              <p>档号：{{ item.archiveNo }}</p>
              <p>全宗：{{ item.fondsName }}</p>
              <p>档案门类：{{ item.categoryName }}</p>
              <p>档案分类：{{ item.archivesClassName }}</p>
            </div>
            <div class="item-top-tag">
              <span v-if="item.isEntity === 1">实体</span>
              <span v-if="item.tid !== null">标签</span>
              <span v-if="item.caseNo !== null">装盒</span>
              <span v-if="item.folderLocation !== '' && item.folderLocation !== null">入库</span>
              <span v-if="item.isBorrow">借阅</span>
              <span v-if="item.processStatus > 1" style="color: #ff8329;border-color: #febd98;background-color: #fff3e5;">审批锁定</span>
              <span v-else style="color: #a6adb6;border: 1px solid #e6e8ed;background-color: #f3f5f9;">空闲</span>
            </div>
            <div class="item-bottom-handle">
              <span @click.stop="handleDetail(item)">查看详情</span>
              <i v-if="item.categoryLevel === 3" class="iconfont icon-liuchengfaqi" @click.stop="initiateLending(item)" />
              <i v-if="item.categoryLevel === 3" class="iconfont icon-jiarujieyueche" @click.stop="addLending(item)" />
            </div>
          </el-row>
        </div>
        <!--分页组件-->
        <el-pagination
          v-if="resultData.length !== 0"
          :current-page="page.page"
          :total="page.total"
          :page-size="page.size"
          :pager-count="5"
          layout="total, prev, pager, next, sizes"
          @size-change="handleSizeChange"
          @current-change="handleCurrentPage"
        />
        <el-empty v-else description="暂无更多数据" />
      </div>
    </div>
    <!-- 档案详情 -->
    <ArchivesInfo ref="archivesInfo" :category-id="categoryId" :arc-id="arcId" :is-title-type="isTitleType" />
    <LendForm ref="lendFormRef" />
  </div>
</template>

<script >
import { crud } from '@crud/crud'
import { FetchInitSearchFonds, FetchInitSearchCategory, FetchInitSearchArchiveCtgNo, FetchResearch, FetchSeniorSearch } from '@/api/archiveUtilize/archiveUtilize'
import { FetchAddBorrowCar } from '@/api/archiveUtilize/cart'
import ArchivesInfo from '@/views/components/archivesDetail/detail'
import LendForm from '../../utillizeRecord/module/utilizationProcess'
import store from '@/store'
import { mapGetters } from 'vuex'
export default {
  name: 'ResultList',
  components: { ArchivesInfo, LendForm },
  mixins: [crud()],
  props: {
    isCommon: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      isTitleType: 3,
      activeNames: ['1'],
      filterFondsText: '',
      fondsOptions: [],
      filterCategoryText: '',
      categoryOptions: [],
      filterLevelText: '',
      levelOptions: [
        {
          label: '电子原文',
          value: '4'
        },
        {
          label: '文件',
          value: '3'
        },
        {
          label: '案卷',
          value: '2'
        },
        {
          label: '项目',
          value: '1'
        }
      ],
      filterClassifyText: '',
      classifyOptions: [],
      // statusOptions: [
      //   {
      //     label: '未装盒',
      //     value: '未装盒'
      //   },
      //   {
      //     label: '已装盒',
      //     value: '已装盒'
      //   },
      //   {
      //     label: '未入库',
      //     value: '未入库'
      //   },
      //   {
      //     label: '已入库',
      //     value: '已入库'
      //   },
      //   {
      //     label: '无实体',
      //     value: '无实体'
      //   },
      //   {
      //     label: '有实体',
      //     value: '有实体'
      //   },
      //   {
      //     label: '实体在库',
      //     value: '实体在库'
      //   },
      //   {
      //     label: '实体待借',
      //     value: '实体待借'
      //   },
      //   {
      //     label: '实体已借',
      //     value: '实体已借'
      //   }
      // ],
      // status: null,
      searchkeywords: '',
      keywords: '',
      categoryId: null,
      arcId: '',
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      checkAll: false,
      isIndeterminate: false,
      fondsKeys: null,
      categoryKeys: null,
      classifysKeys: null,
      levelsKeys: null,
      resultData: [],
      classifyLoading: false,
      resultLoading: false,
      condition: ''
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  watch: {
    filterFondsText(val) {
      this.$refs.tree.filter(val)
    },
    filterCategoryText(val) {
      this.$refs.treeCategory.filter(val)
    },
    filterLevelText(val) {
      this.$refs.treeLevel.filter(val)
    },
    filterClassifyText(val) {
      this.$refs.treeClassify.filter(val)
    }
  },
  mounted() {
    this.getFondsDatas()
    this.getCategoryDataTree()
    this.getArchiveCtgNo(null)
    if (localStorage.getItem('searchKeywords')) {
      this.searchkeywords = localStorage.getItem('searchKeywords')
      this.keywords = localStorage.getItem('searchKeywords')
    }
  },
  methods: {
    getFileType(categoryLevel) {
      if (categoryLevel === 1) {
        return '项目'
      } else if (categoryLevel === 2) {
        return '案卷'
      } else if (categoryLevel === 3) {
        return '文件'
      } else if (categoryLevel === 4) {
        return '电子原文'
      }
      return ''
    },
    highlightKeywords(text) {
      if (!text) {
        return false
      }
      const cleanedText = text.replace(/,/g, ' ') // 将逗号替换为空格
      if (this.keywords.includes(' ')) {
        // 包含多个关键字时，使用正则表达式匹配并标红
        const highlightedText = cleanedText.replace(new RegExp(this.keywords.split(' ').join('|'), 'gi'), match => {
          return "<span style='color: red'>" + match + '</span>'
        })
        return highlightedText
      } else {
        // 只包含一个关键字时，直接标红
        const highlightedText = cleanedText.replace(new RegExp(this.keywords, 'gi'), match => {
          return "<span style='color: red'>" + match + '</span>'
        })
        return highlightedText
      }
    },
    handledResultSearch(type) {
      if (this.searchkeywords) {
        if (type === 'search') {
          this.page.page = 1
        }
        console.log('this.page.page', this.page.page)
        this.$emit('common-search')
        this.resultData = []
        this.resultLoading = true
        this.keywords = this.searchkeywords
        const params = {
          'keywords': this.searchkeywords,
          'archiveCtgNos': this.classifysKeys, // 档案分类
          'categoryIds': this.categoryKeys, // 档案门类
          'categoryLevel': this.levelsKeys, // 档案层级
          'fondsNos': this.fondsKeys, // 全宗
          'searchFondsId': this.user.fonds.id,
          'page': this.page.page - 1,
          'size': this.page.size
        }
        FetchResearch(params).then((res) => {
          this.resultData = res.content
          this.page.total = res.totalElements
          setTimeout(() => {
            this.resultLoading = false
          }, 600)
        }).catch(err => {
          console.log(err)
        })
      } else {
        this.$message({ message: '请输入检索关键字段', type: 'error', offset: 8 })
      }
    },
    getSeniorSearch() {
      this.searchkeywords = ''
      this.resultData = []
      this.resultLoading = true
      const params = {
        'condition': this.condition,
        'archiveCtgNos': this.classifysKeys, // 档案分类
        'categoryIds': this.categoryKeys, // 档案门类
        'categoryLevel': this.levelsKeys, // 档案层级
        'fondsNos': this.fondsKeys, // 全宗
        'page': this.page.page - 1,
        'size': this.page.size
      }
      FetchSeniorSearch(params).then(res => {
        this.resultData = res.content
        this.page.total = res.totalElements
        setTimeout(() => {
          this.resultLoading = false
        }, 600)
      })
    },
    getFondsDatas() {
      FetchInitSearchFonds().then(res => {
        this.fondsOptions = res
      })
    },
    getCategoryDataTree() {
      FetchInitSearchCategory().then(res => {
        this.categoryOptions = res
      })
    },
    getArchiveCtgNo(categoryIds) {
      this.classifyOptions = []
      this.classifyLoading = true
      const params = {
        'categoryIds': categoryIds,
        'search': null
      }
      FetchInitSearchArchiveCtgNo(params).then(res => {
        this.classifyOptions = res
        this.classifyLoading = false
      })
    },
    handleChange(val) {
      console.log(val)
    },
    filterFondsNode(value, data) {
      if (!value) return true
      return data.fondsName.indexOf(value) !== -1
    },
    filterCategoryNode(value, data) {
      if (!value) return true
      return data.cnName.indexOf(value) !== -1
    },
    filterLevelNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    filterClassifyNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    getFondsCheckedKeys() {
      const checkedKeys = this.$refs.tree.getCheckedNodes()
      if (checkedKeys.length === 0) {
        this.fondsKeys = null
      } else {
        this.fondsKeys = checkedKeys.map(item => item.fondsId)
      }
      if (this.isCommon) {
        this.handledResultSearch('search')
      } else {
        this.getSeniorSearch()
      }
    },
    getCategoryCheckedKeys() {
      const checkedKeys = this.$refs.treeCategory.getCheckedNodes()
      if (checkedKeys.length === 0) {
        this.categoryKeys = null
      } else {
        this.categoryKeys = checkedKeys.map(item => item.id)
      }
      this.getArchiveCtgNo(this.categoryKeys)
      if (this.isCommon) {
        this.handledResultSearch('search')
      } else {
        this.getSeniorSearch()
      }
    },
    checkAllChange() {
      this.isIndeterminate = false// 设置全选按钮样式不为半选
      if (this.checkAll) { // 全选
        this.$nextTick(() => { // 这个如果要默认全选就必须加，否则会报错“setCheckedNodes”未定义
          this.$refs.treeClassify.setCheckedNodes(this.classifyOptions)
        })
        // this.
      } else { // 取消选中
        this.$nextTick(() => {
          this.$refs.treeClassify.setCheckedKeys([])
        })
      }
    },
    getClassifyCheckedKeys() {
      const checkedKeys = this.$refs.treeClassify.getCheckedNodes()
      if (checkedKeys.length === 0) {
        this.classifysKeys = null
      } else {
        this.classifysKeys = checkedKeys.map(item => item.code)
      }
      if (this.isCommon) {
        this.handledResultSearch('search')
      } else {
        this.getSeniorSearch()
      }
    },
    getLevelCheckedKeys() {
      const checkedKeys = this.$refs.treeLevel.getCheckedNodes()
      if (checkedKeys.length === 0) {
        this.levelsKeys = null
      } else {
        this.levelsKeys = checkedKeys.map(item => item.value)
      }
      if (this.isCommon) {
        this.handledResultSearch('search')
      } else {
        this.getSeniorSearch()
      }
    },
    returnAdvanced() {
      this.$emit('close-result')
    },
    handleDetail(row) {
      this.categoryId = row.categoryPid
      this.arcId = row.archivesId
      this.$nextTick(() => {
        console.log('this.$refs.archivesInfo', this.$refs.archivesInfo)
        this.$refs.archivesInfo.archivesInfoVisible = true
        this.$refs.archivesInfo.archivesTabIndex = 0
        this.$refs.archivesInfo.isFourTest = true
        if (row.categoryLevel === 2) {
          this.$refs.archivesInfo.isHasFile = false
          this.$refs.archivesInfo.detailTitle = '案卷详情'
          this.$refs.archivesInfo.getDetial(2, row.archivesId)
        } else {
          this.$refs.archivesInfo.isHasFile = true
          this.$refs.archivesInfo.detailTitle = '文件详情'
          this.$refs.archivesInfo.getDetial(3, row.archivesId)
        }
      })
    },
    initiateLending(item) {
      this.$confirm('当前档案即将发起借阅' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        // this.$message({ message: '确定发起借阅', type: 'success', offset: 8 })
        console.log('item', item)
        this.$nextTick(() => {
          this.$refs.lendFormRef.detailArcData = []
          this.$refs.lendFormRef.lendFormVisible = true
          item.checkedId = [1]
          item.childMenu = [{
            value: 1,
            label: '电子查看'
          },
          {
            value: 2,
            label: '下载'
          },
          {
            value: 3,
            label: '打印'
          },
          {
            value: 4,
            label: '实体借阅'
          }]
          this.$refs.lendFormRef.detailArcData.push(item)
        })
      }).catch(() => {
      })
    },
    addLending(data) {
      this.$confirm('当前档案是否加入借阅车' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const params = {
          'archivesId': data.archivesId
        }
        FetchAddBorrowCar(params).then(res => {
          if (res) {
            this.$message({ message: '加入借阅车成功', type: 'success', offset: 8 })
            store.dispatch('initborrowCar').then(() => {})
          } else {
            this.$message({ message: '当前所属档案已在借阅车，请勿重复操作', type: 'error', offset: 8 })
          }
        })
      }).catch(() => {
      })
    },
    handleSizeChange(size) {
      this.page.size = size
      this.page.page = 1
      this.handledResultSearch('page')
    },
    handleCurrentPage(val) {
      this.page.page = val
      this.handledResultSearch('page')
    },
    closeDialog() {

    }
  }
}
</script>

<style lang='scss' scoped>
.result-main{
  display: flex;
  justify-content: space-between;
  height: calc(100vh - 140px);
  .result-left{
    position: relative;
    width: 265px;
    height: calc(100%);
    padding: 20px;
    background-color: #fff;
    box-shadow: 4px 0px 4px 0px rgba(0,0,0,0.04);
    z-index: 9999;
    ::v-deep .el-collapse{
      border: none;
      height: calc(100%);
      overflow: hidden;
      overflow-y: scroll;
      .el-collapse-item__header{
        padding-left: 13px;
        height: 32px;
        background-color: #F3F6FA;
        border-radius: 3px 3px 3px 3px;
        opacity: 1;
        border: 1px solid #CBD1DC;
        .el-icon-arrow-right:before{
          font-family: "iconfont" !important;
          font-style: normal;
          -webkit-font-smoothing: antialiased;
          -moz-osx-font-smoothing: grayscale;
          content: "\e629";
          font-size: 6px;
          color: #545B65;
        }
        .el-collapse-item__arrow.is-active{
          transform: rotate(180deg);
        }
      }
      .el-collapse-item{
        margin-bottom: 16px;
        .el-collapse-item__wrap{
          padding: 12px;
          margin-top: -1px;
          border: 1px solid #CBD1DC;
          // border-top: none;
          border-radius: 0 0 3px 3px;

        }
        .el-collapse-item__content{
          padding-bottom: 0;
          .quick-search{
            margin-bottom: 16px;
          }
          .el-tree{
            max-height: calc(100vh/4 - 25px);
            overflow: hidden;
            overflow-y: scroll;
            .el-tree-node__content {
              height: 30px;
            }
            .el-tree-node__expand-icon{
              font-size: 12px;
              display: none;
            }
            .el-tree-node__label{
              font-size: 14px;
            }
          }
        }
      }
    }
  }
  .result-right{
    flex: 1;
    // background-color: #fff;
    .right-header{
      padding: 20px 20px 14px 20px;
      background-color: #fff;
      .head-search{
        margin-bottom: 10px;
        .search-input{
          margin-left: 10px;
          .input-with-select{
            ::v-deep .el-input__inner{
              width: 320px;
            }
          }
          ::v-deep .el-input-group__append{
            width: auto;
            padding: 0 20px 0 0 !important;
            border-color: #0348F3;

            .el-button{
              background-color: #0348F3 !important;
              color: #fff;
            }
          }
        }
      }
      .change-search{
        cursor: default;
        margin-left: 12px;
        font-size: 14px;
        color: #0348F3;
        line-height: 32px;
      }
      .search-tip{
        font-size: 14px;
        line-height: 22px;
        color: #545B65;
        span{
          color: #ED4A41;
        }
        i{
          font-style: normal;
          padding: 0 4px;
        }
        p{
          display: inline-block;
          padding-left: 12px;
          font-size: 12px;
          color: #A6ADB6;
        }
      }
    }
    .result-list{
      margin: 20px 0 0 0;
      padding: 0 20px;
      height: calc(100vh - 296px);
      overflow: hidden;
      overflow-y: scroll;
      .result-item{
        position: relative;
        padding: 16px 16px 10px 16px;
        margin-bottom: 16px;
        font-size: 14px;
        background-color: #fff;
        border-radius: 3px;
        .result-item-title{
          display: flex;
          justify-content: flex-start;
          margin-bottom: 8px;
          font-size: 16px;
          line-height: 24px;
          color: #0C0E1E;
          span{
            display: block;
            padding: 0 8px;
            margin-right: 6px;
            height: 22px;
            line-height: 22px;
            font-size: 12px;
            border-radius: 3px;
            background-color: #CAE1FF;
            color: #0348F3;
          }
          p{
            max-width: 1050px;
          }
        }
        .result-item-content{
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 1;
          color: #545B65;
        }
        .result-item-info{
          margin-top: 4px;
          font-size: 12px;
          line-height: 20px;
          color: #868E98;
        }
        .item-top-tag{
          position: absolute;
          right: 16px;
          top: 16px;
          display: flex;
          justify-content: flex-start;
          flex-wrap: nowrap;
          align-items: center;
          span{
            display: block;
            // width: 42px;
            padding: 0 4px;
            height: 22px;
            line-height: 22px;
            text-align: center;
            font-size: 12px;
            background-color: #E8F8F5;
            border: 1px solid #B1EBDF;
            border-radius: 3px;
            color: #2ECAAC;
            margin-left: 10px;
          }
        }
        .item-bottom-handle{
          position: absolute;
          right: 16px;
          bottom: 10px;
          display: flex;
          justify-content: flex-start;
          flex-wrap: nowrap;
          align-items: center;
          font-size: 14px;
          color: #0348F3;
          cursor: pointer;
          span{
            display: block;
          }
          i{
            display: block;
            margin-left: 26px;
          }
        }
      }
    }
  }
}
.el-pagination{
  margin: 10px 16px 0 10px !important;
}

::v-deep .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content{
  background-color: transparent !important;
}
::v-deep .el-tree .el-tree-node.is-current>.el-tree-node__content .el-tree-node__label{
  background-color: transparent !important;
  color: #0C0E1E !important;
}
::v-deep .el-tree .is-current>.el-tree-node__content{
  background-color: transparent !important;
  color: #0C0E1E !important;
}

::v-deep .el-collapse::-webkit-scrollbar,
::v-deep .el-collapse-item__content::-webkit-scrollbar,
::v-deep .el-tree::-webkit-scrollbar {
  width: 5px !important;
  height: 5px !important;
  background-color: #fff !important;
}

::v-deep .el-collapse::-webkit-scrollbar-thumb{
  border-radius: 3px;
  background-color: #fff !important;
}
::v-deep .el-collapse-item__content::-webkit-scrollbar-thumb,
::v-deep .el-tree::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background-color: #4578F6 !important;
  // background-color: #fff !important;
}

::v-deep .el-collapse::-webkit-scrollbar-thumb:hover,
::v-deep .el-collapse-item__content::-webkit-scrollbar-thumb:hover,
::v-deep .el-tree::-webkit-scrollbar-thumb:hover {
  // background-color: #4578F6 !important;
  background-color: #fff !important;
}

::v-deep .el-collapse::-webkit-scrollbar-corner,
::v-deep .el-collapse-item__content::-webkit-scrollbar-corner,
::v-deep .el-tree::-webkit-scrollbar-corner {
  background-color: #DDE8FB !important;
}
</style>
