<template>
  <div>
    <el-card>
      <div slot="header">
        <span>{{ title }}</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="_open">
          刷新
        </el-button>
      </div>
      <div
        style="overflow-x: auto;"
        :style="{height:ztreeHeight}"
      >
        <ul :id="treeId" class="ztree" />
      </div>
      <div>
        <el-button type="primary" :loading="loading" size="small" @click="_ok">
          保存
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
/**
 * 菜单+表格+表格列Ztree(公司自己可以再分配)
 */
import { sysTableColumn } from '../../../api'
export default {
  name: 'TableColConfig',
  data() {
    return {
      title: '分配表格列',
      treeId: 'col-config',
      height: '',
      idObj: {
        // 不传id参数后台默认保存当前登录人所在公司
        tableColumnIds: []
      },
      setting: {
        data: {
          simpleData: {
            enable: true,
            idKey: 'id',
            pIdKey: 'pid'
          }
        },
        check: {
          enable: true
        },
        view: {
          showIcon: false
        },
        callback: {
          onClick: this.zTreeOnClick
        }
      },
      treeObj: {},
      loading: false
    }
  },
  computed: {
    ztreeHeight: function() {
      return this.$tableHeight('', 250) + 'px'
    }
  },
  mounted() {
    this._open()
  },
  methods: {
    _open() {
      this.loading = false
      this._getTree()
    },
    _getTree: async function() {
      // 获取当前登录公司的表格列tree
      const result = await sysTableColumn.currentCompanyTree()
      this.treeObj = $.fn.zTree.init($('#' + this.treeId), this.setting, result)
      this._echoTree()
    },
    zTreeOnClick(event, treeId, treeNode) {
      this.treeObj.checkNode(treeNode, !treeNode.checked, true)
    },
    // 回显选中的节点树(当前公司所选中的数据)
    _echoTree: async function() {
      const result = await sysTableColumn.getByCurrentCompanyId()
      if (result.length > 0) {
        for (let i = 0; i < result.length; i++) {
          const node = this.treeObj.getNodeByParam('id', result[i], null)
          if (node) {
            this.treeObj.checkNode(node, true)
          }
        }
      }
    },
    _resultChange(result, msg) {
      if (result) {
        this.$message.success(msg)
      }
      this.loading = false
    },
    _ok() {
      this.$confirm('操作后会重置个人所设置的列数据，确定要保存？', '提示', {
        type: 'warning'
      }).then(() => {
        this._confirmOk()
      })
    },
    _confirmOk: async function() {
      this.loading = true
      const nodesList = []
      const nodes = this.treeObj.getCheckedNodes(true)
      for (let i = 0; i < nodes.length; i++) {
        if (!nodes[i].uri) {
          // 说明是表格列
          nodesList.push(nodes[i].id)
        }
      }
      this.idObj.tableColumnIds = nodesList
      const result = await sysTableColumn.companySave(this.idObj)
      this._resultChange(result, '保存成功!')
    }
  }
}
</script>
