<template>
  <a-modal
    width="800px"
    title="角色列表"
    :visible="value"
    @cancel="$emit('change', false)"
    @ok="selectRole"
  >
    <a-transfer
      :data-source="mockData"
      :list-style="{
        width: '300px',
        height: '500px',
      }"
      show-search
      :target-keys="targetKeys"
      :render="(item) => item.title"
      @change="handleChange"
    />
  </a-modal>
</template>

<script>
import dataService from './data-config'
export default {
  model: { prop: 'value', event: 'change' },
  props: { value: Boolean },
  data() {
    return {
      mockData: [],
      targetKeys: [],
      roleList: [],
    }
  },
  watch: {
    value(val) {
      if (val) {
        this.getRoleList()
      }
    },
  },
  methods: {
    handleChange(nextTargetKeys, direction, moveKeys) {
      this.targetKeys = nextTargetKeys
    },
    getRoleList() {
      dataService.rolesList().then((res) => {
        this.roleList = res
        this.mockData = res.map((item) => {
          return {
            key: item.code,
            title: item.name,
            description: item.code,
          }
        })
      })
    },
    selectRole() {
      const arr = []
      this.roleList.forEach((item) => {
        if (this.targetKeys.includes(item.code)) {
          arr.push(item)
        }
      })
      this.$emit('selectRoleList', arr)
      this.$emit('change', false)
    },
  },
}
</script>
