<template>
  <div class="dg-knowledge-base-select">
    <el-button
      :title="formItem.tooltip"
      :style="formItem.btnStyle"
      type="primary"
      :icon="formItem.icon"
      size="mini"
      :plain="formItem.plain"
      :round="formItem.round"
      :circle="formItem.circle"
      :disabled="formItem.disabled"
      @click="handleClick()"
    >
      <span>{{ formItem.title ? formItem.title : '选择' }}</span>
    </el-button>
    <el-dialog title="文件选择" :visible.sync="dialogVisible" :append-to-body="true" @close="handleClose">
      <dg-table
        v-if="dialogVisible"
        ref="multipleTable"
        row-key="KL_ID"
        :toolbar-items="kl_toolbarItems"
        :table-items="kl_tableItems"
        api-code="sysKnowledge"
        :query-terms="'KL_NODE=' + rowCode"
        :height="height"
        @selectionChange="selectionColChange"
      >
      </dg-table>
    </el-dialog>
    <template v-if="tableModel.tableData.length > 0">
      <el-table ref="knowledgeBaseTable" :data="tableModel.tableData" style="width: 100%">
        <template v-for="item in tableModel.list_tableItems">
          <el-table-column :key="item.KL_ID" :label="item.title" :prop="item.field" :width="item.width">
            <template slot-scope="scope">
              {{ scope.row[item.field] }}
              <div v-if="item.actions && item.actions.length > 0">
                <span v-for="(inItem, idx) in item.actions" :key="idx">
                  <el-button
                    :icon="inItem.icon"
                    :plain="inItem.plain"
                    :type="inItem.type"
                    size="small"
                    :style="inItem.style"
                    :tooltip="item.tooltip"
                    @click="clickHandle(item, scope.row, scope.$index, $event, inItem)"
                  ></el-button>
                </span>
              </div>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </template>
  </div>
</template>

<script>
export default {
  name: 'DgKnowledgeBaseSelect',
  props: {
    formItem: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      dialogVisible: false,
      rowCode: '',
      selectOptions: [],
      kl_toolbarItems: [
        { editer: 'input', placeholder: '请输入文档名称', value: 'KL_TITLE' },
        { editer: 'cascader', placeholder: '发布单位', value: 'PUBLISH_UNIT', options: [] },
        { title: '查询', type: 'primary', editer: 'search', icon: 'el-icon-search' },
        { title: '确定', type: 'primary', editer: 'button', fn: this.handleFileAdd, formItemStyle: 'float:right' },
      ],
      kl_tableItems: [
        { title: '', type: 'selection', width: 50, reserveSelection: true, fixed: 'left' },
        { field: 'KL_TITLE', title: '文件名称', align: 'left', render: this.knowledgeName },
        { field: 'FILE_SIZE', title: '文件大小', align: 'left', width: 80 },
        { field: 'PUBLISH_UNIT', title: '发布单位', align: 'left' },
        { field: 'PUBLISHER', title: '上传用户', align: 'left', width: 100 },
        { field: 'CREATE_TIME', title: '上传时间', align: 'left', sortable: true, width: 160 },
        {
          field: 'NAME_SIX',
          title: '操作',
          align: 'left',
          width: 80,
          actions: [
            {
              tooltip: '下载',
              type: 'primary',
              plain: true,
              icon: 'el-icon-dg-download',
              style: 'padding: 8px; border: none',
              fn: this.handleKLDownload,
            },
          ],
        },
      ],
      tableModel: {
        list_tableItems: [
          { field: 'KL_TITLE', title: '文件名称', align: 'left', render: this.knowledgeName },
          { field: 'FILE_SIZE', title: '文件大小', align: 'left', width: 100 },
          { field: 'PUBLISH_UNIT', title: '发布单位', align: 'left' },
          { field: 'PUBLISHER', title: '上传用户', align: 'left', width: 100 },
          { field: 'CREATE_TIME', title: '上传时间', align: 'left', sortable: true, width: 180 },
          {
            field: 'NAME_SIX',
            title: '操作',
            align: 'left',
            width: 120,
            actions: [
              {
                tooltip: '下载',
                type: 'primary',
                plain: true,
                icon: 'el-icon-dg-download',
                style: 'padding: 8px; border: none',
                fn: this.handleKLDownload,
              },
              {
                tooltip: '删除',
                type: 'danger',
                plain: true,
                icon: 'el-icon-delete',
                style: 'padding: 8px; border: none; margin: 0 10px',
                fn: this.handleKLDelCol,
              },
            ],
          },
        ],
        tableData: [],
      },
      height: '350px',
    }
  },
  watch: {
    'formItem.fileList': {
      deep: true,
      immediate: true,
      handler: function (newVal, oldVal) {
        console.log('监听：fileList----', newVal)
        if (newVal && newVal.length > 0) {
          this.tableModel.tableData = this.formItem.fileList
        }
      },
    },
    'formItem.list_tableItems': {
      deep: true,
      immediate: true,
      handler: function (newVal, oldVal) {
        console.log('监听：formItem.list_tableItems----', newVal)
        if (newVal) {
          this.tableModel.list_tableItems = newVal
        }
      },
    },
  },
  created() {
    console.log('知识库选择组件', this.formItem)
  },
  methods: {
    // 获取组织树
    async getOrgTreeData() {
      let orgs = await this.$store?.dispatch('knowledge/getOrgTreeData')
      this.kl_toolbarItems.find((item) => item.value === 'PUBLISH_UNIT').options = orgs
    },
    async handleKLDownload(action, row, index) {
      if (row.FILE_ADDR) {
        let [name, addr] = row.FILE_ADDR.split(',')
        // let token = localStorage.getItem('token');
        let fileAddr = addr.split('/')[2]
        const res = await this.$api.downloadFile({
          path: addr,
          name: name,
        })
      }
    },
    handleClick() {
      this.dialogVisible = true
      this.getOrgTreeData()
      // 数据加载完毕
      let _this = this
      this.$nextTick(() => {
        _this.toggleSelection(_this.tableModel.tableData)
      })
    },
    // 点击弹窗确定按钮
    handleFileAdd() {
      if (this.selectOptions.length === 0) {
        this.$message.warning('请至少选择一项！')
      } else {
        this.tableModel.tableData = this.selectOptions
        // 触发父组件数据变更方法
        this.formItem.handleDataChange(this.tableModel.tableData, this.formItem.value)
        this.handleClose()
      }
    },
    // 勾选弹窗table选项
    selectionColChange(val) {
      this.selectOptions = val
    },
    // 设置选中的项
    toggleSelection(rows) {
      if (rows.length > 0) {
        rows.forEach((row) => {
          this.$refs.multipleTable.$refs.DgTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.$refs.DgTable.clearSelection()
      }
    },
    handleKLDelCol(action, row, index, e) {
      this.$confirm('是否确定删除该项？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error',
      }).then(() => {
        this.tableModel.tableData.splice(index, 1)
        // 触发父组件数据变更方法
        this.formItem.handleDataChange(this.tableModel.tableData, this.formItem.value)
      })
    },
    handleClose() {
      this.dialogVisible = false
    },
    clickHandle(action, row, index, e, inItem) {
      inItem.fn(action, row, index, e)
    },
  },
}
</script>
