<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form label-width="50px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="安全生产管理制度名称:" label-width="200px">
              <el-input v-model="form.KEYWORDS" placeholder="请输入" class="filter-item"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="10px">
              <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getQuery">
                搜索
              </el-button>
              <el-button v-waves class="filter-item" type="success" icon="el-icon-magic-stick" @click="addCondition">
                添加其他搜索条件
              </el-button>
              <el-button v-waves class="filter-item" type="success" icon="el-icon-magic-stick" @click="clearMessage">
                重置
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-table
      v-loading="listLoading"
      ref="multipleTable"
      :row-key="getRowKey"
      :data="varList"
      :header-cell-style="{
        'font-weight': 'bold',
        'color': '#000'
      }"
      :row-class-name="tableRowClassName"
      tooltip-effect="dark"
      border
      fit
      highlight-current-row
      @cell-mouse-enter="enterSelectionRows"
      @cell-mouse-leave="leaveSelectionRows">
      <el-table-column
        v-if="false"
        :reserve-selection="true"
        type="selection"
        width="55"
        align="center"
      />
      <el-table-column type="expand">
        <template slot-scope="props">
          <div style="text-align: left;padding: 10px;">
            <el-form label-position="left" inline>
              <el-form-item label="标签">
                <el-tag
                  v-for="tag in props.row.labels"
                  :key="tag.BUS_LIBRARY_LABELS_ID"
                  :disable-transitions="false"
                  type="warning"
                  style="margin-right: 10px;margin-bottom: 10px">
                  {{ tag.NAME }}
                </el-tag>
              </el-form-item>
              <el-form-item label="国民经济行业类型">
                <div v-if="(props.row.SPECIFICATION_TYPES && props.row.SPECIFICATION_TYPES.length > 0) && ((!props.row.CATEGORY_LIST) || (!props.row.CATEGORY_LIST[0]) || (props.row.CATEGORY_LIST[0].CATEGORY_ID !== '691346658ed744a1bda2ed3a755f606c')) ">
                  <el-tag
                    v-for="tag in props.row.SPECIFICATION_TYPES"
                    :key="tag.BUS_LIBRARY_LABELS_ID"
                    :disable-transitions="false"
                    type="warning"
                    style="margin-right: 10px;margin-bottom: 10px">
                    {{ tag.CATEGORY_NAME }}
                  </el-tag>
                </div>
                <div v-else>
                  <el-tag type="warning">通用</el-tag>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </template>
      </el-table-column>
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column align="center" prop="REMARKS" label="安全生产管理制度名称" />
      <el-table-column align="center" prop="TYPES" label="类型" >
        <template slot-scope="{row}">
          <el-tag
            v-for="tag in row.TYPES"
            :key="tag.BUS_LIBRARY_LABELS_ID"
            :disable-transitions="false"
            type="warning"
            style="margin-right: 10px;margin-bottom: 10px">
            {{ tag.CATEGORY_NAME }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="false" prop="LABEL" align="center" label="标签" >
        <template slot-scope="{row}">
          <el-tag
            v-for="tag in row.labels"
            :key="tag.BUS_LIBRARY_LABELS_ID"
            :disable-transitions="false"
            type="warning"
            style="margin-right: 10px;margin-bottom: 10px">
            {{ tag.NAME }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column v-if="false" align="center" prop="SPECIFICATION_TYPES" label="国民经济行业类型" width="300px">
        <template slot-scope="{row}">
          <div v-if="(row.SPECIFICATION_TYPES && row.SPECIFICATION_TYPES.length > 0) && ((!row.CATEGORY_LIST) || (!row.CATEGORY_LIST[0]) || (row.CATEGORY_LIST[0].CATEGORY_ID !== '691346658ed744a1bda2ed3a755f606c')) ">
            <el-tag
              v-for="tag in row.SPECIFICATION_TYPES"
              :key="tag.BUS_LIBRARY_LABELS_ID"
              :disable-transitions="false"
              type="warning"
              style="margin-right: 10px;margin-bottom: 10px">
              {{ tag.CATEGORY_NAME }}
            </el-tag>
          </div>
          <div v-else>
            <el-tag type="warning">通用</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="UPLOAD_TIME" label="上传时间" width="200px"/>
      <el-table-column v-if="false" :show-overflow-tooltip="true" align="center" prop="UPLOAD_USER_NAME" width="100px" label="数据来源" >
        <template slot-scope="{row}">
          {{ '资源库数据' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200px">
        <template slot-scope="{row}">
          <el-row>
            <el-col :span="14">
              <el-button v-show="!row.LOCKTOOL" type="primary" icon="el-icon-edit" size="mini" @click="handleExport(row)">导出</el-button>
            </el-col>
            <el-col :span="10">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="getInformation(row)">查看</el-button>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-btn-group">
      <div/>
      <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
    <edit-text-library ref="editTextLibrary" :title="title" @logical-end="saveClose"/>
    <text-library-info ref="textLibraryInfo"/>
    <update-spe-file ref="updateFile"/>
    <update-log ref="updateLog"/>
    <condition ref="condition" @getResult="getCondition"/>
  </div>
</template>
<style>
.el-table .warning-row {
  background: oldlace;
}
</style>
<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves'
import editTextLibrary from './editTextLibrary.vue'
import textLibraryInfo from './textLibraryInfo.vue'
import updateFile from './updateSpeFile.vue'
import updateLog from './updateLog.vue'
import condition from './condition.vue'
import UpdateSpeFile from './updateSpeFile.vue'
export default {
  components: { UpdateSpeFile, Pagination, editTextLibrary, textLibraryInfo, updateFile, updateLog, condition },
  directives: { waves },
  data() {
    return {
      config: config,
      listLoading: true,
      add: false,
      del: false,
      edit: false,
      listQuery: {
        page: 1,
        limit: 10
      },
      total: 0,
      form: {
        KEYWORDS: '',
        labels: [],
        CATEGORY_LIST: [],
        TYPES: [],
        SPECIFICATION_TYPES: [],
        STATUS: ''
      },
      label_name: '',

      varList: [],
      pd: [],
      isEdit: false,
      isLook: false,
      title: ''
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getRowKey(row) {
      return row.BUS_TEXT_LIBRARY_ID
    },
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    addCondition() {
      this.$refs.condition.init()
    },
    getCondition(info) {
      this.form.CATEGORY_LIST = info.CATEGORY_LIST
      this.form.TYPES = info.TYPES
      this.form.SPECIFICATION_TYPES = info.SPECIFICATION_TYPES
      this.form.labels = info.LABELS
    },
    clearMessage() {
      this.label_name = ''
      this.form = {
        KEYWORDS: '',
        labels: [],
        CATEGORY_LIST: [],
        TYPES: [],
        SPECIFICATION_TYPES: [],
        STATUS: ''
      }
      this.$refs.condition.clear()
      this.getList()
    },
    getList() {
      this.listLoading = true
      requestFN(
        '/textLibrary/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.form.KEYWORDS,
          CATEGORY_LIST: JSON.stringify(this.form.CATEGORY_LIST),
          TYPES: JSON.stringify(this.form.TYPES),
          SPECIFICATION_TYPES: JSON.stringify(this.form.SPECIFICATION_TYPES),
          labels: JSON.stringify(this.form.labels),
          STATUS: this.form.STATUS,
          ASSOCIATION: '1',
          CORPINFO_ID: '0',
          LIBRARY_FLAG: '1'
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.total = data.page.totalResult
        this.hasButton()
        this.pd = data.pd
      }).catch((e) => {
        this.listLoading = false
      })
    },
    handleAdd() {
      this.title = '新增'
      this.$refs.editTextLibrary.init()
    },
    handleEdit(e) {
      this.title = '编辑'
      this.$refs.editTextLibrary.init({ e: e, isEdit: true })
    },
    getInformation(e) {
      this.$refs.textLibraryInfo.init({ e: e })
    },
    handleDelete(e) {
      this.$confirm('确定要删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/textLibrary/delete',
          {
            BUS_TEXT_LIBRARY_ID: e.BUS_TEXT_LIBRARY_ID
          }
        ).then((data) => {
          if (data.code === '0') {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.listLoading = false
            this.varList = []
            this.listQuery.page = 1
            this.getList()
          } else {
            this.listLoading = false
            this.$message.error(data.errorMessage)
          }
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch((e) => {
        console.log(e)
      })
    },
    handleLock(e, flag) {
      this.$confirm(flag === '1' ? '确定要锁定吗?' : '确定要解锁吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/textLibrary/lock',
          {
            BUS_TEXT_LIBRARY_ID: e.BUS_TEXT_LIBRARY_ID,
            isLock: flag
          }
        ).then(() => {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch((e) => {
        console.log(e)
      })
    },
    handleTop(e, flag) {
      this.$confirm(flag === '1' ? '确定要置顶吗?' : '确定要取消置顶吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/textLibrary/top',
          {
            BUS_TEXT_LIBRARY_ID: e.BUS_TEXT_LIBRARY_ID,
            isTop: flag
          }
        ).then(() => {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch((e) => {
        console.log(e)
      })
    },
    handleExport(e) {
      this.$confirm('确定要导出文件吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (e.MIGRATION_FLAG === '1') {
          window.open(config.fileUrl + e.PATH)
        } else {
          window.open(e.PATH)
        }
      }).catch((e) => {
        console.log(e)
      })
    },
    batchDel() {
      const _selectData = this.$refs.multipleTable.selection
      if (_selectData == null || _selectData.length == 0) {
        this.$message({
          message: '请选中要删除的项...',
          type: 'error'
        })
        return false
      }
      const _ids = _selectData.filter((item, index) => {
        return item.LOCKTOOL
      })
      if (_ids.length > 0) {
        this.$message.error('选中的数据有锁定数据,请重新选择')
        return
      }
      const ids = _selectData.map((item, index) => {
        return item.BUS_TEXT_LIBRARY_ID
      }).join(',')

      this.$confirm('确定要删除选中的数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/textLibrary/deleteAll',
          {
            DATA_IDS: ids
          }
        ).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.$refs.multipleTable.clearSelection()
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    hasButton: function() {
      var keys = 'textlibraryTwo:add,textlibraryTwo:del,textlibraryTwo:edit,toExcel'
      requestFN(
        '/head/hasButton',
        {
          keys: keys
        }
      ).then((data) => {
        this.add = data.textlibraryTwofhadminadd		// 新增权限
        this.del = data.textlibraryTwofhadmindel		// 删除权限
        this.edit = data.textlibraryTwofhadminedit	// 修改权限
      }).catch((e) => {
        this.listLoading = false
      })
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.ISTOPTIME) {
        return 'warning-row'
      }
    },
    saveClose(e) {
      this.getList()
    },
    openUpdateFile(row) {
      this.$refs.updateFile.init(row)
    },
    openUpdateLog(row) {
      this.$refs.updateLog.init(row)
    },
    setStatus(row, status) {
      this.listLoading = true
      this.$confirm('是否更改状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        requestFN(
          '/textLibrary/setStatus',
          {
            BUS_TEXT_LIBRARY_ID: row.BUS_TEXT_LIBRARY_ID,
            STATUS: status
          }
        ).then((data) => {
          this.listLoading = false
          this.$message({
            type: 'success',
            message: '修改成功!'
          })
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
        this.listLoading = false
      })
    },
    handleCopy(row) {
      this.$confirm('确定要将此条数据添加到本地', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.copyInfo(row)
      }).catch((e) => {
        console.log(e)
        this.$message({
          type: 'info',
          message: '已取消添加'
        })
      })
    },
    copyInfo(row) {
      requestFN(
        '/textLibrary/copyToOperate?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        { BUS_TEXT_LIBRARY_ID: row.BUS_TEXT_LIBRARY_ID }
      ).then((data) => {
        if (data.code === '0') {
          this.$message.success('添加成功')
        } else {
          this.$message.success('添加失败')
        }
      }).catch((e) => {
        this.$message.success('添加失败')
      })
    },
    enterSelectionRows(row, column, cell, event) {
      if (row.ISTOPTIME) {
        this.createTips(event, row, '数据已置顶')
      }
    },
    leaveSelectionRows(row, column, cell, event) {
      if (row.ISTOPTIME) {
        this.removeTips(row)
      }
    },
    createTips(el, row, value) {
      const { BUS_TEXT_LIBRARY_ID } = row
      const tooltipDom = document.createElement('div')
      tooltipDom.style.cssText = `
        display: inline-block;
        max-width: 400px;
        max-height: 400px;
        position: absolute;
        top: ${el.clientY + 5}px;
        left: ${el.clientX}px;
        padding:5px 10px;
        overflow: auto;
        font-size: 12px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #595959;
        background: #fff;
        border-radius: 5px;
        z-index: 19999;
        box-shadow: 0 4px 12px 1px #ccc;
      `
      tooltipDom.innerHTML = value
      tooltipDom.setAttribute('id', `tooltip-${BUS_TEXT_LIBRARY_ID}`)
      // 将浮层插入到body中
      document.body.appendChild(tooltipDom)
    },
    removeTips(row) {
      console.log(row, 'row')
      const { BUS_TEXT_LIBRARY_ID } = row
      const tooltipDomLeave = document.querySelectorAll(`#tooltip-${BUS_TEXT_LIBRARY_ID}`)
      if (tooltipDomLeave.length) {
        tooltipDomLeave.forEach(dom => {
          document.body.removeChild(dom)
        })
      }
    }
  }
}
</script>