<!--
 * @Author: 曹捷
 * @Date: 2021-08-31 16:56:27
 * @LastEditors: 曹捷
 * @LastEditTime: 2021-09-01 10:21:18
 * @Description: 导入规则
-->
<template>
  <a-modal class="obit-modal-default" @cancel="closeDialog" :maskClosable="false" title="导入生成规则"
    v-model:visible="showModal" @ok="saveTable" cancelText="取消" okText="生成" width="50%">
    <a-steps :current="stepIndex">
      <a-step title="选择表" description="可以同时选择数据表" />
      <a-step title="表确认" description="确认要生成的表" />
    </a-steps>
    <a-transfer class="rule-transfer flex-c m-t-30" :data-source="tableList" :titles="['待选择', '选择表']"
      :selected-keys="selectedKeys" :target-keys="targetKeys"
      :render="item => `${item.functionName} (${item.className})`" @change="handleChange"
      @selectChange="handleSelectChange" />
  </a-modal>
</template>

<script>
import { nextTick, reactive, toRefs, onMounted, inject } from 'vue';
import { message } from 'ant-design-vue';

export default {
  props: {
    visible: {
      type: Boolean
    }
  },
  setup (props, context) {
    let http = inject('http')
    let _data = reactive({
      showModal: props.visible,
      stepIndex: 0,
      targetKeys: [],
      selectedKeys: [],
      tableList: []
    })
    let methods = {
      initInfo () {
        http.commonPost('code/gen/list').then(res => {
          res.forEach(element => {
            element.key = element.tableId
            element.title = element.functionName
          })
          _data.tableList = res
        })
      }
    }
    let _methods = {
      saveTable () {
        if (_data.targetKeys.length === 0) {
          message.error('请选择要生成的代码基础表结构');
          return
        }
        let pmList = []
        let resultList = []
        _data.targetKeys.forEach(element => {
          pmList.push(new Promise((resolve, reject) => {
            http.commonPost(`code/gen/${element}`).then(res => {
              console.log('🚀 ~ file: ruleDialog.vue ~ line 63 ~ http.commonPost ~ res', res)
              resultList.push(res)
              resolve()
            })
          }))
        })
        Promise.all(pmList).then(() => {
          context.emit('update:visible', false)
          context.emit('generate', resultList)
        })
      },
      handleChange (nextTargetKeys, direction, moveKeys) {
        _data.targetKeys = nextTargetKeys;
      },
      handleSelectChange (sourceSelectedKeys, targetSelectedKeys) {
        _data.selectedKeys = [...sourceSelectedKeys, ...targetSelectedKeys];
      },
      closeDialog () {
        context.emit('update:visible', false)
      }
    }
    onMounted(() => {
      methods.initInfo()
    })
    return {
      ...toRefs(_data),
      ..._methods
    }
  }
}
</script>

<style lang="less">
.rule-transfer {
  .ant-transfer-list {
    width: 40%;
    min-height: 500px;
  }
}
</style>