<template>
  <a-row>
    <a-col :span="5">
      <a-tree
        v-if="treeData.length"
        v-model:expandedKeys="defaultExpandedKeys"
        :tree-data="treeData"
        :field-names="treeFieldNames"
        @select="treeSelect"
      />
      <a-empty v-else />
    </a-col>
    <a-col :span="19">
      <BasicTable @register="registerTable" :showExpandColumn="false">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'dictType'">
            <Tag :color="formatDictColor(sysDictTypeOptions, record.dictType)">
              {{ formatDictValue(sysDictTypeOptions, record.dictType) }}
            </Tag>
          </template>
          <template v-if="column.key === 'fontColor'">
            <Tag :color="record.fontColor || '#000'">
              {{ record.fontColor }}
            </Tag>
          </template>
          <template v-if="column.key === 'bgColor'">
            <Tag :color="record.bgColor || '#000'">
              {{ record.bgColor }}
            </Tag>
          </template>
          <template v-if="column.key === 'prefixColor'">
            <Tag :color="record.prefixColor || '#000'">
              {{ record.prefixColor }}
            </Tag>
          </template>
          <template v-if="column.key === 'action'">
            <TableAction
              :actions="[
                {
                  auth: ['sys:dict:edit'],
                  icon: 'icon-edit|iconfont',
                  tooltip: '编辑',
                  onClick: handleEdit.bind(null, record),
                },
                {
                  auth: ['sys:dict:remove'],
                  icon: 'icon-delete|iconfont',
                  tooltip: '删除',
                  color: 'error',
                  popConfirm: {
                    title: '是否确认删除',
                    placement: 'left',
                    confirm: handleDelete.bind(null, record),
                  },
                },
              ]"
            />
          </template>
        </template>
        <template #toolbar>
          <a-button
            v-auth="['sys:dict:add']"
            type="primary"
            @click="handleCreate"
            preIcon="icon-plus|iconfont"
            >新增</a-button
          >
        </template>
      </BasicTable>
      <FormModal @register="registerModal" @success="handleSuccess" :destroyOnClose="true" />
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
  import { computed, onBeforeMount, onMounted, ref } from 'vue';
  import { Tag } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import FormModal from './FormModal.vue';
  import { columns, searchFormSchema } from './data';
  import { sysDictQueryPage, sysDictQueryTree, sysDictRemove } from '/@/api/sys/sysDictApi';
  import { formatDictColor, formatDictValue } from '/@/utils';
  import { listDictModel } from '/@/api/common';

  const sysDictTypeOptions = ref([]);
  onBeforeMount(async () => {
    const dictTypeStatus = await listDictModel({ dictCode: 'sys_dict_type' });
    sysDictTypeOptions.value = dictTypeStatus || [];
  });

  onMounted(async () => {
    await getTreeData();
  });

  const props = defineProps({
    type: {
      type: String,
      default: 'DICT_SYS',
    },
  });
  const getTableTitle = computed(() => {
    if (parentId.value == '0') {
      return props.type == 'DICT_SYS' ? '系统 字典列表' : '业务 字典列表';
    } else {
      return treeSelectNodeName.value + ' 字典列表';
    }
  });
  const { createMessage } = useMessage();
  const [registerModal, { openModal }] = useModal();
  const [registerTable, { reload }] = useTable({
    title: getTableTitle,
    api: sysDictQueryPage,
    rowKey: 'id',
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      baseColProps: { span: 8 },
      resetButtonOptions: {
        preIcon: 'icon-delete|iconfont',
      },
      submitButtonOptions: {
        preIcon: 'icon-search|iconfont',
      },
    },
    showIndexColumn: false,
    useSearchForm: true,
    showTableSetting: true,
    tableSetting: {
      setting: false,
    },
    bordered: true,
    actionColumn: {
      auth: ['sys:dict:edit', 'sys:dict:remove'],
      width: 80,
      title: '操作',
      dataIndex: 'action',
    },
    beforeFetch: handleBeforeFetch,
  });

  // 默认父节点
  const parentId = ref('0');
  // 默认展开的节点
  const defaultExpandedKeys = ref(['0']);
  const treeData = ref([]);
  const treeSelectNodeName = ref('');
  // 替换treeNode 中 title,key,children
  const treeFieldNames = { children: 'children', title: 'dictName', key: 'id' };
  // 获取 tree 所有节点信息
  async function getTreeData() {
    const data = await sysDictQueryTree({ dictType: props.type });
    treeData.value = [
      {
        dictName: '根目录',
        id: '0',
        children: data,
      },
    ];
  }

  // 新增按钮事件
  function handleCreate() {
    openModal(true, {
      dictType: props.type,
      parentId: parentId.value,
      isUpdate: false,
    });
  }

  // 编辑按钮事件
  function handleEdit(record: Recordable) {
    console.log('🚀 ~ file: index.vue:165 ~ handleEdit ~ record:', record);
    openModal(true, {
      record,
      dictType: record.dictType || '1',
      isUpdate: true,
    });
  }

  // 删除按钮事件
  async function handleDelete(record: Recordable) {
    console.log(record);
    await sysDictRemove([record.id]);
    createMessage.success('删除成功！');
    await getTreeData();
    await reload();
  }

  // 弹窗回调事件
  async function handleSuccess() {
    await getTreeData();
    await reload();
  }

  function handleBeforeFetch(params) {
    return {
      ...params,
      dictType: props.type,
      parentId: parentId.value,
      orders: [{ field: 'sort', direction: 'ASC' }],
    };
  }

  // tree选中事件
  async function treeSelect(selectedKeys, { selectedNodes }) {
    if (selectedKeys && selectedKeys.length > 0) {
      parentId.value = selectedKeys[0];
      treeSelectNodeName.value = selectedNodes[0]['dictName'];
      await reload();
    }
  }
</script>

<style lang="less" scoped></style>
