<template>
  <div class="container">
    <el-dialog v-model="dialog.visible" draggable :title="dialog.title" :width="props.width" :height="props.height" :close-on-click-modal="false" @close="cancel">
      <el-table ref="tableRef" v-loading="false" :data="columnVos" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" type="index" width="55px" />
        <el-table-column label="名称" align="center" prop="label" />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" name="ExportSelector" setup>
import {propTypes} from '@/utils/propTypes';
import {ExportColumnVo} from "@/api/system/importExport/types";
import {columns} from "@/api/system/importExport";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const emits = defineEmits(['submitCallback']);

// 获取 el-table 的引用
const tableRef = ref<ElTableInstance>(null);
const buttonLoading = ref(false);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const visible = ref(false);

const dialog = reactive<DialogOption>({
  visible: false,
  title: '选择导出列'
});

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  // 不清理，保留字段选择
}

const columnNames = ref<string[]>([]);
/** 多选框选中数据 */
const handleSelectionChange = (selection: ExportColumnVo[]) => {
  columnNames.value = selection.map(item => item.value);
}

/** 提交按钮 */
const submitForm = async () => {
  if (columnNames.value.length === 0) {
    proxy?.$modal.msgWarning('请选择导出列！');
    return;
  }
  emits('submitCallback', columnNames.value);
  cancel();
}

const props = defineProps({
  width: propTypes.string.def('40%'),
  height: propTypes.string.def('10%'),
  className: {
    type: String,
    default: () => ''
  },
});

const columnVos = ref<ExportColumnVo[]>([]);
const init = () => {
  // 打开弹窗
  dialog.visible = true;
  // 初始化数据
  if (props.className && columnVos.value.length === 0) {
    columns(props.className).then((response) => {
      columnVos.value = response.data;
      // 全选
      if (columnVos.value) {
        tableRef.value!.toggleAllSelection();
      }
    })
  }
};

/**
 * 对外暴露子组件方法
 */
defineExpose({
  init
});
</script>
<style lang="scss" scoped>
.container {
  :deep(.el-dialog .el-dialog__body) {
    max-height: calc(100vh - 170px) !important;
    min-height: calc(100vh - 170px) !important;
  }
}
</style>
