<template>
  <el-drawer
    v-model="commonS.isShowSelectModule"
    :append-to-body="true"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :show-close="false"
    size="50%"
  >
    <template #header>
      <h2>请选择想要展示的组件</h2>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button size="large" type="primary" @click="handleSubmit"
          >确 定
        </el-button>
        <el-button size="large" @click="closeDialog">取 消</el-button>
      </div>
    </template>
    <el-table
      ref="singleTableRef"
      :data="tableData"
      highlight-current-row
      size="large"
      style="width: 100%"
      @current-change="handleCurrentChange"
    >
      <el-table-column label="组件名称" property="name" />
      <el-table-column label="描述" property="description" />
    </el-table>
  </el-drawer>
</template>

<script lang="ts" setup>
import { useCommonStore } from "@/store";
import { ElTable } from "element-plus";
import {
  componentsDicts,
  ScreenComponent,
} from "@/views/screens/configs/components";

const commonS = useCommonStore();

const currentRow = ref();
const singleTableRef = ref<InstanceType<typeof ElTable>>();

const setCurrent = (row?: ScreenComponent) => {
  singleTableRef.value && singleTableRef.value.setCurrentRow(row);
};
const handleCurrentChange = (val: ScreenComponent) => {
  currentRow.value = val;
};
const tableData = ref<ScreenComponent[]>([]);

onMounted(() => {
  let allKeys = Object.keys(componentsDicts);
  allKeys.forEach((key) => {
    tableData.value.push(componentsDicts[key]);
  });
  nextTick(() => {
    setCurrent(componentsDicts[commonS.moduleKey as string]);
  });
});

const handleSubmit = () => {
  if (currentRow.value && currentRow.value.key) {
    let key = commonS.moduleKey as string;
    if (key in commonS) {
      commonS[key] = currentRow.value.key;
    } else {
      ElMessage.error("请选择正确的组件, 组件的key不存在");
    }

    commonS.isShowSelectModule = false;
  }
};

const closeDialog = () => {
  commonS.isShowSelectModule = false;
};
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: start;
}
</style>
