<template>
  <div id="handbookFiles" class="w100" v-if="isDialogsVisible">
    <el-dialog :append-to-body="true" width="1000px" :visible.sync="isDialogsVisible" title="选择关联记录" :close-on-click-modal=false :close-on-press-escape=false>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-scrollbar class="left_tree_wrapper">
            <el-tree
              ref="tree"
              class="filter-tree elTree"
              :props="props"
              :load="loadNode"
              node-key="id" lazy
              :expand-on-click-node="false"
              :default-expanded-keys="expandedList"
              @node-click="nodeClick"
            >
              <div slot-scope="{ node, data }" class="custom-tree-node w100">
                <p :title="node.label">
                  {{ node.label }}
                </p>
              </div>
            </el-tree>
          </el-scrollbar>
        </el-col>
        <el-col :span="18">
          <!--<el-scrollbar class="rightPart">-->
          <el-row>
            <el-col :span="12">
              <el-input v-model="keyWords" :placeholder="pleaseEnterTitle" :title="pleaseEnterTitle" class="search_component" clearable @keyup.13.native="getList">
                <el-button slot="append" icon="el-icon-search" type="primary" @click="pages.pageNum = 1;getList()" />
              </el-input>
            </el-col>
          </el-row>
          <!-- 信息表格 -->
          <el-table
            :data="dataList"
            class="main_tab"
            ref="multipleTable"
            stripe
            :header-cell-style="{background: '#E1EAFD !important'}"
            highlight-current-row
            :row-key="getRowKeys"
            @current-change="clickChange"
            @selection-change="handleSelectionChange"
            >
            <el-table-column :reserve-selection="true" type="selection" width="55"/>
            <el-table-column :label="number" type="index" width="50" />
            <el-table-column label="记录名称" prop="recordName" show-overflow-tooltip />
            <el-table-column prop="recordFormworkFileName" label="记录模板">
              <template slot-scope="scope">
                <a
                  class="oprateClass"
                  :href="host + '/document/print/' + scope.row.recordFormworkFile"
                  target="_blank"
                >{{ scope.row.recordFormworkFileName }}</a>
              </template>
            </el-table-column>
            <el-table-column prop="processName" label="所属流程">
              <template slot-scope="scope">
                <div @click="toDetails(scope.row)" class="oprateClass">
                      <span  :class="scope.row.processId ? 'word' : ''">
                        {{ scope.row.processName }}</span
                      >
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="systemName" label="关联制度">
              <template slot-scope="scope">
                <a
                  class="oprateClass"
                  :href="
                   '#/rulesDetail/' + scope.row.systemId + '/' + scope.row.systemVersion
                 "
                  target="_blank"
                >
                  {{ scope.row.systemName }}
                </a>
              </template>
            </el-table-column>
            <el-table-column label="创建人" prop="operatorName" show-overflow-tooltip />
            <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip />
          </el-table>
          <el-pagination style="margin-top: 10px;" :current-page.sync="pages.pageNum" :page-sizes="[10, 15, 20]" :page-size="pages.pageSize" background layout="prev, pager, next, jumper, total" :total="pages.total" @current-change="getList()" />
          <!--</el-scrollbar>-->
        </el-col>
      </el-row>
      <div style="margin-top: 10px;">
        <span v-for="(item, index) in selectedAll" :key="index" class="listItem">
          {{item.recordName }}
          <i @click="deleteSelectedItem(index)" class="el-icon-close"/>
        </span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isDialogsVisible = false">{{ $t('cancelAction') }}</el-button>
        <el-button type="primary" @click="submit">{{ $t('confirmButton') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  recordQuery,
  getTreeNode,
  getRecentPublished
} from '../../../../api/handbookFiles'
import paginations from '../../../../mixins/pagination_mixin'
import fileOperation from '../../../../mixins/fileDownView'

export default {
  mixins: [paginations, fileOperation],
  data () {
    return {
      // 组织树
      props: {
        label: "name",
        isLeaf: "isParent",
        children: "childLs",
      },
      modelid: '',
      dataList: [],
      expandedList: [],
      keyWords: '',
      type: '',
      pages: {
        pageSize: 10,
        pageNum: 1,
        total: 0
      },
      pleaseEnterTitle: this.$t('placeholderText.pleaseEnterTitle'),
      releasePeople: this.$t('releasePeople'),
      classificationSystem: this.$t('classificationSystem'),
      effectiveDate: this.$t('effectiveDate'),
      number: this.$t('bpa_number'),
      version: this.$t('version'),
      uploadTime: this.$t('uploadTime'),
      nodeData: {},
      isDialogsVisible: false,
      multipleSelection: [],
      selectedAll: [],
      selectIndex: -1,
      iechoEcho: false,
      tableRadio: ''
    }
  },
  computed: {
    host () {
      return this.$host
    }
  },
  props: {
    value: {
      type: Boolean,
      default: false
    },
    isMore: {
      type: Boolean,
      default: true
    },
    ruleSelected: {
      type: Array,
      default () {
        return []
      }
    }
  },
  mounted () {
  },
  watch: {
    value (val) {
      this.isDialogsVisible = val
      if (val) {
        this.iechoEcho = true
        this.selectedAll = JSON.parse(JSON.stringify(this.ruleSelected))
      } else {
        this.pages.pageNum = 1
        if(this.isMore){
          this.$refs.multipleTable.clearSelection();
        }
      }
    },
    isDialogsVisible (val) {
      this.$emit('input', val)
    }
  },
  methods: {
    deleteSelectedItem (index) {
      this.iechoEcho = true
      this.dataList.forEach((e, i) => {
        if (e.docId === this.selectedAll[index].docId) {
          this.$refs.multipleTable.toggleRowSelection(e, false)
        }
      })
      this.iechoEcho = false
      this.selectedAll.splice(index, 1)
      this.$forceUpdate()
    },
    nodeClick (data) {
      this.modelid = data.id
      this.type = data.foldername
      this.nodeData = data
      this.getList()
    },
    loadNode (node, resolve) {
      const id = node.data ? node.data.id : '0'
      getTreeNode(id, 0).then(res => {
        if (!res) return false
        if (id === '0') {
          this.expandedList = [res[0].id]
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(res[0].id)
            this.modelid = res[0].id
            this.type = res[0].foldername
            this.nodeData = res[0]
            this.getList()
          })
        }
        resolve(res)
      })
    },
    getRowKeys(row){
      return row.id // 每条数据的唯一识别值
    },
    // 多选
    handleSelectionChange (val) {
      console.log(this.multipleSelection)
      if(!this.iechoEcho){
        this.multipleSelection = val
        this.mergeSelected()
      }
    },
    mergeSelected () {
      let ids = this.multipleSelection.map(item => item.id)
      let selectedAllIds = this.selectedAll.map(item => item.id)
      this.multipleSelection.forEach(val=>{
        if(selectedAllIds.indexOf(val.id) === -1){ //如果list不存在选中的则新增
          this.selectedAll.push(val)
        }
      })
      //获取未选中的listid
      let listIds = this.dataList.filter(item => !ids.includes(item.id)).map(item=> item.id)
      //获取未选中listid对应的obj
      let checkList = this.selectedAll.filter(item => !listIds.includes(item.id));
      console.log(checkList)
      this.selectedAll = checkList
    },
    selectedCheck () {
      this.iechoEcho = true
      this.$refs.multipleTable.clearSelection();
      this.$nextTick(()=>{
        this.dataList.forEach(item => {
          this.selectedAll.forEach(v => {
            if (item.id === v.id) {
              if (this.$refs.multipleTable) {
                this.$refs.multipleTable.toggleRowSelection(item, true)
              }
            }
          })
        })
        this.iechoEcho = false
        this.$forceUpdate()
      })
    },
    getList () {
      const obj = {
        orderby: 'createon',
        pageNum: this.pages.pageNum,
        pageSize: this.pages.pageSize,
        sort: 'desc',
        logic: 'or',
        filters: [
          { key: 'title', opt: 'LIKE', type: 'S', value: this.keyWords }
        ],
        attr: { folderid: this.modelid }
      }
      recordQuery(obj).then(res => {
        if (!res) return false
        this.dataList = res.list
        this.pages.total = res.total
        console.log(this.dataList)
        if (this.isMore && this.selectedAll) {
          this.selectedCheck()
        }
      })
    },
    submit () {
      // if(JSON.stringify(this.tableRadio) === '{}'){
      //   return;
      // }
      //  this.$emit('confirm', this.tableRadio)
      if (this.isMore) {
        const data = JSON.parse(JSON.stringify(this.selectedAll))
        this.$emit('confirm', data)
      } else {
        if (this.selectIndex >= 0) {
          const data = JSON.parse(JSON.stringify(this.dataList[this.selectIndex]))
          this.$emit('confirm', data)
        }
      }
      this.isDialogsVisible = false
    },
    clickChange(item){
        this.tableRadio = item
        console.log(this.tableRadio,item)
    },
    // 流程详情
    toDetails(item) {
      getRecentPublished({
        filters: [
          { key: "name", opt: "LIKE", type: "S", value: item.processName },
          { key: "modelid", value: item.processId },
        ],
      }).then((res) => {
        if (res.list.length < 1) {
          this.$message.error("流程未发布不能查看！！！");
        } else {
          var url = "#/processDetails/" + res.list[0].id;
          window.open(url, "_blank");
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.oprateClass{
  cursor: pointer;
  color: #2d42af !important;
  margin: 0 5px;
}
  .listItem {
    background: #2d42af;
    color: #fff;
    padding: 10px;
    margin: 0 10px 10px 0;
    display: inline-block;
    text-align: center;
    i {
      cursor: pointer;
    }
  }
  .search_component {
    margin-bottom: 15px;
    max-width: 240px;
    vertical-align: middle;
    /deep/ .el-input__inner{
      border-color: #2d42af;
    }
    /deep/ .el-input-group__append {
      background-color: #2d42af;
      border-color: #2d42af;
      &:hover {
        background-color: #5768bf;
        border-color: #5768bf;
      }
      span {
        color: #fff;
      }
    }
  }
  .left_tree_wrapper.el-scrollbar {
    height: 450px!important;
    .custom-tree-node {
      width: calc(100% - 24px);
      display: flex;
      align-items: center;
      box-sizing: border-box;
      p {
        max-width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
  .rightPart {
    height: calc(100vh - 160px) !important;
  }
</style>
