<template>
  <div>
    <a-card :bordered="false" title="选择培训单位">
      <a-transfer
        class="tree-transfer"
        :data-source="dataSource"
        :target-keys="targetKeys"
        :render="item => item.title"
        :show-select-all="false"
        @change="onChange"
      >
        <template slot="children" slot-scope="{ props: { direction, selectedKeys }, on: { itemSelect } }">
          <a-tree
            v-if="direction === 'left'"
            blockNode
            checkable
            checkStrictly
            defaultExpandAll
            :checkedKeys="[...selectedKeys, ...targetKeys]"
            :treeData="treeData"
            @check="
              (_, props) => {
                onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect)
              }
            "
            @select="
              (_, props) => {
                onChecked(_, props, [...selectedKeys, ...targetKeys], itemSelect)
              }
            "
          />
        </template>
      </a-transfer>
    </a-card>
    <a-col :span="24" style="text-align: center;">
      <a-button type="primary" size="default" @click="toPrep" style="margin-right: 8px;">上一步</a-button>
      <a-button type="primary" v-if="['2', '3', '4'].includes(form.trainWay)" size="default" @click="toNext"
        >下一步</a-button
      >
      <a-button v-if="form.trainWay === '1'" size="default" @click="handleSubmit">保存</a-button>
    </a-col>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》'
import { orgList } from '@/api/org/org'
import { listToTree } from '@/utils/util'

const treeData = []

const transferDataSource = []

function flatten(list = []) {
  list.forEach(item => {
    transferDataSource.push(item)
    flatten(item.children)
  })
}
flatten(JSON.parse(JSON.stringify(treeData)))

function isChecked(selectedKeys, eventKey) {
  return selectedKeys.indexOf(eventKey) !== -1
}

export default {
  // import引入的组件需要注入到对象中才能使用
  components: {},
  props: { projectForm: { type: Object } },
  data() {
    // 这里存放数据
    return {
      form: this.projectForm,
      targetKeys: this.projectForm.unitIds || [],
      dataSource: transferDataSource,
      treeData: []
    }
  },
  // 计算属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    onChange(targetKeys) {
      console.log('Target Keys:', targetKeys)
      this.targetKeys = targetKeys
    },
    onChecked(_, e, checkedKeys, itemSelect) {
      const { eventKey } = e.node
      itemSelect(eventKey, !isChecked(checkedKeys, eventKey))
    },
    //获取数据源
    getSourceList(orgType) {
      orgList({ orgType: orgType || 1 }).then(res => {
        if (res.data) {
          this.dataSource = []
          res.data.forEach(item => {
            this.dataSource.push({
              id: item.id,
              key: item.id.toString(),
              title: item.name,
              children: [],
              pid: item.pid
            })
          })
          console.log('dataSource', this.dataSource)
          this.treeData = listToTree(this.dataSource, [], 0)
          console.log('treeData', this.treeData)
        }
      })
    },
    //下一步
    toNext() {
      this.form.unitIds = this.targetKeys
      if (this.form.unitIds.length > 0) {
        this.$emit('nextStep', this.form)
      } else {
        this.$message.warning('请选择培训单位')
      }
    },
    //上一步
    toPrep() {
      this.form.unitIds = this.targetKeys
      console.log('toPrep', this.form)
      this.$emit('prevStep', this.form)
    },
    //提交表单
    handleSubmit() {
      this.form.unitIds = this.targetKeys
      if (this.form.unitIds.length > 0) {
        this.$emit('executeSave', this.form)
      } else {
        this.$message.warning('请选择培训单位')
      }
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // console.log('第2个表单创建了')
    this.getSourceList()
    // console.log('form', this.form)
  },

  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  // 生命周期 - 创建之前
  beforeCreate() {},
  // 生命周期 - 挂载之前
  beforeMount() {},
  // 生命周期 - 更新之前
  beforeUpdate() {},
  // 生命周期 - 更新之后
  updated() {},
  // 生命周期 - 销毁之前
  beforeDestroy() {},
  // 生命周期 - 销毁完成
  destroyed() {
    console.log('第2个表单销毁了')
  },
  // 如果页面有keep-alive缓存功能，这个函数会触发
  activated() {}
}
</script>
<style scoped>
.tree-transfer .ant-transfer-list:first-child {
  width: 50%;
  flex: none;
}
</style>
