<template>
  <div>
    <a-card :bordered="false" title="新增人员">
      <template slot="extra">
        <a-button type="primary" @click="goback">返回</a-button>
      </template>
      <a-row type="flex" justify="center" align="top">
        <a-col :span="4" id="tree">
          <a-page-header title="项目列表" sub-title="" />
          <div v-if="this.orgTree != ''">
            <a-tree
              :treeData="orgTree"
              v-if="orgTree.length"
              @select="onSelect"
              :defaultExpandAll="true"
              :defaultExpandedKeys="defaultExpandedKeys"
              :defaultSelectedKeys="defaultSelectedKeys"
              :replaceFields="replaceFields"
            >
              <a-icon slot="switcherIcon" type="down" />
            </a-tree>
          </div>
        </a-col>
        <a-col :span="20" id="content">
          <a-page-header title="人员选择" sub-title="" />
          <a-transfer
            class="org-transfer"
            :titles="['未选中', '已选择']"
            :operations="['添加', '移除']"
            :data-source="mockData"
            :target-keys="targetKeys"
            :show-search="true"
            :filter-option="(inputValue, item) => item.title.indexOf(inputValue) !== -1"
            :show-select-all="false"
            @change="onChange"
          >
            <template
              slot="children"
              slot-scope="{
                props: { direction, filteredItems, selectedKeys, disabled: listDisabled },
                on: { itemSelectAll, itemSelect },
              }"
            >
              <a-table
                :row-selection="
                  getRowSelection({ disabled: listDisabled, selectedKeys, itemSelectAll, itemSelect })
                "
                :columns="direction === 'left' ? leftColumns : rightColumns"
                :data-source="filteredItems"
                size="small"
                :style="{ pointerEvents: listDisabled ? 'none' : null }"
                :custom-row="
                  ({ key, disabled: itemDisabled }) => ({
                    on: {
                      click: () => {
                        if (itemDisabled || listDisabled) return;
                        itemSelect(key, !selectedKeys.includes(key));
                      },
                    },
                  })
                "
              />
            </template>
          </a-transfer>

          <div class="draw-button-container align-right">
            <a-button type="primary" @click="onSubmit">保存</a-button>
          </div>
        </a-col>
      </a-row>
    </a-card>
  </div>
</template>

<script>
import difference from 'lodash/difference'
import { orgList } from '@/api/org/org'
import { listToTree } from '@/utils/util'
import { personPage } from '@/api/person/person'
import { listPersonByOrgId, addPersonOrg } from '@/api/person/personOrg'
import { STable } from '@/components'

const mockData = []

const leftTableColumns = [
  { title: '姓名', dataIndex: 'title' },
  { title: '用户名', dataIndex: 'description' }
]
const rightTableColumns = [
  { title: '姓名', dataIndex: 'title' },
  { title: '用户名', dataIndex: 'description' }
]

export default {
  components: {
    orgList,
    STable
  },
  data () {
    // 这里存放数据
    return {
      form: this.projectForm,
      // 查询参数
      queryParam: { orgType: 2 },
      replaceFields: { children: 'children', title: 'name', key: 'id', value: 'id' },
      expandedKeys: [],
      autoExpandParent: true,
      defaultExpandedKeys: [],
      defaultSelectedKeys: [],
      orgTree: [],
      orgId: this.$route.query.orgId,
      orgType: 2,
      mockData: mockData,
      targetKeys: [],
      leftColumns: leftTableColumns,
      rightColumns: rightTableColumns,
      isLoading: false
    }
  },
  mounted () {
    this.getPerson()
    this.listPerson()
  },
  // 方法集合
  methods: {
    // 返回
    goback () {
      this.$router.push({
        path: '/personList',
        query: {
          orgType: 2
        }
      })
    },
    async getPerson () {
      await personPage({ pageSize: 9999, pageNum: 1 }).then((res) => {
        if (res.code === 200 && res.rows.length > 0) {
           this.mockData = res.rows.map(item => {
             return {
               key: item.id.toString(),
               title: item.name,
               description: item.userName,
               disabled: false
             }
           })
        }
      })
    },
    async listPerson () {
      await listPersonByOrgId({ orgId: this.orgId }).then((response) => {
        if (response.code === 200 && response.data.length > 0) {
          mockData.filter(item => response.data.indexOf(item.key) > 0).map(item => item.key)
          const newArray = response.data.map(item => { return item.toString() })
          this.targetKeys = newArray
        }
      })
    },
    onSubmit () {
      if (this.isLoading) {
        return false
      }
      this.isLoading = true
      addPersonOrg({ personIds: this.targetKeys, orgId: this.orgId }).then(res => {
        if (res.code === 200) {
          this.$message.success('保存成功')
        } else {
          this.$message.error('保存失败：' + res.msg)
        }
      })
      this.isLoading = false
    },
    onChange (nextTargetKeys) {
      this.targetKeys = nextTargetKeys
    },
    triggerShowSearch (showSearch) {
      this.showSearch = showSearch
    },
    getRowSelection ({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
      return {
        getCheckboxProps: item => ({ props: { disabled: disabled || item.disabled } }),
        onSelectAll (selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .filter(item => !item.disabled)
            .map(({ key }) => key)
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys)
          itemSelectAll(diffKeys, selected)
        },
        onSelect ({ key }, selected) {
          itemSelect(key, selected)
        },
        selectedRowKeys: selectedKeys
      }
    },

    // 选中后触发
    onSelect (selectedKey, info) {
      this.queryParam.orgId = selectedKey.toString()
      this.orgId = selectedKey.toString()
      this.mockData = []
      this.targetKeys = []
      this.getPerson()
      this.listPerson()
    },

    // 树使用的方法
    onExpand (expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },

    // 编辑时初始化人员列表初始化
    initPersonList () {
      if (this.form.personIds) {

      }
    },

    /**
     * 获取到机构树，展开顶级下树节点，考虑到后期数据量变大，不建议全部展开
     */
    async getOrgTree () {
      await orgList({ orgType: this.orgType, pid: this.$route.query.orgId }).then((res) => {
        this.treeLoading = false
        if (!res.code === 200 || !res.data.length) {
          return
        }
        var rootParentId = res.data[0].pid
        this.defaultExpandedKeys = []
        this.defaultSelectedKeys = []
        this.orgTree = listToTree(res.data, [], rootParentId)
        this.orgId = this.orgTree[0].id
        this.defaultSelectedKeys.push(this.orgId)
        for (var item of this.orgTree) {
          if (item.pid === 0) {
            this.defaultExpandedKeys.push(item.id)
          }
        }
      })
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.getOrgTree()
  }
}
</script>
<style lang="less" scoped>
.org-transfer {
  display: flex;
  align-items: center;
  height: 100%;
  padding: 24px 24px 75px;
  /deep/ .ant-transfer-list {
    flex: 1;
    height: 100%;
  }
  /deep/ .ant-transfer-list-body{
    overflow-y: auto;
  }
  /deep/ .ant-transfer-operation .ant-btn {
    margin-left: 0;
  }
}
</style>
