<template>
  <div v-loading="searchLoading" class="search-main">
    <div class="head-container">
      <h2 v-if="this.$route.path.indexOf('dashboard') === -1">模糊检索</h2>
      <div v-if="isHomeSearch" class="search-header">
        <el-checkbox-group v-model="checkList" @change="handleCategoryTypes">
          <el-checkbox v-for="item in categoryTypesOptions" :key="item.value" :label="item.value">{{ item.label }}</el-checkbox>
        </el-checkbox-group>
      </div>
      <div class="search-input">
        <el-input v-model="keywords" placeholder="请输入内容" class="input-with-select" style="width:50%;" @keyup.enter.native="dimSearch">
          <el-select
            slot="prepend"
            v-model="select"
            multiple
            collapse-tags
            placeholder="请选择"
            @change="handleChose"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="handleSearch" />
        </el-input>
      </div>
      <div v-if=" this.$route.path.indexOf('dashboard') === -1 && select.length" style="width:50%; margin:10px auto; font-size: 12px; color: #fff; text-align: left;">
        <p style="margin-left: 20px;">检索条件： <span v-for="(option, index) in select" :key="index">{{ getSelectLabel(option) }}{{ index !== select.length - 1 ? ', ' : '' }}</span></p>
      </div>
    </div>
    <div v-if="this.$route.path.indexOf('dashboard') === -1" class="search-result">
      <div v-show="isShow" class="search-title">
        <!-- <el-button v-if="resNum !== 0" class="lending-btn iconfont" :disabled="selections.length === 0" type="primary" @click="handleLending"><i class="iconfont icon-chuku-fanbai" style="margin-right: 6px;" />借阅</el-button> -->
        <p v-if="resNum === 0" class="search-res-left">检索结果</p>
        <p :class="{'search-res-num' : resNum !== 0 }">本次检索结果共计{{ resNum }}条数据</p>
        <el-checkbox v-if="resNum !== 0" v-model="fixedStatusBar">隐藏状态栏</el-checkbox>
      </div>
      <div v-show="resNum > 0">
        <el-table
          ref="table"
          v-loading="loading"
          class="archives-table"
          :data="tableData"
          style="width: 100%;"
          height="calc(100vh - 534px)"
          @cell-dblclick="handleDbClick"
          @select-all="selectAll"
          @row-click="clickRowHandler"
          @select="handleCurrentChange"
        >
          <el-table-column :selectable="checkboxT" type="selection" align="center" width="55" />
          <el-table-column label="序号" width="55" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ (page.page === 1 ? 0 : (page.page === 0 ? 0 : page.page - 1)) * page.size + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="category_type" label="门类级别" align="center" min-width="100">
            <template slot-scope="scope">
              <span v-if="scope.row.category_type === 5" style="width:56px">文件级</span>
              <span v-if="scope.row.category_type === 4" style="width:56px">卷内级</span>
              <span v-if="scope.row.category_type === 3" style="width:56px">案卷级</span>
            </template>
          </el-table-column>
          <el-table-column prop="category_name" label="门类名称" align="center" show-overflow-tooltip min-width="170" />
          <el-table-column prop="child" label="子条数目" align="center" width="100" />
          <el-table-column prop="archive_no" label="编号" align="center" show-overflow-tooltip min-width="220" />
          <el-table-column prop="maintitle" label="姓名" show-overflow-tooltip align="center" min-width="240" />
          <!-- <el-table-column prop="doc_no" label="发文字号" show-overflow-tooltip width="140" align="center" />
          <el-table-column prop="serial_no" label="序号" width="100" align="center" />
          <el-table-column prop="fonds_no" label="全宗号" align="center" min-width="180" />
          <el-table-column prop="archive_year" label="年度" align="center" min-width="100" />
          <el-table-column prop="security_class" label="密级" align="center" min-width="100" />
          <el-table-column prop="retention" label="保管期限" align="center" min-width="100" />
          <el-table-column prop="arrive_class" label="收发类别" width="140" align="center" />
          <el-table-column prop="temp_no" label="临时卷号" show-overflow-tooltip width="140" align="center" />
          <el-table-column prop="created_date" label="成文日期" align="center" min-width="180" /> -->
          <el-table-column prop="case_name" label="盒名称" show-overflow-tooltip align="center" min-width="200" />
          <el-table-column prop="folder_location_details" label="所在位置" align="center" min-width="300">
            <template slot-scope="scope">
              <span v-if="!scope.row.folder_location_details">-</span>
              <span v-else>
                <el-tag effect="dark">{{ scope.row.folder_location_details }}</el-tag>
              </span>
            </template>
          </el-table-column>
          <!-- 未绑 / 已绑 -->
          <el-table-column label="标签" width="100" align="center" :fixed="fixedStatusBar ? false : 'right' ">
            <template slot-scope="scope">
              <span v-if="scope.row.category_type !== 3" :class="['row-state', 'row-binding', scope.row.tag_no ? 'state-active' : '' ]">{{ scope.row.tag_no ? '已绑': '未绑' }}</span>
            </template>
          </el-table-column>
          <!-- state-active 已装/已入/已借/已绑 -->
          <!-- 未装 / 已装 -->
          <el-table-column label="装盒" width="100" align="center" :fixed="fixedStatusBar ? false : 'right' ">
            <template slot-scope="scope">
              <span v-if="scope.row.category_type !== 3" :class="['row-state', 'row-packing', scope.row.case_name ? 'state-active' : '' ]">{{ scope.row.case_name ? '已装': '未装' }}</span>
            </template>
          </el-table-column>
          <!-- is_storage 为空的情况下即没装盒 / 0 未入 / 1 待入 / 2 已入 / 3 待出-->
          <!-- <span class="row-state row-warehousing">{{ storageTxt[scope.$index] }}</span> -->
          <el-table-column label="入库" width="100" align="center" :fixed="fixedStatusBar ? false : 'right' ">
            <template slot-scope="scope">
              <span v-if="scope.row.category_type !== 3" :class="['row-state', 'row-warehousing', (storageTxt[scope.$index] === '已入' )? 'state-active' : '' ]">{{ storageTxt[scope.$index] }}</span>
            </template>
          </el-table-column>
          <!-- is_borrow 4 已归还 / 为空 - 未加入待借列表 - 在库 / 2 待借阅（在待借列表/借出确认列表） - 待借 / 1待登记 - 不可借-用“—” 表示 / 3 待归还 - 已借 -->
          <el-table-column label="借阅" width="100" align="center" :fixed="fixedStatusBar ? false : 'right' ">
            <template slot-scope="scope">
              <span v-if="scope.row.category_type !== 3" :class="['row-state', 'row-lending', (borrowTxt[scope.$index] === '已借' )? 'state-active' : '' ]">{{ borrowTxt[scope.$index] }}</span>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination :page-size.sync="page.size" :total="page.total" :current-page.sync="page.page" style="margin-top: 8px;" layout="total, prev, pager, next, sizes" @size-change="sizeChangeHandler($event)" @current-change="pageChangeHandler" />
      </div>
      <!-- 详情 -->
      <!-- <detailDialog ref="detailDom" @openCol="openCol" /> -->
      <ArchivesInfo ref="archivesInfo" :category-id="categoryId" :arc-id="arcId" />
      <!-- 借阅 -->
      <el-dialog title="借阅" :visible.sync="lengingVisible" :close-on-click-modal="false" :before-close="handleClose">
        <span class="dialog-right-top" />
        <span class="dialog-left-bottom" />
        <div class="setting-dialog">
          <div class="dialog-delt">
            <p><span>确定将当前档案加入借阅列表？</span></p>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click.native="handleLendingConfirm">确定</el-button>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import ArchivesInfo from '../../archivesManage/archivesList/module/archivesInfo/index'
// import detailDialog from './module/detailDialog.vue'
// , FetchArchivesDetails, FetchArchivesMetadata
import { getCategoryTree } from '@/api/category/category'
import { querySeniorArchives } from '@/api/archivesManage/archivesList'
import { FetchIsExistBorrow, FetchAddArchivesWaitRegister } from '@/api/archivesManage/lendManage'
import CallExternal from '@/api/storeManage/deviceManage/device'
import { mapGetters } from 'vuex'
export default {
  name: 'ArchivesSearch',
  components: { ArchivesInfo },
  provide() {
    return {
      recycleMain: this
    }
  },
  props: {
    isHomeSearch: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      categoryTree: null,
      categoryId: null,
      arcId: null,
      loading: false,
      tableData: [],
      selections: [],
      storageTxt: [],
      borrowTxt: [],
      fixedStatusBar: false,
      searchLoading: false,
      lengingVisible: false,
      keywords: '',
      select: ['maintitle'],
      options: [
        { value: 'maintitle', label: '姓名' },
        { value: 'archive_no', label: '编号' }
        // { value: 'responsibleby', label: '责任者' },
        // { value: 'doc_no', label: '发文字号' },
        // { value: 'record_type', label: '文种' },
        // { value: 'fonds_no', label: '全宗号' },
        // { value: 'archive_year', label: '年度' },
        // { value: 'security_class', label: '密级' },
        // { value: 'retention', label: '保管期限' },
        // { value: 'case_name', label: '盒名称' },
        // { value: 'barcode', label: '条形码' },
        // { value: 'folder_location', label: '地址码' },
        // { value: 'temp_no', label: '临时卷号' }
      ],
      page: {
        total: 0,
        size: 10,
        page: 1
      },
      resNum: 0,
      isShow: false,
      params: {
        criteria: null,
        query: null,
        page: null,
        size: null
      },
      homeSearchWords: '',
      homeSearchSelect: [],
      openLocation: null,
      deviceData: null,
      checkList: [3, 4, 5],
      categoryTypesOptions: [
        {
          label: '案卷级',
          value: 3
        },
        {
          label: '卷内级',
          value: 4
        },
        {
          label: '文件级',
          value: 5
        }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'roles'
    ])
  },
  async created() {
    await this.getDeviceListAll()
  },
  mounted() {
    this.getCateMenu()
    if (localStorage.getItem('homeSearchWords') !== null) {
      this.keywords = localStorage.getItem('homeSearchWords')
      const homeSearchSelect = localStorage.getItem('homeSearchSelect')
      const homeSearchSelectArray = JSON.parse(homeSearchSelect)
      this.select = homeSearchSelectArray
      this.dimSearch()
    }
  },
  methods: {
    handleChose(val) {
      if (val.length < 1) {
        this.$nextTick(() => {
          this.select = ['maintitle'] // 重新设置 v-model 的值
        })
        return
      }
    },
    handleCategoryTypes(val) {
      if (val.length < 1) {
        this.$nextTick(() => {
          this.checkList = [3] // 重新设置 v-model 的值
        })
        return
      }
    },
    getSelectLabel(option) {
      const selectedOption = this.options.find((c) => c.value === option)
      return selectedOption ? selectedOption.label : ''
    },
    checkboxT(row, rowIndex) {
      return row.category_type !== 3
    },
    // table - 全选
    selectAll(val) {
      this.selections = val
    },
    // table - 当前选中得row
    clickRowHandler(row) {
      if (row.category_type !== 3) {
        this.$refs.table.clearSelection()
        this.$refs.table.toggleRowSelection(row)
        this.selections = []
        this.selections.push(row)
      }
    },
    // 触发单选
    handleCurrentChange(selection, row) {
      this.selections = selection
    },
    getCateMenu() {
      getCategoryTree().then(res => {
        this.categoryTree = res
        console.log('this.categoryTree', this.categoryTree)
      })
    },
    findItemById(data, id) {
      if (Array.isArray(data)) {
        for (const item of data) {
          const result = this.findItemById(item, id)
          if (result) return result
        }
      } else if (typeof data === 'object') {
        if (data.id === id) {
          return data
        } else {
          if (data.children && data.children.length > 0) {
            return this.findItemById(data.children, id)
          }
        }
      }
      return null
    },

    // 双击详情
    handleDbClick(row) {
      console.log(this.$refs.archivesInfo)
      this.categoryId = row.category_id
      this.arcId = row.archives_id
      const currentCategory = this.findItemById(this.categoryTree, row.category_id)
      console.log(currentCategory.isType)
      if (currentCategory.isType === 3) {
        this.$refs.archivesInfo.isHasFile = false
        this.$refs.archivesInfo.isTidOrBorrow = false
      } else {
        this.$refs.archivesInfo.isHasFile = true
        this.$refs.archivesInfo.isTidOrBorrow = true
      }

      this.$refs.archivesInfo.isDetailsInfo = true
      this.$refs.archivesInfo.detailTitle = '档案详情'
      this.$refs.archivesInfo.archivesInfoVisible = true
      this.$refs.archivesInfo.archivesTabIndex = 0
      this.$refs.archivesInfo.getDetial(row.archives_id, row.category_id)

      // const params = {
      //   'categoryId': row.category_id,
      //   'archivesId': row.archives_id
      // }
      // FetchArchivesDetails(params).then(res => {
      //   if (res) {
      //     const rowData = {}
      //     res.forEach(item => {
      //       rowData[item.fieldName] = item.context
      //     })

      //     // 是否显示开架按钮
      //     if (rowData.folder_location !== null) {
      //       this.openLocation = rowData.folder_location
      //       this.$refs.detailDom.isShowOpen = true
      //     } else {
      //       this.openLocation = null
      //       this.$refs.detailDom.isShowOpen = false
      //     }

      //     this.$refs.detailDom.rowData = rowData
      //     // 元数据
      //     FetchArchivesMetadata(params).then(res => {
      //       this.$refs.detailDom.xmlStr = res
      //     })
      //     this.$refs.detailDom.detailVisible = true
      //   }
      // })
    },
    // 首页 / 搜索页切换操作
    handleSearch() {
      if (this.select.length === 0) {
        this.$message.warning('请选择检索条件！')
        return
      }

      if (this.$route.path.indexOf('dashboard') !== -1) {
        this.$router.push('/archivesManage/archivesSearch')
        localStorage.setItem('homeSearchWords', this.keywords)
        localStorage.setItem('homeSearchSelect', JSON.stringify(this.select))
        // if (this.roles.includes('admin') || this.roles.includes('archivesSearch:list')) {

        // // localStorage.setItem('homeSearchCheckbox', JSON.stringify([3, 4, 5]))
        // } else {
        //   this.$message({
        //     message: '当前账号没有权限',
        //     type: 'warning'
        //   })
        // }
      } else {
        this.dimSearch()
      }
    },
    // 搜索
    dimSearch() {
      this.searchLoading = true
      this.loading = true
      // const homeSearchCheckbox = JSON.parse(localStorage.getItem('homeSearchCheckbox'))
      // if (homeSearchCheckbox) {
      //   this.checkList = homeSearchCheckbox
      // }
      const arr = this.keywords.trim() // 去空格
      if (arr.length === 0) { // 无关键词时无数据
        this.tableData = []
        this.resNum = 0
        this.isShow = false
        this.page.total = 0
        this.page.size = 10
        this.page.page = 1
        localStorage.removeItem('homeSearchWords')
        localStorage.removeItem('homeSearchSelect')
        this.searchLoading = false
        // localStorage.removeItem('homeSearchCheckbox')
      } else {
        this.params.categoryTypes = this.checkList.join(',')
        this.params.criteria = this.select.join(',')
        this.params.query = this.keywords.replace(/\s+/ig, ' ')
        this.params.page = this.page.page - 1
        this.params.size = this.page.size
        this.doQuery(this.params)
      }
    },
    // 调用搜索接口
    doQuery(params) {
      querySeniorArchives(params).then(res => {
        this.loading = false
        this.searchLoading = false
        this.tableData = res.content
        this.tableData.forEach((item, index) => {
          // 入库状态
          if (item.is_storage === 0) {
            this.storageTxt[index] = '未入'
            if (item.is_borrow === '') {
              this.borrowTxt[index] = '-'
            }
          } else if (item.is_storage === 1) {
            this.storageTxt[index] = '待入'
            if (item.is_borrow === '') {
              this.borrowTxt[index] = '-'
            }
          } else if (item.is_storage === 2) {
            this.storageTxt[index] = '已入'
            if (item.is_borrow === '') {
              this.borrowTxt[index] = '在库'
            }
          } else if (item.is_storage === 3) {
            this.storageTxt[index] = '待出'
            if (item.is_borrow === '') {
              this.borrowTxt[index] = '-'
            }
          } else if (item.is_storage === null) {
            this.storageTxt[index] = '未入'
            if (item.is_borrow === '') {
              this.borrowTxt[index] = '-'
            }
          }

          // 借阅状态
          if (item.is_borrow === 1) {
            this.borrowTxt[index] = '待借'
          } else if (item.is_borrow === 2) {
            this.borrowTxt[index] = '待借'
          } else if (item.is_borrow === 3) {
            this.borrowTxt[index] = '已借'
          } else if (item.is_borrow === null) {
            this.borrowTxt[index] = '在库'
          }
        })

        this.page.total = res.totalElements
        this.resNum = res.totalElements
        this.isShow = true
        localStorage.removeItem('homeSearchWords')
        localStorage.removeItem('homeSearchSelect')
      })
    },
    // 每页条数改变
    sizeChangeHandler(e) {
      this.loading = true
      this.page.size = e
      this.page.page = 1
      this.params.size = e
      this.params.page = 0
      this.doQuery(this.params)
      this.loading = false
    },
    // 当前页改变
    pageChangeHandler(e) {
      this.loading = true
      this.page.page = e
      this.params.page = e - 1
      this.doQuery(this.params)
      this.loading = false
    },
    // 获取密集架相关信息
    getDeviceListAll() {
      const params = {
        sort: 'sequence,asc',
        storeroomId: 'D6490DA3D4261E8C26D0E3'
      }
      CallExternal.getDeviceList(params).then(data => {
        data.content.map(item => {
          if (item.deviceTypeId.name === '密集架') { // 写死状态
            this.deviceData = item
          }
        })
      })
    },
    // 开架
    openCol() {
      const loactionArray = this.openLocation.split(' ')
      const location = this.openLocation.split(' ')[loactionArray.length - 1]
      const pattern = /(\d+)区(\d+)列(\d+)节(\d+)层/
      const matches = location.match(pattern)
      let areaNumber
      let colNumber
      let leNumber
      let divNumber
      let zyNumber
      if (matches !== null) {
        areaNumber = matches[1]
        colNumber = matches[2]
        leNumber = matches[3]
        divNumber = matches[4]
      }
      const last_char = location.length - 1
      if (location[last_char] === '右') {
        zyNumber = '2'
      } else {
        zyNumber = '1'
      }
      const params = {
        deviceId: this.deviceData.id,
        quNo: areaNumber, // 区
        colNo: colNumber, // 列
        leNo: leNumber, // 节
        divNo: divNumber, // 层
        zyNo: zyNumber // 左右  1左 2右
      }
      console.log(params)
      CallExternal.FetchCallExternalOpenCol(params).then(res => {
        if (res.success && res.success === '0') {
          this.$message.success('开架执行成功')
        } else {
          this.$message.error(res.msg)
        }
      }).catch((error) => {
        console.log(error)
        this.$message.error('连接失败')
      })
    },
    // 借阅
    handleLending() {
      const index = this.selections.findIndex((item) => item.is_storage === 0 || item.is_storage === '' || item.is_storage === 1)
      const index2 = this.selections.findIndex((item) => item.is_borrow === 3)
      const index3 = this.selections.findIndex((item) => item.is_storage === 3)
      if (index !== -1) {
        this.$message.error('所选档案还未入库不能借阅')
        return false
      }
      if (index3 !== -1) {
        this.$message.error('待出档案不可借阅')
        return false
      }
      if (index2 !== -1) {
        this.$message.error('当前档案已借出，还未归还')
        return false
      }
      const params = this.selections.map(item => {
        return item.archives_id
      })
      FetchIsExistBorrow(params).then(data => {
        if (data.length === 0) {
          this.lengingVisible = true
        } else if (data.length === this.selections.length) {
          this.$message.error('所选档案不可借阅')
        } else {
          this.$message.error('部分档案不可借阅')
        }
      })
    },
    // 确认借阅
    handleLendingConfirm() {
      const params = this.selections.map(item => {
        return item.archives_id
      })
      FetchAddArchivesWaitRegister(params).then(data => {
        if (data.length !== 0) {
          this.$message.success('借阅成功')
          this.lengingVisible = false
          this.params.categoryTypes = this.checkList.join(',')
          this.params.criteria = this.select.join(',')
          this.params.query = this.keywords.replace(/\s+/ig, ' ')
          this.params.page = this.page.page - 1
          this.params.size = this.page.size
          this.doQuery(this.params)
          this.selections = []
        }
      })
    },
    // 关闭
    handleClose(done) {
      this.lengingVisible = false
      done()
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/archives-manage.scss";
.search-main{
  width: 100%;
}
.head-container{
  padding: 80px 0 30px 0;
  text-align: center;
  h2{
    color: #fff;
    margin-bottom: 30px;
  }
}
.search-header{
  width: 50%;
  text-align: left;
  margin: 0 auto 10px auto;
  ::v-deep .el-checkbox-group{
    margin-left: 15px;

    .el-checkbox__label{
      color: #fff;
    }
  }
}
.search-area {
  height: 100%;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  & .search-input {
    & .el-select .el-input {
      width: 130px;
    }
  }
}
// 补充不生效
::v-deep .el-input-group {
  height: 42px;
  & > input {
    height: 42px;
    border: 1px solid #339cff;
    background-color: #021941;
    &::placeholder {
      color: #fff;
    }
  }
}
::v-deep .el-input-group__prepend {
  width: 125px;
  background-color: #339cff;
  border: 1px solid #339cff;
  border-radius: 34px 0 0 34px;
  border-right: 0;
}
::v-deep .el-input__inner {
  color: #fff;
}
::v-deep .el-input-group__prepend div.el-select .el-input__inner{
  color: #fff;
  text-align: center;
}
::v-deep .el-input-group__append {
  width: 72px;
  left: -20px;
  text-align: center;
  background-color: #339cff;
  border: 1px solid #339cff;
  border-radius: 34px;
  & i {
    font-size: 25px;
    color: #fff;
  }
}
//检索结果
.search-result{
  padding: 0 20px;
  color: #fff;
  .search-title{
    padding:0 20px;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    line-height: 32px;
    .search-res-left{
      flex: 1;
    }
    .search-res-num{
      flex: 1;
      text-align: right;
      margin-right: 30px;
    }
    .el-button{
      margin-right: 20px;
    }
    ::v-deep .el-checkbox{
      .el-checkbox__label{
        color: #fff;
      }
    }
  }
}
::v-deep ::-webkit-scrollbar-corner{
  background: transparent;
}
::v-deep .el-select__tags{
  max-width: 100% !important;
}
::v-deep .el-tag.el-tag--info{
  font-size: 14px;
  color: #fff;
  background-color: transparent !important;
  border: none !important;
  margin: 0 auto !important;
  .el-tag__close{
    color: #fff;
    display: none;
  }
  &:nth-child(2){
    display: none;
    margin: 6px 0 4px -4px !important;
  }
}

.lending-btn{
  border-color: #F65163;
  background-color: #F65163;
  &.is-disabled{
    color: #666;
    border-color:#7A2831;
    background-color: #7A2831;
  }
}
</style>
